QueryField.tsx 15 KB

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