QueryField.tsx 14 KB

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