QueryField.tsx 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. import _ from 'lodash';
  2. import React, { Context } from 'react';
  3. import { Value, Editor as CoreEditor } from 'slate';
  4. import { Editor, Plugin } from '@grafana/slate-react';
  5. import Plain from 'slate-plain-serializer';
  6. import classnames from 'classnames';
  7. import { CompletionItemGroup, TypeaheadOutput } from 'app/types/explore';
  8. import ClearPlugin from './slate-plugins/clear';
  9. import NewlinePlugin from './slate-plugins/newline';
  10. import SelectionShortcutsPlugin from './slate-plugins/selection_shortcuts';
  11. import IndentationPlugin from './slate-plugins/indentation';
  12. import ClipboardPlugin from './slate-plugins/clipboard';
  13. import RunnerPlugin from './slate-plugins/runner';
  14. import SuggestionsPlugin, { SuggestionsState } from './slate-plugins/suggestions';
  15. import { Typeahead } from './Typeahead';
  16. import { makeValue, SCHEMA } from '@grafana/ui';
  17. export const HIGHLIGHT_WAIT = 500;
  18. export interface QueryFieldProps {
  19. additionalPlugins?: Plugin[];
  20. cleanText?: (text: string) => string;
  21. disabled?: boolean;
  22. initialQuery: string | null;
  23. onRunQuery?: () => void;
  24. onChange?: (value: string) => void;
  25. onTypeahead?: (typeahead: TypeaheadInput) => Promise<TypeaheadOutput>;
  26. onWillApplySuggestion?: (suggestion: string, state: SuggestionsState) => string;
  27. placeholder?: string;
  28. portalOrigin?: string;
  29. syntax?: string;
  30. syntaxLoaded?: boolean;
  31. }
  32. export interface QueryFieldState {
  33. suggestions: CompletionItemGroup[];
  34. typeaheadContext: string | null;
  35. typeaheadPrefix: string;
  36. typeaheadText: string;
  37. value: Value;
  38. lastExecutedValue: Value;
  39. }
  40. export interface TypeaheadInput {
  41. prefix: string;
  42. selection?: Selection;
  43. text: string;
  44. value: Value;
  45. wrapperClasses: string[];
  46. labelKey?: string;
  47. }
  48. /**
  49. * Renders an editor field.
  50. * Pass initial value as initialQuery and listen to changes in props.onValueChanged.
  51. * This component can only process strings. Internally it uses Slate Value.
  52. * Implement props.onTypeahead to use suggestions, see PromQueryField.tsx as an example.
  53. */
  54. export class QueryField extends React.PureComponent<QueryFieldProps, QueryFieldState> {
  55. menuEl: HTMLElement | null;
  56. plugins: Plugin[];
  57. resetTimer: NodeJS.Timer;
  58. mounted: boolean;
  59. updateHighlightsTimer: Function;
  60. editor: Editor;
  61. typeaheadRef: Typeahead;
  62. constructor(props: QueryFieldProps, context: Context<any>) {
  63. super(props, context);
  64. this.updateHighlightsTimer = _.debounce(this.updateLogsHighlights, HIGHLIGHT_WAIT);
  65. const { onTypeahead, cleanText, portalOrigin, onWillApplySuggestion } = props;
  66. // Base plugins
  67. this.plugins = [
  68. SuggestionsPlugin({ onTypeahead, cleanText, portalOrigin, onWillApplySuggestion, component: this }),
  69. ClearPlugin(),
  70. RunnerPlugin({ handler: this.executeOnChangeAndRunQueries }),
  71. NewlinePlugin(),
  72. SelectionShortcutsPlugin(),
  73. IndentationPlugin(),
  74. ClipboardPlugin(),
  75. ...(props.additionalPlugins || []),
  76. ].filter(p => p);
  77. this.state = {
  78. suggestions: [],
  79. typeaheadContext: null,
  80. typeaheadPrefix: '',
  81. typeaheadText: '',
  82. value: makeValue(props.initialQuery || '', props.syntax),
  83. lastExecutedValue: null,
  84. };
  85. }
  86. componentDidMount() {
  87. this.mounted = true;
  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 } = 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. }
  104. UNSAFE_componentWillReceiveProps(nextProps: QueryFieldProps) {
  105. if (nextProps.syntaxLoaded && !this.props.syntaxLoaded) {
  106. // Need a bogus edit to re-render the editor after syntax has fully loaded
  107. const editor = this.editor.insertText(' ').deleteBackward(1);
  108. this.onChange(editor.value, true);
  109. }
  110. }
  111. onChange = (value: Value, invokeParentOnValueChanged?: boolean) => {
  112. const documentChanged = value.document !== this.state.value.document;
  113. const prevValue = this.state.value;
  114. // Control editor loop, then pass text change up to parent
  115. this.setState({ value }, () => {
  116. if (documentChanged) {
  117. const textChanged = Plain.serialize(prevValue) !== Plain.serialize(value);
  118. if (textChanged && invokeParentOnValueChanged) {
  119. this.executeOnChangeAndRunQueries();
  120. }
  121. if (textChanged && !invokeParentOnValueChanged) {
  122. this.updateHighlightsTimer();
  123. }
  124. }
  125. });
  126. };
  127. updateLogsHighlights = () => {
  128. const { onChange } = this.props;
  129. if (onChange) {
  130. onChange(Plain.serialize(this.state.value));
  131. }
  132. };
  133. executeOnChangeAndRunQueries = () => {
  134. // Send text change to parent
  135. const { onChange, onRunQuery } = this.props;
  136. if (onChange) {
  137. onChange(Plain.serialize(this.state.value));
  138. }
  139. if (onRunQuery) {
  140. onRunQuery();
  141. this.setState({ lastExecutedValue: this.state.value });
  142. }
  143. };
  144. handleBlur = (event: Event, editor: CoreEditor, next: Function) => {
  145. const { lastExecutedValue } = this.state;
  146. const previousValue = lastExecutedValue ? Plain.serialize(this.state.lastExecutedValue) : null;
  147. const currentValue = Plain.serialize(editor.value);
  148. if (previousValue !== currentValue) {
  149. this.executeOnChangeAndRunQueries();
  150. }
  151. editor.blur();
  152. return next();
  153. };
  154. render() {
  155. const { disabled } = this.props;
  156. const wrapperClassName = classnames('slate-query-field__wrapper', {
  157. 'slate-query-field__wrapper--disabled': disabled,
  158. });
  159. return (
  160. <div className={wrapperClassName}>
  161. <div className="slate-query-field">
  162. <Editor
  163. ref={editor => (this.editor = editor)}
  164. schema={SCHEMA}
  165. autoCorrect={false}
  166. readOnly={this.props.disabled}
  167. onBlur={this.handleBlur}
  168. // onKeyDown={this.onKeyDown}
  169. onChange={(change: { value: Value }) => {
  170. this.onChange(change.value, false);
  171. }}
  172. placeholder={this.props.placeholder}
  173. plugins={this.plugins}
  174. spellCheck={false}
  175. value={this.state.value}
  176. />
  177. </div>
  178. </div>
  179. );
  180. }
  181. }
  182. export default QueryField;