mirror of
https://github.com/zsviczian/obsidian-excalidraw-plugin.git
synced 2026-12-03 06:43:35 +00:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
da124f019b | ||
|
|
6f1f277ed9 | ||
|
|
d7dd08fad6 | ||
|
|
355d7c2d46 |
No files matched your search
+2
-2
@@ -1737,8 +1737,8 @@ changes elsewhere, including `getViewColorPalette()` since its logic itself
|
||||
was already confirmed correct and unchanged.
|
||||
|
||||
**Done (2026-08-14, session 4): `ExcalidrawAutomate.ts` fully triaged, 57 → 0.**
|
||||
On `master` (the `excalidraw-type-import-fix` PR was merged as #2892 in the
|
||||
interim; `master` is now at `2.27.0-beta.2`). Same methodology, three
|
||||
On `master` after the `excalidraw-type-import-fix` was merged (now at
|
||||
`2.27.0-beta.2`). Same methodology, three
|
||||
clusters:
|
||||
|
||||
1. **Safe, fixed (49 of 57).** `cloneElement()`/`cloneElements()`'s inner
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "obsidian-excalidraw-plugin",
|
||||
"name": "Excalidraw",
|
||||
"version": "2.27.0-beta.7",
|
||||
"version": "2.27.0-beta.8",
|
||||
"minAppVersion": "1.8.7",
|
||||
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
|
||||
"author": "Zsolt Viczian",
|
||||
|
||||
Generated
+4
-4
@@ -13,7 +13,7 @@
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"@radix-ui/number": "^1.1.2",
|
||||
"@zsviczian/colormaster": "^1.2.2",
|
||||
"@zsviczian/excalidraw": "0.18.128",
|
||||
"@zsviczian/excalidraw": "0.18.129",
|
||||
"chroma-js": "^3.1.2",
|
||||
"clsx": "^2.0.0",
|
||||
"es6-promise-pool": "2.5.0",
|
||||
@@ -5254,9 +5254,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@zsviczian/excalidraw": {
|
||||
"version": "0.18.128",
|
||||
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.128.tgz",
|
||||
"integrity": "sha512-qpFAx1mTDoHSWqWbRSDd4wXgejKMZewT1cD0Tn+xMnoVMLedFPpApl19GbubxT3/LN4BTqlQASgUX1IdtO7byA==",
|
||||
"version": "0.18.129",
|
||||
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.129.tgz",
|
||||
"integrity": "sha512-sJMaXs6rpoaPsPVlwJ5EqlvfRrfNk6E5ndNhef/IM9YsUOwb06lLM6BfK5rXk3bLP7ehJzNnoCJCVamBnytHgg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@braintree/sanitize-url": "6.0.2",
|
||||
|
||||
+2
-2
@@ -30,7 +30,7 @@
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"@radix-ui/number": "^1.1.2",
|
||||
"@zsviczian/colormaster": "^1.2.2",
|
||||
"@zsviczian/excalidraw": "0.18.128",
|
||||
"@zsviczian/excalidraw": "0.18.129",
|
||||
"chroma-js": "^3.1.2",
|
||||
"clsx": "^2.0.0",
|
||||
"es6-promise-pool": "2.5.0",
|
||||
@@ -106,4 +106,4 @@
|
||||
"node": ">=22.0.0",
|
||||
"npm": ">=10.0.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
+30
-25
@@ -46,7 +46,6 @@ import {
|
||||
getNewUniqueFilepath,
|
||||
} from "../utils/fileUtils";
|
||||
import {
|
||||
errorlog,
|
||||
isVersionNewerThanOther,
|
||||
versionUpdateCheckTimer,
|
||||
calculateUIModeValue,
|
||||
@@ -675,17 +674,16 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
|
||||
private registerInstallCodeblockProcessor() {
|
||||
const codeblockProcessor = async (source: string, el: HTMLElement) => {
|
||||
//Button next to the "List of available scripts" at the top
|
||||
//In try/catch block because this approach is very error prone, depends on
|
||||
//MarkdownRenderer() and index.md structure, in case these are not as
|
||||
//expected this code will break
|
||||
// The mirrored update button is only available in the Script Library
|
||||
// index layout. Other render contexts do not have the adjacent heading.
|
||||
let button2: HTMLButtonElement = null;
|
||||
try {
|
||||
const link: HTMLElement = el.parentElement.querySelector(
|
||||
`a[href="#${el.previousElementSibling.getAttribute(
|
||||
"data-heading",
|
||||
)}"]`,
|
||||
);
|
||||
const heading = el.previousElementSibling?.getAttribute("data-heading");
|
||||
const link = heading
|
||||
? Array.from(el.parentElement?.querySelectorAll("a") ?? []).find(
|
||||
(anchor) => anchor.getAttribute("href") === `#${heading}`,
|
||||
)
|
||||
: null;
|
||||
if (link?.parentElement) {
|
||||
link.addClass("excalidraw-installCodeBlock-link");
|
||||
button2 = link.parentElement.createEl("button", null, (b) => {
|
||||
b.setText(t("UPDATE_SCRIPT"));
|
||||
@@ -693,12 +691,6 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
setButtonBgColor(b, "success");
|
||||
hideElement(b);
|
||||
});
|
||||
} catch (e: unknown) {
|
||||
errorlog({
|
||||
where: "this.registerInstallCodeblockProcessor",
|
||||
source,
|
||||
error: e,
|
||||
});
|
||||
}
|
||||
|
||||
source = source.trim();
|
||||
@@ -766,6 +758,9 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
keepOriginal: boolean = false,
|
||||
): Promise<TFile> {
|
||||
const data = await this.app.vault.read(file);
|
||||
const hasEmbeddedFiles = Object.keys(
|
||||
(JSON_parse<{ files?: Record<string, unknown> }>(data).files ?? {}),
|
||||
).length > 0;
|
||||
const filename =
|
||||
file.name.substring(0, file.name.lastIndexOf(".excalidraw")) +
|
||||
(replaceExtension ? ".md" : ".excalidraw.md");
|
||||
@@ -775,11 +770,17 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
normalizePath(file.path.substring(0, file.path.lastIndexOf(file.name))),
|
||||
);
|
||||
log(fname);
|
||||
const result = await createOrOverwriteFile(
|
||||
this.app,
|
||||
fname,
|
||||
FRONTMATTER + (await this.fileManager.exportSceneToMD(data, false)),
|
||||
);
|
||||
const initialMarkdown =
|
||||
FRONTMATTER + (await this.fileManager.exportSceneToMD(data, false));
|
||||
const result = await createOrOverwriteFile(this.app, fname, initialMarkdown);
|
||||
if (hasEmbeddedFiles) {
|
||||
const convertedMarkdown =
|
||||
await this.fileManager.persistLegacySceneFilesInMarkdown(
|
||||
initialMarkdown,
|
||||
result,
|
||||
);
|
||||
await this.app.vault.modify(result, convertedMarkdown);
|
||||
}
|
||||
if (this.settings.keepInSync) {
|
||||
EXPORT_TYPES.forEach((ext: string) => {
|
||||
const oldIMGpath =
|
||||
@@ -826,9 +827,13 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const path = this.settings.startupScriptPath.endsWith(".md")
|
||||
? this.settings.startupScriptPath
|
||||
: `${this.settings.startupScriptPath}.md`;
|
||||
const path = this.scriptEngine.resolveStartupScriptPath(
|
||||
this.settings.startupScriptPath,
|
||||
);
|
||||
if (!path) {
|
||||
new Notice(t("STARTUP_SCRIPT_JS_DISABLED"));
|
||||
return;
|
||||
}
|
||||
const f = this.app.vault.getFileByPath(path);
|
||||
if (!f || !(f instanceof TFile)) {
|
||||
new Notice(`Startup script not found: ${path}`);
|
||||
|
||||
@@ -548,6 +548,40 @@ export class PluginFileManager {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts binary files embedded in a converted legacy scene and rewrites
|
||||
* the Markdown drawing with durable vault attachment links.
|
||||
*
|
||||
* The target file must already exist because Obsidian determines its
|
||||
* attachment folder relative to that file. This method resolves only after
|
||||
* every embedded file has been persisted.
|
||||
*/
|
||||
public async persistLegacySceneFilesInMarkdown(
|
||||
markdown: string,
|
||||
file: TFile,
|
||||
): Promise<string> {
|
||||
const convertedData = new ExcalidrawData(this.plugin);
|
||||
try {
|
||||
const loaded = await convertedData.loadData(
|
||||
markdown,
|
||||
file,
|
||||
getTextMode(markdown),
|
||||
);
|
||||
if (!loaded) {
|
||||
throw new Error(`Failed to load converted drawing: ${file.path}`);
|
||||
}
|
||||
|
||||
convertedData.disableCompression = true;
|
||||
await convertedData.syncElements(convertedData.scene);
|
||||
return (
|
||||
FRONTMATTER +
|
||||
(await convertedData.generateMDAsync(convertedData.deletedElements))
|
||||
);
|
||||
} finally {
|
||||
convertedData.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------
|
||||
// ------------------ Event Handlers ---------------------
|
||||
// -------------------------------------------------------
|
||||
|
||||
+215
-15
@@ -70,6 +70,11 @@ import { decryptProviderProfiles } from "src/utils/settingsKeyObfuscation";
|
||||
import { getGeminiSupportedSizes } from "src/utils/geminiImageModelUtils";
|
||||
import { URLs } from "src/constants/safeUrls";
|
||||
import { hideElement, setStyle, showElement } from "src/utils/styleUtils";
|
||||
import { errorlog } from "src/utils/coreUtils";
|
||||
import {
|
||||
replaceScriptFileExtension,
|
||||
resolveConfiguredStartupScriptPath,
|
||||
} from "src/utils/scriptFileUtils";
|
||||
import {
|
||||
getMarkdownFontFamilyId,
|
||||
getSelectableFontOptions,
|
||||
@@ -4966,6 +4971,19 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
aliases: ["Excalidraw Automate autocomplete", "EA suggester"],
|
||||
control: { type: "toggle", key: "fieldSuggester" },
|
||||
},
|
||||
{
|
||||
name: t("ALLOW_JS_FILES_NAME"),
|
||||
desc: fragWithHTML(t("ALLOW_JS_FILES_DESC")),
|
||||
aliases: ["JavaScript files", ".js scripts", "sync scripts"],
|
||||
control: {
|
||||
type: "toggle",
|
||||
key: "allowJavaScriptFiles",
|
||||
afterUpdate: async () => {
|
||||
await this.plugin.scriptEngine?.reloadScripts();
|
||||
this.refreshSettingsUI();
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: t("ENABLE_ONLOAD_SCRIPTS_NAME"),
|
||||
desc: fragWithHTML(t("ENABLE_ONLOAD_SCRIPTS_DESC")),
|
||||
@@ -4995,6 +5013,164 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
});
|
||||
}
|
||||
|
||||
private configureScriptFileStorageSetting(setting: Setting): void {
|
||||
setting
|
||||
.setName(t("STORE_SCRIPTS_AS_JS_NAME"))
|
||||
.setDesc(fragWithHTML(t("STORE_SCRIPTS_AS_JS_DESC")))
|
||||
.addDropdown((dropdown) =>
|
||||
dropdown
|
||||
.addOption("md", t("SCRIPT_FILE_EXTENSION_MARKDOWN"))
|
||||
.addOption("js", t("SCRIPT_FILE_EXTENSION_JAVASCRIPT"))
|
||||
.setValue(
|
||||
this.plugin.settings.storeScriptFilesAsJavaScript ? "js" : "md",
|
||||
)
|
||||
.onChange((value) => {
|
||||
this.plugin.settings.storeScriptFilesAsJavaScript = value === "js";
|
||||
this.applySettingsUpdate();
|
||||
this.refreshSettingsUI();
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
private configureScriptFileMigrationSetting(setting: Setting): void {
|
||||
const targetExtension = this.plugin.settings
|
||||
.storeScriptFilesAsJavaScript
|
||||
? "js"
|
||||
: "md";
|
||||
const plan =
|
||||
this.plugin.scriptEngine.getScriptFileMigrationPlan(targetExtension);
|
||||
const buttonText =
|
||||
targetExtension === "js"
|
||||
? t("MIGRATE_SCRIPTS_TO_JS_BUTTON")
|
||||
: t("MIGRATE_SCRIPTS_TO_MD_BUTTON");
|
||||
const skippedStatus = plan.conflicts.length
|
||||
? t("MIGRATE_SCRIPT_FILES_SKIPPED").replace(
|
||||
"{count}",
|
||||
String(plan.conflicts.length),
|
||||
)
|
||||
: "";
|
||||
const getSkippedDetails = (conflicts: string[]): string =>
|
||||
t("MIGRATE_SCRIPT_FILES_SKIPPED_DETAILS")
|
||||
.replace("{count}", String(conflicts.length))
|
||||
.replace(
|
||||
"{files}",
|
||||
conflicts
|
||||
.map(
|
||||
(sourcePath) =>
|
||||
`${sourcePath} → ${replaceScriptFileExtension(
|
||||
sourcePath,
|
||||
targetExtension,
|
||||
)}`,
|
||||
)
|
||||
.join("\n"),
|
||||
);
|
||||
|
||||
setting
|
||||
.setName(buttonText)
|
||||
.setDesc(
|
||||
t("MIGRATE_SCRIPT_FILES_STATUS")
|
||||
.replace("{eligible}", String(plan.renames.length))
|
||||
.replace("{extension}", `.${targetExtension}`)
|
||||
.replace("{skipped}", skippedStatus),
|
||||
)
|
||||
.addButton((button) =>
|
||||
button
|
||||
.setButtonText(buttonText)
|
||||
.setDisabled(plan.renames.length === 0)
|
||||
.onClick(async () => {
|
||||
const currentPlan =
|
||||
this.plugin.scriptEngine.getScriptFileMigrationPlan(
|
||||
targetExtension,
|
||||
);
|
||||
if (currentPlan.renames.length === 0) {
|
||||
const message = currentPlan.conflicts.length
|
||||
? `${t("MIGRATE_SCRIPT_FILES_NONE")}\n\n${getSkippedDetails(
|
||||
currentPlan.conflicts,
|
||||
)}`
|
||||
: t("MIGRATE_SCRIPT_FILES_NONE");
|
||||
new Notice(message, 10000);
|
||||
this.refreshSettingsUI();
|
||||
return;
|
||||
}
|
||||
|
||||
const startupNote = currentPlan.includesStartupScript
|
||||
? t("MIGRATE_SCRIPT_FILES_STARTUP_INCLUDED")
|
||||
: "";
|
||||
const skippedNote = currentPlan.conflicts.length
|
||||
? t("MIGRATE_SCRIPT_FILES_SKIPPED").replace(
|
||||
"{count}",
|
||||
String(currentPlan.conflicts.length),
|
||||
)
|
||||
: "";
|
||||
const confirmation = new MultiOptionConfirmationPrompt<boolean>(
|
||||
this.plugin,
|
||||
t("MIGRATE_SCRIPT_FILES_CONFIRM")
|
||||
.replace("{count}", String(currentPlan.renames.length))
|
||||
.replace("{extension}", `.${targetExtension}`)
|
||||
.replace("{startup}", startupNote)
|
||||
.replace("{skipped}", skippedNote),
|
||||
new Map<string, boolean>([
|
||||
[t("PROMPT_BUTTON_CANCEL"), false],
|
||||
[buttonText, true],
|
||||
]),
|
||||
buttonText,
|
||||
);
|
||||
if (!(await confirmation.waitForClose)) {
|
||||
return;
|
||||
}
|
||||
|
||||
button.setDisabled(true);
|
||||
try {
|
||||
const count =
|
||||
await this.plugin.scriptEngine.migrateScriptFiles(currentPlan);
|
||||
const completeMessage = t("MIGRATE_SCRIPT_FILES_COMPLETE")
|
||||
.replace("{count}", String(count))
|
||||
.replace("{extension}", `.${targetExtension}`);
|
||||
const message = currentPlan.conflicts.length
|
||||
? `${completeMessage}\n\n${getSkippedDetails(
|
||||
currentPlan.conflicts,
|
||||
)}`
|
||||
: completeMessage;
|
||||
new Notice(
|
||||
message,
|
||||
currentPlan.conflicts.length > 0 ? 15000 : undefined,
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
errorlog({
|
||||
where:
|
||||
"ExcalidrawSettingTab.configureScriptFileMigrationSetting",
|
||||
error,
|
||||
});
|
||||
new Notice(t("MIGRATE_SCRIPT_FILES_FAILED"));
|
||||
} finally {
|
||||
this.refreshSettingsUI();
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
private createScriptFileStorageDefinition(): SettingDefinition<SettingBindingKey> {
|
||||
return this.createCustomSettingDefinition({
|
||||
name: t("STORE_SCRIPTS_AS_JS_NAME"),
|
||||
desc: fragWithHTML(t("STORE_SCRIPTS_AS_JS_DESC")),
|
||||
aliases: ["download scripts as JavaScript", "convert scripts to .js"],
|
||||
visible: () => this.plugin.settings.allowJavaScriptFiles,
|
||||
controlType: "dropdown",
|
||||
configure: (setting) => this.configureScriptFileStorageSetting(setting),
|
||||
});
|
||||
}
|
||||
|
||||
private createScriptFileMigrationDefinition(): SettingDefinition<SettingBindingKey> {
|
||||
return this.createCustomSettingDefinition({
|
||||
name: t("MIGRATE_SCRIPT_FILES_NAME"),
|
||||
aliases: ["rename script files", "convert scripts", ".md", ".js"],
|
||||
visible: () => this.plugin.settings.allowJavaScriptFiles,
|
||||
controlType: "action button",
|
||||
configure: (setting) =>
|
||||
this.configureScriptFileMigrationSetting(setting),
|
||||
});
|
||||
}
|
||||
|
||||
private createStartupScriptDefinition(): SettingDefinition<SettingBindingKey> {
|
||||
return this.createCustomSettingDefinition({
|
||||
name: t("STARTUP_SCRIPT_NAME"),
|
||||
@@ -5018,9 +5194,13 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
}
|
||||
|
||||
private getAutomateDefinitions(): SettingDefinitionItem<SettingBindingKey>[] {
|
||||
const specs = this.getAutomateSpecs();
|
||||
return [
|
||||
this.createAutomateInformationDefinition(),
|
||||
...this.toDeclarativeDefinitions(this.getAutomateSpecs()),
|
||||
...this.toDeclarativeDefinitions(specs.slice(0, 2)),
|
||||
this.createScriptFileStorageDefinition(),
|
||||
this.createScriptFileMigrationDefinition(),
|
||||
...this.toDeclarativeDefinitions(specs.slice(2)),
|
||||
this.createStartupScriptDefinition(),
|
||||
this.createAutostartScriptsDefinition(),
|
||||
];
|
||||
@@ -5029,7 +5209,13 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
private renderAutomateSettings(container: HTMLElement): void {
|
||||
const description = container.createDiv({ cls: "setting-item-description" });
|
||||
setSanitizedHtml(description, t("EA_DESC"));
|
||||
this.renderSettingSpecs(container, this.getAutomateSpecs());
|
||||
const specs = this.getAutomateSpecs();
|
||||
this.renderSettingSpecs(container, specs.slice(0, 2));
|
||||
if (this.plugin.settings.allowJavaScriptFiles) {
|
||||
this.configureScriptFileStorageSetting(new Setting(container));
|
||||
this.configureScriptFileMigrationSetting(new Setting(container));
|
||||
}
|
||||
this.renderSettingSpecs(container, specs.slice(2));
|
||||
this.configureStartupScriptSetting(new Setting(container));
|
||||
new AutostartScriptsSettingsComponent(
|
||||
container.createDiv(),
|
||||
@@ -5040,13 +5226,24 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
private configureStartupScriptSetting(setting: Setting): void {
|
||||
let startupScriptPathText: TextComponent;
|
||||
let startupScriptButton: ButtonComponent;
|
||||
const resolveStartupPath = (value: string): string | null => {
|
||||
if (this.plugin.scriptEngine) {
|
||||
return this.plugin.scriptEngine.resolveStartupScriptPath(value);
|
||||
}
|
||||
const path = resolveConfiguredStartupScriptPath(value);
|
||||
if (!path) {
|
||||
return null;
|
||||
}
|
||||
if (path.toLowerCase().endsWith(".js")) {
|
||||
return this.plugin.settings.allowJavaScriptFiles ? path : null;
|
||||
}
|
||||
return path;
|
||||
};
|
||||
const scriptExists = () => {
|
||||
const startupPath = normalizePath(
|
||||
this.plugin.settings.startupScriptPath.endsWith(".md")
|
||||
? this.plugin.settings.startupScriptPath
|
||||
: `${this.plugin.settings.startupScriptPath}.md`,
|
||||
const startupPath = resolveStartupPath(
|
||||
this.plugin.settings.startupScriptPath,
|
||||
);
|
||||
return Boolean(this.app.vault.getAbstractFileByPath(startupPath));
|
||||
return Boolean(startupPath && this.app.vault.getFileByPath(startupPath));
|
||||
};
|
||||
const updateStartupScriptButton = (button: ButtonComponent): void => {
|
||||
const exists = scriptExists();
|
||||
@@ -5072,9 +5269,10 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
});
|
||||
this.addVaultPathSupport(setting, text, "file", {
|
||||
optional: true,
|
||||
extensions: ["md"],
|
||||
resolvePath: (value) =>
|
||||
value && !value.endsWith(".md") ? `${value}.md` : value,
|
||||
extensions: this.plugin.settings.allowJavaScriptFiles
|
||||
? ["md", "js"]
|
||||
: ["md"],
|
||||
resolvePath: (value) => resolveStartupPath(value) ?? value,
|
||||
});
|
||||
})
|
||||
.addButton((button) => {
|
||||
@@ -5090,12 +5288,14 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
);
|
||||
this.applySettingsUpdate();
|
||||
}
|
||||
const startupPath = normalizePath(
|
||||
this.plugin.settings.startupScriptPath.endsWith(".md")
|
||||
? this.plugin.settings.startupScriptPath
|
||||
: `${this.plugin.settings.startupScriptPath}.md`,
|
||||
const startupPath = resolveStartupPath(
|
||||
this.plugin.settings.startupScriptPath,
|
||||
);
|
||||
let file = this.app.vault.getAbstractFileByPath(startupPath);
|
||||
if (!startupPath) {
|
||||
new Notice(t("STARTUP_SCRIPT_JS_DISABLED"));
|
||||
return;
|
||||
}
|
||||
let file = this.app.vault.getFileByPath(startupPath);
|
||||
if (!file) {
|
||||
file = await createOrOverwriteFile(
|
||||
this.app,
|
||||
|
||||
@@ -56,6 +56,8 @@ export interface ExcalidrawSettings {
|
||||
embedUseExcalidrawFolder: boolean;
|
||||
templateFilePath: string;
|
||||
scriptFolderPath: string;
|
||||
allowJavaScriptFiles: boolean;
|
||||
storeScriptFilesAsJavaScript: boolean;
|
||||
fontAssetsPath: string;
|
||||
loadChineseFonts: boolean;
|
||||
loadJapaneseFonts: boolean;
|
||||
@@ -501,6 +503,8 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
|
||||
embedUseExcalidrawFolder: false,
|
||||
templateFilePath: "Excalidraw/Template.excalidraw",
|
||||
scriptFolderPath: "Excalidraw/Scripts",
|
||||
allowJavaScriptFiles: false,
|
||||
storeScriptFilesAsJavaScript: false,
|
||||
fontAssetsPath: "Excalidraw/CJK Fonts",
|
||||
loadChineseFonts: false,
|
||||
loadJapaneseFonts: false,
|
||||
|
||||
+30
-2
@@ -1329,6 +1329,33 @@ export default {
|
||||
FIELD_SUGGESTER_DESC:
|
||||
"Field Suggester borrowed from Breadcrumbs and Templater plugins. The Field Suggester will show an autocomplete menu " +
|
||||
"when you type <code>excalidraw-</code> or <code>ea.</code> with function description as hints on the individual items in the list.",
|
||||
ALLOW_JS_FILES_NAME: "Load JavaScript files from the Scripts folder",
|
||||
ALLOW_JS_FILES_DESC:
|
||||
"When enabled, Excalidraw Automate monitors and runs <code>.js</code> files in the Scripts folder and accepts a <code>.js</code> startup script. " +
|
||||
"By default, Obsidian Sync does not sync non-Markdown files, Obsidian does not open <code>.js</code> files for editing, and File Explorer hides them. Enable <b>Sync all other types</b> and <b>Show all file types</b> in Obsidian when needed. If matching <code>.md</code> and <code>.js</code> scripts exist, the Markdown file is used.",
|
||||
STORE_SCRIPTS_AS_JS_NAME: "Store downloaded scripts as",
|
||||
STORE_SCRIPTS_AS_JS_DESC:
|
||||
"Choose the local file type used for new Script Library downloads and updates. This is independent of whether the remote source is <code>.md</code> or <code>.js</code>.",
|
||||
SCRIPT_FILE_EXTENSION_MARKDOWN: "Markdown (.md)",
|
||||
SCRIPT_FILE_EXTENSION_JAVASCRIPT: "JavaScript (.js)",
|
||||
MIGRATE_SCRIPT_FILES_NAME: "Move existing script files",
|
||||
MIGRATE_SCRIPTS_TO_JS_BUTTON: "Move existing scripts to .js",
|
||||
MIGRATE_SCRIPTS_TO_MD_BUTTON: "Move existing scripts to .md",
|
||||
MIGRATE_SCRIPT_FILES_STATUS:
|
||||
"{eligible} script file(s) can be moved to {extension}. {skipped}",
|
||||
MIGRATE_SCRIPT_FILES_CONFIRM:
|
||||
"Back up your vault before continuing.<br><br><b>{count}</b> script file(s) will be renamed to <code>{extension}</code>. Pinned script paths will be updated. {startup} {skipped}",
|
||||
MIGRATE_SCRIPT_FILES_STARTUP_INCLUDED:
|
||||
"The configured startup script and its setting will also be updated.",
|
||||
MIGRATE_SCRIPT_FILES_SKIPPED:
|
||||
"{count} same-named .md/.js pair(s) will not be moved.",
|
||||
MIGRATE_SCRIPT_FILES_SKIPPED_DETAILS:
|
||||
"Skipped {count} script file(s) because the destination already exists:\n{files}",
|
||||
MIGRATE_SCRIPT_FILES_NONE: "No eligible script files were found to move.",
|
||||
MIGRATE_SCRIPT_FILES_COMPLETE:
|
||||
"Moved {count} script file(s) to {extension}.",
|
||||
MIGRATE_SCRIPT_FILES_FAILED:
|
||||
"Could not move the script files. Completed renames were rolled back where possible.",
|
||||
ENABLE_ONLOAD_SCRIPTS_NAME: "Enable onload scripts",
|
||||
ENABLE_ONLOAD_SCRIPTS_CONFIRMATION:
|
||||
"This file includes an <code>excalidraw-onload-script</code>. Do you want to enable onload scripts?",
|
||||
@@ -1361,9 +1388,10 @@ export default {
|
||||
"This creates a risk if you open drawings from unknown sources: a malicious drawing can make a normal click trigger privileged commands. " +
|
||||
"Only enable this if you trust the file and its source.",
|
||||
STARTUP_SCRIPT_NAME: "Startup script",
|
||||
STARTUP_SCRIPT_JS_DISABLED:
|
||||
"JavaScript startup scripts are disabled. Enable JavaScript files in Excalidraw Automate settings first.",
|
||||
STARTUP_SCRIPT_DESC:
|
||||
"If set, excalidraw will execute the script at plugin startup. This is useful if you want to set any of the Excalidraw Automate hooks. The startup script is a markdown file " +
|
||||
"that should contain the javascript code you want to execute when Excalidraw starts.",
|
||||
"If set, Excalidraw will execute the script at plugin startup. This is useful for configuring Excalidraw Automate hooks. Extensionless paths use a Markdown file; <code>.js</code> files are accepted when JavaScript-file loading is enabled.",
|
||||
STARTUP_SCRIPT_BUTTON_CREATE: "Create startup script",
|
||||
STARTUP_SCRIPT_BUTTON_OPEN: "Open startup script",
|
||||
FILETYPE_NAME: "Display type (✏️) for excalidraw.md files in File Explorer",
|
||||
|
||||
+31
-2
@@ -1298,6 +1298,34 @@ export default {
|
||||
FIELD_SUGGESTER_DESC:
|
||||
"El sugeridor de campos, tomado de los complementos Breadcrumbs y Templater, mostrará un menú de autocompletar " +
|
||||
"cuando escribas <code>excalidraw-</code> o <code>ea.</code> , con descripciones de las funciones como pistas para cada elemento en la lista.",
|
||||
ALLOW_JS_FILES_NAME: "Cargar archivos JavaScript desde la carpeta Scripts",
|
||||
ALLOW_JS_FILES_DESC:
|
||||
"Cuando está activado, Excalidraw Automate supervisa y ejecuta archivos <code>.js</code> en la carpeta Scripts y acepta un script de inicio <code>.js</code>. " +
|
||||
"De forma predeterminada, Obsidian Sync no sincroniza archivos que no sean Markdown, Obsidian no abre archivos <code>.js</code> para editarlos y el Explorador de archivos los oculta. Activa <b>Sincronizar todos los demás tipos</b> y <b>Mostrar todos los tipos de archivo</b> en Obsidian cuando sea necesario. Si existen scripts <code>.md</code> y <code>.js</code> con el mismo nombre, se utiliza el archivo Markdown.",
|
||||
STORE_SCRIPTS_AS_JS_NAME: "Guardar los scripts descargados como",
|
||||
STORE_SCRIPTS_AS_JS_DESC:
|
||||
"Elige el tipo de archivo local para las nuevas descargas y actualizaciones de la Biblioteca de scripts. Es independiente de si la fuente remota es <code>.md</code> o <code>.js</code>.",
|
||||
SCRIPT_FILE_EXTENSION_MARKDOWN: "Markdown (.md)",
|
||||
SCRIPT_FILE_EXTENSION_JAVASCRIPT: "JavaScript (.js)",
|
||||
MIGRATE_SCRIPT_FILES_NAME: "Mover archivos de script existentes",
|
||||
MIGRATE_SCRIPTS_TO_JS_BUTTON: "Mover scripts existentes a .js",
|
||||
MIGRATE_SCRIPTS_TO_MD_BUTTON: "Mover scripts existentes a .md",
|
||||
MIGRATE_SCRIPT_FILES_STATUS:
|
||||
"Se pueden mover {eligible} archivo(s) de script a {extension}. {skipped}",
|
||||
MIGRATE_SCRIPT_FILES_CONFIRM:
|
||||
"Haz una copia de seguridad de tu bóveda antes de continuar.<br><br>Se cambiará la extensión de <b>{count}</b> archivo(s) de script a <code>{extension}</code>. Se actualizarán las rutas de los scripts fijados. {startup} {skipped}",
|
||||
MIGRATE_SCRIPT_FILES_STARTUP_INCLUDED:
|
||||
"También se actualizarán el script de inicio configurado y su ajuste.",
|
||||
MIGRATE_SCRIPT_FILES_SKIPPED:
|
||||
"No se moverán {count} par(es) .md/.js con el mismo nombre.",
|
||||
MIGRATE_SCRIPT_FILES_SKIPPED_DETAILS:
|
||||
"Se omitieron {count} archivo(s) de script porque el destino ya existe:\n{files}",
|
||||
MIGRATE_SCRIPT_FILES_NONE:
|
||||
"No se encontraron archivos de script aptos para mover.",
|
||||
MIGRATE_SCRIPT_FILES_COMPLETE:
|
||||
"Se movieron {count} archivo(s) de script a {extension}.",
|
||||
MIGRATE_SCRIPT_FILES_FAILED:
|
||||
"No se pudieron mover los archivos de script. Los cambios completados se revirtieron cuando fue posible.",
|
||||
ENABLE_ONLOAD_SCRIPTS_NAME: "Habilitar scripts de carga",
|
||||
ENABLE_ONLOAD_SCRIPTS_CONFIRMATION:
|
||||
"Este archivo incluye un <code>excalidraw-onload-script</code>. ¿Quieres habilitar los scripts de carga?",
|
||||
@@ -1331,9 +1359,10 @@ export default {
|
||||
"Esto crea un riesgo si abres dibujos de fuentes desconocidas: un dibujo malicioso puede hacer que un clic normal ejecute comandos privilegiados. " +
|
||||
"Actívalo solo si confías en el archivo y en su origen.",
|
||||
STARTUP_SCRIPT_NAME: "Script de inicio",
|
||||
STARTUP_SCRIPT_JS_DISABLED:
|
||||
"Los scripts de inicio JavaScript están desactivados. Primero habilita los archivos JavaScript en la configuración de Excalidraw Automate.",
|
||||
STARTUP_SCRIPT_DESC:
|
||||
"Si está configurado, Excalidraw ejecutará el script al iniciar el complemento. Esto es útil si quieres establecer cualquiera de los hooks de Excalidraw Automate. El script de inicio es un archivo Markdown " +
|
||||
"que debe contener el código Javascript que quieres ejecutar cuando Excalidraw se inicie",
|
||||
"Si está configurado, Excalidraw ejecutará el script al iniciar el complemento. Es útil para configurar hooks de Excalidraw Automate. Las rutas sin extensión utilizan un archivo Markdown; los archivos <code>.js</code> se aceptan cuando está habilitada la carga de archivos JavaScript.",
|
||||
STARTUP_SCRIPT_BUTTON_CREATE: "Crear script de inicio",
|
||||
STARTUP_SCRIPT_BUTTON_OPEN: "Abrir script de inicio",
|
||||
FILETYPE_NAME:
|
||||
|
||||
+31
-2
@@ -1205,6 +1205,34 @@ export default {
|
||||
FIELD_SUGGESTER_DESC:
|
||||
"Предложение полей (Suggester) позаимствован у плагинов Breadcrumbs и Templater. Предложение полей (Suggester) полей будет показывать " +
|
||||
"меню автозаполнения при вводе текста с описанием функций <code>excalidraw-</code> или <code>ea.</code> в качестве подсказок для отдельных элементов в списке.",
|
||||
ALLOW_JS_FILES_NAME: "Загружать файлы JavaScript из папки скриптов",
|
||||
ALLOW_JS_FILES_DESC:
|
||||
"Если включено, Excalidraw Automate отслеживает и запускает файлы <code>.js</code> в папке скриптов и принимает скрипт запуска <code>.js</code>. " +
|
||||
"По умолчанию Obsidian Sync не синхронизирует файлы, отличные от Markdown, Obsidian не открывает файлы <code>.js</code> для редактирования, а проводник файлов скрывает их. При необходимости включите <b>Синхронизировать все остальные типы</b> и <b>Показывать все типы файлов</b> в Obsidian. Если существуют одноимённые скрипты <code>.md</code> и <code>.js</code>, используется файл Markdown.",
|
||||
STORE_SCRIPTS_AS_JS_NAME: "Хранить загруженные скрипты как",
|
||||
STORE_SCRIPTS_AS_JS_DESC:
|
||||
"Выберите локальный тип файла для новых загрузок и обновлений из библиотеки скриптов. Он не зависит от того, имеет ли удалённый источник расширение <code>.md</code> или <code>.js</code>.",
|
||||
SCRIPT_FILE_EXTENSION_MARKDOWN: "Markdown (.md)",
|
||||
SCRIPT_FILE_EXTENSION_JAVASCRIPT: "JavaScript (.js)",
|
||||
MIGRATE_SCRIPT_FILES_NAME: "Переместить существующие файлы скриптов",
|
||||
MIGRATE_SCRIPTS_TO_JS_BUTTON: "Переместить существующие скрипты в .js",
|
||||
MIGRATE_SCRIPTS_TO_MD_BUTTON: "Переместить существующие скрипты в .md",
|
||||
MIGRATE_SCRIPT_FILES_STATUS:
|
||||
"Можно переместить файлов скриптов в {extension}: {eligible}. {skipped}",
|
||||
MIGRATE_SCRIPT_FILES_CONFIRM:
|
||||
"Перед продолжением создайте резервную копию хранилища.<br><br><b>{count}</b> файл(ов) скриптов будет переименовано в <code>{extension}</code>. Пути закреплённых скриптов будут обновлены. {startup} {skipped}",
|
||||
MIGRATE_SCRIPT_FILES_STARTUP_INCLUDED:
|
||||
"Настроенный скрипт запуска и его параметр также будут обновлены.",
|
||||
MIGRATE_SCRIPT_FILES_SKIPPED:
|
||||
"Одноимённых пар .md/.js, которые не будут перемещены: {count}.",
|
||||
MIGRATE_SCRIPT_FILES_SKIPPED_DETAILS:
|
||||
"Пропущено файлов скриптов, поскольку целевой файл уже существует: {count}.\n{files}",
|
||||
MIGRATE_SCRIPT_FILES_NONE:
|
||||
"Не найдено подходящих файлов скриптов для перемещения.",
|
||||
MIGRATE_SCRIPT_FILES_COMPLETE:
|
||||
"Перемещено файлов скриптов в {extension}: {count}.",
|
||||
MIGRATE_SCRIPT_FILES_FAILED:
|
||||
"Не удалось переместить файлы скриптов. Выполненные переименования по возможности отменены.",
|
||||
ENABLE_ONLOAD_SCRIPTS_NAME: "Включить onload-скрипты",
|
||||
ENABLE_ONLOAD_SCRIPTS_CONFIRMATION:
|
||||
"Этот файл содержит <code>excalidraw-onload-script</code>. Включить onload-скрипты?",
|
||||
@@ -1237,9 +1265,10 @@ export default {
|
||||
"Это создаёт риск при открытии рисунков из неизвестных источников: вредоносный рисунок может превратить обычный клик в запуск привилегированной команды. " +
|
||||
"Включайте это только если доверяете файлу и его источнику.",
|
||||
STARTUP_SCRIPT_NAME: "Сценарий запуска",
|
||||
STARTUP_SCRIPT_JS_DISABLED:
|
||||
"Сценарии запуска JavaScript отключены. Сначала включите файлы JavaScript в настройках Excalidraw Automate.",
|
||||
STARTUP_SCRIPT_DESC:
|
||||
"Если этот параметр установлен, excalidraw будет выполнять скрипт при запуске плагина. Это полезно, если вы хотите установить какой-либо из крючков Excalidraw Automate. " +
|
||||
"Скрипт запуска - это файл в формате markdown, который должен содержать код javascript, который вы хотите выполнять при запуске Excalidraw.",
|
||||
"Если задано, Excalidraw выполнит скрипт при запуске плагина. Это полезно для настройки крючков Excalidraw Automate. Пути без расширения используют файл Markdown; файлы <code>.js</code> принимаются, когда включена загрузка файлов JavaScript.",
|
||||
STARTUP_SCRIPT_BUTTON_CREATE: "Создание сценария запуска",
|
||||
STARTUP_SCRIPT_BUTTON_OPEN: "Открыть сценарий запуска",
|
||||
FILETYPE_NAME:
|
||||
|
||||
@@ -1236,6 +1236,33 @@ export default {
|
||||
FIELD_SUGGESTER_DESC:
|
||||
"开启后,当您在编辑器中输入 <code>excalidraw-</code> 或者 <code>ea.</code> 时,会弹出一个带有函数说明的自动补全提示菜单。<br>" +
|
||||
"该功能借鉴了 Breadcrumbs 和 Templater 插件。",
|
||||
ALLOW_JS_FILES_NAME: "从 Scripts 文件夹加载 JavaScript 文件",
|
||||
ALLOW_JS_FILES_DESC:
|
||||
"启用后,Excalidraw Automate 会监视并运行 Scripts 文件夹中的 <code>.js</code> 文件,也允许使用 <code>.js</code> 启动脚本。" +
|
||||
"默认情况下,Obsidian Sync 不同步非 Markdown 文件,Obsidian 不会打开 <code>.js</code> 文件进行编辑,文件列表也会隐藏它们。需要时请在 Obsidian 中启用<b>同步所有其他文件类型</b>和<b>显示所有文件类型</b>。如果存在同名的 <code>.md</code> 和 <code>.js</code> 脚本,将使用 Markdown 文件。",
|
||||
STORE_SCRIPTS_AS_JS_NAME: "将下载的脚本存储为",
|
||||
STORE_SCRIPTS_AS_JS_DESC:
|
||||
"选择脚本库新下载和更新在本地使用的文件类型。无论远程源是 <code>.md</code> 还是 <code>.js</code>,都会使用此设置。",
|
||||
SCRIPT_FILE_EXTENSION_MARKDOWN: "Markdown (.md)",
|
||||
SCRIPT_FILE_EXTENSION_JAVASCRIPT: "JavaScript (.js)",
|
||||
MIGRATE_SCRIPT_FILES_NAME: "迁移现有脚本文件",
|
||||
MIGRATE_SCRIPTS_TO_JS_BUTTON: "将现有脚本迁移为 .js",
|
||||
MIGRATE_SCRIPTS_TO_MD_BUTTON: "将现有脚本迁移为 .md",
|
||||
MIGRATE_SCRIPT_FILES_STATUS:
|
||||
"有 {eligible} 个脚本文件可迁移为 {extension}。{skipped}",
|
||||
MIGRATE_SCRIPT_FILES_CONFIRM:
|
||||
"继续前请备份仓库。<br><br><b>{count}</b> 个脚本文件将重命名为 <code>{extension}</code>,固定脚本的路径也会更新。{startup} {skipped}",
|
||||
MIGRATE_SCRIPT_FILES_STARTUP_INCLUDED:
|
||||
"已配置的启动脚本及其设置也会更新。",
|
||||
MIGRATE_SCRIPT_FILES_SKIPPED:
|
||||
"有 {count} 对同名 .md/.js 文件不会被迁移。",
|
||||
MIGRATE_SCRIPT_FILES_SKIPPED_DETAILS:
|
||||
"因目标文件已存在,已跳过 {count} 个脚本文件:\n{files}",
|
||||
MIGRATE_SCRIPT_FILES_NONE: "没有找到可迁移的脚本文件。",
|
||||
MIGRATE_SCRIPT_FILES_COMPLETE:
|
||||
"已将 {count} 个脚本文件迁移为 {extension}。",
|
||||
MIGRATE_SCRIPT_FILES_FAILED:
|
||||
"无法迁移脚本文件。已尽可能回滚完成的重命名。",
|
||||
ENABLE_ONLOAD_SCRIPTS_NAME: "加载期脚本(onload)",
|
||||
ENABLE_ONLOAD_SCRIPTS_CONFIRMATION:
|
||||
"此文件包含 <code>excalidraw-onload-script</code>。是否启用加载期脚本?",
|
||||
@@ -1267,9 +1294,10 @@ export default {
|
||||
"如果你打开未知来源的绘图,这会带来风险:恶意绘图可以让一次普通点击触发高权限命令。" +
|
||||
"只有在你信任该文件及其来源时才启用此功能。",
|
||||
STARTUP_SCRIPT_NAME: "启动期脚本(startup)",
|
||||
STARTUP_SCRIPT_JS_DISABLED:
|
||||
"JavaScript 启动脚本已禁用。请先在 Excalidraw Automate 设置中启用 JavaScript 文件。",
|
||||
STARTUP_SCRIPT_DESC:
|
||||
"插件启动时将自动执行该脚本。可用于设置 Excalidraw 自动化钩子。" +
|
||||
"该脚本是包含 javascript 代码的 Markdown 文件。",
|
||||
"插件启动时将自动执行该脚本,可用于设置 Excalidraw Automate 钩子。没有扩展名的路径使用 Markdown 文件;启用 JavaScript 文件加载后可使用 <code>.js</code> 文件。",
|
||||
STARTUP_SCRIPT_BUTTON_CREATE: "创建启动期脚本",
|
||||
STARTUP_SCRIPT_BUTTON_OPEN: "打开启动期脚本",
|
||||
FILETYPE_NAME: "在文件浏览器中为 excalidraw.md 文件添加类型标识符(如 ✏️)",
|
||||
|
||||
@@ -1236,6 +1236,33 @@ export default {
|
||||
FIELD_SUGGESTER_DESC:
|
||||
"開啟後,當您在編輯器中輸入 <code>excalidraw-</code> 或者 <code>ea.</code> 時,會彈出一個帶有函式說明的自動補全提示選單。<br>" +
|
||||
"該功能借鑑了 Breadcrumbs 和 Templater 外掛。",
|
||||
ALLOW_JS_FILES_NAME: "從 Scripts 資料夾載入 JavaScript 檔案",
|
||||
ALLOW_JS_FILES_DESC:
|
||||
"啟用後,Excalidraw Automate 會監視並執行 Scripts 資料夾中的 <code>.js</code> 檔案,也允許使用 <code>.js</code> 啟動指令碼。" +
|
||||
"預設情況下,Obsidian Sync 不會同步非 Markdown 檔案,Obsidian 不會開啟 <code>.js</code> 檔案進行編輯,檔案總管也會隱藏它們。需要時請在 Obsidian 中啟用<b>同步所有其他檔案類型</b>和<b>顯示所有檔案類型</b>。如果存在同名的 <code>.md</code> 和 <code>.js</code> 指令碼,將使用 Markdown 檔案。",
|
||||
STORE_SCRIPTS_AS_JS_NAME: "將下載的指令碼儲存為",
|
||||
STORE_SCRIPTS_AS_JS_DESC:
|
||||
"選擇指令碼庫新下載與更新在本機使用的檔案類型。無論遠端來源是 <code>.md</code> 或 <code>.js</code>,都會使用此設定。",
|
||||
SCRIPT_FILE_EXTENSION_MARKDOWN: "Markdown (.md)",
|
||||
SCRIPT_FILE_EXTENSION_JAVASCRIPT: "JavaScript (.js)",
|
||||
MIGRATE_SCRIPT_FILES_NAME: "遷移現有指令碼檔案",
|
||||
MIGRATE_SCRIPTS_TO_JS_BUTTON: "將現有指令碼遷移為 .js",
|
||||
MIGRATE_SCRIPTS_TO_MD_BUTTON: "將現有指令碼遷移為 .md",
|
||||
MIGRATE_SCRIPT_FILES_STATUS:
|
||||
"有 {eligible} 個指令碼檔案可遷移為 {extension}。{skipped}",
|
||||
MIGRATE_SCRIPT_FILES_CONFIRM:
|
||||
"繼續前請先備份儲存庫。<br><br><b>{count}</b> 個指令碼檔案將重新命名為 <code>{extension}</code>,釘選指令碼的路徑也會更新。{startup} {skipped}",
|
||||
MIGRATE_SCRIPT_FILES_STARTUP_INCLUDED:
|
||||
"已設定的啟動指令碼及其設定也會更新。",
|
||||
MIGRATE_SCRIPT_FILES_SKIPPED:
|
||||
"有 {count} 對同名 .md/.js 檔案不會被遷移。",
|
||||
MIGRATE_SCRIPT_FILES_SKIPPED_DETAILS:
|
||||
"因目標檔案已存在,已略過 {count} 個指令碼檔案:\n{files}",
|
||||
MIGRATE_SCRIPT_FILES_NONE: "找不到可遷移的指令碼檔案。",
|
||||
MIGRATE_SCRIPT_FILES_COMPLETE:
|
||||
"已將 {count} 個指令碼檔案遷移為 {extension}。",
|
||||
MIGRATE_SCRIPT_FILES_FAILED:
|
||||
"無法遷移指令碼檔案。已盡可能回復完成的重新命名。",
|
||||
ENABLE_ONLOAD_SCRIPTS_NAME: "載入期指令碼(onload)",
|
||||
ENABLE_ONLOAD_SCRIPTS_CONFIRMATION:
|
||||
"此檔案包含 <code>excalidraw-onload-script</code>。是否啟用載入期指令碼?",
|
||||
@@ -1267,9 +1294,10 @@ export default {
|
||||
"如果你開啟未知來源的繪圖,這會帶來風險:惡意繪圖可以讓一次普通點選觸發高許可權命令。" +
|
||||
"只有在你信任該檔案及其來源時才啟用此功能。",
|
||||
STARTUP_SCRIPT_NAME: "啟動期指令碼(startup)",
|
||||
STARTUP_SCRIPT_JS_DISABLED:
|
||||
"JavaScript 啟動指令碼已停用。請先在 Excalidraw Automate 設定中啟用 JavaScript 檔案。",
|
||||
STARTUP_SCRIPT_DESC:
|
||||
"外掛啟動時將自動執行該指令碼。可用於設定 Excalidraw 自動化鉤子。" +
|
||||
"該指令碼是包含 javascript 程式碼的 Markdown 檔案。",
|
||||
"外掛啟動時將自動執行該指令碼,可用於設定 Excalidraw Automate 鉤子。沒有副檔名的路徑使用 Markdown 檔案;啟用 JavaScript 檔案載入後可使用 <code>.js</code> 檔案。",
|
||||
STARTUP_SCRIPT_BUTTON_CREATE: "建立啟動期指令碼",
|
||||
STARTUP_SCRIPT_BUTTON_OPEN: "開啟啟動期指令碼",
|
||||
FILETYPE_NAME: "在檔案瀏覽器中為 excalidraw.md 檔案新增型別識別符號(如 ✏️)",
|
||||
|
||||
@@ -22,6 +22,7 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
|
||||
- On Obsidian 1.13 and newer, Excalidraw now uses Obsidian's searchable, multi-page settings. Settings are organized into clearer sections with breadcrumbs, compact help links, and clickable links between related options.
|
||||
- Prefer the previous experience? Turn off **Use searchable settings** at the top of Excalidraw settings and restart Obsidian. Older Obsidian versions continue using the legacy single-page layout automatically.
|
||||
- Settings exposed by installed Excalidraw Automate scripts have moved to **Excalidraw Automate → Settings for installed scripts** and update when a script adds or changes its settings.
|
||||
- Excalidraw Automate can optionally load and monitor JavaScript (\`.js\`) files in the Scripts folder, use an explicit \`.js\` startup script, and store Script Library downloads as either Markdown or JavaScript. Existing scripts can be moved between the two formats while updating startup and pinned-script paths. [#2901](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2901)
|
||||
|
||||
## New from Excalidraw.com
|
||||
- Improved bucket tool and eyedropper support. [#11849](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11849)
|
||||
@@ -31,6 +32,7 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
|
||||
## Fixed
|
||||
- Moving a dirty drawing out of a popout window now safely transfers and persists its latest edits from the replacement main-window view.
|
||||
- Opening the command palette or another Obsidian modal reliably saves dirty drawings, while inline link suggestions no longer trigger a save that can end text editing.
|
||||
- Converting a legacy ".excalidraw" drawing now persists its embedded images as vault attachments during conversion, before the source file can be removed. [#2898](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2898)
|
||||
- Entering text editing no longer scans and sorts the entire vault for link suggestions; file-link candidates are loaded only after typing \`[[\`. [#2907](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2907)
|
||||
- Settings changes are saved promptly without collapsing sections or interrupting fast typing. Writes are serialized, and Excalidraw keeps a device-local recovery copy so an empty or corrupted synchronized **data.json** cannot silently erase a large settings configuration.
|
||||
- Interdependent settings now initialize and refresh consistently, including TODO icons, auto-export formats, Taskbone credentials, filename previews, and custom grid colors. Built-in font previews also use the correct typeface in secondary Obsidian windows.
|
||||
|
||||
+319
-56
@@ -20,11 +20,28 @@ import {
|
||||
} from "../utils/obsidianUtils";
|
||||
import { ButtonDefinition, InputPromptOptions } from "src/types/promptTypes";
|
||||
import { errorlog } from "src/utils/coreUtils";
|
||||
import {
|
||||
type ScriptFileExtension,
|
||||
getPreferredScriptFiles,
|
||||
isScriptFilePath,
|
||||
replaceScriptFileExtension,
|
||||
resolveConfiguredStartupScriptPath,
|
||||
} from "src/utils/scriptFileUtils";
|
||||
|
||||
export type ScriptIconMap = {
|
||||
[key: string]: { name: string; group: string; svgString: string };
|
||||
};
|
||||
|
||||
export interface ScriptFileRenamePlan {
|
||||
renames: Array<{
|
||||
file: TFile;
|
||||
sourcePath: string;
|
||||
destinationPath: string;
|
||||
}>;
|
||||
conflicts: string[];
|
||||
includesStartupScript: boolean;
|
||||
}
|
||||
|
||||
export class ScriptEngine {
|
||||
private plugin: ExcalidrawPlugin;
|
||||
private app: App;
|
||||
@@ -39,12 +56,15 @@ export class ScriptEngine {
|
||||
* linger in views that are still open.
|
||||
*/
|
||||
private elementActionProviders = new Map<string, Set<() => void>>();
|
||||
private scriptFileEventsSuspended = false;
|
||||
private scriptRegistryGeneration = 0;
|
||||
private loadedScriptPaths = new Set<string>();
|
||||
|
||||
constructor(plugin: ExcalidrawPlugin) {
|
||||
this.plugin = plugin;
|
||||
this.app = plugin.app;
|
||||
this.scriptIconMap = {};
|
||||
this.loadScripts();
|
||||
void this.loadScripts();
|
||||
this.registerEventHandlers();
|
||||
}
|
||||
|
||||
@@ -69,63 +89,114 @@ export class ScriptEngine {
|
||||
this.eaInstances.clear();
|
||||
this.eaInstances = null;
|
||||
this.elementActionProviders.clear();
|
||||
this.loadedScriptPaths.clear();
|
||||
this.scriptIconMap = null;
|
||||
this.plugin = null;
|
||||
this.scriptPath = null;
|
||||
}
|
||||
|
||||
private handleSvgFileChange(path: string) {
|
||||
if (!path.endsWith(".svg")) {
|
||||
return;
|
||||
}
|
||||
const scriptFile = this.app.vault.getAbstractFileByPath(
|
||||
getIMGFilename(path, "md"),
|
||||
private isInScriptFolder(path: string): boolean {
|
||||
return Boolean(
|
||||
this.scriptPath && path.startsWith(`${normalizePath(this.scriptPath)}/`),
|
||||
);
|
||||
if (scriptFile && scriptFile instanceof TFile) {
|
||||
this.unloadScript(this.getScriptName(scriptFile), scriptFile.path);
|
||||
this.loadScript(scriptFile);
|
||||
}
|
||||
|
||||
private isJavaScriptPath(path: string): boolean {
|
||||
return path.toLowerCase().endsWith(".js");
|
||||
}
|
||||
|
||||
private isScriptPath(path: string): boolean {
|
||||
return (
|
||||
path.toLowerCase().endsWith(".md") ||
|
||||
(this.plugin.settings.allowJavaScriptFiles && this.isJavaScriptPath(path))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the configured startup-script path without changing the stored
|
||||
* setting. Extensionless paths retain the historical `.md` default; an
|
||||
* explicit `.js` path is accepted only when JavaScript-file loading is
|
||||
* enabled.
|
||||
*/
|
||||
public resolveStartupScriptPath(configuredPath: string): string | null {
|
||||
const path = resolveConfiguredStartupScriptPath(configuredPath);
|
||||
if (!path) {
|
||||
return null;
|
||||
}
|
||||
if (this.isJavaScriptPath(path)) {
|
||||
return this.plugin.settings.allowJavaScriptFiles ? path : null;
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
private async deleteEventHandler(file: TFile) {
|
||||
if (this.scriptFileEventsSuspended) {
|
||||
return;
|
||||
}
|
||||
if (!(file instanceof TFile)) {
|
||||
return;
|
||||
}
|
||||
if (!file.path.startsWith(this.scriptPath)) {
|
||||
if (!this.isInScriptFolder(file.path)) {
|
||||
return;
|
||||
}
|
||||
const scriptName = this.getScriptName(file);
|
||||
this.unloadScript(scriptName, file.path);
|
||||
await this.purgeAutostartPermission(scriptName);
|
||||
this.handleSvgFileChange(file.path);
|
||||
if (isScriptFilePath(file.path)) {
|
||||
const scriptName = this.getScriptName(file);
|
||||
const wasLoaded = Boolean(this.scriptIconMap[file.path]);
|
||||
if (wasLoaded || !this.isJavaScriptPath(file.path)) {
|
||||
await this.reloadScripts();
|
||||
}
|
||||
if (!this.getScriptFileByName(scriptName)) {
|
||||
await this.purgeAutostartPermission(scriptName);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (file.extension.toLowerCase() === "svg") {
|
||||
await this.reloadScripts();
|
||||
}
|
||||
}
|
||||
|
||||
private async createEventHandler(file: TFile) {
|
||||
if (this.scriptFileEventsSuspended) {
|
||||
return;
|
||||
}
|
||||
if (!(file instanceof TFile)) {
|
||||
return;
|
||||
}
|
||||
if (!file.path.startsWith(this.scriptPath)) {
|
||||
if (!this.isInScriptFolder(file.path)) {
|
||||
return;
|
||||
}
|
||||
this.loadScript(file);
|
||||
this.handleSvgFileChange(file.path);
|
||||
if (
|
||||
this.isScriptPath(file.path) ||
|
||||
file.extension.toLowerCase() === "svg"
|
||||
) {
|
||||
await this.reloadScripts();
|
||||
}
|
||||
}
|
||||
|
||||
private async renameEventHandler(file: TAbstractFile, oldPath: string) {
|
||||
if (this.scriptFileEventsSuspended) {
|
||||
return;
|
||||
}
|
||||
if (!(file instanceof TFile)) {
|
||||
return;
|
||||
}
|
||||
const oldFileIsScript = oldPath.startsWith(this.scriptPath);
|
||||
const newFileIsScript = file.path.startsWith(this.scriptPath);
|
||||
if (oldFileIsScript) {
|
||||
const oldScriptName = this.getScriptName(oldPath);
|
||||
this.unloadScript(oldScriptName, oldPath);
|
||||
await this.purgeAutostartPermission(oldScriptName);
|
||||
this.handleSvgFileChange(oldPath);
|
||||
const oldPathWasLoaded = Boolean(this.scriptIconMap[oldPath]);
|
||||
const oldFileWasScript =
|
||||
this.isInScriptFolder(oldPath) && isScriptFilePath(oldPath);
|
||||
const newFileIsScript =
|
||||
this.isInScriptFolder(file.path) && this.isScriptPath(file.path);
|
||||
const iconChanged =
|
||||
(this.isInScriptFolder(oldPath) &&
|
||||
oldPath.toLowerCase().endsWith(".svg")) ||
|
||||
(this.isInScriptFolder(file.path) &&
|
||||
file.extension.toLowerCase() === "svg");
|
||||
const oldScriptName = oldFileWasScript ? this.getScriptName(oldPath) : null;
|
||||
|
||||
if (oldPathWasLoaded || newFileIsScript || iconChanged) {
|
||||
await this.reloadScripts();
|
||||
}
|
||||
if (newFileIsScript) {
|
||||
this.loadScript(file);
|
||||
this.handleSvgFileChange(file.path);
|
||||
if (oldScriptName && !this.getScriptFileByName(oldScriptName)) {
|
||||
await this.purgeAutostartPermission(oldScriptName);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -151,10 +222,7 @@ export class ScriptEngine {
|
||||
if (this.scriptPath === this.plugin.settings.scriptFolderPath) {
|
||||
return;
|
||||
}
|
||||
if (this.scriptPath) {
|
||||
this.unloadScripts();
|
||||
}
|
||||
this.loadScripts();
|
||||
void this.reloadScripts();
|
||||
}
|
||||
|
||||
public getListofScripts(): TFile[] {
|
||||
@@ -163,19 +231,208 @@ export class ScriptEngine {
|
||||
return;
|
||||
}
|
||||
this.scriptPath = normalizePath(this.scriptPath);
|
||||
if (!this.app.vault.getAbstractFileByPath(this.scriptPath)) {
|
||||
if (!this.app.vault.getFolderByPath(this.scriptPath)) {
|
||||
return;
|
||||
}
|
||||
return this.app.vault
|
||||
.getFiles()
|
||||
.filter(
|
||||
(f: TFile) =>
|
||||
f.path.startsWith(`${this.scriptPath}/`) && f.extension === "md",
|
||||
);
|
||||
return getPreferredScriptFiles(
|
||||
this.app.vault
|
||||
.getFiles()
|
||||
.filter(
|
||||
(file) =>
|
||||
this.isInScriptFolder(file.path) && this.isScriptPath(file.path),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
loadScripts() {
|
||||
this.getListofScripts()?.forEach((f) => this.loadScript(f));
|
||||
async loadScripts(
|
||||
generation: number = this.scriptRegistryGeneration,
|
||||
): Promise<void> {
|
||||
await Promise.all(
|
||||
this.getListofScripts()?.map((file) =>
|
||||
this.loadScript(file, generation),
|
||||
) ?? [],
|
||||
);
|
||||
}
|
||||
|
||||
/** Reloads the script command and toolbar registry after discovery changes. */
|
||||
public async reloadScripts(): Promise<void> {
|
||||
const generation = ++this.scriptRegistryGeneration;
|
||||
this.unloadScripts();
|
||||
await this.loadScripts(generation);
|
||||
if (generation !== this.scriptRegistryGeneration) {
|
||||
return;
|
||||
}
|
||||
getExcalidrawViews(this.app, true).forEach((view) =>
|
||||
view.updatePinnedScripts(),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a non-destructive plan for moving scripts to the selected local
|
||||
* extension. A configured startup script outside the Scripts folder is
|
||||
* included. Same-named destination files are reported and skipped.
|
||||
*/
|
||||
public getScriptFileMigrationPlan(
|
||||
targetExtension: ScriptFileExtension,
|
||||
): ScriptFileRenamePlan {
|
||||
const sourceExtension = targetExtension === "js" ? "md" : "js";
|
||||
const scriptFolder = normalizePath(
|
||||
this.plugin.settings.scriptFolderPath.trim(),
|
||||
);
|
||||
const scriptFolderPrefix = scriptFolder ? `${scriptFolder}/` : "";
|
||||
const renamesBySource = new Map<
|
||||
string,
|
||||
ScriptFileRenamePlan["renames"][number]
|
||||
>();
|
||||
|
||||
if (scriptFolderPrefix) {
|
||||
this.app.vault
|
||||
.getFiles()
|
||||
.filter(
|
||||
(file) =>
|
||||
file.path.startsWith(scriptFolderPrefix) &&
|
||||
file.extension.toLowerCase() === sourceExtension,
|
||||
)
|
||||
.forEach((file) => {
|
||||
renamesBySource.set(file.path, {
|
||||
file,
|
||||
sourcePath: file.path,
|
||||
destinationPath: replaceScriptFileExtension(
|
||||
file.path,
|
||||
targetExtension,
|
||||
),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const resolvedStartupPath = resolveConfiguredStartupScriptPath(
|
||||
this.plugin.settings.startupScriptPath,
|
||||
);
|
||||
if (resolvedStartupPath?.toLowerCase().endsWith(`.${sourceExtension}`)) {
|
||||
const startupFile = this.app.vault.getFileByPath(resolvedStartupPath);
|
||||
if (startupFile) {
|
||||
const destinationPath = replaceScriptFileExtension(
|
||||
startupFile.path,
|
||||
targetExtension,
|
||||
);
|
||||
if (!renamesBySource.has(startupFile.path)) {
|
||||
renamesBySource.set(startupFile.path, {
|
||||
file: startupFile,
|
||||
sourcePath: startupFile.path,
|
||||
destinationPath,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const renames: ScriptFileRenamePlan["renames"] = [];
|
||||
const conflicts: string[] = [];
|
||||
for (const rename of renamesBySource.values()) {
|
||||
if (this.app.vault.getAbstractFileByPath(rename.destinationPath)) {
|
||||
conflicts.push(rename.sourcePath);
|
||||
} else {
|
||||
renames.push(rename);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
renames,
|
||||
conflicts,
|
||||
includesStartupScript: Boolean(
|
||||
resolvedStartupPath &&
|
||||
renames.some(({ sourcePath }) => sourcePath === resolvedStartupPath),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a previously confirmed script-extension migration. File events
|
||||
* are suppressed during the batch, pinned paths and the startup path are
|
||||
* updated atomically with settings, and completed renames are rolled back
|
||||
* if a later rename or settings write fails.
|
||||
*/
|
||||
public async migrateScriptFiles(plan: ScriptFileRenamePlan): Promise<number> {
|
||||
for (const rename of plan.renames) {
|
||||
if (
|
||||
rename.file.path !== rename.sourcePath ||
|
||||
this.app.vault.getAbstractFileByPath(rename.destinationPath)
|
||||
) {
|
||||
throw new Error(`Script migration plan is stale: ${rename.sourcePath}`);
|
||||
}
|
||||
}
|
||||
|
||||
const originalPinnedScripts = [...this.plugin.settings.pinnedScripts];
|
||||
const originalStartupScriptPath = this.plugin.settings.startupScriptPath;
|
||||
const destinationBySource = new Map(
|
||||
plan.renames.map(({ sourcePath, destinationPath }) => [
|
||||
sourcePath,
|
||||
destinationPath,
|
||||
]),
|
||||
);
|
||||
const resolvedStartupPath = resolveConfiguredStartupScriptPath(
|
||||
originalStartupScriptPath,
|
||||
);
|
||||
const completed: ScriptFileRenamePlan["renames"] = [];
|
||||
this.scriptFileEventsSuspended = true;
|
||||
|
||||
try {
|
||||
for (const rename of plan.renames) {
|
||||
await this.app.fileManager.renameFile(
|
||||
rename.file,
|
||||
rename.destinationPath,
|
||||
);
|
||||
completed.push(rename);
|
||||
}
|
||||
|
||||
this.plugin.settings.pinnedScripts = originalPinnedScripts.map(
|
||||
(path) => destinationBySource.get(path) ?? path,
|
||||
);
|
||||
const startupDestinationPath = resolvedStartupPath
|
||||
? destinationBySource.get(resolvedStartupPath)
|
||||
: null;
|
||||
if (startupDestinationPath) {
|
||||
this.plugin.settings.startupScriptPath = startupDestinationPath;
|
||||
}
|
||||
await this.plugin.saveSettings();
|
||||
return completed.length;
|
||||
} catch (error: unknown) {
|
||||
this.plugin.settings.pinnedScripts = originalPinnedScripts;
|
||||
this.plugin.settings.startupScriptPath = originalStartupScriptPath;
|
||||
for (const rename of completed.reverse()) {
|
||||
try {
|
||||
await this.app.fileManager.renameFile(rename.file, rename.sourcePath);
|
||||
} catch (rollbackError: unknown) {
|
||||
errorlog({
|
||||
where: "ScriptEngine.migrateScriptFiles.rollback",
|
||||
sourcePath: rename.sourcePath,
|
||||
error: rollbackError,
|
||||
});
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
this.scriptFileEventsSuspended = false;
|
||||
await this.reloadScripts();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Renames one managed script to the requested local extension while keeping
|
||||
* pinned-script and startup-script paths synchronized.
|
||||
*/
|
||||
public async renameManagedScriptFile(
|
||||
file: TFile,
|
||||
destinationPath: string,
|
||||
): Promise<void> {
|
||||
const sourcePath = file.path;
|
||||
const startupScriptPath = resolveConfiguredStartupScriptPath(
|
||||
this.plugin.settings.startupScriptPath,
|
||||
);
|
||||
await this.migrateScriptFiles({
|
||||
renames: [{ file, sourcePath, destinationPath }],
|
||||
conflicts: [],
|
||||
includesStartupScript: startupScriptPath === sourcePath,
|
||||
});
|
||||
}
|
||||
|
||||
public getScriptName(f: TFile | string): string {
|
||||
@@ -210,11 +467,17 @@ export class ScriptEngine {
|
||||
);
|
||||
}
|
||||
|
||||
async addScriptIconToMap(scriptPath: string, name: string) {
|
||||
async addScriptIconToMap(
|
||||
scriptPath: string,
|
||||
name: string,
|
||||
generation: number = this.scriptRegistryGeneration,
|
||||
): Promise<void> {
|
||||
const svgFilePath = getIMGFilename(scriptPath, "svg");
|
||||
const file = this.app.vault.getAbstractFileByPath(svgFilePath);
|
||||
const svgString: string =
|
||||
file && file instanceof TFile ? await this.app.vault.read(file) : null;
|
||||
const file = this.app.vault.getFileByPath(svgFilePath);
|
||||
const svgString: string = file ? await this.app.vault.read(file) : null;
|
||||
if (generation !== this.scriptRegistryGeneration) {
|
||||
return;
|
||||
}
|
||||
this.scriptIconMap = {
|
||||
...this.scriptIconMap,
|
||||
};
|
||||
@@ -227,12 +490,15 @@ export class ScriptEngine {
|
||||
this.updateToolPannels();
|
||||
}
|
||||
|
||||
loadScript(f: TFile) {
|
||||
if (f.extension !== "md") {
|
||||
async loadScript(
|
||||
f: TFile,
|
||||
generation: number = this.scriptRegistryGeneration,
|
||||
): Promise<void> {
|
||||
if (!this.isScriptPath(f.path)) {
|
||||
return;
|
||||
}
|
||||
const scriptName = this.getScriptName(f);
|
||||
void this.addScriptIconToMap(f.path, scriptName);
|
||||
const iconLoad = this.addScriptIconToMap(f.path, scriptName, generation);
|
||||
this.plugin.addCommand({
|
||||
id: scriptName,
|
||||
name: `(Script) ${scriptName}`,
|
||||
@@ -255,14 +521,13 @@ export class ScriptEngine {
|
||||
return false;
|
||||
},
|
||||
});
|
||||
this.loadedScriptPaths.add(f.path);
|
||||
await iconLoad;
|
||||
}
|
||||
|
||||
unloadScripts() {
|
||||
const scripts = this.app.vault
|
||||
.getFiles()
|
||||
.filter((f: TFile) => f.path.startsWith(this.scriptPath));
|
||||
scripts.forEach((f) => {
|
||||
this.unloadScript(this.getScriptName(f), f.path);
|
||||
Array.from(this.loadedScriptPaths).forEach((path) => {
|
||||
this.unloadScript(this.getScriptName(path), path);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -410,9 +675,7 @@ export class ScriptEngine {
|
||||
}
|
||||
|
||||
unloadScript(basename: string, path: string) {
|
||||
if (!path.endsWith(".md")) {
|
||||
return;
|
||||
}
|
||||
this.loadedScriptPaths.delete(path);
|
||||
delete this.scriptIconMap[path];
|
||||
this.scriptIconMap = { ...this.scriptIconMap };
|
||||
this.updateToolPannels();
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { normalizePath, type TFile } from "obsidian";
|
||||
|
||||
export type ScriptFileExtension = "md" | "js";
|
||||
|
||||
/** Returns whether a path names a supported Excalidraw Automate script file. */
|
||||
export const isScriptFilePath = (path: string): boolean =>
|
||||
/\.(?:md|js)$/i.test(path);
|
||||
|
||||
/** Returns a script path with its final `.md` or `.js` suffix replaced. */
|
||||
export const replaceScriptFileExtension = (
|
||||
path: string,
|
||||
extension: ScriptFileExtension,
|
||||
): string =>
|
||||
isScriptFilePath(path)
|
||||
? path.replace(/\.(?:md|js)$/i, `.${extension}`)
|
||||
: path;
|
||||
|
||||
/** Returns the filename stem shared by equivalent `.md` and `.js` scripts. */
|
||||
export const getScriptFileStem = (filename: string): string =>
|
||||
filename.replace(/\.(?:md|js)$/i, "");
|
||||
|
||||
/**
|
||||
* Collapses equivalent `.md` and `.js` paths to one script, preferring the
|
||||
* Markdown file when both exist.
|
||||
*/
|
||||
export const getPreferredScriptFiles = (files: Iterable<TFile>): TFile[] => {
|
||||
const filesByStem = new Map<string, TFile>();
|
||||
for (const file of files) {
|
||||
const stem = getScriptFileStem(file.path);
|
||||
const existing = filesByStem.get(stem);
|
||||
if (
|
||||
!existing ||
|
||||
(existing.extension.toLowerCase() === "js" &&
|
||||
file.extension.toLowerCase() === "md")
|
||||
) {
|
||||
filesByStem.set(stem, file);
|
||||
}
|
||||
}
|
||||
return Array.from(filesByStem.values());
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the extension used for locally managed scripts. JavaScript storage
|
||||
* is effective only when JavaScript script loading is also enabled.
|
||||
*/
|
||||
export const getManagedScriptFileExtension = (
|
||||
allowJavaScriptFiles: boolean,
|
||||
storeScriptFilesAsJavaScript: boolean,
|
||||
): ScriptFileExtension =>
|
||||
allowJavaScriptFiles && storeScriptFilesAsJavaScript ? "js" : "md";
|
||||
|
||||
/** Resolves a configured startup path while preserving the `.md` default. */
|
||||
export const resolveConfiguredStartupScriptPath = (
|
||||
configuredPath: string,
|
||||
): string | null => {
|
||||
const path = normalizePath(configuredPath.trim());
|
||||
if (!path) {
|
||||
return null;
|
||||
}
|
||||
return isScriptFilePath(path) ? path : `${path}.md`;
|
||||
};
|
||||
@@ -8,6 +8,10 @@ import { errorlog } from "./coreUtils";
|
||||
import { getIMGFilename, createOrOverwriteFile } from "./fileUtils";
|
||||
import { hideElement, setButtonBgColor, showElement } from "./styleUtils";
|
||||
import type ExcalidrawPlugin from "src/core/main";
|
||||
import {
|
||||
getManagedScriptFileExtension,
|
||||
getScriptFileStem,
|
||||
} from "./scriptFileUtils";
|
||||
|
||||
export const installButton = async (
|
||||
plugin: ExcalidrawPlugin,
|
||||
@@ -61,13 +65,17 @@ export const installButton = async (
|
||||
});
|
||||
}
|
||||
const fname = decodedURI.substring(decodedURI.lastIndexOf("/") + 1);
|
||||
const scriptStem = getScriptFileStem(fname);
|
||||
const folder = `${plugin.settings.scriptFolderPath}/${SCRIPT_INSTALL_FOLDER}`;
|
||||
const downloaded = plugin.app.vault
|
||||
.getFiles()
|
||||
.filter((f) => f.path.startsWith(folder) && f.name === fname)
|
||||
.sort((a, b) => (a.path > b.path ? 1 : -1));
|
||||
let scriptFile = downloaded[0];
|
||||
const scriptPath = scriptFile?.path ?? `${folder}/${fname}`;
|
||||
const getLocalScriptPath = (): string =>
|
||||
`${folder}/${scriptStem}.${getManagedScriptFileExtension(
|
||||
plugin.settings.allowJavaScriptFiles,
|
||||
plugin.settings.storeScriptFilesAsJavaScript,
|
||||
)}`;
|
||||
let scriptFile =
|
||||
plugin.app.vault.getFileByPath(`${folder}/${scriptStem}.md`) ??
|
||||
plugin.app.vault.getFileByPath(`${folder}/${scriptStem}.js`);
|
||||
let scriptPath = getLocalScriptPath();
|
||||
const svgPath = getIMGFilename(scriptPath, "svg");
|
||||
let svgFile = plugin.app.vault.getFileByPath(svgPath);
|
||||
setButtonText(scriptFile ? "CHECKING" : "INSTALL");
|
||||
@@ -89,6 +97,19 @@ export const installButton = async (
|
||||
};
|
||||
|
||||
try {
|
||||
scriptPath = getLocalScriptPath();
|
||||
if (scriptFile && scriptFile.path !== scriptPath) {
|
||||
if (plugin.app.vault.getFileByPath(scriptPath)) {
|
||||
// Keep the authoritative Markdown variant when both extensions
|
||||
// already exist; format migration reports and skips this pair.
|
||||
scriptPath = scriptFile.path;
|
||||
} else {
|
||||
await plugin.scriptEngine.renameManagedScriptFile(
|
||||
scriptFile,
|
||||
scriptPath,
|
||||
);
|
||||
}
|
||||
}
|
||||
scriptFile = await download(source, scriptFile, scriptPath);
|
||||
if (!scriptFile) {
|
||||
setButtonText("ERROR");
|
||||
@@ -97,7 +118,7 @@ export const installButton = async (
|
||||
svgFile = await download(getIMGFilename(source, "svg"), svgFile, svgPath);
|
||||
setButtonText("UPTODATE");
|
||||
if (Object.keys(plugin.scriptEngine.scriptIconMap).length === 0) {
|
||||
plugin.scriptEngine.loadScripts();
|
||||
await plugin.scriptEngine.loadScripts();
|
||||
}
|
||||
const restartSidepanelTabIfActive = async () => {
|
||||
if (!plugin.scriptEngine || !(scriptFile instanceof TFile)) {
|
||||
@@ -110,7 +131,7 @@ export const installButton = async (
|
||||
}
|
||||
try {
|
||||
await spView.restartTabForScript(scriptName);
|
||||
} catch (error) {
|
||||
} catch (error: unknown) {
|
||||
errorlog({
|
||||
where:
|
||||
"ExcalidrawPlugin.registerInstallCodeblockProcessor.restartSidepanelTab",
|
||||
@@ -121,7 +142,7 @@ export const installButton = async (
|
||||
};
|
||||
await restartSidepanelTabIfActive();
|
||||
new Notice(`Installed: ${scriptFile.basename}`);
|
||||
} catch (e) {
|
||||
} catch (e: unknown) {
|
||||
new Notice(`Error installing script: ${fname}`);
|
||||
errorlog({
|
||||
where:
|
||||
@@ -141,11 +162,12 @@ export const installButton = async (
|
||||
}
|
||||
|
||||
const files = new Map<string, number>();
|
||||
JSON.parse(
|
||||
const directoryInfo = JSON.parse(
|
||||
await request({
|
||||
url: URLs.RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_DIRECTORY_INFO_JSON,
|
||||
}),
|
||||
).forEach((f: RemoteDirectoryInfo) => files.set(f.fname, f.mtime));
|
||||
) as RemoteDirectoryInfo[];
|
||||
directoryInfo.forEach((file) => files.set(file.fname, file.mtime));
|
||||
|
||||
const checkModifyDate = (
|
||||
gitFilename: string,
|
||||
|
||||
+22
-14
@@ -53,6 +53,11 @@ import { getEmptyDrawingElementsRuntime } from "src/constants/emptydrawing";
|
||||
import { makeEntitiesXmlSafe, sanitizedFragment } from "./htmlUtils";
|
||||
import { URLs } from "src/constants/safeUrls";
|
||||
import { isInstanceOfSVGSVGElement } from "./typechecks";
|
||||
import {
|
||||
getPreferredScriptFiles,
|
||||
getScriptFileStem,
|
||||
isScriptFilePath,
|
||||
} from "./scriptFileUtils";
|
||||
export { arrayToMap };
|
||||
export { errorlog, getDataURL } from "./coreUtils";
|
||||
export { addAppendUpdateCustomData } from "./elementCustomDataUtils";
|
||||
@@ -159,10 +164,14 @@ async function checkScriptUpdates() {
|
||||
return;
|
||||
}
|
||||
|
||||
const folder = `${EXCALIDRAW_PLUGIN.settings.scriptFolderPath}/${SCRIPT_INSTALL_FOLDER}/`;
|
||||
const installedScripts = EXCALIDRAW_PLUGIN.app.vault
|
||||
.getFiles()
|
||||
.filter((f) => f.path.startsWith(folder) && f.extension === "md");
|
||||
const folder = `${EXCALIDRAW_PLUGIN.settings.scriptFolderPath}/${SCRIPT_INSTALL_FOLDER}`;
|
||||
const installedScripts = getPreferredScriptFiles(
|
||||
EXCALIDRAW_PLUGIN.app.vault
|
||||
.getFiles()
|
||||
.filter(
|
||||
(file) => file.parent?.path === folder && isScriptFilePath(file.path),
|
||||
),
|
||||
);
|
||||
|
||||
if (installedScripts.length === 0) {
|
||||
return;
|
||||
@@ -185,24 +194,23 @@ async function checkScriptUpdates() {
|
||||
|
||||
// Check if any installed scripts have updates
|
||||
const updates: string[] = [];
|
||||
let hasUpdates = false;
|
||||
for (const scriptFile of installedScripts) {
|
||||
const filename = scriptFile.name;
|
||||
if (files.has(filename)) {
|
||||
const mtime = files.get(filename);
|
||||
if (mtime > scriptFile.stat.mtime) {
|
||||
updates.push(scriptFile.path.split(folder)?.[1]?.split(".md")[0]);
|
||||
hasUpdates = true;
|
||||
}
|
||||
const stem = getScriptFileStem(scriptFile.name);
|
||||
const remoteMtime = Math.max(
|
||||
files.get(`${stem}.md`) ?? 0,
|
||||
files.get(`${stem}.js`) ?? 0,
|
||||
);
|
||||
if (remoteMtime > scriptFile.stat.mtime) {
|
||||
updates.push(stem);
|
||||
}
|
||||
}
|
||||
|
||||
if (hasUpdates) {
|
||||
if (updates.length > 0) {
|
||||
const message = `${t("SCRIPT_UPDATES_AVAILABLE")}\n\n${updates.sort().join("\n")}`;
|
||||
new Notice(message, 8000 + updates.length * 1000);
|
||||
log(message);
|
||||
}
|
||||
} catch (e) {
|
||||
} catch (e: unknown) {
|
||||
log({ where: "Utils/checkScriptUpdates", error: e });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1096,6 +1096,12 @@ End Obsidian Sheets Plus support
|
||||
min-width: calc(6 * var(--default-button-size));
|
||||
}
|
||||
|
||||
/* Radix portals the canvas menu under the owning document's body. Keep it on
|
||||
Obsidian's menu layer so body-level Obsidian tooltips remain above it. */
|
||||
body > [data-radix-portal] .main-menu {
|
||||
z-index: var(--layer-menu);
|
||||
}
|
||||
|
||||
.excalidraw-pen-settings-floating-actions {
|
||||
position: sticky;
|
||||
bottom: -20px;
|
||||
|
||||
Reference in new issue
Block a user