Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(codemirror/autocomplete): coexist with snippets
Elian Doran5c1861b61a0f
diff --git a/apps/client/src/widgets/type_widgets/code/Code.tsx b/apps/client/src/widgets/type_widgets/code/Code.tsxindex 3daab634db..c327a63f1c 100644--- a/apps/client/src/widgets/type_widgets/code/Code.tsx+++ b/apps/client/src/widgets/type_widgets/code/Code.tsx@@ -1,6 +1,6 @@import "./code.css";-import { default as VanillaCodeMirror, getThemeById, isScriptMime } from "@triliumnext/codemirror";+import { default as VanillaCodeMirror, getThemeById } from "@triliumnext/codemirror";import { NoteType } from "@triliumnext/commons";import { Ref } from "preact";import { useCallback, useEffect, useRef, useState } from "preact/hooks";@@ -130,14 +130,14 @@ export function EditableCode({ note, ntxId, noteContext, debounceUpdate, parentCuseKeyboardShortcuts("code-detail", containerRef, parentComponent, ntxId);// Code snippets (#snippet notes with a matching MIME) as `/snippet:<name>` slash commands.- // Disabled for Markdown notes, whose editor provides its own combined slash-command menu, and- // for backend/frontend script notes, where the TypeScript language service owns the editor's- // single autocompletion (CodeMirror allows only one `override` completion config per editor).+ // Disabled for Markdown notes, whose editor provides its own combined slash-command menu. On+ // script notes the snippet source co-exists with the TypeScript language service's source via+ // the editor's shared completion-source registry.useSnippetSlashCommands(editorView,(candidate) => candidate.type === "code" && (candidate.mime === note.mime || candidate.mime === "text/plain"),note.mime,- !note.isMarkdown() && !isScriptMime(note.mime),+ !note.isMarkdown(),note.noteId);diff --git a/apps/client/src/widgets/type_widgets/code/snippets.ts b/apps/client/src/widgets/type_widgets/code/snippets.tsindex f5aed94391..64a2317663 100644--- a/apps/client/src/widgets/type_widgets/code/snippets.ts+++ b/apps/client/src/widgets/type_widgets/code/snippets.ts@@ -1,4 +1,4 @@-import { autocompletion, type Completion, type CompletionContext } from "@codemirror/autocomplete";+import { type Completion, type CompletionContext, type CompletionSource } from "@codemirror/autocomplete";import type { EditorView } from "@codemirror/view";import type VanillaCodeMirror from "@triliumnext/codemirror";import { useCallback, useEffect, useRef } from "preact/hooks";@@ -135,22 +135,33 @@ export function useSnippetSlashCommands(editorView: VanillaCodeMirror | null, mauseEffect(() => { currentNoteIdRef.current = currentNoteId; });useEffect(() => {- if (!editorView || !enabled) return;-- const extension = autocompletion({- override: [(context: CompletionContext) => {- const match = context.matchBefore(SLASH_COMMAND_REGEX);- if (!match) return null;- const options = buildSnippetCompletions(- snippetsRef.current.filter((snippet) => snippet.noteId !== currentNoteIdRef.current)- );- // No matching snippets (e.g. none for this MIME, or only the current note) → no source,- // so an empty completion popup never appears when the user types "/".- return options.length ? { from: match.from, options } : null;- }],- activateOnTyping: true- });+ if (!editorView) return;+ if (!enabled) {+ editorView.setCompletionSource("snippets", null);+ return;+ }- editorView.setNamedExtension("snippetCommands", extension);+ // Contribute the snippet `/snippet:` source to the editor's shared+ // autocompletion. Registering a source (rather than a whole+ // autocompletion) lets it co-exist with other sources — e.g. the+ // TypeScript language service on backend/frontend script notes.+ const source: CompletionSource = (context: CompletionContext) => {+ const match = context.matchBefore(SLASH_COMMAND_REGEX);+ if (!match) return null;+ const options = buildSnippetCompletions(+ snippetsRef.current.filter((snippet) => snippet.noteId !== currentNoteIdRef.current)+ );+ // No matching snippets (e.g. none for this MIME, or only the current note) → no source,+ // so an empty completion popup never appears when the user types "/".+ return options.length ? { from: match.from, options } : null;+ };++ // `setCompletionSource` types its argument via the codemirror package's own copy of+ // @codemirror/autocomplete. Under TypeScript project references that is a distinct type+ // identity from the client's copy, even though it is the same package at runtime, so bridge+ // the two here. (CodeMirror requires a single physical @codemirror/state, which holds.)+ type CmCompletionSource = Parameters<VanillaCodeMirror["setCompletionSource"]>[1];+ editorView.setCompletionSource("snippets", source as unknown as CmCompletionSource);+ return () => editorView.setCompletionSource("snippets", null);}, [editorView, enabled]);}\ No newline at end of filediff --git a/packages/codemirror/package.json b/packages/codemirror/package.jsonindex 31406e433b..6b49cf3d9a 100644--- a/packages/codemirror/package.json+++ b/packages/codemirror/package.json@@ -17,8 +17,8 @@"@codemirror/lang-vue": "0.1.3","@codemirror/lang-xml": "6.1.0","@codemirror/legacy-modes": "6.5.3",- "@codemirror/autocomplete": "6.18.6",- "@codemirror/lint": "6.8.5",+ "@codemirror/autocomplete": "6.20.2",+ "@codemirror/lint": "6.9.6","@codemirror/search": "6.7.0","@codemirror/state": "6.6.0","@codemirror/view": "6.42.1",diff --git a/packages/codemirror/src/index.ts b/packages/codemirror/src/index.tsindex d222e23c4b..0f6c535c97 100644--- a/packages/codemirror/src/index.ts+++ b/packages/codemirror/src/index.ts@@ -3,6 +3,7 @@ import { EditorView, highlightActiveLine, keymap, lineNumbers, placeholder, Viewimport { defaultHighlightStyle, StreamLanguage, syntaxHighlighting, indentUnit, bracketMatching, foldGutter, codeFolding } from "@codemirror/language";import { Compartment, EditorSelection, EditorState, StateEffect, type Extension } from "@codemirror/state";import { highlightSelectionMatches } from "@codemirror/search";+import { autocompletion, type CompletionSource } from "@codemirror/autocomplete";import { vim } from "@replit/codemirror-vim";import { indentationMarkers } from "@replit/codemirror-indentation-markers";import byMimeType from "./syntax_highlighting.js";@@ -57,8 +58,11 @@ export default class CodeMirror extends EditorView {private indentUnitCompartment: Compartment;private searchHighlightCompartment: Compartment;private typeCompletionCompartment: Compartment;+ private completionSourceCompartment: Compartment;private searchPlugin?: SearchHighlighter | null;private namedCompartments = new Map<string, Compartment>();+ /** Named completion sources aggregated into the editor's single autocompletion. */+ private completionSources = new Map<string, CompletionSource>();/** Monotonic token guarding against out-of-order async type-completion updates. */private typeCompletionToken = 0;@@ -70,6 +74,7 @@ export default class CodeMirror extends EditorView {const indentUnitCompartment = new Compartment();const searchHighlightCompartment = new Compartment();const typeCompletionCompartment = new Compartment();+ const completionSourceCompartment = new Compartment();let extensions: Extension[] = [];@@ -84,6 +89,7 @@ export default class CodeMirror extends EditorView {searchMatchHighlightTheme,searchHighlightCompartment.of([]),typeCompletionCompartment.of([]),+ completionSourceCompartment.of([]),highlightActiveLine(),lineNumbers(),themeCompartment.of([@@ -143,6 +149,7 @@ export default class CodeMirror extends EditorView {this.indentUnitCompartment = indentUnitCompartment;this.searchHighlightCompartment = searchHighlightCompartment;this.typeCompletionCompartment = typeCompletionCompartment;+ this.completionSourceCompartment = completionSourceCompartment;}#onDocumentUpdated(v: ViewUpdate) {@@ -335,12 +342,36 @@ export default class CodeMirror extends EditorView {*/async #updateTypeCompletion(mime: string) {const token = ++this.typeCompletionToken;- const extensions = await buildTypeCompletion(mime);+ const { extensions, source } = await buildTypeCompletion(mime);if (token !== this.typeCompletionToken) {return; // a newer setMimeType call superseded this one}this.dispatch({effects: this.typeCompletionCompartment.reconfigure(extensions)});+ this.setCompletionSource("typescript", source);+ }++ /**+ * Registers (or, with `null`, removes) a named autocompletion source. All+ * registered sources are merged into the editor's single `autocompletion()`+ * extension — CodeMirror permits only one `override` config per editor, so+ * features (snippets, the TypeScript language service, …) contribute sources+ * here rather than each adding their own autocompletion.+ */+ setCompletionSource(name: string, source: CompletionSource | null) {+ if (source) {+ this.completionSources.set(name, source);+ } else {+ this.completionSources.delete(name);+ }+ const sources = [...this.completionSources.values()];+ this.dispatch({+ effects: this.completionSourceCompartment.reconfigure(+ sources.length+ ? autocompletion({ override: sources, activateOnTyping: true })+ : []+ )+ });}}diff --git a/packages/codemirror/src/type_completion/index.ts b/packages/codemirror/src/type_completion/index.tsindex 86c8c06b2e..44b6ee9d9a 100644--- a/packages/codemirror/src/type_completion/index.ts+++ b/packages/codemirror/src/type_completion/index.ts@@ -1,4 +1,4 @@-import { autocompletion } from "@codemirror/autocomplete";+import type { CompletionSource } from "@codemirror/autocomplete";import type { Extension } from "@codemirror/state";import backendApiDts from "./backend_api.js";@@ -87,24 +87,36 @@ async function createEnv(mime: string) {);}+export interface TypeCompletion {+ /** Editor extensions wiring the TypeScript environment (sync, lint, hover). */+ extensions: Extension[];+ /** Autocompletion source for the editor's shared `autocompletion()`, or null. */+ source: CompletionSource | null;+}+/**- * Builds the set of CodeMirror extensions that wire the TypeScript language- * service into the editor for the given script MIME type. Returns an empty- * array (no completion) for non-script MIME types.+ * Wires the TypeScript language service into the editor for the given script+ * MIME type. The completion `source` is returned separately (rather than as its+ * own `autocompletion()` extension) so it can be merged with other sources —+ * e.g. snippet slash-commands — into the editor's single autocompletion.+ *+ * Returns empty extensions and a null source for non-script MIME types.*/-export async function buildTypeCompletion(mime: string): Promise<Extension[]> {+export async function buildTypeCompletion(mime: string): Promise<TypeCompletion> {if (!isScriptMime(mime)) {- return [];+ return { extensions: [], source: null };}const env = await createEnv(mime);const { tsFacet, tsSync, tsAutocomplete, tsLinter, tsHover } = await import("@valtown/codemirror-ts");- return [- tsFacet.of({ env, path: SCRIPT_PATH }),- tsSync(),- tsLinter(),- autocompletion({ override: [tsAutocomplete()] }),- tsHover()- ];+ return {+ extensions: [+ tsFacet.of({ env, path: SCRIPT_PATH }),+ tsSync(),+ tsLinter(),+ tsHover()+ ],+ source: tsAutocomplete()+ };}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 47e2ff73a9..3c81444f3a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -6,6 +6,8 @@ settings:overrides:'@codemirror/language': 6.12.3+ '@codemirror/autocomplete': 6.20.2+ '@codemirror/lint': 6.9.6'@lezer/highlight': 1.2.3'@lezer/common': 1.5.2mermaid: 11.15.0@@ -1356,8 +1358,8 @@ importers:specifier: 1.0.3version: 1.0.3'@codemirror/autocomplete':- specifier: 6.18.6- version: 6.18.6+ specifier: 6.20.2+ version: 6.20.2'@codemirror/commands':specifier: 6.10.3version: 6.10.3@@ -1392,8 +1394,8 @@ importers:specifier: 6.5.3version: 6.5.3'@codemirror/lint':- specifier: 6.8.5- version: 6.8.5+ specifier: 6.9.6+ version: 6.9.6'@codemirror/search':specifier: 6.7.0version: 6.7.0@@ -1495,7 +1497,7 @@ importers:version: 6.5.3(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])'@replit/codemirror-lang-nix':specifier: 6.0.1- version: 6.0.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])+ version: 6.0.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])'@replit/codemirror-vim':specifier: 6.3.0version: 6.3.0(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])@@ -1513,7 +1515,7 @@ importers:version: 1.6.1([email protected])'@valtown/codemirror-ts':specifier: 2.3.1- version: 2.3.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])+ version: 2.3.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])codemirror-lang-elixir:specifier: 4.0.1version: 4.0.1@@ -2266,9 +2268,6 @@ packages:peerDependencies:vite: 4.x || 5.x || 6.x- '@codemirror/[email protected]':- resolution: {integrity: sha512-PHHBXFomUs5DF+9tCOM/UoW6XQ4R44lLNNhRaW9PKPTU0D7lIjRg3ElxaJnTwsl/oHiR93WSXDBrekhoUGCPtg==}-'@codemirror/[email protected]':resolution: {integrity: sha512-G5FPkgIiLjOgZMjqVjvuKQ1rGPtHogLldJr33eFJdVLtmwY+giGrlv/ewljLz6b9BSQLkjxuwBc6g6omDM+YxQ==}@@ -2353,9 +2352,6 @@ packages:'@codemirror/[email protected]':resolution: {integrity: sha512-xCsmIzH78MyWkib9jlPaaun57XNkfbMIhagfaZVd0iLTqlpw3jXaIcbZm72MTmmn64eTZpBVNjbyYh+QXnxRsg==}- '@codemirror/[email protected]':- resolution: {integrity: sha512-s3n3KisH7dx3vsoeGMxsbRAgKe4O1vbrnKBClm99PU0fWxmxsx5rR2PfqQgIt+2MMJBHbiJ5rfIdLYfB9NNvsA==}-'@codemirror/[email protected]':resolution: {integrity: sha512-6Kp7r6XfCi/D/5sdXieMfg9pJU1bUEx96WITuLU6ESaKizCz0QHFMjY/TaFSbigDdEAIgi93itLBIUETP4oK+A==}@@ -4952,7 +4948,7 @@ packages:'@replit/[email protected]':resolution: {integrity: sha512-lvzjoYn9nfJzBD5qdm3Ut6G3+Or2wEacYIDJ49h9+19WSChVnxv4ojf+rNmQ78ncuxIt/bfbMvDLMeMP0xze6g==}peerDependencies:- '@codemirror/autocomplete': ^6.0.0+ '@codemirror/autocomplete': 6.20.2'@codemirror/language': 6.12.3'@codemirror/state': ^6.0.0'@codemirror/view': ^6.0.0@@ -6317,8 +6313,8 @@ packages:'@valtown/[email protected]':resolution: {integrity: sha512-v5XiI4WA+bUy0XDgkrqZksqBWgIUeyLZuC94Px/rhXBph8ASmVXaimlGDtt0vH/9t8aDdIZYdr59r9H3oKMFOg==}peerDependencies:- '@codemirror/autocomplete': ^6- '@codemirror/lint': ^6+ '@codemirror/autocomplete': 6.20.2+ '@codemirror/lint': 6.9.6'@codemirror/state': ^6'@codemirror/view': ^6@@ -14970,13 +14966,6 @@ snapshots:unplugin: 1.16.1vite: 8.0.14(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- '@codemirror/[email protected]':- dependencies:- '@codemirror/language': 6.12.3- '@codemirror/state': 6.6.0- '@codemirror/view': 6.42.1- '@lezer/common': 1.5.2-'@codemirror/[email protected]':dependencies:'@codemirror/language': 6.12.3@@ -15222,12 +15211,6 @@ snapshots:dependencies:'@codemirror/language': 6.12.3- '@codemirror/[email protected]':- dependencies:- '@codemirror/state': 6.6.0- '@codemirror/view': 6.42.1- crelt: 1.0.6-'@codemirror/[email protected]':dependencies:'@codemirror/state': 6.6.0@@ -18139,9 +18122,9 @@ snapshots:'@codemirror/state': 6.6.0'@codemirror/view': 6.42.1- '@replit/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])':+ '@replit/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])':dependencies:- '@codemirror/autocomplete': 6.18.6+ '@codemirror/autocomplete': 6.20.2'@codemirror/language': 6.12.3'@codemirror/state': 6.6.0'@codemirror/view': 6.42.1@@ -20412,10 +20395,10 @@ snapshots:d3-selection: 3.0.0d3-transition: 3.0.1([email protected])- '@valtown/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])':+ '@valtown/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])':dependencies:- '@codemirror/autocomplete': 6.18.6- '@codemirror/lint': 6.8.5+ '@codemirror/autocomplete': 6.20.2+ '@codemirror/lint': 6.9.6'@codemirror/state': 6.6.0'@codemirror/view': 6.42.1diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 9b4452d39c..c99ab4866c 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -16,6 +16,8 @@ pmOnFail: ignoreoverrides:"@codemirror/language": "6.12.3"+ "@codemirror/autocomplete": "6.20.2"+ "@codemirror/lint": "6.9.6""@lezer/highlight": "1.2.3""@lezer/common": "1.5.2""mermaid": "11.15.0"