QueryField.tsx 14 KB

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