QueryField.tsx 14 KB

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