Skip to content

Build your personal knowledge base with Trilium Notes

perf(codemirror): build a script note's type completion once

Elian Doran2bc2c305e351
diff --git a/packages/codemirror/src/index.spec.ts b/packages/codemirror/src/index.spec.ts
index d3303a0467..0d3f3ac44a 100644
--- a/packages/codemirror/src/index.spec.ts
+++ b/packages/codemirror/src/index.spec.ts
@@ -4,13 +4,21 @@ import { EditorSelection, EditorState, StateEffect } from "@codemirror/state";
import { EditorView, showTooltip, type ViewUpdate } from "@codemirror/view";
import { afterEach, describe, expect, it, vi } from "vitest";
+vi.mock("./type_completion/index.js", async (importOriginal) => {
+ const original = await importOriginal<typeof import("./type_completion/index.js")>();
+ return { ...original, buildTypeCompletion: vi.fn(original.buildTypeCompletion) };
+});
+
import CodeMirror, { type EditorConfig, getThemeById } from "./index.js";
+import { buildTypeCompletion } from "./type_completion/index.js";
let editor: CodeMirror | undefined;
afterEach(() => {
editor?.destroy();
editor = undefined;
+ // Back to the real build, which `vi.fn()` was given.
+ vi.mocked(buildTypeCompletion).mockReset();
});
describe("CodeMirror", () => {
@@ -596,6 +604,25 @@ describe("CodeMirror", () => {
await editor.setScriptApiContext({ customRequestHandler: true });
expect(editor.getText()).toBe("");
});
+
+ it("builds the completion once while the MIME type and context stay the same", async () => {
+ const buildMock = vi.mocked(buildTypeCompletion);
+ buildMock.mockResolvedValue({ extensions: [], source: null });
+ editor = build();
+
+ // What a code note's effects request on mount.
+ await Promise.all([
+ editor.setMimeType("text/jsx"),
+ editor.setMimeType("text/jsx"),
+ editor.setScriptApiContext({ customRequestHandler: false, bulkActionNote: false }),
+ editor.setMimeType("text/jsx")
+ ]);
+ expect(buildMock).toHaveBeenCalledOnce();
+
+ await editor.setScriptApiContext({ customRequestHandler: true, bulkActionNote: false });
+ await editor.setMimeType("text/css");
+ expect(buildMock).toHaveBeenCalledTimes(3);
+ });
});
describe("concurrent MIME changes", () => {
diff --git a/packages/codemirror/src/index.ts b/packages/codemirror/src/index.ts
index 5d74bc91a2..75281e8715 100644
--- a/packages/codemirror/src/index.ts
+++ b/packages/codemirror/src/index.ts
@@ -105,6 +105,8 @@ export default class CodeMirror extends EditorView {
private completionSources = new Map<string, CompletionSource>();
/** Monotonic token guarding against out-of-order async type-completion updates. */
private typeCompletionToken = 0;
+ /** The latest type-completion build, which a request for the same MIME type and context joins. */
+ private typeCompletionBuild: { key: string; done: Promise<void> } | null = null;
/** Current MIME type, retained so the type completion can be rebuilt when only the api context changes. */
private currentMime: string | null = null;
/** Per-note context tuning the script `api` surface (e.g. custom-request-handler members). */
@@ -506,10 +508,27 @@ export default class CodeMirror extends EditorView {
/**
* Enables the TypeScript language service (full completion, hover docs and
* diagnostics) for backend/frontend script notes, and clears it otherwise.
- * Guarded by a token so a slow async build for a previous MIME type can't
- * overwrite a newer one.
+ * A request for the MIME type and context of the latest build joins that build,
+ * since a code note's effects request the same one several times on mount.
*/
- async #updateTypeCompletion(mime: string) {
+ #updateTypeCompletion(mime: string) {
+ const key = typeCompletionKey(mime, this.scriptApiContext);
+ if (this.typeCompletionBuild?.key === key) {
+ return this.typeCompletionBuild.done;
+ }
+
+ const done = this.#buildTypeCompletion(mime);
+ const build = { key, done };
+ this.typeCompletionBuild = build;
+ // A failed build is not reused, so the next request tries again.
+ done.catch(() => {
+ if (this.typeCompletionBuild === build) this.typeCompletionBuild = null;
+ });
+ return done;
+ }
+
+ /** Guarded by a token so a slow build for a previous MIME type can't overwrite a newer one. */
+ async #buildTypeCompletion(mime: string) {
const token = ++this.typeCompletionToken;
const { extensions, source } = await buildTypeCompletion(mime, this.scriptApiContext);
if (token !== this.typeCompletionToken) {
@@ -545,6 +564,15 @@ export default class CodeMirror extends EditorView {
}
}
+/** Identifies a type-completion build by its MIME type and the context flags that are set. */
+function typeCompletionKey(mime: string, context: ScriptApiContext) {
+ const flags = Object.entries(context)
+ .filter(([ , value ]) => value)
+ .map(([ name ]) => name)
+ .sort();
+ return [ mime, ...flags ].join(" ");
+}
+
/**
* Returns the body-level element CodeMirror renders tooltips into, outside `.cm-editor`, whose
* `overflow: hidden` clips an absolutely positioned tooltip (Safari, iOS).