QueryField.tsx 14 KB

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