Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions plugins/macro/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
{
Expand Down Expand Up @@ -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,
],
Expand Down
73 changes: 73 additions & 0 deletions plugins/macro/src/macro/aceLoader.ts
Original file line number Diff line number Diff line change
@@ -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<AceApi> | 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<AceApi> {
const existing = currentAce();
if (existing) {
return Promise.resolve().then(() => configure(existing));
}
if (pending) return pending;

pending = new Promise<AceApi>((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;
}
14 changes: 14 additions & 0 deletions plugins/macro/src/macro/macro.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
137 changes: 109 additions & 28 deletions plugins/macro/src/macro/macroEditor.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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";
Expand Down Expand Up @@ -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,
Expand All @@ -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<void> {
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() {
Expand All @@ -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,
},
{
Expand All @@ -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),
}),
Expand All @@ -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,
),
);
}
Expand All @@ -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?.();
}
Expand Down
Loading
Loading