QueryField.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  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 BracesPlugin from './slate-plugins/braces';
  8. import ClearPlugin from './slate-plugins/clear';
  9. import NewlinePlugin from './slate-plugins/newline';
  10. import Typeahead from './Typeahead';
  11. export const TYPEAHEAD_DEBOUNCE = 300;
  12. function flattenSuggestions(s: any[]): any[] {
  13. return s ? s.reduce((acc, g) => acc.concat(g.items), []) : [];
  14. }
  15. export const makeFragment = (text: string): Document => {
  16. const lines = text.split('\n').map(line =>
  17. Block.create({
  18. type: 'paragraph',
  19. nodes: [Text.create(line)],
  20. })
  21. );
  22. const fragment = Document.create({
  23. nodes: lines,
  24. });
  25. return fragment;
  26. };
  27. export const getInitialValue = (value: string): Value => Value.create({ document: makeFragment(value) });
  28. export interface Suggestion {
  29. /**
  30. * The label of this completion item. By default
  31. * this is also the text that is inserted when selecting
  32. * this completion.
  33. */
  34. label: string;
  35. /**
  36. * The kind of this completion item. Based on the kind
  37. * an icon is chosen by the editor.
  38. */
  39. kind?: string;
  40. /**
  41. * A human-readable string with additional information
  42. * about this item, like type or symbol information.
  43. */
  44. detail?: string;
  45. /**
  46. * A human-readable string, can be Markdown, that represents a doc-comment.
  47. */
  48. documentation?: string;
  49. /**
  50. * A string that should be used when comparing this item
  51. * with other items. When `falsy` the `label` is used.
  52. */
  53. sortText?: string;
  54. /**
  55. * A string that should be used when filtering a set of
  56. * completion items. When `falsy` the `label` is used.
  57. */
  58. filterText?: string;
  59. /**
  60. * A string or snippet that should be inserted in a document when selecting
  61. * this completion. When `falsy` the `label` is used.
  62. */
  63. insertText?: string;
  64. /**
  65. * Delete number of characters before the caret position,
  66. * by default the letters from the beginning of the word.
  67. */
  68. deleteBackwards?: number;
  69. /**
  70. * Number of steps to move after the insertion, can be negative.
  71. */
  72. move?: number;
  73. }
  74. export interface SuggestionGroup {
  75. /**
  76. * Label that will be displayed for all entries of this group.
  77. */
  78. label: string;
  79. /**
  80. * List of suggestions of this group.
  81. */
  82. items: Suggestion[];
  83. /**
  84. * If true, match only by prefix (and not mid-word).
  85. */
  86. prefixMatch?: boolean;
  87. /**
  88. * If true, do not filter items in this group based on the search.
  89. */
  90. skipFilter?: boolean;
  91. /**
  92. * If true, do not sort items.
  93. */
  94. skipSort?: boolean;
  95. }
  96. interface TypeaheadFieldProps {
  97. additionalPlugins?: any[];
  98. cleanText?: (text: string) => string;
  99. initialValue: string | null;
  100. onBlur?: () => void;
  101. onFocus?: () => void;
  102. onTypeahead?: (typeahead: TypeaheadInput) => TypeaheadOutput;
  103. onValueChanged?: (value: Value) => void;
  104. onWillApplySuggestion?: (suggestion: string, state: TypeaheadFieldState) => string;
  105. placeholder?: string;
  106. portalPrefix?: string;
  107. }
  108. export interface TypeaheadFieldState {
  109. suggestions: SuggestionGroup[];
  110. typeaheadContext: string | null;
  111. typeaheadIndex: number;
  112. typeaheadPrefix: string;
  113. typeaheadText: string;
  114. value: Value;
  115. }
  116. export interface TypeaheadInput {
  117. editorNode: Element;
  118. prefix: string;
  119. selection?: Selection;
  120. text: string;
  121. value: Value;
  122. wrapperNode: Element;
  123. }
  124. export interface TypeaheadOutput {
  125. context?: string;
  126. refresher?: Promise<{}>;
  127. suggestions: SuggestionGroup[];
  128. }
  129. class QueryField extends React.Component<TypeaheadFieldProps, TypeaheadFieldState> {
  130. menuEl: HTMLElement | null;
  131. plugins: any[];
  132. resetTimer: any;
  133. constructor(props, context) {
  134. super(props, context);
  135. // Base plugins
  136. this.plugins = [BracesPlugin(), ClearPlugin(), NewlinePlugin(), ...props.additionalPlugins];
  137. this.state = {
  138. suggestions: [],
  139. typeaheadContext: null,
  140. typeaheadIndex: 0,
  141. typeaheadPrefix: '',
  142. typeaheadText: '',
  143. value: getInitialValue(props.initialValue || ''),
  144. };
  145. }
  146. componentDidMount() {
  147. this.updateMenu();
  148. }
  149. componentWillUnmount() {
  150. clearTimeout(this.resetTimer);
  151. }
  152. componentDidUpdate() {
  153. this.updateMenu();
  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: getInitialValue(nextProps.initialValue) });
  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. const 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. this.setState(
  229. {
  230. suggestions: filteredSuggestions,
  231. typeaheadPrefix: prefix,
  232. typeaheadContext: context,
  233. typeaheadText: text,
  234. },
  235. () => {
  236. if (refresher) {
  237. refresher.then(this.handleTypeahead).catch(e => console.error(e));
  238. }
  239. }
  240. );
  241. }
  242. }, TYPEAHEAD_DEBOUNCE);
  243. applyTypeahead(change: Change, suggestion: Suggestion): Change {
  244. const { cleanText, onWillApplySuggestion } = this.props;
  245. const { typeaheadPrefix, typeaheadText } = this.state;
  246. let suggestionText = suggestion.insertText || suggestion.label;
  247. const move = suggestion.move || 0;
  248. if (onWillApplySuggestion) {
  249. suggestionText = onWillApplySuggestion(suggestionText, { ...this.state });
  250. }
  251. this.resetTypeahead();
  252. // Remove the current, incomplete text and replace it with the selected suggestion
  253. const backward = suggestion.deleteBackwards || typeaheadPrefix.length;
  254. const text = cleanText ? cleanText(typeaheadText) : typeaheadText;
  255. const suffixLength = text.length - typeaheadPrefix.length;
  256. const offset = typeaheadText.indexOf(typeaheadPrefix);
  257. const midWord = typeaheadPrefix && ((suffixLength > 0 && offset > -1) || suggestionText === typeaheadText);
  258. const forward = midWord ? suffixLength + offset : 0;
  259. // If new-lines, apply suggestion as block
  260. if (suggestionText.match(/\n/)) {
  261. const fragment = makeFragment(suggestionText);
  262. return change
  263. .deleteBackward(backward)
  264. .deleteForward(forward)
  265. .insertFragment(fragment)
  266. .focus();
  267. }
  268. return change
  269. .deleteBackward(backward)
  270. .deleteForward(forward)
  271. .insertText(suggestionText)
  272. .move(move)
  273. .focus();
  274. }
  275. onKeyDown = (event, change) => {
  276. const { typeaheadIndex, suggestions } = this.state;
  277. switch (event.key) {
  278. case 'Escape': {
  279. if (this.menuEl) {
  280. event.preventDefault();
  281. event.stopPropagation();
  282. this.resetTypeahead();
  283. return true;
  284. }
  285. break;
  286. }
  287. case ' ': {
  288. if (event.ctrlKey) {
  289. event.preventDefault();
  290. this.handleTypeahead();
  291. return true;
  292. }
  293. break;
  294. }
  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;