QueryField.tsx 14 KB

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