@codemirror/state#Prec TypeScript Examples

The following examples show how to use @codemirror/state#Prec. 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: main.ts    From obsidian-plantuml with MIT License 4 votes vote down vote up
async onload(): Promise<void> {
        console.log('loading plugin plantuml');
        await this.loadSettings();
        this.addSettingTab(new PlantUMLSettingsTab(this));
        this.replacer = new Replacer(this);

        this.serverProcessor = new ServerProcessor(this);
        if (Platform.isDesktopApp) {
            this.localProcessor = new LocalProcessors(this);
        }

        const processor = new DebouncedProcessors(this);

        if (isUsingLivePreviewEnabledEditor()) {
            const view = require("./PumlView");
            addIcon("document-" + view.VIEW_TYPE, LOGO_SVG);
            this.registerView(view.VIEW_TYPE, (leaf) => {
                return new view.PumlView(leaf, this);
            });
            this.registerExtensions(["puml", "pu"], view.VIEW_TYPE);
            this.registerEditorExtension(Prec.lowest(asyncDecoBuilderExt(this)));
        }

        this.registerMarkdownCodeBlockProcessor("plantuml", processor.png);
        this.registerMarkdownCodeBlockProcessor("plantuml-ascii", processor.ascii);
        this.registerMarkdownCodeBlockProcessor("plantuml-svg", processor.svg);
        this.registerMarkdownCodeBlockProcessor("puml", processor.png);
        this.registerMarkdownCodeBlockProcessor("puml-svg", processor.svg);
        this.registerMarkdownCodeBlockProcessor("puml-ascii", processor.ascii);

        //keep this processor for backwards compatibility
        this.registerMarkdownCodeBlockProcessor("plantuml-map", processor.png);


        //internal links
        this.observer = new MutationObserver(async (mutation) => {
            if (mutation.length !== 1) return;
            if (mutation[0].addedNodes.length !== 1) return;
            if (this.hover.linkText === null) return;
            //@ts-ignore
            if (mutation[0].addedNodes[0].className !== "popover hover-popover file-embed is-loaded") return;

            const file = this.app.metadataCache.getFirstLinkpathDest(this.hover.linkText, this.hover.sourcePath);
            if (!file) return;
            if (file.extension !== "puml" && file.extension !== "pu") return;

            const fileContent = await this.app.vault.read(file);
            const imgDiv = createDiv();
            if(this.settings.defaultProcessor === "png") {
                await this.getProcessor().png(fileContent, imgDiv, null);
            }else {
                await this.getProcessor().svg(fileContent, imgDiv, null);
            }

            const node: Node = mutation[0].addedNodes[0];
            node.empty();

            const div = createDiv("", async (element) => {
                element.appendChild(imgDiv);
                element.setAttribute('src', file.path);
                element.onClickEvent((event => {
                    event.stopImmediatePropagation();
                    const leaf = this.app.workspace.getLeaf(event.ctrlKey);
                    leaf.setViewState({
                        type: VIEW_TYPE,
                        state: {file: file.path}
                    })
                }));
            });
            node.appendChild(div);

        });

        this.registerEvent(this.app.workspace.on("hover-link", async (event: any) => {
            const linkText: string = event.linktext;
            if (!linkText) return;
            const sourcePath: string = event.sourcePath;

            if (!linkText.endsWith(".puml") && !linkText.endsWith(".pu")) {
                return;
            }

            this.hover.linkText = linkText;
            this.hover.sourcePath = sourcePath;
        }));

        this.observer.observe(document, {childList: true, subtree: true});

        //embed handling
        this.registerMarkdownPostProcessor(async (element, context) => {
            const embeddedItems = element.querySelectorAll(".internal-embed");
            if (embeddedItems.length === 0) {
                return;
            }

            for (const key in embeddedItems) {
                const item = embeddedItems[key];
                if (typeof item.getAttribute !== "function") return;

                const filename = item.getAttribute("src");
                const file = this.app.metadataCache.getFirstLinkpathDest(filename.split("#")[0], context.sourcePath);
                if (file && file instanceof TFile && (file.extension === "puml" || file.extension === "pu")) {
                    const fileContent = await this.app.vault.read(file);

                    const div = createDiv();
                    if(this.settings.defaultProcessor === "png") {
                        await this.getProcessor().png(fileContent, div, context);
                    }else {
                        await this.getProcessor().svg(fileContent, div, context);
                    }

                    item.parentElement.replaceChild(div, item);
                }
            }

        });
    }
Example #2
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 #3
Source File: main.ts    From obsidian_supercharged_links with MIT License 4 votes vote down vote up
async onload(): Promise<void> {
		console.log('Supercharged links loaded');
		await this.loadSettings();


		this.settings.presetFields.forEach(prop => {
			const property = new Field()
			Object.assign(property, prop)
			this.initialProperties.push(property)
		})
		this.addSettingTab(new SuperchargedLinksSettingTab(this.app, this));
		this.registerMarkdownPostProcessor((el, ctx) => {
			updateElLinks(this.app, this, el, ctx)
		});

		// Plugins watching
		this.registerEvent(this.app.metadataCache.on('changed', debounce((_file) => {
			updateVisibleLinks(this.app, this);
			this.observers.forEach(([observer, type, own_class ]) => {
				const leaves = this.app.workspace.getLeavesOfType(type);
				leaves.forEach(leaf => {
					this.updateContainer(leaf.view.containerEl, this, own_class);
				})
			});
			// Debounced to prevent lag when writing
		}, 4500, true)));


		// Live preview
		const ext = Prec.lowest(buildCMViewPlugin(this.app, this.settings));
		this.registerEditorExtension(ext);

		this.observers = [];

		this.app.workspace.onLayoutReady(() => {
			this.initViewObservers(this);
			this.initModalObservers(this);
		});
		this.registerEvent(this.app.workspace.on("layout-change", () => this.initViewObservers(this)));

		this.addCommand({
			id: "field_options",
			name: "field options",
			hotkeys: [
				{
					modifiers: ["Alt"],
					key: 'O',
				},
			],
			callback: () => {
				const leaf = this.app.workspace.activeLeaf
				if (leaf.view instanceof MarkdownView && leaf.view.file) {
					const fieldsOptionsModal = new NoteFieldsCommandsModal(this.app, this, leaf.view.file)
					fieldsOptionsModal.open()
				}
			},
		});

		/* TODO : add a context menu for fileClass files to show the same options as in FileClassAttributeSelectModal*/
		this.addCommand({
			id: "fileClassAttr_options",
			name: "fileClass attributes options",
			hotkeys: [
				{
					modifiers: ["Alt"],
					key: 'P',
				},
			],
			callback: () => {
				const leaf = this.app.workspace.activeLeaf
				if (leaf.view instanceof MarkdownView && leaf.view.file && `${leaf.view.file.parent.path}/` == this.settings.classFilesPath) {
					const modal = new FileClassAttributeSelectModal(this, leaf.view.file)
					modal.open()
				} else {
					const notice = new Notice("This is not a fileClass", 2500)
				}
			},
		});

		new linkContextMenu(this)
	}
Example #4
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 #5
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} />
    </>
  );
}