@codemirror/view#keymap TypeScript Examples

The following examples show how to use @codemirror/view#keymap. 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: editor.ts    From starboard-notebook with Mozilla Public License 2.0 7 votes vote down vote up
commonExtensions = [
  bracketMatching(),
  closeBrackets(),
  codeFolding(),
  lineNumbers(),
  foldGutter(),
  highlightSpecialChars(),

  starboardHighlighter,
  highlightActiveLine(),
  highlightSelectionMatches(),
  history(),

  keymap.of([
    { key: "Shift-Enter", run: () => true },
    { key: "Alt-Enter", run: () => true },
    { key: "Ctrl-Enter", run: () => true },
    { key: "Tab", run: tabKeyRun },
    { key: "Shift-Tab", run: indentLess },
    ...defaultKeymap,
    ...commentKeymap,
    ...completionKeymap,
    ...historyKeymap,
    ...foldKeymap,
    ...searchKeymap,
  ]),
  autocompletion(),
]
Example #2
Source File: PumlView.ts    From obsidian-plantuml with MIT License 7 votes vote down vote up
extensions: Extension[] = [
        highlightActiveLine(),
        highlightActiveLineGutter(),
        highlightSelectionMatches(),
        drawSelection(),
        keymap.of([...defaultKeymap, indentWithTab]),
        history(),
        search(),
        EditorView.updateListener.of(v => {
            if(v.docChanged) {
                this.requestSave();
                this.renderPreview();
            }
        })
    ]
