@codemirror/state#EditorState TypeScript Examples

The following examples show how to use @codemirror/state#EditorState. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: util.ts    From obsidian-admonition with MIT License 7 votes vote down vote up
isLivePreview = (state: EditorState) => {
    if (requireApiVersion && requireApiVersion("0.13.23")) {
        return state.field(editorLivePreviewField);
    } else {
        const md = state.field(editorViewField);
        const { state: viewState } = md.leaf.getViewState() ?? {};

        return (
            viewState && viewState.mode == "source" && viewState.source == false
        );
    }
}
Example #2
Source File: main.tsx    From obsidian-annotator with GNU Affero General Public License v3.0 6 votes vote down vote up
getDropExtension() {
        return EditorState.transactionFilter.of(transaction => {
            if (transaction.isUserEvent('input.drop')) {
                try {
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    const droppedText = (transaction.changes as any).inserted.map(x => x.text.join('')).join('');

                    if (this.dragData !== null && droppedText == 'drag-event::hypothesis-highlight') {
                        const startPos = transaction.selection.ranges[0].from;
                        // eslint-disable-next-line @typescript-eslint/no-explicit-any
                        const leaf: FileView = Object.keys((transaction.state as any).config.address)
                            // eslint-disable-next-line @typescript-eslint/no-explicit-any
                            .map(x => (transaction.state as any).field({ id: x }))
                            .filter(x => x?.file)[0];

                        const targetFile = leaf.file;

                        const annotationFile = this.app.vault.getAbstractFileByPath(this.dragData.annotationFilePath);
                        if (annotationFile instanceof TFile && targetFile instanceof TFile) {
                            const linkString = this.app.fileManager.generateMarkdownLink(
                                annotationFile,
                                targetFile.path,
                                `#^${this.dragData.annotationId}`,
                                this.dragData.annotationText
                            );
                            this.dragData = null;
                            return { changes: { from: startPos, insert: linkString }, selection: { anchor: startPos } };
                        }
                    }
                } catch (e) {}
            }
            return transaction;
        });
    }
Example #3
Source File: editor.ts    From starboard-notebook with Mozilla Public License 2.0 6 votes vote down vote up
function tabKeyRun(t: { state: EditorState; dispatch: (transaction: Transaction) => void }): boolean {
  if (t.state.selection.ranges.some((r) => !r.empty)) {
    return indentMore({ state: t.state, dispatch: t.dispatch });
  }
  // So we can tab past the editor we don't tab if the cursor is at the very start of the document.
  // Note: this can be improved, we could instead see if we have pressed any keys since focusing the editor and decide
  // based on that.
  const r = t.state.selection.ranges[0];
  if (r && r.to === 0 && r.from === 0) {
    return false;
  }
  t.dispatch(
    t.state.update(t.state.replaceSelection("\t"), {
      scrollIntoView: true,
      annotations: Transaction.userEvent.of("input"),
    })
  );
  return true;
}
Example #4
Source File: highlight.ts    From starboard-notebook with Mozilla Public License 2.0 6 votes vote down vote up
// Async in preparation of highlighters that are loaded dynamically
export async function createCodeMirrorCodeHighlight(
  content: string,
  opts: {
    language?: string;
  }
) {
  const languageExtension = getCodemirrorLanguageExtension(opts.language);

  const editorView = new EditorView({
    state: EditorState.create({
      doc: content,
      extensions: [...commonExtensions, ...(languageExtension ? [languageExtension] : [])],
    }),
  });
  return editorView;
}
Example #5
Source File: PumlView.ts    From obsidian-plantuml with MIT License 6 votes vote down vote up
// load the data into the view
    async setViewData(data: string, clear: boolean) {
        this.data = data;
         if (clear) {
             this.editor.setState(EditorState.create({
                 doc: data,
                 extensions: this.extensions
             }));

         }else {
             this.editor.dispatch({
                 changes: {
                     from: 0,
                     to: this.editor.state.doc.length,
                     insert: data,
                 }
             })
         }
        // if we're in preview view, also render that
        if (this.currentView === 'preview') this.renderPreview();
    }
