QueryField.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. import _ from 'lodash';
  2. import React, { Context } from 'react';
  3. import ReactDOM from 'react-dom';
  4. // @ts-ignore
  5. import { Change, Value } from 'slate';
  6. // @ts-ignore
  7. import { Editor } from 'slate-react';
  8. // @ts-ignore
  9. import Plain from 'slate-plain-serializer';
  10. import classnames from 'classnames';
  11. import { CompletionItem, CompletionItemGroup, TypeaheadOutput } from 'app/types/explore';
  12. import ClearPlugin from './slate-plugins/clear';
  13. import NewlinePlugin from './slate-plugins/newline';
  14. import { TypeaheadWithTheme } from './Typeahead';
  15. import { makeFragment, makeValue } from '@grafana/ui';
  16. export const TYPEAHEAD_DEBOUNCE = 100;
  17. export const HIGHLIGHT_WAIT = 500;
  18. function getSuggestionByIndex(suggestions: CompletionItemGroup[], index: number): CompletionItem {
  19. // Flatten suggestion groups
  20. const flattenedSuggestions = suggestions.reduce((acc, g) => acc.concat(g.items), []);
  21. const correctedIndex = Math.max(index, 0) % flattenedSuggestions.length;
  22. return flattenedSuggestions[correctedIndex];
  23. }
  24. function hasSuggestions(suggestions: CompletionItemGroup[]): boolean {
  25. return suggestions && suggestions.length > 0;
  26. }
  27. export interface QueryFieldProps {
  28. additionalPlugins?: any[];
  29. cleanText?: (text: string) => string;
  30. disabled?: boolean;
  31. initialQuery: string | null;
  32. onRunQuery?: () => void;
  33. onChange?: (value: string) => void;
  34. onTypeahead?: (typeahead: TypeaheadInput) => TypeaheadOutput;
  35. onWillApplySuggestion?: (suggestion: string, state: QueryFieldState) => string;
  36. placeholder?: string;
  37. portalOrigin?: string;
  38. syntax?: string;
  39. syntaxLoaded?: boolean;
  40. }
  41. export interface QueryFieldState {
  42. suggestions: CompletionItemGroup[];
  43. typeaheadContext: string | null;
  44. typeaheadIndex: number;
  45. typeaheadPrefix: string;
  46. typeaheadText: string;
  47. value: any;
  48. lastExecutedValue: Value;
  49. }
  50. export interface TypeaheadInput {
  51. editorNode: Element;
  52. prefix: string;
  53. selection?: Selection;
  54. text: string;
  55. value: Value;
  56. wrapperNode: Element;
  57. }
  58. /**
  59. * Renders an editor field.
  60. * Pass initial value as initialQuery and listen to changes in props.onValueChanged.
  61. * This component can only process strings. Internally it uses Slate Value.
  62. * Implement props.onTypeahead to use suggestions, see PromQueryField.tsx as an example.
  63. */
  64. export class QueryField extends React.PureComponent<QueryFieldProps, QueryFieldState> {
  65. menuEl: HTMLElement | null;
  66. plugins: any[];
  67. resetTimer: any;
  68. mounted: boolean;
  69. updateHighlightsTimer: any;
  70. constructor(props: QueryFieldProps, context: Context<any>) {
  71. super(props, context);
  72. this.updateHighlightsTimer = _.debounce(this.updateLogsHighlights, HIGHLIGHT_WAIT);
  73. // Base plugins
  74. this.plugins = [ClearPlugin(), NewlinePlugin(), ...(props.additionalPlugins || [])].filter(p => p);
  75. this.state = {
  76. suggestions: [],
  77. typeaheadContext: null,
  78. typeaheadIndex: 0,
  79. typeaheadPrefix: '',
  80. typeaheadText: '',
  81. value: makeValue(props.initialQuery || '', props.syntax),
  82. lastExecutedValue: null,
  83. };
  84. }
  85. componentDidMount() {
  86. this.mounted = true;
  87. this.updateMenu();
  88. }
  89. componentWillUnmount() {
  90. this.mounted = false;
  91. clearTimeout(this.resetTimer);
  92. }
  93. componentDidUpdate(prevProps: QueryFieldProps, prevState: QueryFieldState) {
  94. const { initialQuery, syntax } = this.props;
  95. const { value, suggestions } = this.state;
  96. // if query changed from the outside
  97. if (initialQuery !== prevProps.initialQuery) {
  98. // and we have a version that differs
  99. if (initialQuery !== Plain.serialize(value)) {
  100. this.setState({ value: makeValue(initialQuery, syntax) });
  101. }
  102. }
  103. // Only update menu location when suggestion existence or text/selection changed
  104. if (value !== prevState.value || hasSuggestions(suggestions) !== hasSuggestions(prevState.suggestions)) {
  105. this.updateMenu();
  106. }
  107. }
  108. UNSAFE_componentWillReceiveProps(nextProps: QueryFieldProps) {
  109. if (nextProps.syntaxLoaded && !this.props.syntaxLoaded) {
  110. // Need a bogus edit to re-render the editor after syntax has fully loaded
  111. const change = this.state.value
  112. .change()
  113. .insertText(' ')
  114. .deleteBackward();
  115. this.onChange(change, true);
  116. }
  117. }
  118. onChange = ({ value }: Change, invokeParentOnValueChanged?: boolean) => {
  119. const documentChanged = value.document !== this.state.value.document;
  120. const prevValue = this.state.value;
  121. // Control editor loop, then pass text change up to parent
  122. this.setState({ value }, () => {
  123. if (documentChanged) {
  124. const textChanged = Plain.serialize(prevValue) !== Plain.serialize(value);
  125. if (textChanged && invokeParentOnValueChanged) {
  126. this.executeOnChangeAndRunQueries();
  127. }
  128. if (textChanged && !invokeParentOnValueChanged) {
  129. this.updateHighlightsTimer();
  130. }
  131. }
  132. });
  133. // Show suggest menu on text input
  134. if (documentChanged && value.selection.isCollapsed) {
  135. // Need one paint to allow DOM-based typeahead rules to work
  136. window.requestAnimationFrame(this.handleTypeahead);
  137. } else if (!this.resetTimer) {
  138. this.resetTypeahead();
  139. }
  140. };
  141. updateLogsHighlights = () => {
  142. const { onChange } = this.props;
  143. if (onChange) {
  144. onChange(Plain.serialize(this.state.value));
  145. }
  146. };
  147. executeOnChangeAndRunQueries = () => {
  148. // Send text change to parent
  149. const { onChange, onRunQuery } = this.props;
  150. if (onChange) {
  151. onChange(Plain.serialize(this.state.value));
  152. }
  153. if (onRunQuery) {
  154. onRunQuery();
  155. this.setState({ lastExecutedValue: this.state.value });
  156. }
  157. };
  158. handleTypeahead = _.debounce(async () => {
  159. const selection = window.getSelection();
  160. const { cleanText, onTypeahead } = this.props;
  161. const { value } = this.state;
  162. if (onTypeahead && selection.anchorNode) {
  163. const wrapperNode = selection.anchorNode.parentElement;
  164. const editorNode = wrapperNode.closest('.slate-query-field');
  165. if (!editorNode || this.state.value.isBlurred) {
  166. // Not inside this editor
  167. return;
  168. }
  169. const range = selection.getRangeAt(0);
  170. const offset = range.startOffset;
  171. const text = selection.anchorNode.textContent;
  172. let prefix = text.substr(0, offset);
  173. // Label values could have valid characters erased if `cleanText()` is
  174. // blindly applied, which would undesirably interfere with suggestions
  175. const labelValueMatch = prefix.match(/(?:!?=~?"?|")(.*)/);
  176. if (labelValueMatch) {
  177. prefix = labelValueMatch[1];
  178. } else if (cleanText) {
  179. prefix = cleanText(prefix);
  180. }
  181. const { suggestions, context, refresher } = onTypeahead({
  182. editorNode,
  183. prefix,
  184. selection,
  185. text,
  186. value,
  187. wrapperNode,
  188. });
  189. let filteredSuggestions = suggestions
  190. .map(group => {
  191. if (group.items) {
  192. if (prefix) {
  193. // Filter groups based on prefix
  194. if (!group.skipFilter) {
  195. group.items = group.items.filter(c => (c.filterText || c.label).length >= prefix.length);
  196. if (group.prefixMatch) {
  197. group.items = group.items.filter(c => (c.filterText || c.label).indexOf(prefix) === 0);
  198. } else {
  199. group.items = group.items.filter(c => (c.filterText || c.label).indexOf(prefix) > -1);
  200. }
  201. }
  202. // Filter out the already typed value (prefix) unless it inserts custom text
  203. group.items = group.items.filter(c => c.insertText || (c.filterText || c.label) !== prefix);
  204. }
  205. if (!group.skipSort) {
  206. group.items = _.sortBy(group.items, (item: CompletionItem) => item.sortText || item.label);
  207. }
  208. }
  209. return group;
  210. })
  211. .filter(group => group.items && group.items.length > 0); // Filter out empty groups
  212. // Keep same object for equality checking later
  213. if (_.isEqual(filteredSuggestions, this.state.suggestions)) {
  214. filteredSuggestions = this.state.suggestions;
  215. }
  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: CompletionItem): Change {
  232. const { cleanText, onWillApplySuggestion, syntax } = this.props;
  233. const { typeaheadPrefix, typeaheadText } = this.state;
  234. let suggestionText = suggestion.insertText || suggestion.label;
  235. const preserveSuffix = suggestion.kind === 'function';
  236. const move = suggestion.move || 0;
  237. if (onWillApplySuggestion) {
  238. suggestionText = onWillApplySuggestion(suggestionText, { ...this.state });
  239. }
  240. this.resetTypeahead();
  241. // Remove the current, incomplete text and replace it with the selected suggestion
  242. const backward = suggestion.deleteBackwards || typeaheadPrefix.length;
  243. const text = cleanText ? cleanText(typeaheadText) : typeaheadText;
  244. const suffixLength = text.length - typeaheadPrefix.length;
  245. const offset = typeaheadText.indexOf(typeaheadPrefix);
  246. const midWord = typeaheadPrefix && ((suffixLength > 0 && offset > -1) || suggestionText === typeaheadText);
  247. const forward = midWord && !preserveSuffix ? suffixLength + offset : 0;
  248. // If new-lines, apply suggestion as block
  249. if (suggestionText.match(/\n/)) {
  250. const fragment = makeFragment(suggestionText, syntax);
  251. return change
  252. .deleteBackward(backward)
  253. .deleteForward(forward)
  254. .insertFragment(fragment)
  255. .focus();
  256. }
  257. return change
  258. .deleteBackward(backward)
  259. .deleteForward(forward)
  260. .insertText(suggestionText)
  261. .move(move)
  262. .focus();
  263. }
  264. handleEnterAndTabKey = (event: KeyboardEvent, change: Change) => {
  265. const { typeaheadIndex, suggestions } = this.state;
  266. if (this.menuEl) {
  267. // Dont blur input
  268. event.preventDefault();
  269. if (!suggestions || suggestions.length === 0) {
  270. return undefined;
  271. }
  272. const suggestion = getSuggestionByIndex(suggestions, typeaheadIndex);
  273. const nextChange = this.applyTypeahead(change, suggestion);
  274. const insertTextOperation = nextChange.operations.find((operation: any) => operation.type === 'insert_text');
  275. if (insertTextOperation) {
  276. return undefined;
  277. }
  278. return true;
  279. } else if (!event.shiftKey) {
  280. // Run queries if Shift is not pressed, otherwise pass through
  281. this.executeOnChangeAndRunQueries();
  282. return true;
  283. }
  284. return undefined;
  285. };
  286. onKeyDown = (event: KeyboardEvent, change: Change) => {
  287. const { typeaheadIndex } = this.state;
  288. switch (event.key) {
  289. case 'Escape': {
  290. if (this.menuEl) {
  291. event.preventDefault();
  292. event.stopPropagation();
  293. this.resetTypeahead();
  294. return true;
  295. }
  296. break;
  297. }
  298. case ' ': {
  299. if (event.ctrlKey) {
  300. event.preventDefault();
  301. this.handleTypeahead();
  302. return true;
  303. }
  304. break;
  305. }
  306. case 'Enter':
  307. case 'Tab': {
  308. return this.handleEnterAndTabKey(event, change);
  309. break;
  310. }
  311. case 'ArrowDown': {
  312. if (this.menuEl) {
  313. // Select next suggestion
  314. event.preventDefault();
  315. const itemsCount =
  316. this.state.suggestions.length > 0
  317. ? this.state.suggestions.reduce((totalCount, current) => totalCount + current.items.length, 0)
  318. : 0;
  319. this.setState({ typeaheadIndex: Math.min(itemsCount - 1, typeaheadIndex + 1) });
  320. }
  321. break;
  322. }
  323. case 'ArrowUp': {
  324. if (this.menuEl) {
  325. // Select previous suggestion
  326. event.preventDefault();
  327. this.setState({ typeaheadIndex: Math.max(0, typeaheadIndex - 1) });
  328. }
  329. break;
  330. }
  331. default: {
  332. // console.log('default key', event.key, event.which, event.charCode, event.locale, data.key);
  333. break;
  334. }
  335. }
  336. return undefined;
  337. };
  338. resetTypeahead = () => {
  339. if (this.mounted) {
  340. this.setState({ suggestions: [], typeaheadIndex: 0, typeaheadPrefix: '', typeaheadContext: null });
  341. this.resetTimer = null;
  342. }
  343. };
  344. handleBlur = (event: FocusEvent, change: Change) => {
  345. const { lastExecutedValue } = this.state;
  346. const previousValue = lastExecutedValue ? Plain.serialize(this.state.lastExecutedValue) : null;
  347. const currentValue = Plain.serialize(change.value);
  348. // If we dont wait here, menu clicks wont work because the menu
  349. // will be gone.
  350. this.resetTimer = setTimeout(this.resetTypeahead, 100);
  351. if (previousValue !== currentValue) {
  352. this.executeOnChangeAndRunQueries();
  353. }
  354. };
  355. onClickMenu = (item: CompletionItem) => {
  356. // Manually triggering change
  357. const change = this.applyTypeahead(this.state.value.change(), item);
  358. this.onChange(change, true);
  359. };
  360. updateMenu = () => {
  361. const { suggestions } = this.state;
  362. const menu = this.menuEl;
  363. // Exit for unit tests
  364. if (!window.getSelection) {
  365. return;
  366. }
  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: HTMLElement) => {
  393. this.menuEl = el;
  394. };
  395. renderMenu = () => {
  396. const { portalOrigin } = this.props;
  397. const { suggestions, typeaheadIndex, typeaheadPrefix } = 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 origin={portalOrigin}>
  405. <TypeaheadWithTheme
  406. menuRef={this.menuRef}
  407. selectedItem={selectedItem}
  408. onClickItem={this.onClickMenu}
  409. prefix={typeaheadPrefix}
  410. groupedItems={suggestions}
  411. typeaheadIndex={typeaheadIndex}
  412. />
  413. </Portal>
  414. );
  415. };
  416. handlePaste = (event: ClipboardEvent, change: Editor) => {
  417. const pastedValue = event.clipboardData.getData('Text');
  418. const newValue = change.value.change().insertText(pastedValue);
  419. this.onChange(newValue);
  420. return true;
  421. };
  422. render() {
  423. const { disabled } = this.props;
  424. const wrapperClassName = classnames('slate-query-field__wrapper', {
  425. 'slate-query-field__wrapper--disabled': disabled,
  426. });
  427. return (
  428. <div className={wrapperClassName}>
  429. <div className="slate-query-field">
  430. {this.renderMenu()}
  431. <Editor
  432. autoCorrect={false}
  433. readOnly={this.props.disabled}
  434. onBlur={this.handleBlur}
  435. onKeyDown={this.onKeyDown}
  436. onChange={this.onChange}
  437. onPaste={this.handlePaste}
  438. placeholder={this.props.placeholder}
  439. plugins={this.plugins}
  440. spellCheck={false}
  441. value={this.state.value}
  442. />
  443. </div>
  444. </div>
  445. );
  446. }
  447. }
  448. interface PortalProps {
  449. index?: number;
  450. origin: string;
  451. }
  452. class Portal extends React.PureComponent<PortalProps, {}> {
  453. node: HTMLElement;
  454. constructor(props: PortalProps) {
  455. super(props);
  456. const { index = 0, origin = 'query' } = props;
  457. this.node = document.createElement('div');
  458. this.node.classList.add(`slate-typeahead`, `slate-typeahead-${origin}-${index}`);
  459. document.body.appendChild(this.node);
  460. }
  461. componentWillUnmount() {
  462. document.body.removeChild(this.node);
  463. }
  464. render() {
  465. return ReactDOM.createPortal(this.props.children, this.node);
  466. }
  467. }
  468. export default QueryField;