QueryField.tsx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  1. import _ from 'lodash';
  2. import React, { Context } from 'react';
  3. import ReactDOM from 'react-dom';
  4. // @ts-ignore
  5. import { Change, Range, Value, Block } from 'slate';
  6. // @ts-ignore
  7. import { Editor } from 'slate-react';
  8. // @ts-ignore
  9. import Plain from 'slate-plain-serializer';
  10. import classnames from 'classnames';
  11. // @ts-ignore
  12. import { isKeyHotkey } from 'is-hotkey';
  13. import { CompletionItem, CompletionItemGroup, TypeaheadOutput } from 'app/types/explore';
  14. import ClearPlugin from './slate-plugins/clear';
  15. import NewlinePlugin from './slate-plugins/newline';
  16. import { TypeaheadWithTheme } from './Typeahead';
  17. import { makeFragment, makeValue } from '@grafana/ui';
  18. export const TYPEAHEAD_DEBOUNCE = 100;
  19. export const HIGHLIGHT_WAIT = 500;
  20. const SLATE_TAB = ' ';
  21. const isIndentLeftHotkey = isKeyHotkey('mod+[');
  22. const isIndentRightHotkey = isKeyHotkey('mod+]');
  23. const isSelectLeftHotkey = isKeyHotkey('shift+left');
  24. const isSelectRightHotkey = isKeyHotkey('shift+right');
  25. const isSelectUpHotkey = isKeyHotkey('shift+up');
  26. const isSelectDownHotkey = isKeyHotkey('shift+down');
  27. const isSelectLineHotkey = isKeyHotkey('mod+l');
  28. function getSuggestionByIndex(suggestions: CompletionItemGroup[], index: number): CompletionItem {
  29. // Flatten suggestion groups
  30. const flattenedSuggestions = suggestions.reduce((acc, g) => acc.concat(g.items), []);
  31. const correctedIndex = Math.max(index, 0) % flattenedSuggestions.length;
  32. return flattenedSuggestions[correctedIndex];
  33. }
  34. function hasSuggestions(suggestions: CompletionItemGroup[]): boolean {
  35. return suggestions && suggestions.length > 0;
  36. }
  37. export interface QueryFieldProps {
  38. additionalPlugins?: any[];
  39. cleanText?: (text: string) => string;
  40. disabled?: boolean;
  41. initialQuery: string | null;
  42. onRunQuery?: () => void;
  43. onChange?: (value: string) => void;
  44. onTypeahead?: (typeahead: TypeaheadInput) => TypeaheadOutput;
  45. onWillApplySuggestion?: (suggestion: string, state: QueryFieldState) => string;
  46. placeholder?: string;
  47. portalOrigin?: string;
  48. syntax?: string;
  49. syntaxLoaded?: boolean;
  50. }
  51. export interface QueryFieldState {
  52. suggestions: CompletionItemGroup[];
  53. typeaheadContext: string | null;
  54. typeaheadIndex: number;
  55. typeaheadPrefix: string;
  56. typeaheadText: string;
  57. value: any;
  58. lastExecutedValue: Value;
  59. }
  60. export interface TypeaheadInput {
  61. editorNode: Element;
  62. prefix: string;
  63. selection?: Selection;
  64. text: string;
  65. value: Value;
  66. wrapperNode: Element;
  67. }
  68. /**
  69. * Renders an editor field.
  70. * Pass initial value as initialQuery and listen to changes in props.onValueChanged.
  71. * This component can only process strings. Internally it uses Slate Value.
  72. * Implement props.onTypeahead to use suggestions, see PromQueryField.tsx as an example.
  73. */
  74. export class QueryField extends React.PureComponent<QueryFieldProps, QueryFieldState> {
  75. menuEl: HTMLElement | null;
  76. plugins: any[];
  77. resetTimer: any;
  78. mounted: boolean;
  79. updateHighlightsTimer: any;
  80. constructor(props: QueryFieldProps, context: Context<any>) {
  81. super(props, context);
  82. this.updateHighlightsTimer = _.debounce(this.updateLogsHighlights, HIGHLIGHT_WAIT);
  83. // Base plugins
  84. this.plugins = [ClearPlugin(), NewlinePlugin(), ...(props.additionalPlugins || [])].filter(p => p);
  85. this.state = {
  86. suggestions: [],
  87. typeaheadContext: null,
  88. typeaheadIndex: 0,
  89. typeaheadPrefix: '',
  90. typeaheadText: '',
  91. value: makeValue(props.initialQuery || '', props.syntax),
  92. lastExecutedValue: null,
  93. };
  94. }
  95. componentDidMount() {
  96. this.mounted = true;
  97. this.updateMenu();
  98. }
  99. componentWillUnmount() {
  100. this.mounted = false;
  101. clearTimeout(this.resetTimer);
  102. }
  103. componentDidUpdate(prevProps: QueryFieldProps, prevState: QueryFieldState) {
  104. const { initialQuery, syntax } = this.props;
  105. const { value, suggestions } = this.state;
  106. // if query changed from the outside
  107. if (initialQuery !== prevProps.initialQuery) {
  108. // and we have a version that differs
  109. if (initialQuery !== Plain.serialize(value)) {
  110. this.setState({ value: makeValue(initialQuery || '', syntax) });
  111. }
  112. }
  113. // Only update menu location when suggestion existence or text/selection changed
  114. if (value !== prevState.value || hasSuggestions(suggestions) !== hasSuggestions(prevState.suggestions)) {
  115. this.updateMenu();
  116. }
  117. }
  118. UNSAFE_componentWillReceiveProps(nextProps: QueryFieldProps) {
  119. if (nextProps.syntaxLoaded && !this.props.syntaxLoaded) {
  120. // Need a bogus edit to re-render the editor after syntax has fully loaded
  121. const change = this.state.value
  122. .change()
  123. .insertText(' ')
  124. .deleteBackward();
  125. this.onChange(change, true);
  126. }
  127. }
  128. onChange = ({ value }: Change, invokeParentOnValueChanged?: boolean) => {
  129. const documentChanged = value.document !== this.state.value.document;
  130. const prevValue = this.state.value;
  131. // Control editor loop, then pass text change up to parent
  132. this.setState({ value }, () => {
  133. if (documentChanged) {
  134. const textChanged = Plain.serialize(prevValue) !== Plain.serialize(value);
  135. if (textChanged && invokeParentOnValueChanged) {
  136. this.executeOnChangeAndRunQueries();
  137. }
  138. if (textChanged && !invokeParentOnValueChanged) {
  139. this.updateHighlightsTimer();
  140. }
  141. }
  142. });
  143. // Show suggest menu on text input
  144. if (documentChanged && value.selection.isCollapsed) {
  145. // Need one paint to allow DOM-based typeahead rules to work
  146. window.requestAnimationFrame(this.handleTypeahead);
  147. } else if (!this.resetTimer) {
  148. this.resetTypeahead();
  149. }
  150. };
  151. updateLogsHighlights = () => {
  152. const { onChange } = this.props;
  153. if (onChange) {
  154. onChange(Plain.serialize(this.state.value));
  155. }
  156. };
  157. executeOnChangeAndRunQueries = () => {
  158. // Send text change to parent
  159. const { onChange, onRunQuery } = this.props;
  160. if (onChange) {
  161. onChange(Plain.serialize(this.state.value));
  162. }
  163. if (onRunQuery) {
  164. onRunQuery();
  165. this.setState({ lastExecutedValue: this.state.value });
  166. }
  167. };
  168. handleTypeahead = _.debounce(async () => {
  169. const selection = window.getSelection();
  170. const { cleanText, onTypeahead } = this.props;
  171. const { value } = this.state;
  172. if (onTypeahead && selection.anchorNode) {
  173. const wrapperNode = selection.anchorNode.parentElement;
  174. const editorNode = wrapperNode.closest('.slate-query-field');
  175. if (!editorNode || this.state.value.isBlurred) {
  176. // Not inside this editor
  177. return;
  178. }
  179. const range = selection.getRangeAt(0);
  180. const offset = range.startOffset;
  181. const text = selection.anchorNode.textContent;
  182. let prefix = text.substr(0, offset);
  183. // Label values could have valid characters erased if `cleanText()` is
  184. // blindly applied, which would undesirably interfere with suggestions
  185. const labelValueMatch = prefix.match(/(?:!?=~?"?|")(.*)/);
  186. if (labelValueMatch) {
  187. prefix = labelValueMatch[1];
  188. } else if (cleanText) {
  189. prefix = cleanText(prefix);
  190. }
  191. const { suggestions, context, refresher } = onTypeahead({
  192. editorNode,
  193. prefix,
  194. selection,
  195. text,
  196. value,
  197. wrapperNode,
  198. });
  199. let filteredSuggestions = suggestions
  200. .map(group => {
  201. if (group.items) {
  202. if (prefix) {
  203. // Filter groups based on prefix
  204. if (!group.skipFilter) {
  205. group.items = group.items.filter(c => (c.filterText || c.label).length >= prefix.length);
  206. if (group.prefixMatch) {
  207. group.items = group.items.filter(c => (c.filterText || c.label).indexOf(prefix) === 0);
  208. } else {
  209. group.items = group.items.filter(c => (c.filterText || c.label).indexOf(prefix) > -1);
  210. }
  211. }
  212. // Filter out the already typed value (prefix) unless it inserts custom text
  213. group.items = group.items.filter(c => c.insertText || (c.filterText || c.label) !== prefix);
  214. }
  215. if (!group.skipSort) {
  216. group.items = _.sortBy(group.items, (item: CompletionItem) => item.sortText || item.label);
  217. }
  218. }
  219. return group;
  220. })
  221. .filter(group => group.items && group.items.length > 0); // Filter out empty groups
  222. // Keep same object for equality checking later
  223. if (_.isEqual(filteredSuggestions, this.state.suggestions)) {
  224. filteredSuggestions = this.state.suggestions;
  225. }
  226. this.setState(
  227. {
  228. suggestions: filteredSuggestions,
  229. typeaheadPrefix: prefix,
  230. typeaheadContext: context,
  231. typeaheadText: text,
  232. },
  233. () => {
  234. if (refresher) {
  235. refresher.then(this.handleTypeahead).catch(e => console.error(e));
  236. }
  237. }
  238. );
  239. }
  240. }, TYPEAHEAD_DEBOUNCE);
  241. applyTypeahead(change: Change, suggestion: CompletionItem): Change {
  242. const { cleanText, onWillApplySuggestion, syntax } = this.props;
  243. const { typeaheadPrefix, typeaheadText } = this.state;
  244. let suggestionText = suggestion.insertText || suggestion.label;
  245. const preserveSuffix = suggestion.kind === 'function';
  246. const move = suggestion.move || 0;
  247. if (onWillApplySuggestion) {
  248. suggestionText = onWillApplySuggestion(suggestionText, { ...this.state });
  249. }
  250. this.resetTypeahead();
  251. // Remove the current, incomplete text and replace it with the selected suggestion
  252. const backward = suggestion.deleteBackwards || typeaheadPrefix.length;
  253. const text = cleanText ? cleanText(typeaheadText) : typeaheadText;
  254. const suffixLength = text.length - typeaheadPrefix.length;
  255. const offset = typeaheadText.indexOf(typeaheadPrefix);
  256. const midWord = typeaheadPrefix && ((suffixLength > 0 && offset > -1) || suggestionText === typeaheadText);
  257. const forward = midWord && !preserveSuffix ? suffixLength + offset : 0;
  258. // If new-lines, apply suggestion as block
  259. if (suggestionText.match(/\n/)) {
  260. const fragment = makeFragment(suggestionText, syntax);
  261. return change
  262. .deleteBackward(backward)
  263. .deleteForward(forward)
  264. .insertFragment(fragment)
  265. .focus();
  266. }
  267. return change
  268. .deleteBackward(backward)
  269. .deleteForward(forward)
  270. .insertText(suggestionText)
  271. .move(move)
  272. .focus();
  273. }
  274. handleEnterKey = (event: KeyboardEvent, change: Change) => {
  275. event.preventDefault();
  276. if (event.shiftKey) {
  277. // pass through if shift is pressed
  278. return undefined;
  279. } else if (!this.menuEl) {
  280. this.executeOnChangeAndRunQueries();
  281. return true;
  282. } else {
  283. return this.selectSuggestion(change);
  284. }
  285. };
  286. selectSuggestion = (change: Change) => {
  287. const { typeaheadIndex, suggestions } = this.state;
  288. event.preventDefault();
  289. if (!suggestions || suggestions.length === 0) {
  290. return undefined;
  291. }
  292. const suggestion = getSuggestionByIndex(suggestions, typeaheadIndex);
  293. const nextChange = this.applyTypeahead(change, suggestion);
  294. const insertTextOperation = nextChange.operations.find((operation: any) => operation.type === 'insert_text');
  295. return insertTextOperation ? true : undefined;
  296. };
  297. handleTabKey = (change: Change): void => {
  298. const {
  299. startBlock,
  300. endBlock,
  301. selection: { startOffset, startKey, endOffset, endKey },
  302. } = change.value;
  303. if (this.menuEl) {
  304. this.selectSuggestion(change);
  305. return;
  306. }
  307. const first = startBlock.getFirstText();
  308. const startBlockIsSelected =
  309. startOffset === 0 && startKey === first.key && endOffset === first.text.length && endKey === first.key;
  310. if (startBlockIsSelected || !startBlock.equals(endBlock)) {
  311. this.handleIndent(change, 'right');
  312. } else {
  313. change.insertText(SLATE_TAB);
  314. }
  315. };
  316. handleIndent = (change: Change, indentDirection: 'left' | 'right') => {
  317. const curSelection = change.value.selection;
  318. const selectedBlocks = change.value.document.getBlocksAtRange(curSelection);
  319. if (indentDirection === 'left') {
  320. for (const block of selectedBlocks) {
  321. const blockWhitespace = block.text.length - block.text.trimLeft().length;
  322. const rangeProperties = {
  323. anchorKey: block.getFirstText().key,
  324. anchorOffset: blockWhitespace,
  325. focusKey: block.getFirstText().key,
  326. focusOffset: blockWhitespace,
  327. };
  328. // @ts-ignore
  329. const whitespaceToDelete = Range.create(rangeProperties);
  330. change.deleteBackwardAtRange(whitespaceToDelete, Math.min(SLATE_TAB.length, blockWhitespace));
  331. }
  332. } else {
  333. const { startText } = change.value;
  334. const textBeforeCaret = startText.text.slice(0, curSelection.startOffset);
  335. const isWhiteSpace = /^\s*$/.test(textBeforeCaret);
  336. for (const block of selectedBlocks) {
  337. change.insertTextByKey(block.getFirstText().key, 0, SLATE_TAB);
  338. }
  339. if (isWhiteSpace) {
  340. change.moveStart(-SLATE_TAB.length);
  341. }
  342. }
  343. };
  344. handleSelectVertical = (change: Change, direction: 'up' | 'down') => {
  345. const { focusBlock } = change.value;
  346. const adjacentBlock =
  347. direction === 'up'
  348. ? change.value.document.getPreviousBlock(focusBlock.key)
  349. : change.value.document.getNextBlock(focusBlock.key);
  350. if (!adjacentBlock) {
  351. return true;
  352. }
  353. const adjacentText = adjacentBlock.getFirstText();
  354. change.moveFocusTo(adjacentText.key, Math.min(change.value.anchorOffset, adjacentText.text.length)).focus();
  355. return true;
  356. };
  357. handleSelectUp = (change: Change) => this.handleSelectVertical(change, 'up');
  358. handleSelectDown = (change: Change) => this.handleSelectVertical(change, 'down');
  359. onKeyDown = (event: KeyboardEvent, change: Change) => {
  360. const { typeaheadIndex } = this.state;
  361. // Shortcuts
  362. if (isIndentLeftHotkey(event)) {
  363. event.preventDefault();
  364. this.handleIndent(change, 'left');
  365. return true;
  366. } else if (isIndentRightHotkey(event)) {
  367. event.preventDefault();
  368. this.handleIndent(change, 'right');
  369. return true;
  370. } else if (isSelectLeftHotkey(event)) {
  371. event.preventDefault();
  372. if (change.value.focusOffset > 0) {
  373. change.moveFocus(-1);
  374. }
  375. return true;
  376. } else if (isSelectRightHotkey(event)) {
  377. event.preventDefault();
  378. if (change.value.focusOffset < change.value.startText.text.length) {
  379. change.moveFocus(1);
  380. }
  381. return true;
  382. } else if (isSelectUpHotkey(event)) {
  383. event.preventDefault();
  384. this.handleSelectUp(change);
  385. return true;
  386. } else if (isSelectDownHotkey(event)) {
  387. event.preventDefault();
  388. this.handleSelectDown(change);
  389. return true;
  390. } else if (isSelectLineHotkey(event)) {
  391. event.preventDefault();
  392. const { focusBlock, document } = change.value;
  393. change.moveAnchorToStartOfBlock(focusBlock.key);
  394. const nextBlock = document.getNextBlock(focusBlock.key);
  395. if (nextBlock) {
  396. change.moveFocusToStartOfNextBlock();
  397. } else {
  398. change.moveFocusToEndOfText();
  399. }
  400. return true;
  401. }
  402. switch (event.key) {
  403. case 'Escape': {
  404. if (this.menuEl) {
  405. event.preventDefault();
  406. event.stopPropagation();
  407. this.resetTypeahead();
  408. return true;
  409. }
  410. break;
  411. }
  412. case ' ': {
  413. if (event.ctrlKey) {
  414. event.preventDefault();
  415. this.handleTypeahead();
  416. return true;
  417. }
  418. break;
  419. }
  420. case 'Enter':
  421. return this.handleEnterKey(event, change);
  422. case 'Tab': {
  423. event.preventDefault();
  424. return this.handleTabKey(change);
  425. }
  426. case 'ArrowDown': {
  427. if (this.menuEl) {
  428. // Select next suggestion
  429. event.preventDefault();
  430. const itemsCount =
  431. this.state.suggestions.length > 0
  432. ? this.state.suggestions.reduce((totalCount, current) => totalCount + current.items.length, 0)
  433. : 0;
  434. this.setState({ typeaheadIndex: Math.min(itemsCount - 1, typeaheadIndex + 1) });
  435. }
  436. break;
  437. }
  438. case 'ArrowUp': {
  439. if (this.menuEl) {
  440. // Select previous suggestion
  441. event.preventDefault();
  442. this.setState({ typeaheadIndex: Math.max(0, typeaheadIndex - 1) });
  443. }
  444. break;
  445. }
  446. default: {
  447. // console.log('default key', event.key, event.which, event.charCode, event.locale, data.key);
  448. break;
  449. }
  450. }
  451. return undefined;
  452. };
  453. resetTypeahead = () => {
  454. if (this.mounted) {
  455. this.setState({ suggestions: [], typeaheadIndex: 0, typeaheadPrefix: '', typeaheadContext: null });
  456. this.resetTimer = null;
  457. }
  458. };
  459. handleBlur = (event: FocusEvent, change: Change) => {
  460. const { lastExecutedValue } = this.state;
  461. const previousValue = lastExecutedValue ? Plain.serialize(this.state.lastExecutedValue) : null;
  462. const currentValue = Plain.serialize(change.value);
  463. // If we dont wait here, menu clicks wont work because the menu
  464. // will be gone.
  465. this.resetTimer = setTimeout(this.resetTypeahead, 100);
  466. if (previousValue !== currentValue) {
  467. this.executeOnChangeAndRunQueries();
  468. }
  469. };
  470. onClickMenu = (item: CompletionItem) => {
  471. // Manually triggering change
  472. const change = this.applyTypeahead(this.state.value.change(), item);
  473. this.onChange(change, true);
  474. };
  475. updateMenu = () => {
  476. const { suggestions } = this.state;
  477. const menu = this.menuEl;
  478. // Exit for unit tests
  479. if (!window.getSelection) {
  480. return;
  481. }
  482. const selection = window.getSelection();
  483. const node = selection.anchorNode;
  484. // No menu, nothing to do
  485. if (!menu) {
  486. return;
  487. }
  488. // No suggestions or blur, remove menu
  489. if (!hasSuggestions(suggestions)) {
  490. menu.removeAttribute('style');
  491. return;
  492. }
  493. // Align menu overlay to editor node
  494. if (node) {
  495. // Read from DOM
  496. const rect = node.parentElement.getBoundingClientRect();
  497. const scrollX = window.scrollX;
  498. const scrollY = window.scrollY;
  499. // Write DOM
  500. requestAnimationFrame(() => {
  501. menu.style.opacity = '1';
  502. menu.style.top = `${rect.top + scrollY + rect.height + 4}px`;
  503. menu.style.left = `${rect.left + scrollX - 2}px`;
  504. });
  505. }
  506. };
  507. menuRef = (el: HTMLElement) => {
  508. this.menuEl = el;
  509. };
  510. renderMenu = () => {
  511. const { portalOrigin } = this.props;
  512. const { suggestions, typeaheadIndex, typeaheadPrefix } = this.state;
  513. if (!hasSuggestions(suggestions)) {
  514. return null;
  515. }
  516. const selectedItem = getSuggestionByIndex(suggestions, typeaheadIndex);
  517. // Create typeahead in DOM root so we can later position it absolutely
  518. return (
  519. <Portal origin={portalOrigin}>
  520. <TypeaheadWithTheme
  521. menuRef={this.menuRef}
  522. selectedItem={selectedItem}
  523. onClickItem={this.onClickMenu}
  524. prefix={typeaheadPrefix}
  525. groupedItems={suggestions}
  526. typeaheadIndex={typeaheadIndex}
  527. />
  528. </Portal>
  529. );
  530. };
  531. getCopiedText(textBlocks: string[], startOffset: number, endOffset: number) {
  532. if (!textBlocks.length) {
  533. return undefined;
  534. }
  535. const excludingLastLineLength = textBlocks.slice(0, -1).join('').length + textBlocks.length - 1;
  536. return textBlocks.join('\n').slice(startOffset, excludingLastLineLength + endOffset);
  537. }
  538. handleCopy = (event: ClipboardEvent, change: Change) => {
  539. event.preventDefault();
  540. const { document, selection, startOffset, endOffset } = change.value;
  541. const selectedBlocks = document.getBlocksAtRangeAsArray(selection).map((block: Block) => block.text);
  542. const copiedText = this.getCopiedText(selectedBlocks, startOffset, endOffset);
  543. if (copiedText) {
  544. event.clipboardData.setData('Text', copiedText);
  545. }
  546. return true;
  547. };
  548. handlePaste = (event: ClipboardEvent, change: Change) => {
  549. event.preventDefault();
  550. const pastedValue = event.clipboardData.getData('Text');
  551. const lines = pastedValue.split('\n');
  552. if (lines.length) {
  553. change.insertText(lines[0]);
  554. for (const line of lines.slice(1)) {
  555. change.splitBlock().insertText(line);
  556. }
  557. }
  558. return true;
  559. };
  560. handleCut = (event: ClipboardEvent, change: Change) => {
  561. this.handleCopy(event, change);
  562. change.deleteAtRange(change.value.selection);
  563. return true;
  564. };
  565. render() {
  566. const { disabled } = this.props;
  567. const wrapperClassName = classnames('slate-query-field__wrapper', {
  568. 'slate-query-field__wrapper--disabled': disabled,
  569. });
  570. return (
  571. <div className={wrapperClassName}>
  572. <div className="slate-query-field">
  573. {this.renderMenu()}
  574. <Editor
  575. autoCorrect={false}
  576. readOnly={this.props.disabled}
  577. onBlur={this.handleBlur}
  578. onKeyDown={this.onKeyDown}
  579. onChange={this.onChange}
  580. onCopy={this.handleCopy}
  581. onPaste={this.handlePaste}
  582. onCut={this.handleCut}
  583. placeholder={this.props.placeholder}
  584. plugins={this.plugins}
  585. spellCheck={false}
  586. value={this.state.value}
  587. />
  588. </div>
  589. </div>
  590. );
  591. }
  592. }
  593. interface PortalProps {
  594. index?: number;
  595. origin: string;
  596. }
  597. class Portal extends React.PureComponent<PortalProps, {}> {
  598. node: HTMLElement;
  599. constructor(props: PortalProps) {
  600. super(props);
  601. const { index = 0, origin = 'query' } = props;
  602. this.node = document.createElement('div');
  603. this.node.classList.add(`slate-typeahead`, `slate-typeahead-${origin}-${index}`);
  604. document.body.appendChild(this.node);
  605. }
  606. componentWillUnmount() {
  607. document.body.removeChild(this.node);
  608. }
  609. render() {
  610. return ReactDOM.createPortal(this.props.children, this.node);
  611. }
  612. }
  613. export default QueryField;