QueryField.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. import _ from 'lodash';
  2. import React, { Context } from 'react';
  3. import ReactDOM from 'react-dom';
  4. // @ts-ignore
  5. import { Change, Value } 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 { CompletionItem, CompletionItemGroup, TypeaheadOutput } from 'app/types/explore';
  12. import ClearPlugin from './slate-plugins/clear';
  13. import NewlinePlugin from './slate-plugins/newline';
  14. import { TypeaheadWithTheme } from './Typeahead';
  15. import { makeFragment, makeValue } from './Value';
  16. import PlaceholdersBuffer from './PlaceholdersBuffer';
  17. export const TYPEAHEAD_DEBOUNCE = 100;
  18. function getSuggestionByIndex(suggestions: CompletionItemGroup[], index: number): CompletionItem {
  19. // Flatten suggestion groups
  20. const flattenedSuggestions = suggestions.reduce((acc, g) => acc.concat(g.items), []);
  21. const correctedIndex = Math.max(index, 0) % flattenedSuggestions.length;
  22. return flattenedSuggestions[correctedIndex];
  23. }
  24. function hasSuggestions(suggestions: CompletionItemGroup[]): boolean {
  25. return suggestions && suggestions.length > 0;
  26. }
  27. export interface QueryFieldProps {
  28. additionalPlugins?: any[];
  29. cleanText?: (text: string) => string;
  30. disabled?: boolean;
  31. initialQuery: string | null;
  32. onExecuteQuery?: () => void;
  33. onQueryChange?: (value: string) => void;
  34. onTypeahead?: (typeahead: TypeaheadInput) => TypeaheadOutput;
  35. onWillApplySuggestion?: (suggestion: string, state: QueryFieldState) => string;
  36. placeholder?: string;
  37. portalOrigin?: string;
  38. syntax?: string;
  39. syntaxLoaded?: boolean;
  40. }
  41. export interface QueryFieldState {
  42. suggestions: CompletionItemGroup[];
  43. typeaheadContext: string | null;
  44. typeaheadIndex: number;
  45. typeaheadPrefix: string;
  46. typeaheadText: string;
  47. value: Value;
  48. lastExecutedValue: Value;
  49. }
  50. export interface TypeaheadInput {
  51. editorNode: Element;
  52. prefix: string;
  53. selection?: Selection;
  54. text: string;
  55. value: Value;
  56. wrapperNode: Element;
  57. }
  58. /**
  59. * Renders an editor field.
  60. * Pass initial value as initialQuery and listen to changes in props.onValueChanged.
  61. * This component can only process strings. Internally it uses Slate Value.
  62. * Implement props.onTypeahead to use suggestions, see PromQueryField.tsx as an example.
  63. */
  64. export class QueryField extends React.PureComponent<QueryFieldProps, QueryFieldState> {
  65. menuEl: HTMLElement | null;
  66. placeholdersBuffer: PlaceholdersBuffer;
  67. plugins: any[];
  68. resetTimer: any;
  69. mounted: boolean;
  70. constructor(props: QueryFieldProps, context: Context<any>) {
  71. super(props, context);
  72. this.placeholdersBuffer = new PlaceholdersBuffer(props.initialQuery || '');
  73. // Base plugins
  74. this.plugins = [ClearPlugin(), NewlinePlugin(), ...(props.additionalPlugins || [])].filter(p => p);
  75. this.state = {
  76. suggestions: [],
  77. typeaheadContext: null,
  78. typeaheadIndex: 0,
  79. typeaheadPrefix: '',
  80. typeaheadText: '',
  81. value: makeValue(this.placeholdersBuffer.toString(), props.syntax),
  82. lastExecutedValue: null,
  83. };
  84. }
  85. componentDidMount() {
  86. this.mounted = true;
  87. this.updateMenu();
  88. }
  89. componentWillUnmount() {
  90. this.mounted = false;
  91. clearTimeout(this.resetTimer);
  92. }
  93. componentDidUpdate(prevProps: QueryFieldProps, prevState: QueryFieldState) {
  94. const { initialQuery, syntax } = this.props;
  95. const { value, suggestions } = this.state;
  96. // if query changed from the outside
  97. if (initialQuery !== prevProps.initialQuery) {
  98. // and we have a version that differs
  99. if (initialQuery !== Plain.serialize(value)) {
  100. this.placeholdersBuffer = new PlaceholdersBuffer(initialQuery || '');
  101. this.setState({ value: makeValue(this.placeholdersBuffer.toString(), syntax) });
  102. }
  103. }
  104. // Only update menu location when suggestion existence or text/selection changed
  105. if (value !== prevState.value || hasSuggestions(suggestions) !== hasSuggestions(prevState.suggestions)) {
  106. this.updateMenu();
  107. }
  108. }
  109. componentWillReceiveProps(nextProps: QueryFieldProps) {
  110. if (nextProps.syntaxLoaded && !this.props.syntaxLoaded) {
  111. // Need a bogus edit to re-render the editor after syntax has fully loaded
  112. const change = this.state.value
  113. .change()
  114. .insertText(' ')
  115. .deleteBackward();
  116. if (this.placeholdersBuffer.hasPlaceholders()) {
  117. change.move(this.placeholdersBuffer.getNextMoveOffset()).focus();
  118. }
  119. this.onChange(change, true);
  120. }
  121. }
  122. onChange = ({ value }: Change, invokeParentOnValueChanged?: boolean) => {
  123. const documentChanged = value.document !== this.state.value.document;
  124. const prevValue = this.state.value;
  125. // Control editor loop, then pass text change up to parent
  126. this.setState({ value }, () => {
  127. if (documentChanged) {
  128. const textChanged = Plain.serialize(prevValue) !== Plain.serialize(value);
  129. if (textChanged && invokeParentOnValueChanged) {
  130. this.executeOnQueryChangeAndExecuteQueries();
  131. }
  132. }
  133. });
  134. // Show suggest menu on text input
  135. if (documentChanged && value.selection.isCollapsed) {
  136. // Need one paint to allow DOM-based typeahead rules to work
  137. window.requestAnimationFrame(this.handleTypeahead);
  138. } else if (!this.resetTimer) {
  139. this.resetTypeahead();
  140. }
  141. };
  142. executeOnQueryChangeAndExecuteQueries = () => {
  143. // Send text change to parent
  144. const { onQueryChange, onExecuteQuery } = this.props;
  145. if (onQueryChange) {
  146. onQueryChange(Plain.serialize(this.state.value));
  147. }
  148. if (onExecuteQuery) {
  149. onExecuteQuery();
  150. this.setState({ lastExecutedValue: this.state.value });
  151. }
  152. };
  153. handleTypeahead = _.debounce(async () => {
  154. const selection = window.getSelection();
  155. const { cleanText, onTypeahead } = this.props;
  156. const { value } = this.state;
  157. if (onTypeahead && selection.anchorNode) {
  158. const wrapperNode = selection.anchorNode.parentElement;
  159. const editorNode = wrapperNode.closest('.slate-query-field');
  160. if (!editorNode || this.state.value.isBlurred) {
  161. // Not inside this editor
  162. return;
  163. }
  164. const range = selection.getRangeAt(0);
  165. const offset = range.startOffset;
  166. const text = selection.anchorNode.textContent;
  167. let prefix = text.substr(0, offset);
  168. // Label values could have valid characters erased if `cleanText()` is
  169. // blindly applied, which would undesirably interfere with suggestions
  170. const labelValueMatch = prefix.match(/(?:!?=~?"?|")(.*)/);
  171. if (labelValueMatch) {
  172. prefix = labelValueMatch[1];
  173. } else if (cleanText) {
  174. prefix = cleanText(prefix);
  175. }
  176. const { suggestions, context, refresher } = onTypeahead({
  177. editorNode,
  178. prefix,
  179. selection,
  180. text,
  181. value,
  182. wrapperNode,
  183. });
  184. let filteredSuggestions = suggestions
  185. .map(group => {
  186. if (group.items) {
  187. if (prefix) {
  188. // Filter groups based on prefix
  189. if (!group.skipFilter) {
  190. group.items = group.items.filter(c => (c.filterText || c.label).length >= prefix.length);
  191. if (group.prefixMatch) {
  192. group.items = group.items.filter(c => (c.filterText || c.label).indexOf(prefix) === 0);
  193. } else {
  194. group.items = group.items.filter(c => (c.filterText || c.label).indexOf(prefix) > -1);
  195. }
  196. }
  197. // Filter out the already typed value (prefix) unless it inserts custom text
  198. group.items = group.items.filter(c => c.insertText || (c.filterText || c.label) !== prefix);
  199. }
  200. if (!group.skipSort) {
  201. group.items = _.sortBy(group.items, (item: CompletionItem) => item.sortText || item.label);
  202. }
  203. }
  204. return group;
  205. })
  206. .filter(group => group.items && group.items.length > 0); // Filter out empty groups
  207. // Keep same object for equality checking later
  208. if (_.isEqual(filteredSuggestions, this.state.suggestions)) {
  209. filteredSuggestions = this.state.suggestions;
  210. }
  211. this.setState(
  212. {
  213. suggestions: filteredSuggestions,
  214. typeaheadPrefix: prefix,
  215. typeaheadContext: context,
  216. typeaheadText: text,
  217. },
  218. () => {
  219. if (refresher) {
  220. refresher.then(this.handleTypeahead).catch(e => console.error(e));
  221. }
  222. }
  223. );
  224. }
  225. }, TYPEAHEAD_DEBOUNCE);
  226. applyTypeahead(change: Change, suggestion: CompletionItem): Change {
  227. const { cleanText, onWillApplySuggestion, syntax } = this.props;
  228. const { typeaheadPrefix, typeaheadText } = this.state;
  229. let suggestionText = suggestion.insertText || suggestion.label;
  230. const preserveSuffix = suggestion.kind === 'function';
  231. const move = suggestion.move || 0;
  232. if (onWillApplySuggestion) {
  233. suggestionText = onWillApplySuggestion(suggestionText, { ...this.state });
  234. }
  235. this.resetTypeahead();
  236. // Remove the current, incomplete text and replace it with the selected suggestion
  237. const backward = suggestion.deleteBackwards || typeaheadPrefix.length;
  238. const text = cleanText ? cleanText(typeaheadText) : typeaheadText;
  239. const suffixLength = text.length - typeaheadPrefix.length;
  240. const offset = typeaheadText.indexOf(typeaheadPrefix);
  241. const midWord = typeaheadPrefix && ((suffixLength > 0 && offset > -1) || suggestionText === typeaheadText);
  242. const forward = midWord && !preserveSuffix ? suffixLength + offset : 0;
  243. // If new-lines, apply suggestion as block
  244. if (suggestionText.match(/\n/)) {
  245. const fragment = makeFragment(suggestionText, syntax);
  246. return change
  247. .deleteBackward(backward)
  248. .deleteForward(forward)
  249. .insertFragment(fragment)
  250. .focus();
  251. }
  252. return change
  253. .deleteBackward(backward)
  254. .deleteForward(forward)
  255. .insertText(suggestionText)
  256. .move(move)
  257. .focus();
  258. }
  259. handleEnterAndTabKey = (event: KeyboardEvent, change: Change) => {
  260. const { typeaheadIndex, suggestions } = this.state;
  261. if (this.menuEl) {
  262. // Dont blur input
  263. event.preventDefault();
  264. if (!suggestions || suggestions.length === 0) {
  265. return undefined;
  266. }
  267. const suggestion = getSuggestionByIndex(suggestions, typeaheadIndex);
  268. const nextChange = this.applyTypeahead(change, suggestion);
  269. const insertTextOperation = nextChange.operations.find((operation: any) => operation.type === 'insert_text');
  270. if (insertTextOperation) {
  271. const suggestionText = insertTextOperation.text;
  272. this.placeholdersBuffer.setNextPlaceholderValue(suggestionText);
  273. if (this.placeholdersBuffer.hasPlaceholders()) {
  274. nextChange.move(this.placeholdersBuffer.getNextMoveOffset()).focus();
  275. }
  276. }
  277. return true;
  278. } else {
  279. this.executeOnQueryChangeAndExecuteQueries();
  280. return undefined;
  281. }
  282. };
  283. onKeyDown = (event: KeyboardEvent, change: Change) => {
  284. const { typeaheadIndex } = this.state;
  285. switch (event.key) {
  286. case 'Escape': {
  287. if (this.menuEl) {
  288. event.preventDefault();
  289. event.stopPropagation();
  290. this.resetTypeahead();
  291. return true;
  292. }
  293. break;
  294. }
  295. case ' ': {
  296. if (event.ctrlKey) {
  297. event.preventDefault();
  298. this.handleTypeahead();
  299. return true;
  300. }
  301. break;
  302. }
  303. case 'Enter':
  304. case 'Tab': {
  305. return this.handleEnterAndTabKey(event, change);
  306. break;
  307. }
  308. case 'ArrowDown': {
  309. if (this.menuEl) {
  310. // Select next suggestion
  311. event.preventDefault();
  312. const itemsCount =
  313. this.state.suggestions.length > 0
  314. ? this.state.suggestions.reduce((totalCount, current) => totalCount + current.items.length, 0)
  315. : 0;
  316. this.setState({ typeaheadIndex: Math.min(itemsCount - 1, typeaheadIndex + 1) });
  317. }
  318. break;
  319. }
  320. case 'ArrowUp': {
  321. if (this.menuEl) {
  322. // Select previous suggestion
  323. event.preventDefault();
  324. this.setState({ typeaheadIndex: Math.max(0, typeaheadIndex - 1) });
  325. }
  326. break;
  327. }
  328. default: {
  329. // console.log('default key', event.key, event.which, event.charCode, event.locale, data.key);
  330. break;
  331. }
  332. }
  333. return undefined;
  334. };
  335. resetTypeahead = () => {
  336. if (this.mounted) {
  337. this.setState({ suggestions: [], typeaheadIndex: 0, typeaheadPrefix: '', typeaheadContext: null });
  338. this.resetTimer = null;
  339. }
  340. };
  341. handleBlur = (event: FocusEvent, change: Change) => {
  342. const { lastExecutedValue } = this.state;
  343. const previousValue = lastExecutedValue ? Plain.serialize(this.state.lastExecutedValue) : null;
  344. const currentValue = Plain.serialize(change.value);
  345. // If we dont wait here, menu clicks wont work because the menu
  346. // will be gone.
  347. this.resetTimer = setTimeout(this.resetTypeahead, 100);
  348. // Disrupting placeholder entry wipes all remaining placeholders needing input
  349. this.placeholdersBuffer.clearPlaceholders();
  350. if (previousValue !== currentValue) {
  351. this.executeOnQueryChangeAndExecuteQueries();
  352. }
  353. };
  354. onClickMenu = (item: CompletionItem) => {
  355. // Manually triggering change
  356. const change = this.applyTypeahead(this.state.value.change(), item);
  357. this.onChange(change, true);
  358. };
  359. updateMenu = () => {
  360. const { suggestions } = this.state;
  361. const menu = this.menuEl;
  362. const selection = window.getSelection();
  363. const node = selection.anchorNode;
  364. // No menu, nothing to do
  365. if (!menu) {
  366. return;
  367. }
  368. // No suggestions or blur, remove menu
  369. if (!hasSuggestions(suggestions)) {
  370. menu.removeAttribute('style');
  371. return;
  372. }
  373. // Align menu overlay to editor node
  374. if (node) {
  375. // Read from DOM
  376. const rect = node.parentElement.getBoundingClientRect();
  377. const scrollX = window.scrollX;
  378. const scrollY = window.scrollY;
  379. // Write DOM
  380. requestAnimationFrame(() => {
  381. menu.style.opacity = '1';
  382. menu.style.top = `${rect.top + scrollY + rect.height + 4}px`;
  383. menu.style.left = `${rect.left + scrollX - 2}px`;
  384. });
  385. }
  386. };
  387. menuRef = (el: HTMLElement) => {
  388. this.menuEl = el;
  389. };
  390. renderMenu = () => {
  391. const { portalOrigin } = this.props;
  392. const { suggestions, typeaheadIndex, typeaheadPrefix } = this.state;
  393. if (!hasSuggestions(suggestions)) {
  394. return null;
  395. }
  396. const selectedItem = getSuggestionByIndex(suggestions, typeaheadIndex);
  397. // Create typeahead in DOM root so we can later position it absolutely
  398. return (
  399. <Portal origin={portalOrigin}>
  400. <TypeaheadWithTheme
  401. menuRef={this.menuRef}
  402. selectedItem={selectedItem}
  403. onClickItem={this.onClickMenu}
  404. prefix={typeaheadPrefix}
  405. groupedItems={suggestions}
  406. typeaheadIndex={typeaheadIndex}
  407. />
  408. </Portal>
  409. );
  410. };
  411. handlePaste = (event: ClipboardEvent, change: Editor) => {
  412. const pastedValue = event.clipboardData.getData('Text');
  413. const newValue = change.value.change().insertText(pastedValue);
  414. this.onChange(newValue);
  415. return true;
  416. };
  417. render() {
  418. const { disabled } = this.props;
  419. const wrapperClassName = classnames('slate-query-field__wrapper', {
  420. 'slate-query-field__wrapper--disabled': disabled,
  421. });
  422. return (
  423. <div className={wrapperClassName}>
  424. <div className="slate-query-field">
  425. {this.renderMenu()}
  426. <Editor
  427. autoCorrect={false}
  428. readOnly={this.props.disabled}
  429. onBlur={this.handleBlur}
  430. onKeyDown={this.onKeyDown}
  431. onChange={this.onChange}
  432. onPaste={this.handlePaste}
  433. placeholder={this.props.placeholder}
  434. plugins={this.plugins}
  435. spellCheck={false}
  436. value={this.state.value}
  437. />
  438. </div>
  439. </div>
  440. );
  441. }
  442. }
  443. interface PortalProps {
  444. index?: number;
  445. origin: string;
  446. }
  447. class Portal extends React.PureComponent<PortalProps, {}> {
  448. node: HTMLElement;
  449. constructor(props: PortalProps) {
  450. super(props);
  451. const { index = 0, origin = 'query' } = props;
  452. this.node = document.createElement('div');
  453. this.node.classList.add(`slate-typeahead`, `slate-typeahead-${origin}-${index}`);
  454. document.body.appendChild(this.node);
  455. }
  456. componentWillUnmount() {
  457. document.body.removeChild(this.node);
  458. }
  459. render() {
  460. return ReactDOM.createPortal(this.props.children, this.node);
  461. }
  462. }
  463. export default QueryField;