QueryField.tsx 15 KB

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