handler.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. // Copyright (c) Jupyter Development Team.
  2. // Distributed under the terms of the Modified BSD License.
  3. import {
  4. CodeEditor
  5. } from '@jupyterlab/codeeditor';
  6. import {
  7. IDataConnector, Text
  8. } from '@jupyterlab/coreutils';
  9. import {
  10. ReadonlyJSONObject, JSONObject, JSONArray
  11. } from '@phosphor/coreutils';
  12. import {
  13. IDisposable
  14. } from '@phosphor/disposable';
  15. import {
  16. Message, MessageLoop
  17. } from '@phosphor/messaging';
  18. import {
  19. Signal
  20. } from '@phosphor/signaling';
  21. import {
  22. Completer
  23. } from './widget';
  24. /**
  25. * A class added to editors that can host a completer.
  26. */
  27. const COMPLETER_ENABLED_CLASS: string = 'jp-mod-completer-enabled';
  28. /**
  29. * A class added to editors that have an active completer.
  30. */
  31. const COMPLETER_ACTIVE_CLASS: string = 'jp-mod-completer-active';
  32. /**
  33. * A completion handler for editors.
  34. */
  35. export
  36. class CompletionHandler implements IDisposable {
  37. /**
  38. * Construct a new completion handler for a widget.
  39. */
  40. constructor(options: CompletionHandler.IOptions) {
  41. this.completer = options.completer;
  42. this.completer.selected.connect(this.onCompletionSelected, this);
  43. this.completer.visibilityChanged.connect(this.onVisibilityChanged, this);
  44. this._connector = options.connector;
  45. }
  46. /**
  47. * The completer widget managed by the handler.
  48. */
  49. readonly completer: Completer;
  50. /**
  51. * The data connector used to populate completion requests.
  52. *
  53. * #### Notes
  54. * The only method of this connector that will ever be called is `fetch`, so
  55. * it is acceptable for the other methods to be simple functions that return
  56. * rejected promises.
  57. */
  58. get connector(): IDataConnector<CompletionHandler.IReply, void, CompletionHandler.IRequest> {
  59. return this._connector;
  60. }
  61. set connector(connector: IDataConnector<CompletionHandler.IReply, void, CompletionHandler.IRequest>) {
  62. this._connector = connector;
  63. }
  64. /**
  65. * The editor used by the completion handler.
  66. */
  67. get editor(): CodeEditor.IEditor | null {
  68. return this._editor;
  69. }
  70. set editor(newValue: CodeEditor.IEditor | null) {
  71. if (newValue === this._editor) {
  72. return;
  73. }
  74. let editor = this._editor;
  75. // Clean up and disconnect from old editor.
  76. if (editor && !editor.isDisposed) {
  77. const model = editor.model;
  78. editor.host.classList.remove(COMPLETER_ENABLED_CLASS);
  79. model.selections.changed.disconnect(this.onSelectionsChanged, this);
  80. model.value.changed.disconnect(this.onTextChanged, this);
  81. }
  82. // Reset completer state.
  83. this.completer.reset();
  84. this.completer.editor = newValue;
  85. // Update the editor and signal connections.
  86. editor = this._editor = newValue;
  87. if (editor) {
  88. const model = editor.model;
  89. this._enabled = false;
  90. model.selections.changed.connect(this.onSelectionsChanged, this);
  91. model.value.changed.connect(this.onTextChanged, this);
  92. // On initial load, manually check the cursor position.
  93. this.onSelectionsChanged();
  94. }
  95. }
  96. /**
  97. * Get whether the completion handler is disposed.
  98. */
  99. get isDisposed(): boolean {
  100. return this._isDisposed;
  101. }
  102. /**
  103. * Dispose of the resources used by the handler.
  104. */
  105. dispose(): void {
  106. if (this.isDisposed) {
  107. return;
  108. }
  109. this._isDisposed = true;
  110. Signal.clearData(this);
  111. }
  112. /**
  113. * Invoke the handler and launch a completer.
  114. */
  115. invoke(): void {
  116. MessageLoop.sendMessage(this, CompletionHandler.Msg.InvokeRequest);
  117. }
  118. /**
  119. * Process a message sent to the completion handler.
  120. */
  121. processMessage(msg: Message): void {
  122. switch (msg.type) {
  123. case CompletionHandler.Msg.InvokeRequest.type:
  124. this.onInvokeRequest(msg);
  125. break;
  126. default:
  127. break;
  128. }
  129. }
  130. /**
  131. * Get the state of the text editor at the given position.
  132. */
  133. protected getState(editor: CodeEditor.IEditor, position: CodeEditor.IPosition): Completer.ITextState {
  134. return {
  135. text: editor.model.value.text,
  136. lineHeight: editor.lineHeight,
  137. charWidth: editor.charWidth,
  138. line: position.line,
  139. column: position.column
  140. };
  141. }
  142. /**
  143. * Handle a completion selected signal from the completion widget.
  144. */
  145. protected onCompletionSelected(completer: Completer, value: string): void {
  146. const model = completer.model;
  147. const editor = this._editor;
  148. if (!editor || !model) {
  149. return;
  150. }
  151. const patch = model.createPatch(value);
  152. if (!patch) {
  153. return;
  154. }
  155. const { offset, text } = patch;
  156. editor.model.value.text = text;
  157. const position = editor.getPositionAt(offset);
  158. if (position) {
  159. editor.setCursorPosition(position);
  160. }
  161. }
  162. /**
  163. * Handle `invoke-request` messages.
  164. */
  165. protected onInvokeRequest(msg: Message): void {
  166. // If there is no completer model, bail.
  167. if (!this.completer.model) {
  168. return;
  169. }
  170. // If a completer session is already active, bail.
  171. if (this.completer.model.original) {
  172. return;
  173. }
  174. let editor = this._editor;
  175. if (editor) {
  176. this._makeRequest(editor.getCursorPosition())
  177. .catch(reason => { console.log('Invoke request bailed', reason); });
  178. }
  179. }
  180. /**
  181. * Handle selection changed signal from an editor.
  182. *
  183. * #### Notes
  184. * If a sub-class reimplements this method, then that class must either call
  185. * its super method or it must take responsibility for adding and removing
  186. * the completer completable class to the editor host node.
  187. *
  188. * Despite the fact that the editor widget adds a class whenever there is a
  189. * primary selection, this method checks independently for two reasons:
  190. *
  191. * 1. The editor widget connects to the same signal to add that class, so
  192. * there is no guarantee that the class will be added before this method
  193. * is invoked so simply checking for the CSS class's existence is not an
  194. * option. Secondarily, checking the editor state should be faster than
  195. * querying the DOM in either case.
  196. * 2. Because this method adds a class that indicates whether completer
  197. * functionality ought to be enabled, relying on the behavior of the
  198. * `jp-mod-has-primary-selection` to filter out any editors that have
  199. * a selection means the semantic meaning of `jp-mod-completer-enabled`
  200. * is obscured because there may be cases where the enabled class is added
  201. * even though the completer is not available.
  202. */
  203. protected onSelectionsChanged(): void {
  204. const model = this.completer.model;
  205. const editor = this._editor;
  206. if (!editor) {
  207. return;
  208. }
  209. const host = editor.host;
  210. // If there is no model, return.
  211. if (!model) {
  212. this._enabled = false;
  213. host.classList.remove(COMPLETER_ENABLED_CLASS);
  214. return;
  215. }
  216. const position = editor.getCursorPosition();
  217. const line = editor.getLine(position.line);
  218. if (!line) {
  219. this._enabled = false;
  220. model.reset(true);
  221. host.classList.remove(COMPLETER_ENABLED_CLASS);
  222. return;
  223. }
  224. const { start, end } = editor.getSelection();
  225. // If there is a text selection, return.
  226. if (start.column !== end.column || start.line !== end.line) {
  227. this._enabled = false;
  228. model.reset(true);
  229. host.classList.remove(COMPLETER_ENABLED_CLASS);
  230. return;
  231. }
  232. // If the part of the line before the cursor is white space, return.
  233. if (line.slice(0, position.column).match(/^\s*$/)) {
  234. this._enabled = false;
  235. model.reset(true);
  236. host.classList.remove(COMPLETER_ENABLED_CLASS);
  237. return;
  238. }
  239. // Enable completion.
  240. if (!this._enabled) {
  241. this._enabled = true;
  242. host.classList.add(COMPLETER_ENABLED_CLASS);
  243. }
  244. // Dispatch the cursor change.
  245. model.handleCursorChange(this.getState(editor, editor.getCursorPosition()));
  246. }
  247. /**
  248. * Handle a text changed signal from an editor.
  249. */
  250. protected onTextChanged(): void {
  251. const model = this.completer.model;
  252. if (!model || !this._enabled) {
  253. return;
  254. }
  255. // If there is a text selection, no completion is allowed.
  256. const editor = this.editor;
  257. if (!editor) {
  258. return;
  259. }
  260. const { start, end } = editor.getSelection();
  261. if (start.column !== end.column || start.line !== end.line) {
  262. return;
  263. }
  264. // Dispatch the text change.
  265. model.handleTextChange(this.getState(editor, editor.getCursorPosition()));
  266. }
  267. /**
  268. * Handle a visiblity change signal from a completer widget.
  269. */
  270. protected onVisibilityChanged(completer: Completer): void {
  271. // Completer is not active.
  272. if (completer.isDisposed || completer.isHidden) {
  273. if (this._editor) {
  274. this._editor.host.classList.remove(COMPLETER_ACTIVE_CLASS);
  275. this._editor.focus();
  276. }
  277. return;
  278. }
  279. // Completer is active.
  280. if (this._editor) {
  281. this._editor.host.classList.add(COMPLETER_ACTIVE_CLASS);
  282. }
  283. }
  284. /**
  285. * Make a completion request.
  286. */
  287. private _makeRequest(position: CodeEditor.IPosition): Promise<void> {
  288. const editor = this.editor;
  289. if (!editor) {
  290. return Promise.reject(new Error('No active editor'));
  291. }
  292. const text = editor.model.value.text;
  293. const offset = Text.jsIndexToCharIndex(editor.getOffsetAt(position), text);
  294. const pending = ++this._pending;
  295. const state = this.getState(editor, position);
  296. const request: CompletionHandler.IRequest = { text, offset };
  297. return this._connector.fetch(request).then(reply => {
  298. if (this.isDisposed) {
  299. throw new Error('Handler is disposed');
  300. }
  301. // If a newer completion request has created a pending request, bail.
  302. if (pending !== this._pending) {
  303. throw new Error('A newer completion request is pending');
  304. }
  305. this._onReply(state, reply);
  306. }).catch(reason => {
  307. // Completion request failures or negative results fail silently.
  308. const model = this.completer.model;
  309. if (model) {
  310. model.reset(true);
  311. }
  312. });
  313. }
  314. /**
  315. * Receive a completion reply from the connector.
  316. *
  317. * @param state - The state of the editor when completion request was made.
  318. *
  319. * @param reply - The API response returned for a completion request.
  320. */
  321. private _onReply(state: Completer.ITextState, reply: CompletionHandler.IReply): void {
  322. const model = this.completer.model;
  323. const text = state.text;
  324. if (!model) {
  325. return;
  326. }
  327. // Update the original request.
  328. model.original = state;
  329. // Dedupe the matches.
  330. const matches: string[] = [];
  331. const matchSet = new Set(reply.matches || []);
  332. if (reply.matches) {
  333. matchSet.forEach(match => { matches.push(match); });
  334. }
  335. // Extract the optional type map. The current implementation uses
  336. // _jupyter_types_experimental which provide string type names. We make no
  337. // assumptions about the names of the types, so other kernels can provide
  338. // their own types.
  339. const types = reply.metadata._jupyter_types_experimental as JSONArray;
  340. const typeMap: Completer.TypeMap = { };
  341. if (types) {
  342. types.forEach((item: JSONObject) => {
  343. // For some reason the _jupyter_types_experimental list has two entries
  344. // for each match, with one having a type of "<unknown>". Discard those
  345. // and use undefined to indicate an unknown type.
  346. const text = item.text as string;
  347. const type = item.type as string;
  348. if (matchSet.has(text) && type !== '<unknown>') {
  349. typeMap[text] = type;
  350. }
  351. });
  352. }
  353. // Update the options, including the type map.
  354. model.setOptions(matches, typeMap);
  355. // Update the cursor.
  356. model.cursor = {
  357. start: Text.charIndexToJsIndex(reply.start, text),
  358. end: Text.charIndexToJsIndex(reply.end, text)
  359. };
  360. }
  361. private _connector: IDataConnector<CompletionHandler.IReply, void, CompletionHandler.IRequest>;
  362. private _editor: CodeEditor.IEditor | null = null;
  363. private _enabled = false;
  364. private _pending = 0;
  365. private _isDisposed = false;
  366. }
  367. /**
  368. * A namespace for cell completion handler statics.
  369. */
  370. export
  371. namespace CompletionHandler {
  372. /**
  373. * The instantiation options for cell completion handlers.
  374. */
  375. export
  376. interface IOptions {
  377. /**
  378. * The completion widget the handler will connect to.
  379. */
  380. completer: Completer;
  381. /**
  382. * The data connector used to populate completion requests.
  383. *
  384. * #### Notes
  385. * The only method of this connector that will ever be called is `fetch`, so
  386. * it is acceptable for the other methods to be simple functions that return
  387. * rejected promises.
  388. */
  389. connector: IDataConnector<IReply, void, IRequest>;
  390. }
  391. /**
  392. * A reply to a completion request.
  393. */
  394. export
  395. interface IReply {
  396. /**
  397. * The starting index for the substring being replaced by completion.
  398. */
  399. start: number;
  400. /**
  401. * The end index for the substring being replaced by completion.
  402. */
  403. end: number;
  404. /**
  405. * A list of matching completion strings.
  406. */
  407. matches: string[];
  408. /**
  409. * Any metadata that accompanies the completion reply.
  410. */
  411. metadata: ReadonlyJSONObject;
  412. }
  413. /**
  414. * The details of a completion request.
  415. */
  416. export
  417. interface IRequest {
  418. /**
  419. * The cursor offset position within the text being completed.
  420. */
  421. offset: number;
  422. /**
  423. * The text being completed.
  424. */
  425. text: string;
  426. }
  427. /**
  428. * A namespace for completion handler messages.
  429. */
  430. export
  431. namespace Msg {
  432. /* tslint:disable */
  433. /**
  434. * A singleton `'invoke-request'` message.
  435. */
  436. export
  437. const InvokeRequest = new Message('invoke-request');
  438. /* tslint:enable */
  439. }
  440. }