QueryField.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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. if (cleanText) {
  206. prefix = cleanText(prefix);
  207. }
  208. const { suggestions, context, refresher } = onTypeahead({
  209. editorNode,
  210. prefix,
  211. selection,
  212. text,
  213. value,
  214. wrapperNode,
  215. });
  216. let filteredSuggestions = suggestions
  217. .map(group => {
  218. if (group.items) {
  219. if (prefix) {
  220. // Filter groups based on prefix
  221. if (!group.skipFilter) {
  222. group.items = group.items.filter(c => (c.filterText || c.label).length >= prefix.length);
  223. if (group.prefixMatch) {
  224. group.items = group.items.filter(c => (c.filterText || c.label).indexOf(prefix) === 0);
  225. } else {
  226. group.items = group.items.filter(c => (c.filterText || c.label).indexOf(prefix) > -1);
  227. }
  228. }
  229. // Filter out the already typed value (prefix) unless it inserts custom text
  230. group.items = group.items.filter(c => c.insertText || (c.filterText || c.label) !== prefix);
  231. }
  232. if (!group.skipSort) {
  233. group.items = _.sortBy(group.items, item => item.sortText || item.label);
  234. }
  235. }
  236. return group;
  237. })
  238. .filter(group => group.items && group.items.length > 0); // Filter out empty groups
  239. // Keep same object for equality checking later
  240. if (_.isEqual(filteredSuggestions, this.state.suggestions)) {
  241. filteredSuggestions = this.state.suggestions;
  242. }
  243. this.setState(
  244. {
  245. suggestions: filteredSuggestions,
  246. typeaheadPrefix: prefix,
  247. typeaheadContext: context,
  248. typeaheadText: text,
  249. },
  250. () => {
  251. if (refresher) {
  252. refresher.then(this.handleTypeahead).catch(e => console.error(e));
  253. }
  254. }
  255. );
  256. }
  257. }, TYPEAHEAD_DEBOUNCE);
  258. applyTypeahead(change: Change, suggestion: Suggestion): Change {
  259. const { cleanText, onWillApplySuggestion, syntax } = this.props;
  260. const { typeaheadPrefix, typeaheadText } = this.state;
  261. let suggestionText = suggestion.insertText || suggestion.label;
  262. const move = suggestion.move || 0;
  263. if (onWillApplySuggestion) {
  264. suggestionText = onWillApplySuggestion(suggestionText, { ...this.state });
  265. }
  266. this.resetTypeahead();
  267. // Remove the current, incomplete text and replace it with the selected suggestion
  268. const backward = suggestion.deleteBackwards || typeaheadPrefix.length;
  269. const text = cleanText ? cleanText(typeaheadText) : typeaheadText;
  270. const suffixLength = text.length - typeaheadPrefix.length;
  271. const offset = typeaheadText.indexOf(typeaheadPrefix);
  272. const midWord = typeaheadPrefix && ((suffixLength > 0 && offset > -1) || suggestionText === typeaheadText);
  273. const forward = midWord ? suffixLength + offset : 0;
  274. // If new-lines, apply suggestion as block
  275. if (suggestionText.match(/\n/)) {
  276. const fragment = makeFragment(suggestionText, syntax);
  277. return change
  278. .deleteBackward(backward)
  279. .deleteForward(forward)
  280. .insertFragment(fragment)
  281. .focus();
  282. }
  283. return change
  284. .deleteBackward(backward)
  285. .deleteForward(forward)
  286. .insertText(suggestionText)
  287. .move(move)
  288. .focus();
  289. }
  290. onKeyDown = (event, change) => {
  291. const { typeaheadIndex, suggestions } = this.state;
  292. switch (event.key) {
  293. case 'Escape': {
  294. if (this.menuEl) {
  295. event.preventDefault();
  296. event.stopPropagation();
  297. this.resetTypeahead();
  298. return true;
  299. }
  300. break;
  301. }
  302. case ' ': {
  303. if (event.ctrlKey) {
  304. event.preventDefault();
  305. this.handleTypeahead();
  306. return true;
  307. }
  308. break;
  309. }
  310. case 'Enter':
  311. case 'Tab': {
  312. if (this.menuEl) {
  313. // Dont blur input
  314. event.preventDefault();
  315. if (!suggestions || suggestions.length === 0) {
  316. return undefined;
  317. }
  318. const suggestion = getSuggestionByIndex(suggestions, typeaheadIndex);
  319. this.applyTypeahead(change, suggestion);
  320. return true;
  321. }
  322. break;
  323. }
  324. case 'ArrowDown': {
  325. if (this.menuEl) {
  326. // Select next suggestion
  327. event.preventDefault();
  328. this.setState({ typeaheadIndex: typeaheadIndex + 1 });
  329. }
  330. break;
  331. }
  332. case 'ArrowUp': {
  333. if (this.menuEl) {
  334. // Select previous suggestion
  335. event.preventDefault();
  336. this.setState({ typeaheadIndex: Math.max(0, typeaheadIndex - 1) });
  337. }
  338. break;
  339. }
  340. default: {
  341. // console.log('default key', event.key, event.which, event.charCode, event.locale, data.key);
  342. break;
  343. }
  344. }
  345. return undefined;
  346. };
  347. resetTypeahead = () => {
  348. this.setState({
  349. suggestions: [],
  350. typeaheadIndex: 0,
  351. typeaheadPrefix: '',
  352. typeaheadContext: null,
  353. });
  354. };
  355. handleBlur = () => {
  356. const { onBlur } = this.props;
  357. // If we dont wait here, menu clicks wont work because the menu
  358. // will be gone.
  359. this.resetTimer = setTimeout(this.resetTypeahead, 100);
  360. if (onBlur) {
  361. onBlur();
  362. }
  363. };
  364. handleFocus = () => {
  365. const { onFocus } = this.props;
  366. if (onFocus) {
  367. onFocus();
  368. }
  369. };
  370. onClickMenu = (item: Suggestion) => {
  371. // Manually triggering change
  372. const change = this.applyTypeahead(this.state.value.change(), item);
  373. this.onChange(change);
  374. };
  375. updateMenu = () => {
  376. const { suggestions } = this.state;
  377. const menu = this.menuEl;
  378. const selection = window.getSelection();
  379. const node = selection.anchorNode;
  380. // No menu, nothing to do
  381. if (!menu) {
  382. return;
  383. }
  384. // No suggestions or blur, remove menu
  385. if (!hasSuggestions(suggestions)) {
  386. menu.removeAttribute('style');
  387. return;
  388. }
  389. // Align menu overlay to editor node
  390. if (node) {
  391. // Read from DOM
  392. const rect = node.parentElement.getBoundingClientRect();
  393. const scrollX = window.scrollX;
  394. const scrollY = window.scrollY;
  395. // Write DOM
  396. requestAnimationFrame(() => {
  397. menu.style.opacity = '1';
  398. menu.style.top = `${rect.top + scrollY + rect.height + 4}px`;
  399. menu.style.left = `${rect.left + scrollX - 2}px`;
  400. });
  401. }
  402. };
  403. menuRef = el => {
  404. this.menuEl = el;
  405. };
  406. renderMenu = () => {
  407. const { portalOrigin } = this.props;
  408. const { suggestions, typeaheadIndex, typeaheadPrefix } = this.state;
  409. if (!hasSuggestions(suggestions)) {
  410. return null;
  411. }
  412. const selectedItem = getSuggestionByIndex(suggestions, typeaheadIndex);
  413. // Create typeahead in DOM root so we can later position it absolutely
  414. return (
  415. <Portal origin={portalOrigin}>
  416. <Typeahead
  417. menuRef={this.menuRef}
  418. selectedItem={selectedItem}
  419. onClickItem={this.onClickMenu}
  420. prefix={typeaheadPrefix}
  421. groupedItems={suggestions}
  422. />
  423. </Portal>
  424. );
  425. };
  426. render() {
  427. return (
  428. <div className="slate-query-field">
  429. {this.renderMenu()}
  430. <Editor
  431. autoCorrect={false}
  432. onBlur={this.handleBlur}
  433. onKeyDown={this.onKeyDown}
  434. onChange={this.onChange}
  435. onFocus={this.handleFocus}
  436. placeholder={this.props.placeholder}
  437. plugins={this.plugins}
  438. spellCheck={false}
  439. value={this.state.value}
  440. />
  441. </div>
  442. );
  443. }
  444. }
  445. class Portal extends React.PureComponent<{ index?: number; origin: string }, {}> {
  446. node: HTMLElement;
  447. constructor(props) {
  448. super(props);
  449. const { index = 0, origin = 'query' } = props;
  450. this.node = document.createElement('div');
  451. this.node.classList.add(`slate-typeahead`, `slate-typeahead-${origin}-${index}`);
  452. document.body.appendChild(this.node);
  453. }
  454. componentWillUnmount() {
  455. document.body.removeChild(this.node);
  456. }
  457. render() {
  458. return ReactDOM.createPortal(this.props.children, this.node);
  459. }
  460. }
  461. export default QueryField;