QueryField.tsx 16 KB

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