diff --git a/plugins/macro/src/index.ts b/plugins/macro/src/index.ts index 6275050..0de56da 100644 --- a/plugins/macro/src/index.ts +++ b/plugins/macro/src/index.ts @@ -43,6 +43,10 @@ const MacroPlugin: Plugin = { "macro.editor.emptyCode": "Macro code is empty", "macro.editor.executed": "Macro executed successfully", "macro.editor.error": "Execution error: ", + "macro.editor.loading": "Loading syntax editor. You can keep editing.", + "macro.editor.loadFailed": "Syntax editor could not load. You can still edit, run and save.", + "macro.editor.retry": "Retry syntax editor", + "macro.editor.useRich": "Use syntax editor", }, } as any, { @@ -70,6 +74,10 @@ const MacroPlugin: Plugin = { "macro.editor.emptyCode": "宏代码不能为空", "macro.editor.executed": "宏执行成功", "macro.editor.error": "执行错误: ", + "macro.editor.loading": "正在加载语法编辑器,您仍可继续编辑。", + "macro.editor.loadFailed": "无法加载语法编辑器,您仍可编辑、运行和保存。", + "macro.editor.retry": "重试语法编辑器", + "macro.editor.useRich": "使用语法编辑器", }, } as any, ], diff --git a/plugins/macro/src/macro/aceLoader.ts b/plugins/macro/src/macro/aceLoader.ts new file mode 100644 index 0000000..136f616 --- /dev/null +++ b/plugins/macro/src/macro/aceLoader.ts @@ -0,0 +1,73 @@ +// Part of the Chili3d Project, under the AGPL-3.0 License. +// See LICENSE file in the project root for full license information. + +const ACE_VERSION = "1.44.0"; +const ACE_BASE = `https://cdn.jsdelivr.net/npm/ace-builds@${ACE_VERSION}/src-min-noconflict`; + +export interface AceEditor { + getValue(): string; + setTheme(theme: string): void; + destroy(): void; + focus(): void; +} + +export interface AceApi { + version: string; + config: { set(key: string, value: string): void }; + edit(element: HTMLElement, options: { mode: string; selectionStyle: string }): AceEditor; +} + +let pending: Promise | undefined; + +function currentAce(): AceApi | undefined { + return (globalThis as typeof globalThis & { ace?: AceApi }).ace; +} + +function configure(ace: AceApi): AceApi { + if ( + ace.version !== ACE_VERSION || + typeof ace.edit !== "function" || + typeof ace.config?.set !== "function" + ) { + throw new Error("A different or incomplete syntax editor is already loaded."); + } + ace.config.set("basePath", ACE_BASE); + return ace; +} + +export function loadAce(): Promise { + const existing = currentAce(); + if (existing) { + return Promise.resolve().then(() => configure(existing)); + } + if (pending) return pending; + + pending = new Promise((resolve, reject) => { + const script = document.createElement("script"); + script.src = `${ACE_BASE}/ace.js`; + script.async = true; + script.crossOrigin = "anonymous"; + script.onload = () => { + script.onload = null; + script.onerror = null; + try { + const ace = currentAce(); + if (!ace) throw new Error("The syntax editor did not initialize."); + resolve(configure(ace)); + } catch (error) { + script.remove(); + reject(error); + } + }; + script.onerror = () => { + script.onload = null; + script.onerror = null; + script.remove(); + reject(new Error("The syntax editor could not be downloaded.")); + }; + document.head.appendChild(script); + }).finally(() => { + pending = undefined; + }); + return pending; +} diff --git a/plugins/macro/src/macro/macro.module.css b/plugins/macro/src/macro/macro.module.css index 064928c..641b0f6 100644 --- a/plugins/macro/src/macro/macro.module.css +++ b/plugins/macro/src/macro/macro.module.css @@ -86,9 +86,23 @@ flex-direction: column; gap: 16px; width: 600px; + max-width: calc(100vw - 64px); min-height: 400px; } +.codeInput { + box-sizing: border-box; + width: 100%; + min-height: 300px; + padding: 12px; + resize: vertical; + border: 1px solid var(--border-color); + border-radius: 4px; + background-color: var(--panel-background-color); + color: var(--foreground-color); + font: 13px / 1.5 monospace; +} + .field { display: flex; flex-direction: column; diff --git a/plugins/macro/src/macro/macroEditor.ts b/plugins/macro/src/macro/macroEditor.ts index 2dec4dc..25115aa 100644 --- a/plugins/macro/src/macro/macroEditor.ts +++ b/plugins/macro/src/macro/macroEditor.ts @@ -1,8 +1,6 @@ // Part of the Chili3d Project, under the AGPL-3.0 License. // See LICENSE file in the project root for full license information. -//@ts-expect-error -import ace from "https://cdn.jsdelivr.net/npm/ace-builds@1.44.0/+esm"; import { Config, type DialogButton, @@ -12,7 +10,8 @@ import { Localize, PubSub, } from "@chili3d/core"; -import { div, input, label } from "@chili3d/element"; +import { button, div, input, label, span, textarea } from "@chili3d/element"; +import { type AceApi, type AceEditor, loadAce } from "./aceLoader"; import style from "./macro.module.css"; import { runMacro } from "./macroRunner"; import type { MacroDefinition, MacroStorage } from "./macroStorage"; @@ -48,11 +47,14 @@ export class MacroEditor extends HTMLElement { private macro: MacroDefinition | undefined; private onSaveCallback: (() => void) | undefined; private nameInput: HTMLInputElement | null = null; - private codeTextarea: HTMLDivElement | null = null; - private editor?: { - getValue: () => string; - setTheme: (theme: string) => void; - }; + private codeInput: HTMLTextAreaElement | null = null; + private editorHost: HTMLDivElement | null = null; + private status: HTMLSpanElement | null = null; + private retryButton: HTMLButtonElement | null = null; + private editor?: AceEditor; + private ace?: AceApi; + private generation = 0; + private loading = false; constructor( readonly app: IApplication, @@ -65,25 +67,86 @@ export class MacroEditor extends HTMLElement { this.macro = macro; this.onSaveCallback = onSave; - const dom = this.createDom(macro); - - this.embeddingEditor(); + this.createDom(macro); PubSub.default.pub( "showDialog", (macro ? "macro.editor.titleEdit" : "macro.editor.titleNew") as I18nKeys, - dom, + this, this.buttons(), ); } - private embeddingEditor() { - ace.config.set("basePath", "https://cdn.jsdelivr.net/npm/ace-builds@1.44.0/src-min-noconflict"); - this.editor = ace.edit(this.codeTextarea!, { - mode: "ace/mode/javascript", - selectionStyle: "text", - }); - this.editor?.setTheme(this.isDarkTheme() ? "ace/theme/dracula" : "ace/theme/xcode"); + connectedCallback() { + void this.loadEditor(); + } + + disconnectedCallback() { + this.generation++; + this.loading = false; + if (this.editor && this.codeInput) this.codeInput.value = this.editor.getValue(); + this.editor?.destroy(); + this.editor = undefined; + } + + private getCode(): string { + return this.editor?.getValue() ?? this.codeInput?.value ?? ""; + } + + private async loadEditor(): Promise { + const status = this.status; + const retryButton = this.retryButton; + if (this.loading || this.editor || !this.isConnected || !status || !retryButton) return; + this.loading = true; + const generation = ++this.generation; + status.textContent = I18n.translate("macro.editor.loading" as I18nKeys); + retryButton.hidden = true; + try { + const ace = await loadAce(); + if (!this.isConnected || generation !== this.generation) return; + this.ace = ace; + status.textContent = ""; + if (document.activeElement === this.codeInput) { + retryButton.textContent = I18n.translate("macro.editor.useRich" as I18nKeys); + retryButton.hidden = false; + } else { + this.useEditor(); + } + } catch { + if (!this.isConnected || generation !== this.generation) return; + status.textContent = I18n.translate("macro.editor.loadFailed" as I18nKeys); + retryButton.textContent = I18n.translate("macro.editor.retry" as I18nKeys); + retryButton.hidden = false; + } finally { + if (generation === this.generation) this.loading = false; + } + } + + private useEditor(focus = false) { + const status = this.status; + const retryButton = this.retryButton; + if (!this.ace || !this.isConnected || !this.codeInput || !this.editorHost || !status || !retryButton) + return; + this.editorHost.textContent = this.codeInput.value; + this.editorHost.hidden = false; + try { + this.editor = this.ace.edit(this.editorHost, { + mode: "ace/mode/javascript", + selectionStyle: "text", + }); + this.editor.setTheme(this.isDarkTheme() ? "ace/theme/dracula" : "ace/theme/xcode"); + this.codeInput.hidden = true; + retryButton.hidden = true; + if (focus) this.editor.focus(); + } catch { + this.editor?.destroy(); + this.editor = undefined; + this.editorHost.hidden = true; + status.textContent = I18n.translate("macro.editor.loadFailed" as I18nKeys); + retryButton.textContent = I18n.translate("macro.editor.retry" as I18nKeys); + retryButton.hidden = false; + this.ace = undefined; + } } private isDarkTheme() { @@ -103,7 +166,7 @@ export class MacroEditor extends HTMLElement { return [ { content: "macro.editor.run" as I18nKeys, - onclick: async () => await runMacro(this.app, this.editor?.getValue() ?? ""), + onclick: async () => await runMacro(this.app, this.getCode()), shouldClose: () => false, }, { @@ -119,27 +182,41 @@ export class MacroEditor extends HTMLElement { private createDom(macro: MacroDefinition | undefined) { this.nameInput = input({ + id: "macro-editor-name", className: style.input, value: macro?.name ?? "", placeholder: I18n.translate("macro.editor.namePlaceholder" as I18nKeys), }); - this.codeTextarea = div({ - id: "macro-editor-code", - className: style.codeEditor, - textContent: macro?.code ?? DefaultCode, + this.codeInput = textarea({ + id: "macro-editor-code-input", + className: style.codeInput, + value: macro?.code ?? DefaultCode, + spellcheck: false, onkeydown: (e) => { if (e.key === "Enter") { e.stopPropagation(); } }, }); + this.editorHost = div({ id: "macro-editor-code", className: style.codeEditor, hidden: true }); + this.status = span({ role: "status" }); + this.retryButton = button({ + type: "button", + className: style.actionButton, + hidden: true, + onclick: () => { + if (this.ace) this.useEditor(true); + else void this.loadEditor(); + }, + }); - return div( - { className: style.editorContainer }, + this.className = style.editorContainer; + this.replaceChildren( div( { className: style.field }, label({ + htmlFor: "macro-editor-name", className: style.inputLabel, textContent: new Localize("macro.editor.name" as I18nKeys), }), @@ -148,10 +225,14 @@ export class MacroEditor extends HTMLElement { div( { className: style.field }, label({ + htmlFor: "macro-editor-code-input", className: style.inputLabel, textContent: new Localize("macro.editor.code" as I18nKeys), }), - this.codeTextarea, + this.codeInput, + this.editorHost, + this.status, + this.retryButton, ), ); } @@ -163,7 +244,7 @@ export class MacroEditor extends HTMLElement { return; } - const code = this.editor?.getValue() ?? ""; + const code = this.getCode(); await this.storage.saveMacro(name, code, this.macro?.id); this.onSaveCallback?.(); } diff --git a/plugins/macro/test/aceLoader.test.ts b/plugins/macro/test/aceLoader.test.ts new file mode 100644 index 0000000..553aa80 --- /dev/null +++ b/plugins/macro/test/aceLoader.test.ts @@ -0,0 +1,89 @@ +// Part of the Chili3d Project, under the AGPL-3.0 License. +// See LICENSE file in the project root for full license information. + +import { afterEach, beforeEach, describe, expect, rs, test } from "@rstest/core"; +import type { AceApi } from "../src/macro/aceLoader"; + +describe("Optional Ace delivery", () => { + let scripts: HTMLScriptElement[]; + let previous: unknown; + const scope = globalThis as typeof globalThis & { ace?: unknown }; + + beforeEach(() => { + rs.resetModules(); + scripts = []; + previous = scope.ace; + delete scope.ace; + rs.spyOn(document.head, "appendChild").mockImplementation((node: T): T => { + scripts.push(node as unknown as HTMLScriptElement); + return node; + }); + }); + + afterEach(() => { + if (previous === undefined) delete scope.ace; + else scope.ace = previous; + rs.restoreAllMocks(); + }); + + function api(): AceApi { + return { + version: "1.44.0", + config: { set: rs.fn((_key: string, _value: string) => undefined) }, + edit: rs.fn(() => ({ + getValue: () => "", + setTheme: rs.fn((_theme: string) => undefined), + destroy: rs.fn(), + focus: rs.fn(), + })), + }; + } + + test("imports alone fetch nothing; concurrent requests share one pinned library", async () => { + const { loadAce } = await import("../src/macro/aceLoader"); + expect(scripts).toHaveLength(0); + const one = loadAce(); + const two = loadAce(); + expect(two).toBe(one); + expect(scripts).toHaveLength(1); + expect(scripts[0].src).toBe( + "https://cdn.jsdelivr.net/npm/ace-builds@1.44.0/src-min-noconflict/ace.js", + ); + const ace = api(); + scope.ace = ace; + scripts[0].dispatchEvent(new Event("load")); + await expect(one).resolves.toBe(ace); + await expect(two).resolves.toBe(ace); + expect(ace.config.set).toHaveBeenCalledWith( + "basePath", + "https://cdn.jsdelivr.net/npm/ace-builds@1.44.0/src-min-noconflict", + ); + await expect(loadAce()).resolves.toBe(ace); + expect(scripts).toHaveLength(1); + }); + + test("a failed download settles and a retry creates a new request to the same pinned URL", async () => { + const { loadAce } = await import("../src/macro/aceLoader"); + const failed = loadAce(); + expect(scripts).toHaveLength(1); + scripts[0].dispatchEvent(new Event("error")); + await expect(failed).rejects.toThrow("could not be downloaded"); + const retried = loadAce(); + expect(retried).not.toBe(failed); + expect(scripts).toHaveLength(2); + expect(scripts[1].src).toBe(scripts[0].src); + const ace = api(); + scope.ace = ace; + scripts[1].dispatchEvent(new Event("load")); + await expect(retried).resolves.toBe(ace); + }); + + test("a different existing Ace is reported without overwriting that global or fetching another", async () => { + const existing = { ...api(), version: "1.0.0" }; + scope.ace = existing; + const { loadAce } = await import("../src/macro/aceLoader"); + await expect(loadAce()).rejects.toThrow("different or incomplete syntax editor"); + expect(scope.ace).toBe(existing); + expect(scripts).toHaveLength(0); + }); +}); diff --git a/plugins/macro/test/macroEditor.test.ts b/plugins/macro/test/macroEditor.test.ts new file mode 100644 index 0000000..2d93ca6 --- /dev/null +++ b/plugins/macro/test/macroEditor.test.ts @@ -0,0 +1,192 @@ +// Part of the Chili3d Project, under the AGPL-3.0 License. +// See LICENSE file in the project root for full license information. + +import { type DialogButton, PubSub, type PubSubEventMap } from "@chili3d/core"; +import { createMockApplication } from "@chili3d/core/test-utils"; +import { afterEach, beforeEach, describe, expect, rs, test } from "@rstest/core"; +import type { AceApi } from "../src/macro/aceLoader"; +import { MacroEditor } from "../src/macro/macroEditor"; +import type { MacroStorage } from "../src/macro/macroStorage"; + +const control = rs.hoisted(() => ({ load: rs.fn<() => Promise>() })); +rs.mock("../src/macro/aceLoader", () => ({ loadAce: control.load })); +rs.mock("../src/macro/macro.module.css", () => ({ + editorContainer: "editor", + field: "field", + inputLabel: "input-label", + input: "input", + codeInput: "code-input", + codeEditor: "rich-editor", + actionButton: "action", +})); + +describe("Macro editor dependency lifecycle", () => { + let buttons: DialogButton[]; + let resolve: (ace: AceApi) => void; + let editor: MacroEditor; + let richValue: string; + let initialRichCode: string; + const destroyed = rs.fn(); + const focused = rs.fn(); + const saved = rs.fn(async (_name: string, _code: string, _id?: string) => undefined); + const onSave = rs.fn(); + const rich = { + getValue: () => richValue, + setTheme: rs.fn((_theme: string) => undefined), + destroy: destroyed, + focus: focused, + }; + const ace: AceApi = { + version: "1.44.0", + config: { set: rs.fn((_key: string, _value: string) => undefined) }, + edit: rs.fn((host: HTMLElement) => { + initialRichCode = host.textContent ?? ""; + richValue = initialRichCode; + return rich; + }), + }; + const onDialog: PubSubEventMap["showDialog"] = (_title, content, choices) => { + buttons = choices as DialogButton[]; + document.body.appendChild(content); + }; + + beforeEach(() => { + rs.clearAllMocks(); + control.load.mockReset(); + control.load.mockImplementation(() => new Promise((done) => (resolve = done))); + buttons = []; + richValue = ""; + initialRichCode = ""; + PubSub.default.sub("showDialog", onDialog); + editor = new MacroEditor(createMockApplication(), { saveMacro: saved } as unknown as MacroStorage); + }); + + afterEach(() => { + document.body.replaceChildren(); + PubSub.default.remove("showDialog", onDialog); + rs.restoreAllMocks(); + }); + + function open() { + editor.show(undefined, onSave); + expect(editor.isConnected).toBe(true); + expect(buttons).toHaveLength(3); + const code = editor.querySelector("#macro-editor-code-input"); + expect(code).not.toBeNull(); + return code!; + } + + test("registration creates no editor request; the mounted dialog stays editable while loading", () => { + expect(control.load).not.toHaveBeenCalled(); + const code = open(); + expect(control.load).toHaveBeenCalledTimes(1); + code.value = "console.log('typed while loading');"; + expect(code.hidden).toBe(false); + expect(code.disabled).toBe(false); + expect(editor.querySelector('[role="status"]')?.textContent).toContain("macro.editor.loading"); + }); + + test("an element attached before show does not request a library for an absent editor", () => { + document.body.appendChild(editor); + expect(editor.isConnected).toBe(true); + expect(editor.querySelector("textarea")).toBeNull(); + expect(control.load).not.toHaveBeenCalled(); + }); + + test("failure retains edits and retries without recreating the dialog", async () => { + control.load.mockRejectedValueOnce(new Error("offline")); + const code = open(); + code.value = "const unchanged = 7;"; + await rs.waitFor(() => + expect(editor.querySelector('[role="status"]')?.textContent).toContain("loadFailed"), + ); + expect(code.value).toBe("const unchanged = 7;"); + expect(code.hidden).toBe(false); + editor.querySelector("input")!.focus(); + editor.querySelector("button")!.click(); + expect(control.load).toHaveBeenCalledTimes(2); + resolve(ace); + await rs.waitFor(() => expect(code.hidden).toBe(true)); + expect(initialRichCode).toBe("const unchanged = 7;"); + expect(editor.isConnected).toBe(true); + }); + + test("finishing a download does not switch the control underneath someone typing", async () => { + const code = open(); + code.value = "const selected = 12;"; + code.focus(); + resolve(ace); + await rs.waitFor(() => expect(editor.querySelector("button")?.textContent).toContain("useRich")); + expect(code.hidden).toBe(false); + expect(document.activeElement).toBe(code); + expect(ace.edit).not.toHaveBeenCalled(); + editor.querySelector("button")!.click(); + expect(initialRichCode).toBe("const selected = 12;"); + expect(code.hidden).toBe(true); + expect(focused).toHaveBeenCalledTimes(1); + }); + + test("a late download after cancel does not create a rich editor or reattach content", async () => { + const code = open(); + code.value = "const pending = 3;"; + editor.remove(); + resolve(ace); + await rs.waitFor(() => expect(control.load.mock.results[0].value).resolves.toBe(ace)); + expect(ace.edit).not.toHaveBeenCalled(); + expect(editor.isConnected).toBe(false); + expect(code.value).toBe("const pending = 3;"); + }); + + test("close-before-confirm preserves the latest rich text before disposing the editor", async () => { + open(); + editor.querySelector("input")!.value = "Saved macro"; + resolve(ace); + await rs.waitFor(() => expect(ace.edit).toHaveBeenCalledTimes(1)); + richValue = "console.log('latest rich edit');"; + const confirm = buttons.find((button) => button.content === "common.confirm"); + expect(confirm).not.toBeUndefined(); + expect(confirm!.shouldClose!()).toBe(true); + editor.remove(); + expect(destroyed).toHaveBeenCalledTimes(1); + await confirm!.onclick!(); + expect(saved).toHaveBeenCalledWith("Saved macro", "console.log('latest rich edit');", undefined); + expect(onSave).toHaveBeenCalledTimes(1); + }); + + test("close-before-confirm also saves the latest fallback text after a failed download", async () => { + control.load.mockRejectedValueOnce(new Error("offline")); + const code = open(); + editor.querySelector("input")!.value = "Plain macro"; + code.value = "console.log('latest fallback edit');"; + await rs.waitFor(() => + expect(editor.querySelector('[role="status"]')?.textContent).toContain("loadFailed"), + ); + const confirm = buttons.find((button) => button.content === "common.confirm"); + expect(confirm).not.toBeUndefined(); + expect(confirm!.shouldClose!()).toBe(true); + editor.remove(); + await confirm!.onclick!(); + expect(saved).toHaveBeenCalledWith("Plain macro", "console.log('latest fallback edit');", undefined); + expect(destroyed).not.toHaveBeenCalled(); + expect(onSave).toHaveBeenCalledTimes(1); + }); + + test("a closed editor cannot attach or dispose the next editor sharing its pending library", async () => { + const pending = new Promise((done) => (resolve = done)); + control.load.mockReturnValue(pending); + open(); + editor.remove(); + const next = new MacroEditor(createMockApplication(), { + saveMacro: saved, + } as unknown as MacroStorage); + next.show(undefined, onSave); + expect(next.isConnected).toBe(true); + resolve(ace); + await rs.waitFor(() => expect(ace.edit).toHaveBeenCalledTimes(1)); + expect(next.querySelector("textarea")?.hidden).toBe(true); + expect(editor.isConnected).toBe(false); + expect(destroyed).not.toHaveBeenCalled(); + next.remove(); + expect(destroyed).toHaveBeenCalledTimes(1); + }); +});