Example #6
Source File: PumlView.ts    From obsidian-plantuml with MIT License 6 votes vote down vote up
constructor(leaf: WorkspaceLeaf, plugin: PlantumlPlugin) {
        super(leaf);
        this.plugin = plugin;

        this.debounced = debounce(this.plugin.getProcessor().png, this.plugin.settings.debounce * 1000, true);

        this.sourceEl = this.contentEl.createDiv({cls: 'plantuml-source-view', attr: {'style': 'display: block'}});
        this.previewEl = this.contentEl.createDiv({cls: 'plantuml-preview-view', attr: {'style': 'display: none'}});

        const vault = (this.app.vault as any);

        if (vault.getConfig("showLineNumber")) {
            this.extensions.push(lineNumbers());
        }
        if(vault.getConfig("lineWrap")) {
            this.extensions.push(EditorView.lineWrapping);
        }

        this.editor = new EditorView({
            state: EditorState.create({
                extensions: this.extensions,
                doc: this.data,
            }),
            parent: this.sourceEl,
            dispatch: syncDispatch(views.length),
        });
        this.dispatchId = views.push(this.editor) - 1;

    }
Example #7
Source File: editor.tsx    From nota with MIT License 6 votes vote down vote up
Editor: React.FC<EditorProps> = ({ embedded }) => {
  let ref = useRef<HTMLDivElement>(null);
  let state = useContext(StateContext)!;

  useEffect(() => {
    let visualExts = [
      syntaxHighlighting(defaultHighlightStyle, { fallback: true }),
      EditorView.lineWrapping,
      theme,
    ];
    let editingExts = [keymap.of([...keyBindings, indentWithTab])];
    let customExts = [
      EditorView.updateListener.of(
        action(update => {
          if (update.docChanged) {
            state.contents = update.state.doc.toJSON().join("\n");
          }
        })
      ),
    ];
    let _editor = new EditorView({
      state: EditorState.create({
        doc: state.contents,
        extensions: [notaLang, visualExts, editingExts, customExts, basicSetup],
      }),
      parent: ref.current!,
    });
  }, []);

  return <div className={classNames("nota-editor", { embedded })} ref={ref} />;
}
Example #8
Source File: Editor.tsx    From react-jupyter-notebook with MIT License 5 votes vote down vote up
function Editor(props: EditorPropsType) {
  const {
    editable=true,
    onChange=(value) => console.log(value),
  } = props;

  const [state, setState] = useState<{[key:string]: any}>({});

  const extensions = [
    javascript(),
    lineNumbers(),
    // onChange listener
    EditorView.updateListener.of((viewUpdate: ViewUpdate) => {
      if (viewUpdate.docChanged && typeof onChange === 'function') {
        const doc = viewUpdate.state.doc;
        const value = doc.toString();
        onChange(value);
      }
    }),
    // Jupyter theme
    EditorView.theme(
      {
        '&.cm-editor': {
          border: "1px solid rgb(224, 224, 224)",
          backgroundColor: "rgb(245, 245, 245)",
        },
        '&.cm-editor.cm-focused': {
          outline: "1px solid #1976d2",
        },
        '.cm-gutters': {
          minWidth: "37px",
          display: "initial",
          backgroundColor: "rgb(238, 238, 238)"
        }
      },
      {dark: false},
    ),
    // Editable
    EditorView.editable.of(editable),
  ];

  const codeMirrorRef = useRef<HTMLDivElement>(null);
  useEffect(() => {
    if (codeMirrorRef.current && !state.view) {
      const view = new EditorView({
        state: EditorState.create({
          extensions: extensions,
          doc: "TEST",
        }),
        parent: codeMirrorRef.current,
      })
      setState((state) => ({...state, view}))
    }
  }, [codeMirrorRef.current])

  return (
    <div ref={codeMirrorRef}/>
  )
}
Example #9
Source File: main.ts    From better-word-count with MIT License 5 votes vote down vote up
// activeLeafChange(leaf: WorkspaceLeaf) {
  //   if (!(leaf.view.getViewType() === "markdown")) {
  //     this.barManager.updateAltStatusBar();
  //   }
  // }

  // async saveSettings(): Promise<void> {
  //   await this.saveData(this.settings);
  // }

  // initLeaf(): void {
  //   if (this.app.workspace.getLeavesOfType(VIEW_TYPE_STATS).length) {
  //     return;
  //   }
  //   this.app.workspace.getRightLeaf(false).setViewState({
  //     type: VIEW_TYPE_STATS,
  //   });
  // }


  createCMExtension() {

    const cmStateField = StateField.define<DecorationSet>({
      create(state: EditorState) {
        return  Decoration.none;
      },
      update(effects: DecorationSet, tr: Transaction) {
        let text = "";
        const selection = tr.newSelection.main;
        if (selection.empty) {
          const textIter = tr.newDoc.iter();
          while (!textIter.done) {
            text = text + textIter.next().value;
          }
        } else {
          const textIter = tr.newDoc.iterRange(selection.from, selection.to);
          while (!textIter.done) {
            text = text + textIter.next().value;
          }
        }

        BetterWordCount.updateStatusBar(text);
        
        return effects;
      },

      provide: (f: any) => EditorView.decorations.from(f),
    });
    
    this.registerEditorExtension(cmStateField);
  }
