diff --git a/scripts/testing/codeBlockInsertion.source.test.mjs b/scripts/testing/codeBlockInsertion.source.test.mjs new file mode 100644 index 00000000..db39e2c3 --- /dev/null +++ b/scripts/testing/codeBlockInsertion.source.test.mjs @@ -0,0 +1,97 @@ +/** Execute the shared clipboard/context-menu workflow, including deferred UI decisions. */ +import assert from "node:assert/strict"; +import test from "node:test"; +import { sourceHarness } from "./sourceHarness.mjs"; + +let fixture; +const harness = sourceHarness({ + "../../shared/Dialogs/Prompt": { + GenericInputPrompt: { Prompt: async (...args) => fixture.input(args[3]) }, + MultiOptionConfirmationPrompt: class { + constructor(plugin, message, buttons, cta, toggle) { + fixture.prompts.push({ message, buttons, cta, toggle }); + this.toggleValue = fixture.remember; + this.waitForClose = Promise.resolve().then(() => fixture.choose()); + } + }, + }, + "../../shared/MarkdownImage": { insertMarkdownImage: async (...args) => fixture.images.push(args) }, + "../../utils/excalidrawViewUtils": { addBackOfTheNoteCard: async (...args) => { fixture.cards.push(args); return "card"; } }, + "../../constants/constants": { CaptureUpdateAction: { EVENTUALLY: "EVENTUALLY" } }, + "./pastedCodeCardSizing": { fitPastedCodeBlockCard: async (...args) => fixture.fits.push(args) }, + "../../lang/helpers": { t: key => key }, +}); +const { insertCodeBlock } = await harness.importModule("src/view/managers/codeBlockInsertion.ts"); +test.after(() => harness.close()); +const fenced = "```js\nconsole.log(1);\n```"; +function setup(preference = "ask") { + fixture = { prompts: [], cards: [], images: [], fits: [], inputs: [], saves: 0, remember: false, + choose: () => "embeddable", input(title) { this.inputs.push(title); return title === "PASTE_CODEBLOCK_LANGUAGE" ? "js" : "Code"; } }; + const view = { file: {}, excalidrawAPI: {}, currentPosition: { x: 12, y: 34 }, isClosingOrMigrating: () => false, + getBackOfTheNoteSections: async () => ["Code", "Code 1"], + plugin: { app: {}, settings: { pasteCodeBlockAs: preference }, async saveSettings() { fixture.saves++; } } }; + return { view, f: fixture }; +} +test("code insertion asks by default and inserts the chosen Markdown image without a card title", async () => { + const { view, f } = setup(); f.choose = () => "markdown-image"; + await insertCodeBlock(view, " \r\n```js\r\nconsole.log(1);\r\n``` "); + assert.equal(f.prompts.length, 1); assert.equal(f.cards.length, 0); assert.equal(f.inputs.length, 0); + assert.deepEqual(f.images, [[view, fenced, { x: 12, y: 34 }]]); assert.equal(f.saves, 0); +}); +test("remembering either format serializes the preference and avoids the next prompt", async () => { + for (const decision of ["embeddable", "markdown-image"]) { + const { view, f } = setup(); f.choose = () => decision; f.remember = true; + await insertCodeBlock(view, fenced); await insertCodeBlock(view, fenced); + assert.equal(view.plugin.settings.pasteCodeBlockAs, decision); assert.equal(f.saves, 1); assert.equal(f.prompts.length, 1); + assert.equal((decision === "embeddable" ? f.cards : f.images).length, 2); + } +}); +test("unremembered choices keep asking and closing the dialog makes no changes", async () => { + const { view, f } = setup(); await insertCodeBlock(view, fenced); + f.choose = () => null; f.remember = true; await insertCodeBlock(view, fenced); + assert.equal(f.prompts.length, 2); assert.equal(f.cards.length, 1); assert.equal(f.images.length, 0); + assert.equal(view.plugin.settings.pasteCodeBlockAs, "ask"); assert.equal(f.saves, 0); +}); +test("configured formats bypass the chooser and preserve language, unique card title and initial-fit history", async () => { + for (const preference of ["embeddable", "markdown-image"]) { + const { view, f } = setup(preference); await insertCodeBlock(view, "console.log(1);"); + assert.equal(f.prompts.length, 0); assert.equal(f.inputs[0], "PASTE_CODEBLOCK_LANGUAGE"); + if (preference === "embeddable") { + assert.equal(f.cards[0][1], "Code 2"); assert.equal(f.cards[0][3], fenced); + assert.equal(f.cards[0][7], "EVENTUALLY"); assert.deepEqual(f.fits, [[view, "card"]]); + } else { assert.equal(f.images[0][1], fenced); assert.equal(f.inputs.length, 1); assert.deepEqual(f.fits, []); } + } +}); +test("missing and unfamiliar preferences safely ask without deleting persisted keys", async () => { + for (const preference of [undefined, "future-format"]) { + const { view, f } = setup(preference); view.plugin.settings.pasteCodeBlockAs = preference; + f.choose = () => null; await insertCodeBlock(view, fenced); + assert.equal(f.prompts.length, 1); assert.equal(view.plugin.settings.pasteCodeBlockAs, preference); + } +}); +test("a file switch, API replacement or migration during a dialog cancels insertion and remembering", async () => { + for (const retire of [view => view.file = {}, view => view.excalidrawAPI = {}, view => view.isClosingOrMigrating = () => true]) { + const { view, f } = setup(); f.remember = true; f.choose = () => { retire(view); return "markdown-image"; }; + await insertCodeBlock(view, fenced); + assert.deepEqual(f.cards, []); assert.deepEqual(f.images, []); assert.equal(f.saves, 0); + } +}); +test("cancelled language and title prompts and empty clipboard content are no-ops", async () => { + for (const source of ["plain code", fenced]) { + const { view, f } = setup("embeddable"); f.input = () => { throw "No input given."; }; + await insertCodeBlock(view, source); + assert.deepEqual(f.cards, []); assert.deepEqual(f.images, []); assert.equal(f.saves, 0); + } + const { view, f } = setup(); await insertCodeBlock(view, " \r\n "); + assert.deepEqual(f.prompts, []); assert.deepEqual(f.cards, []); +}); +test("deferred language, title, settings writes and section lookup retain the exact drawing owner", async () => { + for (const phase of ["language", "title", "save", "sections"]) { + const { view, f } = setup(phase === "save" ? "ask" : "embeddable"); + if (phase === "language" || phase === "title") f.input = () => { view.file = {}; return "value"; }; + if (phase === "save") { f.remember = true; view.plugin.saveSettings = async () => { view.file = {}; }; } + if (phase === "sections") view.getBackOfTheNoteSections = async () => { view.file = {}; return []; }; + await insertCodeBlock(view, phase === "language" ? "plain code" : fenced); + assert.deepEqual(f.cards, []); assert.deepEqual(f.images, []); + } +}); diff --git a/scripts/testing/host/codeBlockFormats.mjs b/scripts/testing/host/codeBlockFormats.mjs new file mode 100644 index 00000000..bd7093c6 --- /dev/null +++ b/scripts/testing/host/codeBlockFormats.mjs @@ -0,0 +1,147 @@ +/** Real editor paste/menu routing, modal controls, local Markdown images and settings persistence. */ +export async function exerciseCodeBlockFormats(c, env, modifier) { + const { p, doc, win, check, openDrawing, saveReopen, click, key, input, geometry } = env; + await c.case("native:code-block-format:" + geometry().requested.id, ["P01", "P02", "P05"], async () => { + let view = await openDrawing("code-formats"); + view.excalidrawAPI.updateScene({ elements: [], captureUpdate: "NEVER" }); + const source = " \r\n```js\r\nconsole.log('code format');\r\n``` \r\n"; + const normalized = "```js\nconsole.log('code format');\n```"; + const settingsPath = app.vault.configDir + "/plugins/obsidian-excalidraw-plugin/data.json"; + const disk = async () => JSON.parse(await app.vault.adapter.read(settingsPath)); + const ownedModals = new Set(); + c.defer(() => { for (const modal of ownedModals) if (modal.isConnected) modal.querySelector(".modal-close-button")?.click(); }); + const chooser = () => [...doc.querySelectorAll(".modal")].find(modal => modal.querySelector(".excalidraw-multiOptionConfirmationPrompt-message")?.textContent.includes("Insert this code block")); + const choose = async (label, remember = false) => { + let modal; + await c.waitFor(() => { + c.observations.codeFormat = { preference: p.settings.pasteCodeBlockAs, modifiers: view.modifierKeyDown, active: doc.activeElement?.outerHTML.slice(0, 500), modals: [...doc.querySelectorAll(".modal")].map(modal => modal.textContent.slice(0, 800)), elements: view.excalidrawAPI.getSceneElements().map(element => element.type) }; + return modal = chooser(); + }, "code format chooser in owning window"); + ownedModals.add(modal); + if (remember) await click(modal.querySelector(".checkbox-container")); + const button = [...modal.querySelectorAll("button")].find(button => button.textContent === label); + await click(button); + await c.waitFor(() => !modal.isConnected, "format chooser closes"); + }; + const title = async (value) => { + let modal; + await c.waitFor(() => modal = [...doc.querySelectorAll(".modal")].find(modal => modal.querySelector(".modal-title")?.textContent === "Code Block Title"), "embeddable title prompt"); + ownedModals.add(modal); + const area = modal.querySelector("textarea"); area.value = value; + area.dispatchEvent(new win.Event("input", { bubbles: true })); + await click(modal.querySelector("button.mod-cta")); + }; + const paste = async () => { + const transfer = new win.DataTransfer(); transfer.setData("text/plain", source); + const editor = view.containerEl.querySelector(".excalidraw"); editor.focus(); + await key("Escape", "Escape", 27); + const r = view.containerEl.querySelector("canvas.interactive").getBoundingClientRect(); + await input("Input.dispatchMouseEvent", { type: "mouseMoved", x: r.x + r.width / 2, y: r.y + r.height / 2, button: "none" }); + editor.dispatchEvent(new win.ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: transfer })); + }; + const menu = async () => { + // Substitute only the OS clipboard boundary; leave the user's clipboard intact. + // The owning editor renders its real context menu and receives trusted clicks. + const clipboard = win.navigator.clipboard; + const original = Object.getOwnPropertyDescriptor(clipboard, "readText"); + Object.defineProperty(clipboard, "readText", { configurable: true, value: async () => source }); + const restore = () => original ? Object.defineProperty(clipboard, "readText", original) : delete clipboard.readText; + c.defer(restore); + try { + view.excalidrawAPI.updateScene({ appState: { selectedElementIds: {} }, captureUpdate: "NEVER", forceFlushSync: true }); + const canvas = view.containerEl.querySelector("canvas.interactive"), r = canvas.getBoundingClientRect(); + const point = { x: r.x + r.width * 0.12, y: r.y + r.height * 0.6 }; + await input("Input.dispatchMouseEvent", ["mousePressed", "mouseReleased"].map(type => ({ type, ...point, button: "right", buttons: type === "mousePressed" ? 2 : 0, clickCount: 1 }))); + let button; + await c.waitFor(() => button = doc.querySelector('.context-menu [data-testid="pasteCodeblock"] button'), "Paste code block context-menu action"); + await click(button); + await c.waitFor(() => !doc.querySelector('.context-menu [data-testid="pasteCodeblock"]'), "context menu closes"); + } finally { restore(); } + }; + const inserted = async (before, type) => { + let element; + await c.waitFor(() => element = view.excalidrawAPI.getSceneElements().find(element => !before.has(element.id) && element.type === type), "inserted " + type); + return element; + }; + const ids = () => new Set(view.excalidrawAPI.getSceneElements().map(element => element.id)); + const assertImage = element => { + check(element.customData?.markdownImage?.source === "local", "code image is not editable local Markdown"); + check(view.excalidrawData.getMarkdownImage(element.fileId)?.markdown === normalized, "code image source/fences/line endings changed"); + check(element.width > 0 && element.height > 0, "code image has no rendered geometry"); + }; + + p.settings.pasteCodeBlockAs = "ask"; await p.saveSettings(); + // Clearing the seed drawing is a real edit. Flush it before comparing data: + // opening any modal blurs the canvas and legitimately autosaves that edit. + await view.forceSave(true, true); + const initialData = view.data; + await paste(); await choose("Cancel", true); + check(ids().size === 0, "cancel inserted an element"); + check(view.data === initialData, "cancel changed drawing or back-of-note data after the baseline flush"); + check(p.settings.pasteCodeBlockAs === "ask" && (await disk()).pasteCodeBlockAs === "ask", "cancel remembered a preference"); + + await paste(); await choose("Markdown image"); + let image = await inserted(new Set(), "image"); assertImage(image); + check(p.settings.pasteCodeBlockAs === "ask" && (await disk()).pasteCodeBlockAs === "ask", "unremembered choice persisted"); + const imageId = image.id; + view.containerEl.querySelector(".excalidraw").focus(); + await key("z", "KeyZ", 90, modifier); + await c.waitFor(() => !ids().has(imageId), "image insertion has one undo step"); + // Local Markdown images use the existing deletion confirmation, including + // undo. Resolve it before redo or cleanup can wait for its save forever. + let deletionModal; + await c.waitFor(() => deletionModal = [...doc.querySelectorAll(".modal")].find(modal => modal.querySelector(".excalidraw-multiOptionConfirmationPrompt-message")?.textContent.includes("Delete the Markdown text stored for this image?")), "existing Markdown deletion prompt after undo"); + ownedModals.add(deletionModal); + await click([...deletionModal.querySelectorAll("button")].find(button => button.textContent === "Keep Markdown text")); + await c.waitFor(() => !deletionModal.isConnected && !view.markdownImageController.markdownImageDeletionPrompt && !view.isSaveInProgress(), "Markdown deletion choice and save settle"); + view.containerEl.querySelector(".excalidraw").focus(); + await key("z", "KeyZ", 90, modifier | 8); + await c.waitFor(() => ids().has(imageId), "image redo"); + image = view.excalidrawAPI.getSceneElements().find(element => element.id === imageId); + assertImage(image); + view.excalidrawAPI.mutateElement(image, { width: 440, height: 180 }); + view.excalidrawAPI.updateScene({ captureUpdate: "IMMEDIATELY" }); + view = await saveReopen(view); + image = view.excalidrawAPI.getSceneElements().find(element => element.id === imageId); + assertImage(image); check(image.width === 440 && image.height === 180, "image resize/source did not persist"); + + let before = ids(); + await menu(); await choose("Interactive embeddable"); await title("Format card"); + const card = await inserted(before, "embeddable"); + await c.waitFor(() => view.excalidrawAPI.getSceneElements().find(element => element.id === card.id)?.height < 350, "chosen embeddable keeps initial autosize"); + check(p.settings.pasteCodeBlockAs === "ask", "embeddable unremembered choice changed setting"); + + before = ids(); await menu(); await choose("Markdown image", true); + assertImage(await inserted(before, "image")); + check(p.settings.pasteCodeBlockAs === "markdown-image" && (await disk()).pasteCodeBlockAs === "markdown-image", "remembered image choice did not reach data.json"); + before = ids(); await paste(); assertImage(await inserted(before, "image")); + check(!chooser(), "remembered format still asks"); + + // Exercise the shared specification through the legacy control and declarative binding. + const tab = p.settingsTab, specs = tab.getCodeBlockInsertionSpecs(); + const container = doc.body.createDiv(); c.defer(() => container.remove()); + tab.renderSettingSpecs(container, specs); + const select = container.querySelector("select"); + check(select && [...select.options].map(option => option.value).sort().join() === ["ask", "embeddable", "markdown-image"].sort().join(), "setting is missing one of the requested formats"); + select.value = "ask"; select.dispatchEvent(new win.Event("change", { bubbles: true })); + await c.waitFor(async () => p.settings.pasteCodeBlockAs === "ask" && (await disk()).pasteCodeBlockAs === "ask", "legacy setting persists Always ask"); + container.remove(); + const flatten = items => items.flatMap(item => [item, ...flatten(item.items || [])]); + const definitions = flatten(tab.getSettingDefinitions()); + const definition = definitions.find(item => item.control?.key === "pasteCodeBlockAs"); + check(definition, "code format setting is missing from the complete declarative tree"); + check(definition.control.key === "pasteCodeBlockAs" && Object.keys(definition.control.options).length === 3, "declarative setting diverges from legacy setting"); + await tab.setControlValue("pasteCodeBlockAs", "embeddable"); + check((await disk()).pasteCodeBlockAs === "embeddable", "declarative preference was not serialized"); + before = ids(); await paste(); await title("Configured card"); + await inserted(before, "embeddable"); check(!chooser(), "configured Embeddable still asks"); + + p.settings.pasteCodeBlockAs = "ask"; await p.saveSettings(); + before = ids(); await paste(); await choose("Interactive embeddable", true); await title("Remembered card"); + await inserted(before, "embeddable"); + check((await disk()).pasteCodeBlockAs === "embeddable", "remembered embeddable was not serialized"); + view = await saveReopen(view); + check(view.excalidrawAPI.getSceneElements().filter(element => element.type === "image").every(element => view.excalidrawData.getMarkdownImage(element.fileId)?.markdown === normalized), "saved code images lost editable source"); + return { assertions: ["real editor paste event and trusted context-menu action share chooser", "cancel and both unremembered formats", "both remembered formats serialize and bypass chooser", "legacy control and declarative binding expose all three options", "Markdown image source, undo/redo and resized save/reopen", "embeddable titles and initial autosize preserved"], clipboard: "synthetic paste payload; context-menu OS clipboard read substituted without touching user clipboard", owner: geometry().requested.id }; + }); +} diff --git a/scripts/testing/host/codeCards.mjs b/scripts/testing/host/codeCards.mjs index 7f25d041..a0ce9f14 100644 --- a/scripts/testing/host/codeCards.mjs +++ b/scripts/testing/host/codeCards.mjs @@ -6,8 +6,9 @@ import { behaviorEnvironment } from "./behaviorEnvironment.mjs"; import { behaviorInputDriver } from "./behaviorMatrix.mjs"; import { completeConsoleErrors } from "./debuggerSession.mjs"; import { settleBrowserDiagnostics, splitWindowErrors } from "./browserDiagnostics.mjs"; +import { exerciseCodeBlockFormats } from "./codeBlockFormats.mjs"; -export const codeCardCaseIds = ["main", "popout"].map(context => "native:workflow-code-card-2894:" + context); +export const codeCardCaseIds = ["main", "popout"].flatMap(context => ["native:workflow-code-card-2894:" + context, "native:code-block-format:" + context]); export async function runCodeCardScenario({ cli, drawingPath }) { const template = readFileSync(new URL("../../../tests/vault/Drawings/Uncompressed.excalidraw.md", import.meta.url), "utf8"); @@ -16,11 +17,12 @@ export async function runCodeCardScenario({ cli, drawingPath }) { const execute = new Function(`return async function(c,path,context,template,modifier){ const env=await (${behaviorEnvironment.toString()})(c,path,context,template,${completeConsoleErrors.toString()},${settleBrowserDiagnostics.toString()}); await (${exerciseCodeCards.toString()})(c,env,modifier); + await (${exerciseCodeBlockFormats.toString()})(c,env,modifier); return {tests:c.tests,consoleErrors:c.externalConsoleErrors||[],windowErrors:env.windowErrors,browserIdle:env.browserIdle}; }`)(); const result = await runInAppTask({ cli, execute, args: [drawingPath, { id, input: "mouse" }, template, process.platform === "darwin" ? 4 : 2], - timeoutMs: 180000, cleanupMs: 60000, onRequest: behaviorInputDriver(cli), + timeoutMs: 240000, cleanupMs: 60000, onRequest: behaviorInputDriver(cli), }).catch(error => { error.evidence = [...tests, ...(error.evidence || [])]; throw error; }); tests.push(...result.tests); consoleErrors.push(...result.consoleErrors); windowErrors.push(...result.windowErrors); browserIdle.push(...result.browserIdle); } @@ -34,6 +36,7 @@ export async function runCodeCardScenario({ cli, drawingPath }) { async function exerciseCodeCards(c, env, modifier) { const { p, doc, win, check, openDrawing, saveReopen, geometry, click, key } = env; await c.case("native:workflow-code-card-2894:" + geometry().requested.id, ["P02", "P05"], async () => { + p.settings.pasteCodeBlockAs = "embeddable"; let view = await openDrawing("pasted-code"); view.excalidrawAPI.updateScene({ elements: [], captureUpdate: "NEVER" }); const ea = p.ea.getAPI(view); @@ -61,7 +64,7 @@ async function exerciseCodeCards(c, env, modifier) { const api = view.excalidrawAPI, before = new Set(api.getSceneElements().map(element => element.id)); const source = variant.plain ? variant.body : (variant.whitespace ? " \r\n " : "") + "```" + variant.type + "\r\n" + variant.body + "\r\n```" + (variant.whitespace ? " \r\n" : ""); const pending = view.pasteCodeBlock(source); - if (variant.plain) await prompt("type codeblock type", variant.type); + if (variant.plain) await prompt("Code block language", variant.type); await prompt("Code Block Title", "Pasted code"); await pending; let element = api.getSceneElements().find(element => element.type === "embeddable" && !before.has(element.id)); diff --git a/scripts/testing/host/devices.mjs b/scripts/testing/host/devices.mjs index bdf8eb01..1be8520c 100644 --- a/scripts/testing/host/devices.mjs +++ b/scripts/testing/host/devices.mjs @@ -311,6 +311,7 @@ async function exerciseDevice(c, path, fixture, profile) { "tabletUIMode", "phoneUIMode", "penModeSingleFingerPanning", + "pasteCodeBlockAs", ].map((key) => [key, p.settings[key]]), ); const desktopMode = localStorage.getItem("excalidraw.desktopUIMode"); @@ -685,6 +686,42 @@ async function exerciseDevice(c, path, fixture, profile) { api.updateScene({ appState: { zenModeEnabled: false }, captureUpdate: "NEVER" }); } } + // The shared chooser must wrap and remain tappable in each actual host mode. + p.settings.pasteCodeBlockAs = "ask"; + const codeSource = "```js\nconsole.log('device code');\n```"; + const insertion = view.pasteCodeBlock(codeSource); + let codeModal; + c.defer(() => { if (codeModal?.isConnected) codeModal.querySelector(".modal-close-button")?.click(); }); + let lastGeometry, stableSince; + await c.waitFor(() => { + codeModal = [...doc.querySelectorAll(".modal")].find(modal => modal.querySelector(".excalidraw-multiOptionConfirmationPrompt-message")?.textContent.includes("Insert this code block")); + if (!codeModal) return false; + const geometry = JSON.stringify([...codeModal.querySelectorAll("button,.checkbox-container")].map(element => rect(element))); + if (geometry !== lastGeometry) { lastGeometry = geometry; stableSince = Date.now(); } + return Date.now() - stableSince > 150; + }, "stable code format chooser"); + const codeControls = [...codeModal.querySelectorAll("button,.checkbox-container")]; + const tapCodeControl = async element => { + const bounds = rect(element), x = bounds.x + bounds.width / 2, y = bounds.y + bounds.height / 2; + check(bounds.width > 0 && bounds.height > 0 && bounds.x >= 0 && bounds.right <= innerWidth && bounds.y >= 0 && bounds.bottom <= innerHeight && element.contains(doc.elementFromPoint(x, y)), "Code format control clipped or covered"); + if (profile.input === "mouse") await input("mouseMoved", x, y); + await input(profile.input === "touch" ? "touchStart" : "mousePressed", x, y); + await input(profile.input === "touch" ? "touchEnd" : "mouseReleased", x, y); + }; + for (const control of codeControls) { + const bounds = rect(control), x = bounds.x + bounds.width / 2, y = bounds.y + bounds.height / 2; + check(bounds.width > 0 && bounds.height > 0 && bounds.x >= 0 && bounds.right <= innerWidth && bounds.y >= 0 && bounds.bottom <= innerHeight && control.contains(doc.elementFromPoint(x, y)), "Code format option or remember toggle is unusable"); + } + const toggle = codeModal.querySelector(".checkbox-container"); + await tapCodeControl(toggle); check(toggle.classList.contains("is-enabled"), "Code format remember toggle did not enable"); + await tapCodeControl(toggle); check(!toggle.classList.contains("is-enabled"), "Code format remember toggle did not disable"); + const markdownButton = [...codeModal.querySelectorAll("button")].find(button => button.textContent === "Markdown image"); + const codeFormat = { bounds: rect(codeModal), controls: codeControls.map(element => ({ text: element.textContent, bounds: rect(element) })), trustedInput: profile.input }; + await tapCodeControl(markdownButton); await insertion; + const codeImage = api.getSceneElements().find(element => element.type === "image" && element.customData?.markdownImage?.source === "local"); + check(codeImage && view.excalidrawData.getMarkdownImage(codeImage.fileId)?.markdown === codeSource, "Device code choice did not insert an editable Markdown image"); + check((await view.saveWithOutcome()).status === "persisted", "Device code image did not save"); + check((await p.ea.getSceneFromFile(file)).elements.some(element => element.id === codeImage.id), "Device code image missing from disk"); await c.requestHost("screenshot", { id: profile.id }); return { assertions: [ @@ -695,6 +732,8 @@ async function exerciseDevice(c, path, fixture, profile) { "trusted pointer selects and draws", "device edit saves to disk", "applicable Zen footer controls do not overlap and accept trusted input", + "code format options and remember toggle fit and accept trusted input", + "chosen code image preserves editable source and saves", ], requested: profile, actual: { @@ -712,6 +751,7 @@ async function exerciseDevice(c, path, fixture, profile) { coarsePointer: matchMedia("(pointer: coarse)").matches, events, zenControls, + codeFormat, }, }; } diff --git a/scripts/testing/host/lifecycle.mjs b/scripts/testing/host/lifecycle.mjs index 67616847..24f1a8cd 100644 --- a/scripts/testing/host/lifecycle.mjs +++ b/scripts/testing/host/lifecycle.mjs @@ -145,7 +145,7 @@ async function exerciseLifecycle(c, prefix, fixture, migrationRoute) { const oldPlugin = plugin, oldViews = [main.view, survivor.view], oldRuntime = plugin.getCLIRuntime(); const settingsPath = app.vault.configDir + "/plugins/obsidian-excalidraw-plugin/data.json"; const markerKey = "__excalidrawReloadRegression"; - const settingsKeys = ["zoomMax", "linkOpacity", "exportPaddingSVG", "allowWheelZoom", "pinnedScripts", "scriptEngineSettings", markerKey]; + const settingsKeys = ["zoomMax", "linkOpacity", "exportPaddingSVG", "allowWheelZoom", "pasteCodeBlockAs", "pinnedScripts", "scriptEngineSettings", markerKey]; const originalSettings = Object.fromEntries(settingsKeys.map(key => [key, { present: Object.prototype.hasOwnProperty.call(plugin.settings, key), value: plugin.settings[key], @@ -162,7 +162,7 @@ async function exerciseLifecycle(c, prefix, fixture, migrationRoute) { const marker = { retained: true, zero: 0, flag: false, paths: ["custom/settings"] }; const scriptKey = "__excalidrawReloadCaptureNote"; const noteTypes = { Custom: { template: "Templates/Custom.md", enabled: false, padding: 0 } }; - Object.assign(plugin.settings, { zoomMax: 7, linkOpacity: 0.37, exportPaddingSVG: 0, allowWheelZoom: true, + Object.assign(plugin.settings, { zoomMax: 7, linkOpacity: 0.37, exportPaddingSVG: 0, allowWheelZoom: true, pasteCodeBlockAs: "markdown-image", pinnedScripts: [scriptKey], scriptEngineSettings: { ...plugin.settings.scriptEngineSettings, [scriptKey]: { noteTypes } }, [markerKey]: marker }); await plugin.saveSettings(); const persistedBeforeUnload = await app.vault.adapter.read(settingsPath); @@ -183,6 +183,7 @@ async function exerciseLifecycle(c, prefix, fixture, migrationRoute) { check(plugin !== oldPlugin && plugin.getCLIRuntime() !== oldRuntime, "plugin reload reused retired instance"); check(plugin.settings.zoomMax === 7 && plugin.settings.linkOpacity === 0.37 && plugin.settings.exportPaddingSVG === 0, "reload reset non-default or zero settings"); + check(plugin.settings.pasteCodeBlockAs === "markdown-image", "plugin reload reset the remembered code-block format"); check(plugin.settings[markerKey]?.retained && plugin.settings[markerKey]?.zero === 0 && plugin.settings[markerKey]?.flag === false && plugin.settings[markerKey]?.paths?.[0] === marker.paths[0], "reload lost unknown nested settings"); plugin.settings[markerKey].replacementInstance = true; diff --git a/scripts/testing/markdownImageInsertion.source.test.mjs b/scripts/testing/markdownImageInsertion.source.test.mjs new file mode 100644 index 00000000..e0a69a10 --- /dev/null +++ b/scripts/testing/markdownImageInsertion.source.test.mjs @@ -0,0 +1,49 @@ +/** A code paste may finish rendering after its drawing has been replaced. */ +import assert from "node:assert/strict"; +import test from "node:test"; +import { sourceHarness } from "./sourceHarness.mjs"; +let f; +const render = { width: 400, border: {}, transclusion: { border: {} } }; +const harness = sourceHarness({ + obsidian: { TFile: class {} }, + "src/core": { getEA: () => f.ea }, + "src/constants/constants": { fileid: () => "source-id", MD_EX_SECTIONS: {} }, + "src/shared/EmbeddedFileLoader": { EmbeddedFile: class {}, EmbeddedFilesLoader: class { + async renderMarkdownToSVG() { f.onRender(); return { dataURL: "data:image/svg+xml,test", size: { width: 400, height: 140 } }; } + } }, + "src/shared/ExcalidrawData": { getTransclusion() {}, REGEX_LINK: {} }, + "src/utils/elementCustomDataUtils": { addAppendUpdateCustomData: (el, data) => el.customData = { ...el.customData, ...data }, setMarkdownImageRenderedSize() {} }, + "src/types/markdownImageTypes": { MARKDOWN_IMAGE_CUSTOM_DATA_KEY: "markdownImage", MARKDOWN_IMAGE_SCHEMA_VERSION: 1 }, + "src/utils/markdownImageUtils": { resolveMarkdownImageRenderSettings: () => render, getMarkdownImageDisplayGeometry() {}, getMarkdownImageCropGeometry() {} }, + "src/utils/pathUtils": { cleanSectionHeading: s => s }, + "src/utils/coreUtils": { errorlog: error => { throw error; } }, +}); +const { insertMarkdownImage } = await harness.importModule("src/shared/MarkdownImage.ts"); +test.after(() => harness.close()); +function setup() { + f = { commits: 0, destroyed: 0, dirty: 0, selected: 0, sources: new Map(), onRender() {}, onAddImage() {} }; + const el = { id: "element", type: "image", fileId: "temporary" }; + f.ea = { imagesDict: {}, async addImage() { f.onAddImage(); return el.id; }, getElement: () => el, + async addElementsToView() { f.commits++; return true; }, destroy() { f.destroyed++; } }; + f.view = { file: {}, excalidrawAPI: { selectElements() { f.selected++; } }, currentPosition: { x: 1, y: 2 }, + isClosingOrMigrating: () => false, plugin: { settings: { markdownImageSettings: { defaults: render } } }, + excalidrawData: { setMarkdownImage: (id, source) => f.sources.set(id, source) }, + getViewElements: () => [el], rememberMarkdownImageRender() {}, setDirty() { f.dirty++; } }; + return f; +} +test("Markdown image insertion retains editable local text and commits once", async () => { + const state = setup(); const element = await insertMarkdownImage(state.view, "```js\nx();\n```"); + assert.equal(element.type, "image"); assert.equal(element.customData.markdownImage.source, "local"); + assert.equal(state.sources.get(element.fileId).markdown, "```js\nx();\n```"); + assert.equal(state.commits, 1); assert.equal(state.destroyed, 1); assert.equal(state.dirty, 1); assert.equal(state.selected, 1); +}); +test("Markdown image render and decode cannot insert into a replaced file, API or migrating view", async () => { + for (const phase of ["onRender", "onAddImage"]) { + for (const retire of [view => view.file = {}, view => view.excalidrawAPI = { selectElements() {} }, view => view.isClosingOrMigrating = () => true]) { + const state = setup(); state[phase] = () => retire(state.view); + assert.equal(await insertMarkdownImage(state.view, "```js\nx();\n```"), null); + assert.equal(state.commits, 0); assert.equal(state.sources.size, 0); assert.equal(state.dirty, 0); + assert.equal(state.destroyed, phase === "onAddImage" ? 1 : 0); + } + } +}); diff --git a/scripts/testing/settings/settingsManagerLifecycle.source.test.mjs b/scripts/testing/settings/settingsManagerLifecycle.source.test.mjs index 4de406b5..26b6e1ab 100644 --- a/scripts/testing/settings/settingsManagerLifecycle.source.test.mjs +++ b/scripts/testing/settings/settingsManagerLifecycle.source.test.mjs @@ -13,7 +13,7 @@ const defaults = { mdSVGwidth: 500, mdFont: "Virgil", mdFontColor: "#000000", mdBorderColor: "#000000", markdownImageSettings: { defaults: { width: 500, fontFamily: "Virgil", fontColor: "#000000", border: { enabled: false, color: "#000000" }, css: "", transclusion: { border: {} } } }, - markdownImageDeletionPreference: "keep", previewImageType: "SVGIMG", + markdownImageDeletionPreference: "keep", pasteCodeBlockAs: "ask", previewImageType: "SVGIMG", oEmbedAllowed: false, zoomMax: 3, allowWheelZoom: false, pinnedScripts: [], scriptEngineSettings: {}, }; async function fixture(t, options = {}) { @@ -263,3 +263,19 @@ test("nonempty settings containing only unknown keys remain valid and preserved" assert.deepEqual(state.disk.futureSetting, unknown.futureSetting); assert.equal(state.recoveryReads, 0); assert.equal(state.prompts, 0); }); + +test("code block format defaults to asking and remembered formats survive a fresh settings manager", async (t) => { + for (const preference of ["markdown-image", "embeddable"]) { + const initial = await fixture(t); + delete initial.state.disk.pasteCodeBlockAs; + await initial.manager.loadSettings(); + assert.equal(initial.host.settings.pasteCodeBlockAs, "ask"); + initial.host.settings.pasteCodeBlockAs = preference; + await initial.manager.saveSettings(); + const reloaded = await fixture(t, { load: async () => structuredClone(initial.state.disk) }); + await reloaded.manager.loadSettings(); + assert.equal(reloaded.host.settings.pasteCodeBlockAs, preference); + assert.deepEqual(reloaded.host.settings.futureSetting, initial.original.futureSetting); + assert.equal(reloaded.state.prompts, 0); + } +}); diff --git a/src/core/settings.ts b/src/core/settings.ts index 6ce6b6f4..4ccda484 100644 --- a/src/core/settings.ts +++ b/src/core/settings.ts @@ -1091,10 +1091,14 @@ export class ExcalidrawSettingTab extends PluginSettingTab { name: t("EMBED_TOEXCALIDRAW_HEAD"), description: t("EMBED_TOEXCALIDRAW_DESC"), buildDefinitions: () => [ + ...this.toDeclarativeDefinitions(this.getCodeBlockInsertionSpecs()), this.createYouTubeDefinition(t("PDF_TO_IMAGE"), "nB4cOfn0xAs"), ...this.toDeclarativeDefinitions(this.getPdfImportSpecs()), ], - renderLegacy: (container) => this.renderPdfImportSettings(container), + renderLegacy: (container) => { + this.renderSettingSpecs(container, this.getCodeBlockInsertionSpecs()); + this.renderPdfImportSettings(container); + }, children: [ { name: t("MD_EMBED_CUSTOMDATA_HEAD_NAME"), @@ -4625,6 +4629,23 @@ export class ExcalidrawSettingTab extends PluginSettingTab { this.renderSettingSpecs(container, this.getMarkdownImageStyleSpecs()); } + private getCodeBlockInsertionSpecs(): SettingSpec[] { + return [{ + name: t("PASTE_CODEBLOCK_AS"), + desc: t("PASTE_CODEBLOCK_AS_DESC"), + aliases: ["clipboard", "paste code", "code block", "Markdown image", "embeddable"], + control: { + type: "dropdown", + key: "pasteCodeBlockAs", + options: [ + { value: "ask", label: t("PASTE_CODEBLOCK_ASK") }, + { value: "markdown-image", label: t("MARKDOWN_IMAGE_TITLE") }, + { value: "embeddable", label: t("PASTE_CODEBLOCK_EMBEDDABLE") }, + ], + }, + }]; + } + private getMarkdownImageDeletionSpecs(): SettingSpec[] { return [ { diff --git a/src/core/settingsDefaults.ts b/src/core/settingsDefaults.ts index e24cd480..bd38b999 100644 --- a/src/core/settingsDefaults.ts +++ b/src/core/settingsDefaults.ts @@ -10,6 +10,7 @@ * array binds directly against these same keys and defaults. */ import { Modifier } from "obsidian"; +import type { CodeBlockInsertionPreference } from "src/types/codeBlockTypes"; import { PenStyle } from "src/types/penTypes"; import { DynamicStyle, GridSettings } from "src/types/types"; import { PreviewImageType } from "src/types/utilTypes"; @@ -182,6 +183,7 @@ export interface ExcalidrawSettings { mdCSS: string; markdownImageSettings: MarkdownImageSettings; markdownImageDeletionPreference: MarkdownImageDeletionPreference; + pasteCodeBlockAs: CodeBlockInsertionPreference; scriptEngineSettings: { [key: string]: { [key: string]: ScriptSettingValue | string | number | boolean; @@ -653,6 +655,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = { }, }, markdownImageDeletionPreference: "ask", + pasteCodeBlockAs: "ask", scriptEngineSettings: {}, autostartScripts: {}, autostartScriptFailures: {}, diff --git a/src/lang/locale/en.ts b/src/lang/locale/en.ts index 8651c683..b620b7c5 100644 --- a/src/lang/locale/en.ts +++ b/src/lang/locale/en.ts @@ -290,6 +290,18 @@ export default { CONVERT_CARD_TO_FILE: "Move back-of-note card to File", ERROR_TRY_AGAIN: "Please try again.", PASTE_CODEBLOCK: "Paste code block", + PASTE_CODEBLOCK_AS: "Paste code block as", + PASTE_CODEBLOCK_AS_DESC: "Choose how to insert code from the clipboard or the Paste code block menu action.", + PASTE_CODEBLOCK_ASK: "Always ask", + PASTE_CODEBLOCK_EMBEDDABLE: "Interactive embeddable", + PASTE_CODEBLOCK_CHOOSE: "Insert this code block as an interactive embeddable or a Markdown image?", + PASTE_CODEBLOCK_REMEMBER: "Remember my choice", + PASTE_CODEBLOCK_REMEMBER_DESC: "You can change this later in Excalidraw settings under Embed files into Excalidraw.", + PASTE_CODEBLOCK_LANGUAGE: "Code block language", + PASTE_CODEBLOCK_LANGUAGE_PLACEHOLDER: "javascript, html, python, etc.", + PASTE_CODEBLOCK_TITLE: "Code Block Title", + PASTE_CODEBLOCK_TITLE_PLACEHOLDER: "Enter title or leave empty for automatic title", + PASTE_CODEBLOCK_DEFAULT_TITLE: "Code Block", INVERT_IMAGES_IN_DARK_MODE: "Invert image(s) in dark mode", INSERT_LATEX: `Insert LaTeX formula (e.g. \\binom{n}{k} = \\frac{n!}{k!(n-k)!}).`, ENTER_LATEX: "Enter a valid LaTeX expression", diff --git a/src/lang/locale/es.ts b/src/lang/locale/es.ts index 87609d3e..c0c16d86 100644 --- a/src/lang/locale/es.ts +++ b/src/lang/locale/es.ts @@ -290,6 +290,18 @@ export default { CONVERT_CARD_TO_FILE: "Mover tarjeta del reverso-de-la-nota a un Archivo", ERROR_TRY_AGAIN: "Por favor, inténtalo de nuevo.", PASTE_CODEBLOCK: "Pegar un Bloque de Código", + PASTE_CODEBLOCK_AS: "Pegar bloque de código como", + PASTE_CODEBLOCK_AS_DESC: "Elige cómo insertar código desde el portapapeles o desde la opción Pegar un Bloque de Código del menú.", + PASTE_CODEBLOCK_ASK: "Preguntar siempre", + PASTE_CODEBLOCK_EMBEDDABLE: "Elemento incrustado interactivo", + PASTE_CODEBLOCK_CHOOSE: "¿Insertar este bloque de código como elemento incrustado interactivo o como imagen Markdown?", + PASTE_CODEBLOCK_REMEMBER: "Recordar mi elección", + PASTE_CODEBLOCK_REMEMBER_DESC: "Puedes cambiarlo después en los ajustes de Excalidraw, en Incrustar archivos en Excalidraw.", + PASTE_CODEBLOCK_LANGUAGE: "Lenguaje del bloque de código", + PASTE_CODEBLOCK_LANGUAGE_PLACEHOLDER: "javascript, html, python, etc.", + PASTE_CODEBLOCK_TITLE: "Título del bloque de código", + PASTE_CODEBLOCK_TITLE_PLACEHOLDER: "Introduce un título o déjalo vacío para usar uno automático", + PASTE_CODEBLOCK_DEFAULT_TITLE: "Bloque de código", INSERT_LATEX: `Insertar fórmula LaTeX (ej. \\binom{n}{k} = \\frac{n!}{k!(n-k)!}).`, ENTER_LATEX: "Ingresa una expresión LaTeX válida", READ_RELEASE_NOTES: "Leer las notas de la última versión", diff --git a/src/lang/locale/ru.ts b/src/lang/locale/ru.ts index 032906e3..acd39d2a 100644 --- a/src/lang/locale/ru.ts +++ b/src/lang/locale/ru.ts @@ -271,6 +271,18 @@ export default { CONVERT_CARD_TO_FILE: "Переместить сноску в файл", ERROR_TRY_AGAIN: "Пожалуйста, попробуйте еще раз.", PASTE_CODEBLOCK: "Вставить блок кода", + PASTE_CODEBLOCK_AS: "Вставлять блок кода как", + PASTE_CODEBLOCK_AS_DESC: "Выберите способ вставки кода из буфера обмена или через пункт меню «Вставить блок кода».", + PASTE_CODEBLOCK_ASK: "Всегда спрашивать", + PASTE_CODEBLOCK_EMBEDDABLE: "Интерактивное встраивание", + PASTE_CODEBLOCK_CHOOSE: "Вставить этот блок кода как интерактивное встраивание или изображение Markdown?", + PASTE_CODEBLOCK_REMEMBER: "Запомнить мой выбор", + PASTE_CODEBLOCK_REMEMBER_DESC: "Это можно изменить в настройках Excalidraw в разделе «Встраивание файлов в Excalidraw».", + PASTE_CODEBLOCK_LANGUAGE: "Язык блока кода", + PASTE_CODEBLOCK_LANGUAGE_PLACEHOLDER: "javascript, html, python и т. д.", + PASTE_CODEBLOCK_TITLE: "Заголовок блока кода", + PASTE_CODEBLOCK_TITLE_PLACEHOLDER: "Введите заголовок или оставьте пустым для автоматического названия", + PASTE_CODEBLOCK_DEFAULT_TITLE: "Блок кода", INSERT_LATEX: `Вставьте формулу LaTeX (например, \\\binom{n}{k} = \\\frac{n!}{k!(n-k)!}).`, ENTER_LATEX: "Введите правильное выражение LaTeX", READ_RELEASE_NOTES: "Прочитать последние заметки о выпуске", diff --git a/src/lang/locale/zh-cn.ts b/src/lang/locale/zh-cn.ts index 39d0e89a..2afb8c49 100644 --- a/src/lang/locale/zh-cn.ts +++ b/src/lang/locale/zh-cn.ts @@ -260,6 +260,18 @@ export default { CONVERT_CARD_TO_FILE: "将“背景笔记”卡片保存到文件", ERROR_TRY_AGAIN: "请重试。", PASTE_CODEBLOCK: "粘贴代码块", + PASTE_CODEBLOCK_AS: "代码块粘贴方式", + PASTE_CODEBLOCK_AS_DESC: "选择从剪贴板或“粘贴代码块”菜单插入代码的方式。", + PASTE_CODEBLOCK_ASK: "始终询问", + PASTE_CODEBLOCK_EMBEDDABLE: "交互式嵌入", + PASTE_CODEBLOCK_CHOOSE: "将此代码块插入为交互式嵌入还是 Markdown 图像?", + PASTE_CODEBLOCK_REMEMBER: "记住我的选择", + PASTE_CODEBLOCK_REMEMBER_DESC: "之后可在 Excalidraw 设置的“嵌入到绘图中的文件”中更改。", + PASTE_CODEBLOCK_LANGUAGE: "代码块语言", + PASTE_CODEBLOCK_LANGUAGE_PLACEHOLDER: "javascript、html、python 等", + PASTE_CODEBLOCK_TITLE: "代码块标题", + PASTE_CODEBLOCK_TITLE_PLACEHOLDER: "输入标题,或留空以自动命名", + PASTE_CODEBLOCK_DEFAULT_TITLE: "代码块", INVERT_IMAGES_IN_DARK_MODE: "深色主题下反转颜色", INSERT_LATEX: `插入 LaTeX 公式到当前绘图中`, ENTER_LATEX: "输入 LaTeX 公式", diff --git a/src/lang/locale/zh-tw.ts b/src/lang/locale/zh-tw.ts index e84c96eb..9c558e92 100644 --- a/src/lang/locale/zh-tw.ts +++ b/src/lang/locale/zh-tw.ts @@ -260,6 +260,18 @@ export default { CONVERT_CARD_TO_FILE: "將“背景筆記”卡片儲存到檔案", ERROR_TRY_AGAIN: "請重試。", PASTE_CODEBLOCK: "貼上程式碼塊", + PASTE_CODEBLOCK_AS: "程式碼區塊貼上方式", + PASTE_CODEBLOCK_AS_DESC: "選擇從剪貼簿或「貼上程式碼塊」選單插入程式碼的方式。", + PASTE_CODEBLOCK_ASK: "一律詢問", + PASTE_CODEBLOCK_EMBEDDABLE: "互動式嵌入", + PASTE_CODEBLOCK_CHOOSE: "要將此程式碼區塊插入為互動式嵌入還是 Markdown 圖片?", + PASTE_CODEBLOCK_REMEMBER: "記住我的選擇", + PASTE_CODEBLOCK_REMEMBER_DESC: "之後可在 Excalidraw 設定的「嵌入到繪圖中的檔案」中變更。", + PASTE_CODEBLOCK_LANGUAGE: "程式碼區塊語言", + PASTE_CODEBLOCK_LANGUAGE_PLACEHOLDER: "javascript、html、python 等", + PASTE_CODEBLOCK_TITLE: "程式碼區塊標題", + PASTE_CODEBLOCK_TITLE_PLACEHOLDER: "輸入標題,或留空以自動命名", + PASTE_CODEBLOCK_DEFAULT_TITLE: "程式碼區塊", INVERT_IMAGES_IN_DARK_MODE: "深色主題下反轉顏色", INSERT_LATEX: `插入 LaTeX 公式到當前繪圖中`, ENTER_LATEX: "輸入 LaTeX 公式", diff --git a/src/shared/Dialogs/Messages.ts b/src/shared/Dialogs/Messages.ts index 65825d9a..2ba869d2 100644 --- a/src/shared/Dialogs/Messages.ts +++ b/src/shared/Dialogs/Messages.ts @@ -18,6 +18,9 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
`, "2.29.2": ` +## New and improved +- Paste code blocks as interactive embeddables or editable Markdown images, and optionally remember your choice in Excalidraw settings. + ## Fixed - Empty settings records now trigger recovery instead of silently resetting preferences and script settings. - Extracting a local Markdown image to a note now defaults to the drawing's folder. You can still choose another destination. [#3009](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/3009) diff --git a/src/shared/MarkdownImage.ts b/src/shared/MarkdownImage.ts index d6051710..84ddfba6 100644 --- a/src/shared/MarkdownImage.ts +++ b/src/shared/MarkdownImage.ts @@ -459,14 +459,17 @@ export async function insertMarkdownImage( source: string | TFile | EmbeddedFile = "", position: { x: number; y: number } = view.currentPosition, ): Promise