QueryField.tsx 15 KB

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