QueryField.tsx 21 KB

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