QueryField.tsx 17 KB

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