QueryField.tsx 14 KB

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