QueryField.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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. onRunQuery?: () => void;
  33. onChange?: (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.executeOnChangeAndRunQueries();
  131. }
  132. if (textChanged && !invokeParentOnValueChanged) {
  133. this.updateLogsHighlights();
  134. }
  135. }
  136. });
  137. // Show suggest menu on text input
  138. if (documentChanged && value.selection.isCollapsed) {
  139. // Need one paint to allow DOM-based typeahead rules to work
  140. window.requestAnimationFrame(this.handleTypeahead);
  141. } else if (!this.resetTimer) {
  142. this.resetTypeahead();
  143. }
  144. };
  145. updateLogsHighlights = () => {
  146. const { onChange } = this.props;
  147. if (onChange) {
  148. onChange(Plain.serialize(this.state.value));
  149. }
  150. };
  151. executeOnChangeAndRunQueries = () => {
  152. // Send text change to parent
  153. const { onChange, onRunQuery } = this.props;
  154. if (onChange) {
  155. onChange(Plain.serialize(this.state.value));
  156. }
  157. if (onRunQuery) {
  158. onRunQuery();
  159. this.setState({ lastExecutedValue: this.state.value });
  160. }
  161. };
  162. handleTypeahead = _.debounce(async () => {
  163. const selection = window.getSelection();
  164. const { cleanText, onTypeahead } = this.props;
  165. const { value } = this.state;
  166. if (onTypeahead && selection.anchorNode) {
  167. const wrapperNode = selection.anchorNode.parentElement;
  168. const editorNode = wrapperNode.closest('.slate-query-field');
  169. if (!editorNode || this.state.value.isBlurred) {
  170. // Not inside this editor
  171. return;
  172. }
  173. const range = selection.getRangeAt(0);
  174. const offset = range.startOffset;
  175. const text = selection.anchorNode.textContent;
  176. let prefix = text.substr(0, offset);
  177. // Label values could have valid characters erased if `cleanText()` is
  178. // blindly applied, which would undesirably interfere with suggestions
  179. const labelValueMatch = prefix.match(/(?:!?=~?"?|")(.*)/);
  180. if (labelValueMatch) {
  181. prefix = labelValueMatch[1];
  182. } else if (cleanText) {
  183. prefix = cleanText(prefix);
  184. }
  185. const { suggestions, context, refresher } = onTypeahead({
  186. editorNode,
  187. prefix,
  188. selection,
  189. text,
  190. value,
  191. wrapperNode,
  192. });
  193. let filteredSuggestions = suggestions
  194. .map(group => {
  195. if (group.items) {
  196. if (prefix) {
  197. // Filter groups based on prefix
  198. if (!group.skipFilter) {
  199. group.items = group.items.filter(c => (c.filterText || c.label).length >= prefix.length);
  200. if (group.prefixMatch) {
  201. group.items = group.items.filter(c => (c.filterText || c.label).indexOf(prefix) === 0);
  202. } else {
  203. group.items = group.items.filter(c => (c.filterText || c.label).indexOf(prefix) > -1);
  204. }
  205. }
  206. // Filter out the already typed value (prefix) unless it inserts custom text
  207. group.items = group.items.filter(c => c.insertText || (c.filterText || c.label) !== prefix);
  208. }
  209. if (!group.skipSort) {
  210. group.items = _.sortBy(group.items, (item: CompletionItem) => item.sortText || item.label);
  211. }
  212. }
  213. return group;
  214. })
  215. .filter(group => group.items && group.items.length > 0); // Filter out empty groups
  216. // Keep same object for equality checking later
  217. if (_.isEqual(filteredSuggestions, this.state.suggestions)) {
  218. filteredSuggestions = this.state.suggestions;
  219. }
  220. this.setState(
  221. {
  222. suggestions: filteredSuggestions,
  223. typeaheadPrefix: prefix,
  224. typeaheadContext: context,
  225. typeaheadText: text,
  226. },
  227. () => {
  228. if (refresher) {
  229. refresher.then(this.handleTypeahead).catch(e => console.error(e));
  230. }
  231. }
  232. );
  233. }
  234. }, TYPEAHEAD_DEBOUNCE);
  235. applyTypeahead(change: Change, suggestion: CompletionItem): Change {
  236. const { cleanText, onWillApplySuggestion, syntax } = this.props;
  237. const { typeaheadPrefix, typeaheadText } = this.state;
  238. let suggestionText = suggestion.insertText || suggestion.label;
  239. const preserveSuffix = suggestion.kind === 'function';
  240. const move = suggestion.move || 0;
  241. if (onWillApplySuggestion) {
  242. suggestionText = onWillApplySuggestion(suggestionText, { ...this.state });
  243. }
  244. this.resetTypeahead();
  245. // Remove the current, incomplete text and replace it with the selected suggestion
  246. const backward = suggestion.deleteBackwards || typeaheadPrefix.length;
  247. const text = cleanText ? cleanText(typeaheadText) : typeaheadText;
  248. const suffixLength = text.length - typeaheadPrefix.length;
  249. const offset = typeaheadText.indexOf(typeaheadPrefix);
  250. const midWord = typeaheadPrefix && ((suffixLength > 0 && offset > -1) || suggestionText === typeaheadText);
  251. const forward = midWord && !preserveSuffix ? suffixLength + offset : 0;
  252. // If new-lines, apply suggestion as block
  253. if (suggestionText.match(/\n/)) {
  254. const fragment = makeFragment(suggestionText, syntax);
  255. return change
  256. .deleteBackward(backward)
  257. .deleteForward(forward)
  258. .insertFragment(fragment)
  259. .focus();
  260. }
  261. return change
  262. .deleteBackward(backward)
  263. .deleteForward(forward)
  264. .insertText(suggestionText)
  265. .move(move)
  266. .focus();
  267. }
  268. handleEnterAndTabKey = (event: KeyboardEvent, change: Change) => {
  269. const { typeaheadIndex, suggestions } = this.state;
  270. if (this.menuEl) {
  271. // Dont blur input
  272. event.preventDefault();
  273. if (!suggestions || suggestions.length === 0) {
  274. return undefined;
  275. }
  276. const suggestion = getSuggestionByIndex(suggestions, typeaheadIndex);
  277. const nextChange = this.applyTypeahead(change, suggestion);
  278. const insertTextOperation = nextChange.operations.find((operation: any) => operation.type === 'insert_text');
  279. if (insertTextOperation) {
  280. const suggestionText = insertTextOperation.text;
  281. this.placeholdersBuffer.setNextPlaceholderValue(suggestionText);
  282. if (this.placeholdersBuffer.hasPlaceholders()) {
  283. nextChange.move(this.placeholdersBuffer.getNextMoveOffset()).focus();
  284. }
  285. }
  286. return true;
  287. } else {
  288. this.executeOnChangeAndRunQueries();
  289. return undefined;
  290. }
  291. };
  292. onKeyDown = (event: KeyboardEvent, change: Change) => {
  293. const { typeaheadIndex } = this.state;
  294. switch (event.key) {
  295. case 'Escape': {
  296. if (this.menuEl) {
  297. event.preventDefault();
  298. event.stopPropagation();
  299. this.resetTypeahead();
  300. return true;
  301. }
  302. break;
  303. }
  304. case ' ': {
  305. if (event.ctrlKey) {
  306. event.preventDefault();
  307. this.handleTypeahead();
  308. return true;
  309. }
  310. break;
  311. }
  312. case 'Enter':
  313. case 'Tab': {
  314. return this.handleEnterAndTabKey(event, change);
  315. break;
  316. }
  317. case 'ArrowDown': {
  318. if (this.menuEl) {
  319. // Select next suggestion
  320. event.preventDefault();
  321. const itemsCount =
  322. this.state.suggestions.length > 0
  323. ? this.state.suggestions.reduce((totalCount, current) => totalCount + current.items.length, 0)
  324. : 0;
  325. this.setState({ typeaheadIndex: Math.min(itemsCount - 1, typeaheadIndex + 1) });
  326. }
  327. break;
  328. }
  329. case 'ArrowUp': {
  330. if (this.menuEl) {
  331. // Select previous suggestion
  332. event.preventDefault();
  333. this.setState({ typeaheadIndex: Math.max(0, typeaheadIndex - 1) });
  334. }
  335. break;
  336. }
  337. default: {
  338. // console.log('default key', event.key, event.which, event.charCode, event.locale, data.key);
  339. break;
  340. }
  341. }
  342. return undefined;
  343. };
  344. resetTypeahead = () => {
  345. if (this.mounted) {
  346. this.setState({ suggestions: [], typeaheadIndex: 0, typeaheadPrefix: '', typeaheadContext: null });
  347. this.resetTimer = null;
  348. }
  349. };
  350. handleBlur = (event: FocusEvent, change: Change) => {
  351. const { lastExecutedValue } = this.state;
  352. const previousValue = lastExecutedValue ? Plain.serialize(this.state.lastExecutedValue) : null;
  353. const currentValue = Plain.serialize(change.value);
  354. // If we dont wait here, menu clicks wont work because the menu
  355. // will be gone.
  356. this.resetTimer = setTimeout(this.resetTypeahead, 100);
  357. // Disrupting placeholder entry wipes all remaining placeholders needing input
  358. this.placeholdersBuffer.clearPlaceholders();
  359. if (previousValue !== currentValue) {
  360. this.executeOnChangeAndRunQueries();
  361. }
  362. };
  363. onClickMenu = (item: CompletionItem) => {
  364. // Manually triggering change
  365. const change = this.applyTypeahead(this.state.value.change(), item);
  366. this.onChange(change, true);
  367. };
  368. updateMenu = () => {
  369. const { suggestions } = this.state;
  370. const menu = this.menuEl;
  371. const selection = window.getSelection();
  372. const node = selection.anchorNode;
  373. // No menu, nothing to do
  374. if (!menu) {
  375. return;
  376. }
  377. // No suggestions or blur, remove menu
  378. if (!hasSuggestions(suggestions)) {
  379. menu.removeAttribute('style');
  380. return;
  381. }
  382. // Align menu overlay to editor node
  383. if (node) {
  384. // Read from DOM
  385. const rect = node.parentElement.getBoundingClientRect();
  386. const scrollX = window.scrollX;
  387. const scrollY = window.scrollY;
  388. // Write DOM
  389. requestAnimationFrame(() => {
  390. menu.style.opacity = '1';
  391. menu.style.top = `${rect.top + scrollY + rect.height + 4}px`;
  392. menu.style.left = `${rect.left + scrollX - 2}px`;
  393. });
  394. }
  395. };
  396. menuRef = (el: HTMLElement) => {
  397. this.menuEl = el;
  398. };
  399. renderMenu = () => {
  400. const { portalOrigin } = this.props;
  401. const { suggestions, typeaheadIndex, typeaheadPrefix } = this.state;
  402. if (!hasSuggestions(suggestions)) {
  403. return null;
  404. }
  405. const selectedItem = getSuggestionByIndex(suggestions, typeaheadIndex);
  406. // Create typeahead in DOM root so we can later position it absolutely
  407. return (
  408. <Portal origin={portalOrigin}>
  409. <TypeaheadWithTheme
  410. menuRef={this.menuRef}
  411. selectedItem={selectedItem}
  412. onClickItem={this.onClickMenu}
  413. prefix={typeaheadPrefix}
  414. groupedItems={suggestions}
  415. typeaheadIndex={typeaheadIndex}
  416. />
  417. </Portal>
  418. );
  419. };
  420. handlePaste = (event: ClipboardEvent, change: Editor) => {
  421. const pastedValue = event.clipboardData.getData('Text');
  422. const newValue = change.value.change().insertText(pastedValue);
  423. this.onChange(newValue);
  424. return true;
  425. };
  426. render() {
  427. const { disabled } = this.props;
  428. const wrapperClassName = classnames('slate-query-field__wrapper', {
  429. 'slate-query-field__wrapper--disabled': disabled,
  430. });
  431. return (
  432. <div className={wrapperClassName}>
  433. <div className="slate-query-field">
  434. {this.renderMenu()}
  435. <Editor
  436. autoCorrect={false}
  437. readOnly={this.props.disabled}
  438. onBlur={this.handleBlur}
  439. onKeyDown={this.onKeyDown}
  440. onChange={this.onChange}
  441. onPaste={this.handlePaste}
  442. placeholder={this.props.placeholder}
  443. plugins={this.plugins}
  444. spellCheck={false}
  445. value={this.state.value}
  446. />
  447. </div>
  448. </div>
  449. );
  450. }
  451. }
  452. interface PortalProps {
  453. index?: number;
  454. origin: string;
  455. }
  456. class Portal extends React.PureComponent<PortalProps, {}> {
  457. node: HTMLElement;
  458. constructor(props: PortalProps) {
  459. super(props);
  460. const { index = 0, origin = 'query' } = props;
  461. this.node = document.createElement('div');
  462. this.node.classList.add(`slate-typeahead`, `slate-typeahead-${origin}-${index}`);
  463. document.body.appendChild(this.node);
  464. }
  465. componentWillUnmount() {
  466. document.body.removeChild(this.node);
  467. }
  468. render() {
  469. return ReactDOM.createPortal(this.props.children, this.node);
  470. }
  471. }
  472. export default QueryField;