Example #3
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 #4
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 #5
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 #6
Source File: main.ts    From quick_latex_obsidian with MIT License 4 votes vote down vote up
private readonly makeExtensionThing = ():Extension => Prec.high(keymap.of([
		{
			key: '$',
			run: (): boolean => {
				const view = this.app.workspace.getActiveViewOfType(MarkdownView)
				if (!view) return false

				const editor  = view.editor
				
				if (editor.getSelection().length > 0) {
					// enclose selected text
					if (this.settings.encloseSelection_toggle) {
						const anchor = editor.getCursor("anchor")
						const head = editor.getCursor("head")
						editor.replaceSelection(`$${editor.getSelection()}$`)
						if (anchor.line > head.line) {
							editor.setSelection({line:anchor.line,ch:anchor.ch},{line:head.line,ch:head.ch+1})
						} else if (anchor.line < head.line) {
							editor.setSelection({line:anchor.line,ch:anchor.ch+1},{line:head.line,ch:head.ch})
						} else {
							editor.setSelection({line:anchor.line,ch:anchor.ch+1},{line:head.line,ch:head.ch+1})
						}
						return true
					}
					return false
				} else {
					// close math symbol
					const position = editor.getCursor()
					const prev_char = editor.getRange(
						{line:position.line,ch:position.ch-1},
						{line:position.line,ch:position.ch})
					const next_char = editor.getRange(
						{line:position.line,ch:position.ch},
						{line:position.line,ch:position.ch+1})
					const next2_char = editor.getRange(
						{line:position.line,ch:position.ch},
						{line:position.line,ch:position.ch+2})
					if (prev_char != "$" && next_char == "$"){
						if (next2_char == "$$") {
							editor.setCursor({line:position.line,ch:position.ch+2})
							return true
						} else {
							editor.setCursor({line:position.line,ch:position.ch+1})
							return true
						}
					}
					// auto close math
					if (this.settings.autoCloseMath_toggle && this.vimAllow_autoCloseMath) {
						editor.replaceSelection("$");
					}
					// move into math
					if (this.settings.moveIntoMath_toggle) {
						const position = editor.getCursor();
						const t = editor.getRange(
							{ line: position.line, ch: position.ch - 1 },
							{ line: position.line, ch: position.ch })
						const t2 = editor.getRange(
							{ line: position.line, ch: position.ch },
							{ line: position.line, ch: position.ch + 1 })
						const t_2 = editor.getRange(
							{ line: position.line, ch: position.ch - 2 },
							{ line: position.line, ch: position.ch })
						if (t == '$' && t2 != '$') {
							editor.setCursor({ line: position.line, ch: position.ch - 1 })
						} else if (t_2 == '$$') {
							editor.setCursor({ line: position.line, ch: position.ch - 1 })
						};
					}
					return false
				}
			},

		},
		{
			key: 'Tab',
			run: (): boolean => {
				const view = this.app.workspace.getActiveViewOfType(MarkdownView)
				if (!view) return false

				const editor  = view.editor

				// Tab shortcut for matrix block
				if (this.settings.addMatrixBlock_toggle) {
					if (this.withinAnyBrackets_document(editor,
					'\\begin{' + this.settings.addMatrixBlock_parameter,
					'\\end{' + this.settings.addMatrixBlock_parameter,
					)) {
						editor.replaceSelection(' & ')
						return true
					};
				}

				// Tab shortcut for cases block
				if (this.settings.addCasesBlock_toggle) {
					if (this.withinAnyBrackets_document(editor,
					'\\begin{cases}',
					'\\end{cases}'
					)) {
						editor.replaceSelection(' & ')
						return true
					};
				}
				

				// Tab to go to next #tab
				const position = editor.getCursor();
				const current_line = editor.getLine(position.line);
				const tab_position = current_line.indexOf("#tab");
				if (tab_position!=-1){
					editor.replaceRange("",
					{line:position.line, ch:tab_position},
					{line:position.line, ch:tab_position+4})
					editor.setCursor({line:position.line, ch:tab_position})
					return true
				}
				return false
			},
		},
		{
			key: 'Space',
			run: (): boolean => {
				const view = this.app.workspace.getActiveViewOfType(MarkdownView)
				if (!view) return false
				
				const editor  = view.editor

				if (!this.settings.autoFraction_toggle &&
					!this.settings.autoLargeBracket_toggle &&
					!this.settings.autoEncloseSup_toggle &&
					!this.settings.autoEncloseSub_toggle &&
					!this.settings.customShorthand_toggle) return false;
				
				if (this.withinMath(editor)) {
					const position = editor.getCursor();
					const current_line = editor.getLine(position.line);
					const last_dollar = current_line.lastIndexOf('$', position.ch - 1);

					// check for custom shorthand
					if (this.settings.customShorthand_toggle && !this.withinText(editor, position.ch)) {
						let keyword:string = "";
						let keyword_length:number = 0;
						for (let i = 0 ; i < this.shorthand_array.length ; i++) {
							keyword_length = this.shorthand_array[i][0].length;
							if ( keyword_length > position.ch) {
								continue;
							} else if ( keyword_length == position.ch ) {
								keyword = "@" + editor.getRange(
									{ line: position.line, ch: position.ch - keyword_length },
									{ line: position.line, ch: position.ch });
							} else {
								keyword = editor.getRange(
									{ line: position.line, ch: position.ch - keyword_length - 1 },
									{ line: position.line, ch: position.ch });
							}
							if (keyword[0].toLowerCase() == keyword[0].toUpperCase() || 
								keyword[0] == "@" ) {
								if (this.shorthand_array[i][0] == keyword.slice(- keyword_length) && 
									this.shorthand_array[i][1] != keyword) {
									const replace_slash = (keyword[0]=="\\" && this.shorthand_array[i][1][0]=="\\") ? 1 : 0;
									const set_cursor_position = this.shorthand_array[i][1].indexOf("#cursor");
									editor.replaceRange(this.shorthand_array[i][1],
										{ line: position.line, ch: position.ch - keyword_length - replace_slash },
										{ line: position.line, ch: position.ch });
									if (set_cursor_position != -1) {
										editor.replaceRange("",
										{line:position.line, ch:position.ch - keyword_length + set_cursor_position},
										{line:position.line, ch:position.ch - keyword_length + set_cursor_position+7});
										editor.setCursor({line:position.line, ch:position.ch - keyword_length + set_cursor_position})
									} else if (this.shorthand_array[i][1].slice(-2) == "{}") {
										editor.setCursor(
											{ line: position.line, 
											ch: position.ch + this.shorthand_array[i][1].length - keyword_length - 1 - replace_slash}
											);
									} else {
										
									}									
									return true;
								};
							};
						}
					};

					// find last unbracketed subscript within last 10 characters and perform autoEncloseSub
					// ignore expression that contain + - * / ^
					const last_math = current_line.lastIndexOf('$', position.ch - 1);
					if (this.settings.autoEncloseSub_toggle) {
						let last_subscript = current_line.lastIndexOf('_', position.ch);
						if (last_subscript != -1 && last_subscript > last_math) {
							const letter_after_subscript = editor.getRange(
								{ line: position.line, ch: last_subscript + 1 },
								{ line: position.line, ch: last_subscript + 2 });
							if (letter_after_subscript != "{" && 
								(position.ch - last_subscript) <= 10 ) {
								editor.replaceSelection("}");
								editor.replaceRange("{", {line:position.line, ch:last_subscript+1});
								return true;
							};
						};
					};
				
					// retrieve the last unbracketed superscript
					let last_superscript = current_line.lastIndexOf('^', position.ch);
					
					while (last_superscript != -1) {
						const two_letters_after_superscript = editor.getRange(
							{ line: position.line, ch: last_superscript + 1 },
							{ line: position.line, ch: last_superscript + 3 });
						if (two_letters_after_superscript[0] == '{' || two_letters_after_superscript == ' {') {
							last_superscript = current_line.lastIndexOf('^', last_superscript - 1);
						} else if (last_superscript < last_math) {
							last_superscript = -1
							break;
						} else {
							break;
						}
					}

					// retrieve the last divide symbol
					let last_divide = current_line.lastIndexOf('/', position.ch - 1);

					// perform autoEncloseSup
					if (this.settings.autoEncloseSup_toggle) {
						if (last_superscript > last_divide) {
							return this.autoEncloseSup(editor, event, last_superscript);
						};
					};

					// perform autoFraction
					if (this.settings.autoFraction_toggle && !this.withinText(editor, last_divide)) {
						if (last_divide > last_dollar) {
							const brackets = [['(', ')'], ['{', '}'], ['[', ']']];
							// if any brackets in denominator still unclosed, dont do autoFraction yet
							if (!brackets.some(e => this.unclosed_bracket(editor, e[0], e[1], position.ch, last_divide)[0])) {
								return this.autoFractionCM6(editor, last_superscript);
							};
						};
					};

					// perform autoLargeBracket
					if (this.settings.autoLargeBracket_toggle) {
						let symbol_before = editor.getRange(
							{ line: position.line, ch: position.ch - 1 },
							{ line: position.line, ch: position.ch })
						if (symbol_before == ')' || symbol_before == ']') {
							return this.autoLargeBracket(editor, event);
						};
					}
				}
			},

		},
		{
			key: 'Enter',
			run: (): boolean => {
				const view = this.app.workspace.getActiveViewOfType(MarkdownView)
				if (!view) return false
				const editor  = view.editor
				if (this.settings.addAlignBlock_toggle) {
					if (this.withinAnyBrackets_document(
						editor,
						'\\begin{' + this.settings.addAlignBlock_parameter,
						'\\end{' + this.settings.addAlignBlock_parameter)
					) {
						editor.replaceSelection('\\\\\n&')
						return true;
					}
				}

				if (this.settings.addMatrixBlock_toggle) {
					if (this.withinAnyBrackets_document(
						editor,
						'\\begin{' + this.settings.addMatrixBlock_parameter,
						'\\end{' + this.settings.addMatrixBlock_parameter
					)) {
						editor.replaceSelection(' \\\\ ')
						return true;
					}
				}

				if (this.settings.addCasesBlock_toggle) {
					if (this.withinAnyBrackets_document(
						editor,
						'\\begin{cases}',
						'\\end{cases}'
					)) {
						editor.replaceSelection(' \\\\\n')
						return true;
					}
				}
				// double enter for $$
				if (this.withinMath(editor)) {
					const position = editor.getCursor();
					const prev2_Char = editor.getRange(
						{ line: position.line, ch: position.ch - 2 },
						{ line: position.line, ch: position.ch })
					const next2_Char = editor.getRange(
						{ line: position.line, ch: position.ch },
						{ line: position.line, ch: position.ch + 2 })
					if (prev2_Char=="$$"&&next2_Char=="$$") {
						editor.replaceSelection('\n')
						editor.setCursor(position)
						return false
					}							
				}
				return false
			},
		},
		{
			key: '{',
			run: (): boolean => {
				const view = this.app.workspace.getActiveViewOfType(MarkdownView)
				if (!view) return false

				const editor  = view.editor

				if (this.withinMath(editor)) {
					if (this.settings.autoCloseCurly_toggle) {
						const position = editor.getCursor();
						const brackets = [['(', ')'], ['{', '}'], ['[', ']']];
						const next_char = editor.getRange(
							{ line: position.line, ch: position.ch },
							{ line: position.line, ch: position.ch+1 });
						const next_2char = editor.getRange(
							{ line: position.line, ch: position.ch },
							{ line: position.line, ch: position.ch+2 });
						const followed_by_$spacetabnonedoubleslash = (['$',' ','	',''].contains(next_char) || next_2char == '\\\\');
						if (!this.withinAnyBrackets_inline(editor, brackets) && followed_by_$spacetabnonedoubleslash) {
							editor.replaceSelection('{}');
							editor.setCursor({line:position.line, ch:position.ch+1});
							return true;
						};
					};
				};
				return false
			},

		},
		{
			key: '[',
			run: (): boolean => {
				const view = this.app.workspace.getActiveViewOfType(MarkdownView)
				if (!view) return false

				const editor  = view.editor

				if (this.withinMath(editor)) {
					if (this.settings.autoCloseSquare_toggle) {
						const position = editor.getCursor();
						const brackets = [['(', ')'], ['{', '}'], ['[', ']']];
						const next_char = editor.getRange(
							{ line: position.line, ch: position.ch },
							{ line: position.line, ch: position.ch+1 });
						const next_2char = editor.getRange(
							{ line: position.line, ch: position.ch },
							{ line: position.line, ch: position.ch+2 });
						const followed_by_$spacetabnonedoubleslash = (['$',' ','	',''].contains(next_char) || next_2char == '\\\\');
						if (!this.withinAnyBrackets_inline(editor, brackets) && followed_by_$spacetabnonedoubleslash) {
							editor.replaceSelection('[]');
							editor.setCursor({line:position.line, ch:position.ch+1});
							return true;
						};
					};
				};
				return false
			},
		},
		{
			key: '(',
			run: (): boolean => {
				const view = this.app.workspace.getActiveViewOfType(MarkdownView)
				if (!view) return false

				const editor  = view.editor

				if (this.withinMath(editor)) {
					if (this.settings.autoCloseRound_toggle) {
						const position = editor.getCursor();
						const brackets = [['(', ')'], ['{', '}'], ['[', ']']];
						const next_char = editor.getRange(
							{ line: position.line, ch: position.ch },
							{ line: position.line, ch: position.ch+1 });
						const next_2char = editor.getRange(
							{ line: position.line, ch: position.ch },
							{ line: position.line, ch: position.ch+2 });
						const followed_by_$spacetabnonedoubleslash = (['$',' ','	',''].contains(next_char) || next_2char == '\\\\');
						if (!this.withinAnyBrackets_inline(editor, brackets) && followed_by_$spacetabnonedoubleslash) {
							editor.replaceSelection('()');
							editor.setCursor({line:position.line, ch:position.ch+1});
							return true;
						};
					};
				};
				return false
			},

		},
		{
			key: '}',
			run: (): boolean => {
				const view = this.app.workspace.getActiveViewOfType(MarkdownView)
				if (!view) return false

				const editor  = view.editor

				if (this.withinMath(editor)) {
					if (this.settings.autoCloseRound_toggle) {
						const position = editor.getCursor();
						const end = editor.getLine(position.line).length
						const next_sym = editor.getRange({line:position.line,ch:position.ch},{line:position.line,ch:position.ch+1})
						if (!this.unclosed_bracket(editor, "{", "}", end, 0)[0] &&
						 !this.unclosed_bracket(editor, "{", "}", end, 0, false)[0] &&
						 next_sym == "}") {
							editor.setCursor({line:position.line,ch:position.ch+1})
							return true;
						} else {
							return false;
						};
					};
				};
				return false
			},
		},
		{
			key: ']',
			run: (): boolean => {
				const view = this.app.workspace.getActiveViewOfType(MarkdownView)
				if (!view) return false

				const editor  = view.editor

				if (this.withinMath(editor)) {
					if (this.settings.autoCloseRound_toggle) {
						const position = editor.getCursor();
						const end = editor.getLine(position.line).length
						const next_sym = editor.getRange({line:position.line,ch:position.ch},{line:position.line,ch:position.ch+1})
						if (!this.unclosed_bracket(editor, "[", "]", end, 0)[0] &&
						 !this.unclosed_bracket(editor, "[", "]", end, 0, false)[0] &&
						 next_sym == "]") {
							editor.setCursor({line:position.line,ch:position.ch+1})
							return true;
						} else {
							return false;
						};
					};
				};
				return false
			},
		},
		{
			key: ')',
			run: (): boolean => {
				const view = this.app.workspace.getActiveViewOfType(MarkdownView)
				if (!view) return false

				const editor  = view.editor

				if (this.withinMath(editor)) {
					if (this.settings.autoCloseRound_toggle) {
						const position = editor.getCursor();
						const end = editor.getLine(position.line).length
						const next_sym = editor.getRange({line:position.line,ch:position.ch},{line:position.line,ch:position.ch+1})
						if (!this.unclosed_bracket(editor, "(", ")", end, 0)[0] &&
						 !this.unclosed_bracket(editor, "(", ")", end, 0, false)[0] &&
						 next_sym == ")") {
							editor.setCursor({line:position.line,ch:position.ch+1})
							return true;
						} else {
							return false;
						};
					};
				};
				return false
			},
		},
		{
			key: 'm',
			run: (): boolean => {
				const view = this.app.workspace.getActiveViewOfType(MarkdownView)
				if (!view) return false

				const editor  = view.editor
				
				if (!this.withinMath(editor)) return false
				
				const position = editor.getCursor();

				if (!this.settings.autoSumLimit_toggle) return;
				if (this.withinMath(editor)) {
					if (editor.getRange(
						{ line: position.line, ch: position.ch - 3 },
						{ line: position.line, ch: position.ch }) == '\\su') {
						editor.replaceSelection('m\\limits')
						return true;
					};
				};
				return false
			},
		},
	]));
Example #7
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 #8
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} />
    </>
  );
}