Example #10
Source File: index.tsx    From fe-v5 with Apache License 2.0 5 votes vote down vote up
export default function PromqlEditor(props: Props) {
  const { onChange, value, className, style = {}, editable = true, xCluster } = props;
  const [view, setView] = useState<EditorView>();
  const containerRef = useRef<HTMLDivElement>(null);
  const url = '/api/n9e/prometheus';

  function myHTTPClient(resource: string, options = {}): Promise<Response> {
    return fetch(resource, {
      method: 'Get',
      headers: new Headers({
        'X-Cluster': xCluster,
        Authorization: `Bearer ${localStorage.getItem('access_token') || ''}`,
      }),
      ...options,
    });
  }
  const promQL = new PromQLExtension().setComplete({
    remote: { fetchFn: myHTTPClient, url },
    // remote: { url: 'http://10.86.76.13:8090' },
  });
  useEffect(() => {
    const v = new EditorView({
      state: EditorState.create({
        doc: value,
        extensions: [
          baseTheme,
          basicSetup,
          promQL.asExtension(),
          EditorView.updateListener.of((update: ViewUpdate): void => {
            onChange?.(update.state.doc.toString());
          }),
          EditorView.editable.of(editable),
        ],
      }),
      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
      // tslint:disable-next-line:no-non-null-assertion
      parent: containerRef.current!,
    });
    setView(v);
  }, []);

  return <div ref={containerRef} className={className} style={Object.assign({ fontSize: 12 }, style)}></div>;
}
Example #11
Source File: index.ts    From obsidian-banners with MIT License 5 votes vote down vote up
getViewPlugin = (plugin: BannersPlugin) => ViewPlugin.fromClass(class BannerPV implements PluginValue {
  decor: DecorationSet;

  constructor(view: EditorView) {
    this.decor = this.decorate(view.state);
  }

  update(_update: ViewUpdate) {
    const { docChanged, view, state, startState } = _update;
    if (docChanged || state.facet(bannerDecorFacet) !== startState.facet(bannerDecorFacet) || state.facet(iconDecorFacet) !== startState.facet(iconDecorFacet)) {
      this.decor = this.decorate(view.state);
    }
  }

  decorate(state: EditorState): DecorationSet {
    // If there's no YAML, stop here
    const cursor =  syntaxTree(state).cursor();
    cursor.firstChild();
    if (cursor.name !== YAML_SEPARATOR_TOKEN) { return Decoration.none }

    // Get all frontmatter fields to later process
    const frontmatter: {[key: string]: string} = {};
    let key;
    while (cursor.nextSibling() && cursor.name !== YAML_SEPARATOR_TOKEN) {
      const { from, to, name } = cursor;
      if (name === YAML_DEF_NAME_TOKEN) {
        key = state.sliceDoc(from, to);
      } else if (YAML_DEF_VAL_TOKENS.includes(name) && !frontmatter[key]) {
        const isStr = name === YAML_DEF_STR_TOKEN;
        const val = state.sliceDoc(from + (isStr ? 1 : 0), to - (isStr ? 1 : 0));
        frontmatter[key] = val;
      }
    };

    const bannerData = plugin.metaManager.getBannerData(frontmatter);
    const { src, icon } = bannerData;
    const { contentEl, file } = state.field(editorViewField);
    const widgets: Decoration[] = [];

    // Add banner widgets if applicable
    if (src) {
      const settingsFacet = state.facet(bannerDecorFacet);
      widgets.push(
        Decoration.widget({ widget: new BannerWidget(plugin, bannerData, file.path, contentEl, settingsFacet) }),
        Decoration.widget({ widget: new SpacerWidget() }),
        Decoration.line({ class: 'has-banner' })
      );
    }

    // Add icon widget if applicable
    if (icon) {
      const settingsFacet = state.facet(iconDecorFacet);
      widgets.push(
        Decoration.widget({ widget: new IconWidget(plugin, icon, file, settingsFacet) }),
        Decoration.line({ class: "has-banner-icon", attributes: { "data-icon-v": settingsFacet.iconVerticalAlignment }})
      );
    }

    return Decoration.set(widgets.map(w => w.range(0)), true);
  }
}, {
  decorations: v => v.decor
})
Example #12
Source File: code.tsx    From nota with MIT License 5 votes vote down vote up
Listing: React.FC<ListingProps> = props => {
  let ctx = usePlugin(ListingPlugin);
  let ref = useRef(null);

  useEffect(() => {
    let language = props.language || ctx.language;

    let code = joinRecursive(props.children as any);
    let parseResult = null;
    if (props.delimiters) {
      parseResult = parseWithDelimiters(code, props.delimiters.delimiters);
      if (parseResult.error) {
        throw parseResult.error;
      } else {
        code = parseResult.outputCode!;
      }
    }

    let editor = new EditorView({
      state: EditorState.create({
        doc: code,
        extensions: [
          lineNumbers(),
          syntaxHighlighting(defaultHighlightStyle, { fallback: true }),
          theme,
          EditorView.editable.of(props.editable || false),
          props.wrap || ctx.wrap ? EditorView.lineWrapping : [],
          highlightField,
        ]
          .concat(language ? [language] : [])
          .concat(props.extensions || []),
      }),
      parent: ref.current!,
    });

    if (props.onLoad) {
      props.onLoad(editor);
    }

    if (props.delimiters) {
      props.delimiters.onParse(parseResult!.ranges!);
    }
  }, []);

  return <div className="listing" ref={ref} />;
}
Example #13
Source File: editor.ts    From starboard-notebook with Mozilla Public License 2.0 4 votes vote down vote up
export function createCodeMirrorEditor(
  element: HTMLElement,
  cell: Cell,
  opts: {
    language?: string;
    wordWrap?: "off" | "on" | "wordWrapColumn" | "bounded";
  },
  runtime: Runtime
) {
  const listen = EditorView.updateListener.of((update) => {
    if (update.docChanged) {
      cell.textContent = update.state.doc.toString();
    }
  });

  const readOnlyCompartment = new Compartment();
  const readOnlyExtension = EditorView.editable.of(!cell.metadata.properties.locked);

  const cellSwitchExtension = keymap.of([
    {
      key: "ArrowUp",
      run: (target) => {
        if (target.state.selection.ranges.length === 1 && target.state.selection.ranges[0].empty) {
          const firstLine = target.state.doc.line(1);
          const cursorPosition = target.state.selection.ranges[0].head;
          if (firstLine.from <= cursorPosition && cursorPosition <= firstLine.to) {
            runtime.controls.focusCell({ id: cell.id, focusTarget: "previous" });
            return true;
          }
        }
        return false;
      },
    },
    {
      key: "ArrowDown",
      run: (target) => {
        if (target.state.selection.ranges.length === 1 && target.state.selection.ranges[0].empty) {
          const lastline = target.state.doc.line(target.state.doc.lines);
          const cursorPosition = target.state.selection.ranges[0].head;
          if (lastline.from <= cursorPosition && cursorPosition <= lastline.to) {
            runtime.controls.focusCell({ id: cell.id, focusTarget: "next" });
            return true;
          }
        }
        return false;
      },
    },
  ]);

  const languageExtension = getCodemirrorLanguageExtension(opts.language);
  const editorView = new EditorView({
    state: EditorState.create({
      doc: cell.textContent.length === 0 ? undefined : cell.textContent,
      extensions: [
        cellSwitchExtension,
        ...commonExtensions,
        ...(languageExtension ? [languageExtension] : []),
        ...(opts.wordWrap === "on" ? [EditorView.lineWrapping] : []),
        readOnlyCompartment.of(readOnlyExtension),
        listen,
      ],
    }),
  });

  const setEditable = (editor: EditorView, locked: boolean | undefined) => {
    editor.dispatch({
      effects: readOnlyCompartment.reconfigure(EditorView.editable.of(!locked)),
    });
  };

  let isLocked: boolean | undefined = cell.metadata.properties.locked;
  runtime.controls.subscribeToCellChanges(cell.id, () => {
    // Note this function will be called on ALL text changes, so any letter typed,
    // it's probably better for performance to only ask cm to change it's editable state if it actually changed.
    if (isLocked === cell.metadata.properties.locked) return;
    isLocked = cell.metadata.properties.locked;
    setEditable(editorView, isLocked);
  });

  element.appendChild(editorView.dom);
  return editorView;
}
Example #14
Source File: index.tsx    From pintora with MIT License 4 votes vote down vote up
Editor = (props: Props) => {
  const { code, onCodeChange, editorOptions, errorInfo } = props
  const wrapperRef = useRef<HTMLDivElement>()
  const viewRef = useRef<EditorView>()
  const stateRef = useRef<EditorState>()

  useEffect(() => {
    if (!wrapperRef.current) return

    let editor = viewRef.current
    let state = stateRef.current
    if (viewRef.current) viewRef.current.destroy()
    if (!state) {
      const onUpdateExtension = EditorView.updateListener.of(update => {
        if (update.docChanged && state) {
          const newCode = update.view.state.doc.toJSON().join('\n')
          onCodeChange(newCode)
        }
      })
      const extensions: Extension[] = [
        keymap.of(standardKeymap),
        history(),
        keymap.of(historyKeymap),
        onUpdateExtension,
        keymap.of(searchKeymap),
        lineNumbers(),
        search({ top: true }),
        highlightActiveLine(),
        oneDark,
        keymap.of(tabKeymaps),
      ]
      if (editorOptions.language === 'json') {
        extensions.push(json())
      }

      state = EditorState.create({
        doc: code,
        extensions,
      })
      stateRef.current = state
    }

    editor = new EditorView({
      parent: wrapperRef.current,
      state: state,
    })
    viewRef.current = editor

    return () => {
      if (viewRef.current) {
        viewRef.current.destroy()
      }
    }
  }, [])

  useEffect(() => {
    const view = viewRef.current
    if (view && view.state) {
      const state = view.state
      const currentCode = state.doc.toJSON().join('\n')
      // console.log('currentCode == code', currentCode == code)
      if (currentCode !== code) {
        view.dispatch(state.update({ changes: { from: 0, to: currentCode.length, insert: code } }))
      }
    }
  }, [code])

  useEffect(() => {
    const view = viewRef.current
    if (view) {
      if (errorInfo) {
        const spec = setDiagnostics(view.state, [
          {
            severity: 'error',
            message: errorInfo.message,
            from: errorInfo.offset,
            to: errorInfo.offset,
          },
        ])
        view.dispatch(spec)
      } else {
        view.dispatch(setDiagnostics(view.state, []))
      }
    }
  }, [errorInfo])

  // TOOD: highlight error
  // useEffect(() => {
  // }, [errorInfo])

  return <div className="CMEditor" ref={wrapperRef as any}></div>
}
Example #15
Source File: index.tsx    From fe-v5 with Apache License 2.0 4 votes vote down vote up
ExpressionInput = ({ url, headers, value, onChange, executeQuery, readonly = false }: CMExpressionInputProps, ref) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const viewRef = useRef<EditorView | null>(null);
  const executeQueryCallback = useRef(executeQuery);
  const realValue = useRef<string | undefined>(value || '');
  const defaultHeaders = {
    Authorization: `Bearer ${localStorage.getItem('access_token') || ''}`,
  };

  useEffect(() => {
    executeQueryCallback.current = executeQuery;
    promqlExtension
      .activateCompletion(true)
      .activateLinter(true)
      .setComplete({
        remote: {
          url,
          fetchFn: (resource, options = {}) => {
            const params = options.body?.toString();
            const search = params ? `?${params}` : '';
            return fetch(resource + search, {
              method: 'Get',
              headers: new Headers(
                headers
                  ? {
                      ...defaultHeaders,
                      ...headers,
                    }
                  : defaultHeaders,
              ),
            });
          },
        },
      });

    // Create or reconfigure the editor.
    const view = viewRef.current;
    if (view === null) {
      // If the editor does not exist yet, create it.
      if (!containerRef.current) {
        throw new Error('expected CodeMirror container element to exist');
      }

      const startState = EditorState.create({
        doc: value,
        extensions: [
          baseTheme,
          highlightSpecialChars(),
          history(),
          EditorState.allowMultipleSelections.of(true),
          indentOnInput(),
          bracketMatching(),
          closeBrackets(),
          autocompletion(),
          highlightSelectionMatches(),
          promqlHighlighter,
          EditorView.lineWrapping,
          keymap.of([...closeBracketsKeymap, ...defaultKeymap, ...historyKeymap, ...commentKeymap, ...completionKeymap, ...lintKeymap]),
          placeholder('Expression (press Shift+Enter for newlines)'),
          promqlExtension.asExtension(),
          EditorView.editable.of(!readonly),
          keymap.of([
            {
              key: 'Escape',
              run: (v: EditorView): boolean => {
                v.contentDOM.blur();
                return false;
              },
            },
          ]),
          Prec.override(
            keymap.of([
              {
                key: 'Enter',
                run: (v: EditorView): boolean => {
                  if (typeof executeQueryCallback.current === 'function') {
                    executeQueryCallback.current(realValue.current);
                  }
                  return true;
                },
              },
              {
                key: 'Shift-Enter',
                run: insertNewlineAndIndent,
              },
            ]),
          ),
          EditorView.updateListener.of((update: ViewUpdate): void => {
            if (typeof onChange === 'function') {
              const val = update.state.doc.toString();
              if (val !== realValue.current) {
                realValue.current = val;
                onChange(val);
              }
            }
          }),
        ],
      });

      const view = new EditorView({
        state: startState,
        parent: containerRef.current,
      });

      viewRef.current = view;

      if (ref) {
        ref.current = view;
      }

      view.focus();
    }
  }, [onChange, JSON.stringify(headers)]);

  useEffect(() => {
    if (realValue.current !== value) {
      const oldValue = realValue.current;
      realValue.current = value || '';
      const view = viewRef.current;
      if (view === null) {
        return;
      }
      view.dispatch(
        view.state.update({
          changes: { from: 0, to: oldValue?.length || 0, insert: value },
        }),
      );
    }
  }, [value]);

  return (
    <div
      className={classNames({ 'ant-input': true, readonly: readonly, 'promql-input': true })}
      onBlur={() => {
        if (typeof onChange === 'function') {
          onChange(realValue.current);
        }
      }}
    >
      <div className='input-content' ref={containerRef} />
    </div>
  );
}
Example #16
Source File: expressionInput.tsx    From fe-v5 with Apache License 2.0 4 votes vote down vote up
ExpressionInput: FC<CMExpressionInputProps> = ({ value, onExpressionChange, queryHistory, metricNames, isLoading, executeQuery }) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const viewRef = useRef<EditorView | null>(null);
  const executeQueryCallback = useRef(executeQuery);
  const [showMetricsExplorer, setShowMetricsExplorer] = useState<boolean>(false);

  useEffect(() => {
    executeQueryCallback.current = executeQuery;
    promqlExtension
      .activateCompletion(true)
      .activateLinter(true)
      .setComplete({
        remote: { url, fetchFn: myHTTPClient, cache: { initialMetricList: metricNames } },
      });

    // Create or reconfigure the editor.
    const view = viewRef.current;
    if (view === null) {
      // If the editor does not exist yet, create it.
      if (!containerRef.current) {
        throw new Error('expected CodeMirror container element to exist');
      }

      const startState = EditorState.create({
        doc: value,
        extensions: [
          baseTheme,
          highlightSpecialChars(),
          history(),
          EditorState.allowMultipleSelections.of(true),
          indentOnInput(),
          bracketMatching(),
          closeBrackets(),
          autocompletion(),
          highlightSelectionMatches(),
          promqlHighlighter,
          EditorView.lineWrapping,
          keymap.of([...closeBracketsKeymap, ...defaultKeymap, ...historyKeymap, ...commentKeymap, ...completionKeymap, ...lintKeymap]),
          placeholder('Expression (press Shift+Enter for newlines)'),
          promqlExtension.asExtension(),
          // This keymap is added without precedence so that closing the autocomplete dropdown
          // via Escape works without blurring the editor.
          keymap.of([
            {
              key: 'Escape',
              run: (v: EditorView): boolean => {
                v.contentDOM.blur();
                return false;
              },
            },
          ]),
          Prec.override(
            keymap.of([
              {
                key: 'Enter',
                run: (v: EditorView): boolean => {
                  executeQueryCallback.current();
                  return true;
                },
              },
              {
                key: 'Shift-Enter',
                run: insertNewlineAndIndent,
              },
            ]),
          ),
          EditorView.updateListener.of((update: ViewUpdate): void => {
            onExpressionChange(update.state.doc.toString());
          }),
        ],
      });

      const view = new EditorView({
        state: startState,
        parent: containerRef.current,
      });

      viewRef.current = view;

      view.focus();
    }
  }, [executeQuery, onExpressionChange, queryHistory]);

  const insertAtCursor = (value: string) => {
    const view = viewRef.current;
    if (view === null) {
      return;
    }
    const { from, to } = view.state.selection.ranges[0];
    view.dispatch(
      view.state.update({
        changes: { from, to, insert: value },
      }),
    );
  };

  return (
    <>
      <div className='prometheus-input-box'>
        <div className='input-prefix'>
          <span>PromQL: </span>
        </div>
        <div className='input'>
          <div className='input-content' ref={containerRef} />
        </div>
        <div className='suffix'>
          <Button size='large' className='metrics' icon={<GlobalOutlined />} onClick={() => setShowMetricsExplorer(true)}></Button>
          <Button size='large' type='primary' className='execute' onClick={executeQuery}>
            Execute
          </Button>
        </div>
      </div>

      {/* 点击按钮的弹出Modal */}
      <MetricsExplorer show={showMetricsExplorer} updateShow={setShowMetricsExplorer} metrics={metricNames} insertAtCursor={insertAtCursor} />
    </>
  );
}