model.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. // Copyright (c) Jupyter Development Team.
  2. // Distributed under the terms of the Modified BSD License.
  3. import {
  4. IIterator,
  5. IterableOrArrayLike,
  6. iter,
  7. map,
  8. toArray
  9. } from '@lumino/algorithm';
  10. import { JSONExt, ReadonlyPartialJSONArray } from '@lumino/coreutils';
  11. import { StringExt } from '@lumino/algorithm';
  12. import { ISignal, Signal } from '@lumino/signaling';
  13. import { CompletionHandler } from './handler';
  14. import { Completer } from './widget';
  15. /**
  16. * An implementation of a completer model.
  17. */
  18. export class CompleterModel implements Completer.IModel {
  19. /**
  20. * A signal emitted when state of the completer menu changes.
  21. */
  22. get stateChanged(): ISignal<this, void> {
  23. return this._stateChanged;
  24. }
  25. /**
  26. * The original completion request details.
  27. */
  28. get original(): Completer.ITextState | null {
  29. return this._original;
  30. }
  31. set original(newValue: Completer.ITextState | null) {
  32. const unchanged =
  33. this._original === newValue ||
  34. (this._original &&
  35. newValue &&
  36. JSONExt.deepEqual(newValue, this._original));
  37. if (unchanged) {
  38. return;
  39. }
  40. this._reset();
  41. // Set both the current and original to the same value when original is set.
  42. this._current = this._original = newValue;
  43. this._stateChanged.emit(undefined);
  44. }
  45. /**
  46. * The current text change details.
  47. */
  48. get current(): Completer.ITextState | null {
  49. return this._current;
  50. }
  51. set current(newValue: Completer.ITextState | null) {
  52. const unchanged =
  53. this._current === newValue ||
  54. (this._current && newValue && JSONExt.deepEqual(newValue, this._current));
  55. if (unchanged) {
  56. return;
  57. }
  58. const original = this._original;
  59. // Original request must always be set before a text change. If it isn't
  60. // the model fails silently.
  61. if (!original) {
  62. return;
  63. }
  64. const cursor = this._cursor;
  65. // Cursor must always be set before a text change. This happens
  66. // automatically in the completer handler, but since `current` is a public
  67. // attribute, this defensive check is necessary.
  68. if (!cursor) {
  69. return;
  70. }
  71. const current = (this._current = newValue);
  72. if (!current) {
  73. this._stateChanged.emit(undefined);
  74. return;
  75. }
  76. const originalLine = original.text.split('\n')[original.line];
  77. const currentLine = current.text.split('\n')[current.line];
  78. // If the text change means that the original start point has been preceded,
  79. // then the completion is no longer valid and should be reset.
  80. if (!this._subsetMatch && currentLine.length < originalLine.length) {
  81. this.reset(true);
  82. return;
  83. }
  84. const { start, end } = cursor;
  85. // Clip the front of the current line.
  86. let query = current.text.substring(start);
  87. // Clip the back of the current line by calculating the end of the original.
  88. const ending = original.text.substring(end);
  89. query = query.substring(0, query.lastIndexOf(ending));
  90. this._query = query;
  91. this._stateChanged.emit(undefined);
  92. }
  93. /**
  94. * The cursor details that the API has used to return matching options.
  95. */
  96. get cursor(): Completer.ICursorSpan | null {
  97. return this._cursor;
  98. }
  99. set cursor(newValue: Completer.ICursorSpan | null) {
  100. // Original request must always be set before a cursor change. If it isn't
  101. // the model fails silently.
  102. if (!this.original) {
  103. return;
  104. }
  105. this._cursor = newValue;
  106. }
  107. /**
  108. * The query against which items are filtered.
  109. */
  110. get query(): string {
  111. return this._query;
  112. }
  113. set query(newValue: string) {
  114. this._query = newValue;
  115. }
  116. /**
  117. * A flag that is true when the model value was modified by a subset match.
  118. */
  119. get subsetMatch(): boolean {
  120. return this._subsetMatch;
  121. }
  122. set subsetMatch(newValue: boolean) {
  123. this._subsetMatch = newValue;
  124. }
  125. /**
  126. * Get whether the model is disposed.
  127. */
  128. get isDisposed(): boolean {
  129. return this._isDisposed;
  130. }
  131. /**
  132. * Dispose of the resources held by the model.
  133. */
  134. dispose(): void {
  135. // Do nothing if already disposed.
  136. if (this._isDisposed) {
  137. return;
  138. }
  139. this._isDisposed = true;
  140. Signal.clearData(this);
  141. }
  142. /**
  143. * The list of visible items in the completer menu.
  144. *
  145. * #### Notes
  146. * This is a read-only property.
  147. */
  148. completionItems?(): CompletionHandler.ICompletionItems {
  149. let query = this._query;
  150. if (query) {
  151. return this._markup(query);
  152. }
  153. return this._completionItems;
  154. }
  155. /**
  156. * Set the list of visible items in the completer menu, and append any
  157. * new types to KNOWN_TYPES.
  158. */
  159. setCompletionItems?(newValue: CompletionHandler.ICompletionItems): void {
  160. if (
  161. JSONExt.deepEqual(
  162. (newValue as unknown) as ReadonlyPartialJSONArray,
  163. (this._completionItems as unknown) as ReadonlyPartialJSONArray
  164. )
  165. ) {
  166. return;
  167. }
  168. this._completionItems = newValue;
  169. this._orderedTypes = Private.findOrderedCompletionItemTypes(
  170. this._completionItems
  171. );
  172. this._stateChanged.emit(undefined);
  173. }
  174. /**
  175. * The list of visible items in the completer menu.
  176. *
  177. * #### Notes
  178. * This is a read-only property.
  179. */
  180. items(): IIterator<Completer.IItem> {
  181. return this._filter();
  182. }
  183. /**
  184. * The unfiltered list of all available options in a completer menu.
  185. */
  186. options(): IIterator<string> {
  187. return iter(this._options);
  188. }
  189. /**
  190. * The map from identifiers (a.b) to types (function, module, class, instance,
  191. * etc.).
  192. *
  193. * #### Notes
  194. * A type map is currently only provided by the latest IPython kernel using
  195. * the completer reply metadata field `_jupyter_types_experimental`. The
  196. * values are completely up to the kernel.
  197. *
  198. */
  199. typeMap(): Completer.TypeMap {
  200. return this._typeMap;
  201. }
  202. /**
  203. * An ordered list of all the known types in the typeMap.
  204. *
  205. * #### Notes
  206. * To visually encode the types of the completer matches, we assemble an
  207. * ordered list. This list begins with:
  208. * ```
  209. * ['function', 'instance', 'class', 'module', 'keyword']
  210. * ```
  211. * and then has any remaining types listed alphebetically. This will give
  212. * reliable visual encoding for these known types, but allow kernels to
  213. * provide new types.
  214. */
  215. orderedTypes(): string[] {
  216. return this._orderedTypes;
  217. }
  218. /**
  219. * Set the available options in the completer menu.
  220. */
  221. setOptions(
  222. newValue: IterableOrArrayLike<string>,
  223. typeMap?: Completer.TypeMap
  224. ) {
  225. const values = toArray(newValue || []);
  226. const types = typeMap || {};
  227. if (
  228. JSONExt.deepEqual(values, this._options) &&
  229. JSONExt.deepEqual(types, this._typeMap)
  230. ) {
  231. return;
  232. }
  233. if (values.length) {
  234. this._options = values;
  235. this._typeMap = types;
  236. this._orderedTypes = Private.findOrderedTypes(types);
  237. } else {
  238. this._options = [];
  239. this._typeMap = {};
  240. this._orderedTypes = [];
  241. }
  242. this._stateChanged.emit(undefined);
  243. }
  244. /**
  245. * Handle a cursor change.
  246. */
  247. handleCursorChange(change: Completer.ITextState): void {
  248. // If there is no active completion, return.
  249. if (!this._original) {
  250. return;
  251. }
  252. const { column, line } = change;
  253. const { current, original } = this;
  254. if (!original) {
  255. return;
  256. }
  257. // If a cursor change results in a the cursor being on a different line
  258. // than the original request, cancel.
  259. if (line !== original.line) {
  260. this.reset(true);
  261. return;
  262. }
  263. // If a cursor change results in the cursor being set to a position that
  264. // precedes the original column, cancel.
  265. if (column < original.column) {
  266. this.reset(true);
  267. return;
  268. }
  269. const { cursor } = this;
  270. if (!cursor || !current) {
  271. return;
  272. }
  273. // If a cursor change results in the cursor being set to a position beyond
  274. // the end of the area that would be affected by completion, cancel.
  275. const cursorDelta = cursor.end - cursor.start;
  276. const originalLine = original.text.split('\n')[original.line];
  277. const currentLine = current.text.split('\n')[current.line];
  278. const inputDelta = currentLine.length - originalLine.length;
  279. if (column > original.column + cursorDelta + inputDelta) {
  280. this.reset(true);
  281. return;
  282. }
  283. }
  284. /**
  285. * Handle a text change.
  286. */
  287. handleTextChange(change: Completer.ITextState): void {
  288. const original = this._original;
  289. // If there is no active completion, return.
  290. if (!original) {
  291. return;
  292. }
  293. const { text, column, line } = change;
  294. const last = text.split('\n')[line][column - 1];
  295. // If last character entered is not whitespace or if the change column is
  296. // greater than or equal to the original column, update completion.
  297. if ((last && last.match(/\S/)) || change.column >= original.column) {
  298. this.current = change;
  299. return;
  300. }
  301. // If final character is whitespace, reset completion.
  302. this.reset(false);
  303. }
  304. /**
  305. * Create a resolved patch between the original state and a patch string.
  306. *
  307. * @param patch - The patch string to apply to the original value.
  308. *
  309. * @returns A patched text change or undefined if original value did not exist.
  310. */
  311. createPatch(patch: string): Completer.IPatch | undefined {
  312. const original = this._original;
  313. const cursor = this._cursor;
  314. const current = this._current;
  315. if (!original || !cursor || !current) {
  316. return undefined;
  317. }
  318. let { start, end } = cursor;
  319. // Also include any filtering/additional-typing that has occurred
  320. // since the completion request in the patched length.
  321. end = end + (current.text.length - original.text.length);
  322. return { start, end, value: patch };
  323. }
  324. /**
  325. * Reset the state of the model and emit a state change signal.
  326. *
  327. * @param hard - Reset even if a subset match is in progress.
  328. */
  329. reset(hard = false) {
  330. // When the completer detects a common subset prefix for all options,
  331. // it updates the model and sets the model source to that value, triggering
  332. // a reset. Unless explicitly a hard reset, this should be ignored.
  333. if (!hard && this._subsetMatch) {
  334. return;
  335. }
  336. this._reset();
  337. this._stateChanged.emit(undefined);
  338. }
  339. /**
  340. * Check if CompletionItem matches against query.
  341. * Highlight matching prefix by adding <mark> tags.
  342. */
  343. private _markup(query: string): CompletionHandler.ICompletionItems {
  344. const items = this._completionItems;
  345. let results: CompletionHandler.ICompletionItem[] = [];
  346. for (let item of items) {
  347. // See if label matches query string
  348. // With ICompletionItems, the label may include parameters, so we exclude them from the matcher.
  349. // e.g. Given label `foo(b, a, r)` and query `bar`,
  350. // don't count parameters, `b`, `a`, and `r` as matches.
  351. const index = item.label.indexOf('(');
  352. const prefix = index > -1 ? item.label.substring(0, index) : item.label;
  353. let match = StringExt.matchSumOfSquares(prefix, query);
  354. // Filter non-matching items.
  355. if (match !== null) {
  356. // Highlight label text if there's a match
  357. let marked = StringExt.highlight(
  358. item.label,
  359. match.indices,
  360. Private.mark
  361. );
  362. results.push({
  363. label: marked.join(''),
  364. // If no insertText is present, preserve original label value
  365. // by setting it as the insertText.
  366. insertText: item.insertText ? item.insertText : item.label,
  367. type: item.type,
  368. icon: item.icon,
  369. documentation: item.documentation,
  370. deprecated: item.deprecated,
  371. score: match.score
  372. } as CompletionHandler.ICompletionItem);
  373. }
  374. results.sort((a, b) => (a as any).score - (b as any).score);
  375. }
  376. return results;
  377. }
  378. /**
  379. * Apply the query to the complete options list to return the matching subset.
  380. */
  381. private _filter(): IIterator<Completer.IItem> {
  382. const options = this._options || [];
  383. const query = this._query;
  384. if (!query) {
  385. return map(options, option => ({ raw: option, text: option }));
  386. }
  387. const results: Private.IMatch[] = [];
  388. for (const option of options) {
  389. const match = StringExt.matchSumOfSquares(option, query);
  390. if (match) {
  391. const marked = StringExt.highlight(option, match.indices, Private.mark);
  392. results.push({
  393. raw: option,
  394. score: match.score,
  395. text: marked.join('')
  396. });
  397. }
  398. }
  399. return map(results.sort(Private.scoreCmp), result => ({
  400. text: result.text,
  401. raw: result.raw
  402. }));
  403. }
  404. /**
  405. * Reset the state of the model.
  406. */
  407. private _reset(): void {
  408. this._current = null;
  409. this._cursor = null;
  410. this._completionItems = [];
  411. this._options = [];
  412. this._original = null;
  413. this._query = '';
  414. this._subsetMatch = false;
  415. this._typeMap = {};
  416. this._orderedTypes = [];
  417. }
  418. private _current: Completer.ITextState | null = null;
  419. private _cursor: Completer.ICursorSpan | null = null;
  420. private _isDisposed = false;
  421. private _completionItems: CompletionHandler.ICompletionItems = [];
  422. private _options: string[] = [];
  423. private _original: Completer.ITextState | null = null;
  424. private _query = '';
  425. private _subsetMatch = false;
  426. private _typeMap: Completer.TypeMap = {};
  427. private _orderedTypes: string[] = [];
  428. private _stateChanged = new Signal<this, void>(this);
  429. }
  430. /**
  431. * A namespace for completer model private data.
  432. */
  433. namespace Private {
  434. /**
  435. * The list of known type annotations of completer matches.
  436. */
  437. const KNOWN_TYPES = ['function', 'instance', 'class', 'module', 'keyword'];
  438. /**
  439. * The map of known type annotations of completer matches.
  440. */
  441. const KNOWN_MAP = KNOWN_TYPES.reduce((acc, type) => {
  442. acc[type] = null;
  443. return acc;
  444. }, {} as Completer.TypeMap);
  445. /**
  446. * A filtered completion menu matching result.
  447. */
  448. export interface IMatch {
  449. /**
  450. * The raw text of a completion match.
  451. */
  452. raw: string;
  453. /**
  454. * A score which indicates the strength of the match.
  455. *
  456. * A lower score is better. Zero is the best possible score.
  457. */
  458. score: number;
  459. /**
  460. * The highlighted text of a completion match.
  461. */
  462. text: string;
  463. }
  464. /**
  465. * Mark a highlighted chunk of text.
  466. */
  467. export function mark(value: string): string {
  468. return `<mark>${value}</mark>`;
  469. }
  470. /**
  471. * A sort comparison function for item match scores.
  472. *
  473. * #### Notes
  474. * This orders the items first based on score (lower is better), then
  475. * by locale order of the item text.
  476. */
  477. export function scoreCmp(a: IMatch, b: IMatch): number {
  478. const delta = a.score - b.score;
  479. if (delta !== 0) {
  480. return delta;
  481. }
  482. return a.raw.localeCompare(b.raw);
  483. }
  484. /**
  485. * Compute a reliably ordered list of types for ICompletionItems.
  486. *
  487. * #### Notes
  488. * The resulting list always begins with the known types:
  489. * ```
  490. * ['function', 'instance', 'class', 'module', 'keyword']
  491. * ```
  492. * followed by other types in alphabetical order.
  493. *
  494. */
  495. export function findOrderedCompletionItemTypes(
  496. items: CompletionHandler.ICompletionItems
  497. ): string[] {
  498. const newTypeSet = new Set<string>();
  499. items.forEach(item => {
  500. if (
  501. item.type &&
  502. !KNOWN_TYPES.includes(item.type) &&
  503. !newTypeSet.has(item.type!)
  504. ) {
  505. newTypeSet.add(item.type!);
  506. }
  507. });
  508. const newTypes = Array.from(newTypeSet);
  509. newTypes.sort((a, b) => a.localeCompare(b));
  510. return KNOWN_TYPES.concat(newTypes);
  511. }
  512. /**
  513. * Compute a reliably ordered list of types.
  514. *
  515. * #### Notes
  516. * The resulting list always begins with the known types:
  517. * ```
  518. * ['function', 'instance', 'class', 'module', 'keyword']
  519. * ```
  520. * followed by other types in alphabetical order.
  521. */
  522. export function findOrderedTypes(typeMap: Completer.TypeMap): string[] {
  523. const filtered = Object.keys(typeMap)
  524. .map(key => typeMap[key])
  525. .filter(
  526. (value: string | null): value is string =>
  527. !!value && !(value in KNOWN_MAP)
  528. )
  529. .sort((a, b) => a.localeCompare(b));
  530. return KNOWN_TYPES.concat(filtered);
  531. }
  532. }