diff --git a/docs/DRAWING_EMBED_CONTROLS.md b/docs/DRAWING_EMBED_CONTROLS.md index 63bc1941..e80a8060 100644 --- a/docs/DRAWING_EMBED_CONTROLS.md +++ b/docs/DRAWING_EMBED_CONTROLS.md @@ -5,10 +5,11 @@ the toolbar below the image; touch layouts keep the controls visible. Drag the bottom-right corner to resize, or focus it and use the arrow keys. A completed resize changes only that occurrence in the containing note, with one undo step. -For an `area=`, `frame=` or `clippedframe=` reference such as -`![[Drawing#^frame=abcdefgh|300]]`, the toolbar also offers **Adjust padding**, -using the square-dot icon. A compact -horizontal Obsidian slider appears directly below the toolbar and previews +The toolbar offers **Outer padding** for default thumbnails, whole scenes, groups +and frame references, using the **box-select** icon. **Area expansion** keeps the +**square-dot** icon for `area=` references: it includes more of the surrounding +drawing. Outer padding adds space without including additional elements. +A compact horizontal Obsidian slider appears directly below the toolbar and previews padding from 0 to 2000: 0, 10, then increments of 50. You can drag, click the track, use the arrow keys, or scroll over the slider. Closing the popup or pressing Enter saves one source change; Escape cancels. **Use default padding** removes the explicit @@ -20,11 +21,34 @@ note, replaced widget, or plugin unload cancels the gesture and its pending preview. Paths, aliases, Markdown titles, dimensions, and table escapes are preserved. Identical embeds remain independent. -Padding controls require an editable Live Preview source binding and a nonempty -area or frame reference. They are absent for whole drawings, text/group references, +Padding controls require an editable Live Preview source binding. They are absent for text references, Reading view, read-only editors, nested Markdown transclusions, and Canvas. Reading view retains preview and open-drawing actions. +Padding is independent of the selected view. For example, +`![[Drawing#^as-image,padding=30|300]]` follows the current default thumbnail with +30 units of outer padding; `![[Drawing#^frame=,padding=30|300]]` shows the whole +scene with that padding. Switching views retains the padding override. Thumbnail +contents stay clipped to the original frame rectangle before padding is added. + +## Drawing images inside a scene + +Select a drawing-backed image and use **Configure drawing preview** (scan-eye) +next to its existing image actions. The popover previews the chosen view and +padding without editing the scene. **Anchor at original size (100%)** follows +the rendered source dimensions and disables manual resizing. **Apply** commits; +Cancel or Escape discards the draft. + +When the source drawing appears in several images in the same scene, Apply asks +whether to update **All images** or **Only this image**. Only edited settings are +applied, preserving each copy's other view, padding and anchor choices. Each +image retains its center; unanchored images retain their area when the aspect +ratio changes. Anchored images follow their new intrinsic dimensions. + +Configuration is saved in each image's embedded-file link, including `|100%`. +Independent references are created internally; the source drawing is never +duplicated or modified. One Undo restores the previous references and geometry. + ## Frames and drawing thumbnails Select a named frame or marker frame and use **Set as drawing thumbnail** in its @@ -78,19 +102,27 @@ For frame metadata, thumbnails, navigation and source controls, run `--devices --device-profiles=phone-portrait-light,tablet-portrait-full-light` for focused phone/tablet emulation. Complete profiles include these cases too. -The 2026-11-11 Windows checks on Obsidian 1.14.5 passed nine desktop frame cases -(main window, popout and actual plugin reload), eight frame cases in phone/tablet -emulation, and the six existing embed regressions. The final desktop run uses -`scan-eye`; mobile emulation preceded this icon-only substitution. Reports under -`.test-work/reports/frame-semantics-2026-11-11-07/` retain the mobile and prior -regression results; `frame-semantics-2026-11-11-08/` records the successful desktop -rerun. Earlier failed receipts remain intact. All cleanup gates passed. +The final 2026-11-11 Windows run on Obsidian 1.14.5 passed thirteen desktop frame +cases (main window, popout and actual plugin reload), twelve frame cases in +phone/tablet emulation, both device profiles, and the six existing embed regressions. +It exercises the selected-image popover, both shared-source choices, native +Undo/Redo, intrinsic-size anchoring, cancellation and save/reopen. Saved links +retain their configuration while following the writer's existing path-shortening +rules. SVG, SVG-image and PNG checks verify padded thumbnail dimensions and +ensure padding never reveals neighboring elements outside the thumbnail frame. -Focused source checks passed 101/101; bundle/runner checks passed 18/18. -Targeted lint added no findings (24 existing findings remain in adjacent legacy -code). The production bundle is 5,114,584 bytes, leaving 128,296 bytes under 5 MiB. -Physical touch devices, other operating systems and the minimum supported host -version remain manual checks. Complete regression profiles were not run. +The aggregate report records **37 passed, zero failed or blocked**, with artifact +hashes, source stability and baseline restoration verified. Reports are under +`.test-work/reports/preview-config-2026-11-11-03/`; earlier failed receipts remain +intact. Desktop console/window errors are zero and all cleanup gates passed. + +Focused source checks passed 111/111, existing image-geometry/parsing checks +32/32, and bundle/runner/host-contract checks 19/19. Targeted lint added no +findings (24 existing findings remain in adjacent legacy code); CSS policy lint, +inventory and feature mappings passed. The production bundle is 5,128,954 bytes, +leaving 113,926 bytes under 5 MiB. Physical touch devices, other operating systems +and the minimum supported host version remain manual checks. Complete regression +profiles were not run. ## Investigation checkpoint: 2026-11-10 diff --git a/scripts/testing/drawingImagePreview.source.test.mjs b/scripts/testing/drawingImagePreview.source.test.mjs new file mode 100644 index 00000000..a805fea7 --- /dev/null +++ b/scripts/testing/drawingImagePreview.source.test.mjs @@ -0,0 +1,116 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import vm from "node:vm"; +import { readFileSync } from "node:fs"; +import ts from "typescript"; +import { sourceHarness } from "./sourceHarness.mjs"; + +function productionScale() { + const compile = (path, dependencies = {}) => { + const source = readFileSync(new URL("../../" + path, import.meta.url), "utf8"), exports = {}; + const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText; + vm.runInNewContext(code, { exports, require: name => dependencies[name] ?? {}, Date }); return exports; + }; + return compile("src/utils/utils.ts", { + "../constants/constants": { EXCALIDRAW_PLUGIN: null, mutateElement: (el, _map, patch) => Object.assign(el, patch) }, + "./elementCustomDataUtils": compile("src/utils/elementCustomDataUtils.ts"), + "./collectionUtils": { arrayToMap: elements => new Map(elements.map(el => [el.id, el])) }, + "src/types/markdownImageTypes": { MARKDOWN_IMAGE_CUSTOM_DATA_KEY: "markdownImage" }, + "roughjs/bin/math": { Random: class {} }, + }).scaleLoadedImage; +} + +async function fixture() { + const prompts = [], errors = [], notices = [], renders = [], history = [], registry = new Map(), payloads = []; + const file = { path: "Host.md" }, drawing = { path: "Source.md", basename: "Source " }; + const graph = sourceHarness({ obsidian: { Notice: class { constructor(value) { notices.push(value); } }, parseYaml: () => ({}) }, + "src/constants/constants": { CaptureUpdateAction: { IMMEDIATELY: "IMMEDIATELY" }, fileid: () => "new-" + registry.size + "-" + renders.length }, + "src/shared/Dialogs/DrawingImagePreviewPopover": { DrawingImagePreviewPopover: class {} }, + "src/lang/helpers": { t: key => key === "PREVIEW_SHARED_HELP" ? '“{drawing}” appears in {count} images in this scene.' : key }, + "src/utils/coreUtils": { errorlog: error => errors.push(error) }, + }); + const { DrawingImagePreviewController } = await graph.importModule("src/view/managers/DrawingImagePreviewController.ts"); + const { getDrawingPreviewParts } = await graph.importModule("src/utils/drawingPreviewLink.ts"); + class Descriptor { + file = drawing; isMarkdownSection = false; colorMap = null; + constructor(_plugin, _host, link) { this.linkParts = { original: link }; } + shouldScale() { return !this.linkParts.original.endsWith("|100%"); } + setImage(image) { this.image = image; } + } + class Loader { + async getObsidianImage(descriptor) { + renders.push(descriptor.linkParts.original); if (pause) await pause; + const parts = getDrawingPreviewParts(descriptor.linkParts.original), p = parts.padding ?? 0; + const size = parts.blockref === "tall" ? { width: 100 + 2*p, height: 300 + 2*p } : { width: 300 + 2*p, height: 100 + 2*p }; + return { fileId: "generated", mimeType: "image/svg+xml", dataURL: "data:image/svg+xml;base64,AA==", created: 1, hasSVGwithBitmap: false, size }; + } + } + class Prompt { + titleEl = { setText() {} }; + constructor(_plugin, message, buttons) { this.message = message; this.buttons = buttons; this.waitForClose = new Promise(resolve => { this.choose = resolve; }); prompts.push(this); } + close() { this.choose(null); } + } + const source = new Descriptor(null, null, "Source.md"); registry.set("shared", source); + registry.set("other", new Descriptor(null, null, "Source.md#^frame=tall,padding=20|100%")); + const image = (id, fileId, x, width, height) => ({ id, fileId, type: "image", x, y: 10, width, height, version: 1, versionNonce: 1, customData: { retained: true }, crop: null }); + let elements = [image("one", "shared", 0, 300, 100), image("two", "shared", 400, 150, 50), image("three", "other", 650, 100, 300)], alive = true, pause; + const api = { getAppState: () => ({ theme: "light" }), addFiles: data => payloads.push(data) }; + const view = { file, excalidrawAPI: api, plugin: { _loaded: true, isExcalidrawFile: candidate => candidate === drawing }, + excalidrawData: { getFile: id => registry.get(id), setFile: (id, value) => registry.set(id, value) }, + getViewElements: () => elements, updateScene: update => { history.push(elements); elements = update.elements; }, setDirty() {}, + }; + const controller = new DrawingImagePreviewController(view, { Prompt, EmbeddedFile: Descriptor, EmbeddedFilesLoader: Loader, scaleLoadedImage: productionScale() }); + return { controller, source, view, prompts, errors, notices, renders, registry, payloads, elements: () => elements, + async apply(changes, choice = "one") { const result = controller.apply("one", source, changes, () => alive); prompts.at(-1).choose(choice); return await result; }, + undo() { elements = history.pop(); }, retire() { alive = false; controller.reset(); }, + pause() { let resume; pause = new Promise(resolve => { resume = resolve; }); return resume; }, + changeTarget() { elements = elements.map(el => el.id === "one" ? { ...el, version: 10 } : el); }, + close() { controller.reset(); graph.close(); }, + }; +} + +test("only this image gets a new persisted link and uses real external-update geometry; undo retains the original reference", async () => { + const f = await fixture(); + try { + assert.equal(await f.apply({ frame: "tall", padding: 30 }), true); + const [one, two, three] = f.elements(); + assert.notEqual(one.fileId, "shared"); assert.equal(two.fileId, "shared"); assert.equal(three.fileId, "other"); + assert.equal(f.registry.get(one.fileId).linkParts.original, "Source.md#^frame=tall,padding=30"); + assert.ok(Math.abs(one.width * one.height - 30000) < .001); assert.equal(one.x + one.width/2, 150); assert.equal(one.y + one.height/2, 60); + assert.equal(one.customData.retained, true); assert.equal(f.payloads.length, 1); + assert.match(f.prompts[0].message, /Source <drawing>/); assert.doesNotMatch(f.prompts[0].message, /fileId|shared/); + f.undo(); assert.equal(f.elements()[0].fileId, "shared"); assert.equal(f.registry.get("shared").linkParts.original, "Source.md"); + } finally { f.close(); } +}); + +test("apply to all copies changes only edited fields, preserving distinct views, anchoring and each image center", async () => { + const f = await fixture(); + try { + const old = f.elements().map(el => ({ center: [el.x+el.width/2,el.y+el.height/2], area: el.width*el.height })); + assert.equal(await f.apply({ padding: 50 }, "all"), true); + const elements = f.elements(); assert.equal(elements[0].fileId, elements[1].fileId); + assert.equal(f.registry.get(elements[0].fileId).linkParts.original, "Source.md#^as-image,padding=50"); + assert.equal(f.registry.get(elements[2].fileId).linkParts.original, "Source.md#^frame=tall,padding=50|100%"); + for (let i=0;i<3;i++) { const el=elements[i]; assert.deepEqual([el.x+el.width/2,el.y+el.height/2],old[i].center); if(i<2)assert.ok(Math.abs(el.width*el.height-old[i].area)<.001); } + assert.equal(elements[2].width, 200); assert.equal(elements[2].height, 400); assert.equal(elements[2].customData.isAnchored, true); + } finally { f.close(); } +}); + +test("100% anchoring follows rendered intrinsic dimensions and remains in the link", async () => { + const f = await fixture(); + try { assert.equal(await f.apply({ anchored: true }), true); const el=f.elements()[0]; + assert.equal(f.registry.get(el.fileId).linkParts.original, "Source.md|100%"); assert.equal(el.width,300); assert.equal(el.height,100); assert.equal(el.customData.isAnchored,true); + } finally { f.close(); } +}); + +test("cancel, stale scene changes and retired views do not register partial links or write a scene", async () => { + for (const kind of ["cancel", "changed", "retired"]) { + const f=await fixture(); + try { + if(kind==='cancel')assert.equal(await f.apply({padding:20},null),false); + else {const resume=f.pause(), pending=f.apply({padding:20}); await new Promise(resolve=>setImmediate(resolve)); + if(kind==='changed')f.changeTarget();else f.retire(); resume(); assert.equal(await pending,false);} + assert.equal(f.registry.size,2); assert.equal(f.payloads.length,0); assert.equal(f.elements()[0].fileId,'shared'); + } finally {f.close();} + } +}); diff --git a/scripts/testing/drawingPreviewLink.source.test.mjs b/scripts/testing/drawingPreviewLink.source.test.mjs new file mode 100644 index 00000000..30715f7c --- /dev/null +++ b/scripts/testing/drawingPreviewLink.source.test.mjs @@ -0,0 +1,37 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { sourceHarness } from "./sourceHarness.mjs"; +const graph = sourceHarness({ "./pathUtils": { cleanBlockRef: value => value, cleanSectionHeading: value => value } }); +const { rewriteDrawingPreviewLink: rewrite, getDrawingPreviewParts: parts } = await graph.importModule("src/utils/drawingPreviewLink.ts"); +const { getEmbeddedFileMasterLink: restore } = await graph.importModule("src/utils/linkUtils.ts"); +const { getThumbnailPaddingConfig } = await graph.importModule("src/utils/thumbnailPadding.ts"); +test.after(() => graph.close()); + +test("thumbnail and whole-scene padding remain independent of frame selection and anchoring", () => { + assert.equal(rewrite("Draw.md", { padding: 40 }), "Draw.md#^as-image,padding=40"); + assert.equal(rewrite("Draw.md#^group=abc", { padding: 40 }), "Draw.md#^group=abc,padding=40"); + assert.equal(parts("Draw.md#^as-image,padding=40|100%").blockref, "as-image"); + assert.equal(parts("Draw.md#^as-image,padding=40|100%").padding, 40); + assert.equal(rewrite("Draw.md#^frame=,padding=40|100%", { frame: null }), "Draw.md#^as-image,padding=40|100%"); + assert.equal(rewrite("Draw.md#^as-image,padding=40|100%", { frame: "b" }), "Draw.md#^frame=b,padding=40|100%"); + assert.equal(rewrite("Draw.md#^frame=b,padding=40|100%", { padding: null }), "Draw.md#^frame=b|100%"); + assert.equal(rewrite("Draw.md#^frame=b,padding=40|100%", { anchored: false }), "Draw.md#^frame=b,padding=40"); + assert.equal(rewrite("100% ../Draw.md#^area=a|Caption", { anchored: true }), "100% ../Draw.md#^area=a|Caption|100%"); +}); + +test("preview changes preserve raw encoding, padding, other aliases and the shared master-map link", () => { + const old = "../Draw%20one%23%5Eclippedframe%3DOld%2Cpadding%3D00%2E50|Alias|100%"; + assert.equal(rewrite(old, { frame: "new" }), "../Draw%20one%23%5Eclippedframe%3Dnew%2Cpadding%3D00%2E50|Alias|100%"); + assert.equal(rewrite("Draw.md#^frame=Part,padding=10, two", { padding: 20 }), "Draw.md#^frame=Part,padding=10, two,padding=20"); + assert.equal(restore("Draw.md|100%", "^as-image,padding=40|100%"), "Draw.md#^as-image,padding=40|100%"); + assert.equal(restore("Draw.md|100%", "^frame=b,padding=40"), "Draw.md#^frame=b,padding=40|100%"); + assert.equal(restore("Draw.md", "^frame=b,padding=40|Caption"), "Draw.md#^frame=b,padding=40|Caption"); + assert.equal(restore("Draw.md|100%", null), "Draw.md|100%"); +}); + +test("outer thumbnail padding enlarges the viewport while retaining the original frame clip", () => { + const frame = { id: "f", x: 100, y: 200, width: 300, height: 150 }; + const config = getThumbnailPaddingConfig({ exportingFrame: frame, withBackground: false, withTheme: true }, { theme: "dark" }, 25, 2); + assert.deepEqual(config, { exportingFrame: frame, padding: 0, scale: 2, fit: "none", origin: "canvas", x: 75, y: 175, width: 350, height: 200, theme: "dark", canvasBackgroundColor: false }); + assert.equal(config.exportingFrame, frame); +}); diff --git a/scripts/testing/drawingPreviewLoader.source.test.mjs b/scripts/testing/drawingPreviewLoader.source.test.mjs new file mode 100644 index 00000000..fdd2a2cb --- /dev/null +++ b/scripts/testing/drawingPreviewLoader.source.test.mjs @@ -0,0 +1,39 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import vm from "node:vm"; +import { readFileSync } from "node:fs"; +import ts from "typescript"; + +const compile = (path, dependencies = {}) => { + const code = ts.transpileModule(readFileSync(new URL("../../" + path, import.meta.url), "utf8"), { + compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 }, + }).outputText; + const exports = {}; vm.runInNewContext(code, { exports, require: name => dependencies[name] ?? {} }); return exports; +}; +const parts = compile("src/utils/embeddedFilenameParts.ts"); +const links = compile("src/utils/linkUtils.ts", { "./pathUtils": { cleanBlockRef: value => value, cleanSectionHeading: value => value } }); +const { EmbeddedFile } = compile("src/shared/EmbeddedFileLoader.ts", { + "../utils/sceneDataUtils": links, "../utils/embeddedAssetUtils": parts, obsidian: { Notice: class {} }, +}); +const drawing = { path: "Folder/Draw.md", extension: "md" }, note = { path: "Note.md", extension: "md" }; +const plugin = { settings: { mdSVGwidth: 500, mdSVGmaxHeight: 500 }, isExcalidrawFile: file => file === drawing, + app: { metadataCache: { getFirstLinkpathDest: path => path === "Note.md" ? note : drawing } } }; + +test("embedded drawing loader recognizes padded default and whole-scene links while retaining 100%", () => { + for (const [link, frame, anchored] of [ + ["Draw.md#^as-image,padding=40|100%", false, true], + ["Draw.md#^frame=,padding=30", true, false], + ["Draw.md#^frame=some-id,padding=20|100%", true, true], + ]) { + const file = new EmbeddedFile(plugin, "Host.md", link); + assert.equal(file.file, drawing); assert.equal(file.filenameparts.filepath, drawing.path); + assert.equal(file.isMarkdownSection, false); assert.equal(file.filenameparts.hasFrameref, frame); + assert.equal(file.shouldScale(), !anchored); assert.equal(file.linkParts.original, link); + assert.ok(file.filenameparts.padding > 0); + } +}); + +test("an ordinary Markdown block named as-image keeps its section-transclusion behavior", () => { + const file = new EmbeddedFile(plugin, "Host.md", "Note.md#^as-image"); + assert.equal(file.file, note); assert.equal(file.isMarkdownSection, true); +}); diff --git a/scripts/testing/embedControls.source.test.mjs b/scripts/testing/embedControls.source.test.mjs index 7f1e83b4..df807759 100644 --- a/scripts/testing/embedControls.source.test.mjs +++ b/scripts/testing/embedControls.source.test.mjs @@ -56,7 +56,7 @@ test("padding toolbar action requires both an area-rendering capability and a wr try { const button = f.buttons.find(button => button.getAttribute("data-excalidraw-embed-action") === "padding"); assert.equal(!!button, area && writable); - if (button) assert.equal(button.icon, "square-dot"); + if (button) assert.equal(button.icon, "box-select"); } finally { f.close(); } } diff --git a/scripts/testing/embedFrame.source.test.mjs b/scripts/testing/embedFrame.source.test.mjs index 19cfd9e7..f842faee 100644 --- a/scripts/testing/embedFrame.source.test.mjs +++ b/scripts/testing/embedFrame.source.test.mjs @@ -15,8 +15,8 @@ test("frame selection preserves raw paths, clipping, dimensions, titles, padding ['![Caption|200]( "Keep title")', '![Caption|200]( "Keep title")'], ['![Caption](Map%20one%23%5Eclippedframe%3DOld%2Cpadding%3D00%2E50 "Keep")', '![Caption](Map%20one%23%5Eclippedframe%3Dframe-id%2Cpadding%3D00%2E50 "Keep")'], ]) assert.equal(rewriteEmbedFrame(text, "frame-id"), expected); - assert.equal(rewriteEmbedFrame('![[Map#^frame=Old,padding=50|200]]', null), '![[Map|200]]'); - assert.equal(rewriteEmbedFrame('![[Map#^clippedframe=Old,padding=50|200]]', ''), '![[Map#^frame=|200]]'); + assert.equal(rewriteEmbedFrame('![[Map#^frame=Old,padding=50|200]]', null), '![[Map#^as-image,padding=50|200]]'); + assert.equal(rewriteEmbedFrame('![[Map#^clippedframe=Old,padding=50|200]]', ''), '![[Map#^frame=,padding=50|200]]'); for (const ref of ['../Other', 'frame#evil', 'Name,padding=20']) assert.equal(rewriteEmbedFrame('![[Map]]', ref), null); }); diff --git a/scripts/testing/embedLocales.test.mjs b/scripts/testing/embedLocales.test.mjs index d0e564e8..adb8387e 100644 --- a/scripts/testing/embedLocales.test.mjs +++ b/scripts/testing/embedLocales.test.mjs @@ -47,3 +47,25 @@ test("frame controls have complete maintained translations", () => { } } }); + +test("preview configuration and scope explanations have maintained translations", () => { + let expected; + for (const language of ["en", "ru", "es", "zh-cn", "zh-tw"]) { + const path = new URL(`../../src/lang/locale/${language}.ts`, import.meta.url), source = readFileSync(path, "utf8"); + const tree = ts.createSourceFile(path.pathname, source, ts.ScriptTarget.Latest, true), strings = new Map(); + const visit = node => { + if (ts.isPropertyAssignment(node) && node.getStart(tree) < source.indexOf("FRAME_NAVIGATE:") && node.name.text?.startsWith("PREVIEW_")) { + assert.ok(ts.isStringLiteral(node.initializer)); strings.set(node.name.text, node.initializer.text); + } + ts.forEachChild(node, visit); + }; + visit(tree); assert.equal(strings.size, 15, language); expected ??= [...strings.keys()].sort(); + assert.deepEqual([...strings.keys()].sort(), expected, language); + for (const [key, value] of strings) { + assert.ok(value.trim()); assert.doesNotMatch(value, /\uFFFD/, language + ": " + key); + if (language === "ru") assert.match(value, /\p{Script=Cyrillic}/u, key); + if (language.startsWith("zh-")) assert.match(value, /\p{Script=Han}/u, key); + } + for (const token of ["{drawing}","{count}"]) assert.ok(strings.get("PREVIEW_SHARED_HELP").includes(token)); + } +}); diff --git a/scripts/testing/embedPadding.source.test.mjs b/scripts/testing/embedPadding.source.test.mjs index c30a45a0..aebd6fd5 100644 --- a/scripts/testing/embedPadding.source.test.mjs +++ b/scripts/testing/embedPadding.source.test.mjs @@ -21,7 +21,7 @@ test("padding edits preserve wiki, Markdown, encoded paths, titles, aliases and ['![Map](Map%20one%23%5Earea%3Dabcdefgh%2Cpadding%3D10 "Keep")', '![Map](Map%20one%23%5Earea%3Dabcdefgh,padding=50 "Keep")'], ]) assert.equal(rewriteEmbedPadding(text, 50), expected); assert.equal(rewriteEmbedPadding("![[Map#^area=abcdefgh,padding=50|200]]", null), "![[Map#^area=abcdefgh|200]]"); - for (const target of ["Map", "Map#^text", "Map#^group=abcdefgh", "Map#^frame=", "Map#^area=", "Map#^area=abc,padding=-1", "Map#^area=abc,padding=1,padding=2"]) + for (const target of ["Map#^text", "Map#^group=", "Map#^area=", "Map#^area=abc,padding=-1", "Map#^area=abc,padding=1,padding=2"]) assert.equal(withAreaPadding(target, 10), null, target); for (const value of [-1, 2001, NaN, Infinity]) assert.equal(withAreaPadding("Map#^area=abc", value), null); assert.equal(withAreaPadding("Map#^frame=Part, One,padding=20", 50), "Map#^frame=Part, One,padding=50"); diff --git a/scripts/testing/host/drawingImagePreview.mjs b/scripts/testing/host/drawingImagePreview.mjs new file mode 100644 index 00000000..679d6c0f --- /dev/null +++ b/scripts/testing/host/drawingImagePreview.mjs @@ -0,0 +1,82 @@ +/** Trusted in-scene controls, shared-source scope and persisted link/geometry behavior. */ +export async function exerciseDrawingImagePreview(c, env, template, drawing, context, modifier) { + const { p, leaf, doc, check, click, key } = env; + let view = await env.openDrawing("Image-host", {}, template); + const ea = p.ea.getAPI(view); let first, variant; + try { + first = await ea.addImage(0, 500, drawing, false, false); + variant = await ea.addImage(500, 500, drawing.path + "#^frame=frame-marker,padding=20|100%", false, true); + await ea.addElementsToView(false, true, true); + } finally { ea.destroy(); } + const get = id => view.getViewElements().find(el => el.id === id); + const duplicate = { ...structuredClone(get(first)), id: "shared-copy", x: 300, width: get(first).width/2, height: get(first).height/2, index: null }; + view.updateScene({ elements: [...view.getViewElements(), duplicate], captureUpdate: "IMMEDIATELY" }); + const originalId = get(first).fileId; + const link = id => view.excalidrawData.getFile(get(id).fileId).linkParts.original; + const center = id => { const el=get(id); return [el.x+el.width/2,el.y+el.height/2]; }; + const oldCenters = [first, "shared-copy", variant].map(center); + const oldAreas = [first,"shared-copy"].map(id=>get(id).width*get(id).height); + const open = async () => { + await view.zoomToElementId(first, false); + await c.waitFor(() => view.containerEl.querySelector('[data-excalidraw-element-action="configure-drawing-preview"]'), "drawing image settings action"); + await click(view.containerEl.querySelector('[data-excalidraw-element-action="configure-drawing-preview"]')); + await c.waitFor(() => doc.querySelector(".excalidraw-drawing-preview-popover select"), "drawing preview popover opens in owner document"); + return doc.querySelector(".excalidraw-drawing-preview-popover"); + }; + const chooseFrame = async popup => { + const select = popup.querySelector("select"), index = [...select.options].findIndex(option => option.value === "frame:frame-marker"); + check(index>=0,"marker frame missing from image settings"); select.focus(); await key("Home","Home",36); + for(let i=0;i { + const slider=popup.querySelector('input[type="range"]'); slider.focus(); await key("Home","Home",36); + for(let i=0;i { + c.caseTrace = { ...c.caseTrace, imageSettings: { all, html: popup.outerHTML, links: [first,"shared-copy",variant].map(link) } }; + await click([...popup.querySelectorAll("button")].find(button=>button.textContent==="Apply")); + await c.waitFor(()=> { + c.caseTrace.imageSettings.after = { popover: popup.isConnected, disabled: popup.querySelector(".mod-cta")?.disabled, + currentLink: link(first), prompt: doc.querySelector(".modal-container")?.textContent }; + return doc.querySelector(".excalidraw-multiOptionConfirmationPrompt-buttonContainer"); + },"shared drawing scope prompt"); + const buttons=[...doc.querySelectorAll(".excalidraw-multiOptionConfirmationPrompt-buttonContainer button")]; + const body=doc.querySelector(".excalidraw-multiOptionConfirmationPrompt-message").textContent; + check(body.includes("3 images")&&!/fileId|file id/.test(body),"scope explanation exposes internal references or misses distinct-view copies"); + await click(buttons.find(button=>all?button.textContent.startsWith("All 3"):button.textContent==="Only this image")); + await c.waitFor(()=>!doc.querySelector(".excalidraw-drawing-preview-popover"),"image settings commit closes popover"); + }; + let popup=await open(); await chooseFrame(popup); await choosePadding(popup,3); await apply(popup,false); + check(get(first).fileId!==originalId && get("shared-copy").fileId===originalId,"only-this-image changed a shared copy"); + check(link(first).includes("#^frame=frame-marker,padding=30"),"image settings not persisted to embedded link"); + check(link(variant).includes("padding=20|100%"),"only-this-image changed a distinct view"); + check(Math.abs(get(first).width*get(first).height-oldAreas[0])<.01,"frame change did not retain image area"); + check(JSON.stringify(center(first))===JSON.stringify(oldCenters[0]),"frame change moved image center"); + view.containerEl.querySelector(".excalidraw").focus(); await key("z","KeyZ",90,modifier); + await c.waitFor(()=>get(first).fileId===originalId,"one undo restores old preview reference"); + await key("z","KeyZ",90,modifier|8); + await c.waitFor(()=>link(first).includes("padding=30"),"redo restores preview reference"); + popup=await open(); await choosePadding(popup,5); await apply(popup,true); + check(link(first).includes("frame=frame-marker,padding=50"),"apply-all lost chosen frame"); + check(link("shared-copy").includes("as-image,padding=50"),"apply-all pinned a default-thumbnail copy"); + check(link(variant).includes("frame=frame-marker,padding=50|100%"),"apply-all lost another copy's anchor or frame"); + for(let i=0;i<3;i++)check(JSON.stringify(center([first,"shared-copy",variant][i]))===JSON.stringify(oldCenters[i]),"apply-all changed a copy's center"); + popup=await open(); await click(popup.querySelector(".checkbox-container")); await apply(popup,true); + for(const id of [first,"shared-copy",variant]){ + const el=get(id), source=view.excalidrawData.getFile(el.fileId); + check(link(id).endsWith("|100%")&&el.customData.isAnchored,"100% state absent from link or derived canvas flag"); + check(Math.abs(el.width-source.size.width)<.01&&Math.abs(el.height-source.size.height)<.01,"anchored copy does not use intrinsic size"); + } + const before=JSON.stringify(view.getViewElements()), beforeLinks=[first,"shared-copy",variant].map(link); + const savedLinks=beforeLinks.map(value=>value.replace(/^[^#|]*/,app.metadataCache.fileToLinktext(drawing,view.file.path))); + popup=await open(); await choosePadding(popup,9); await key("Escape","Escape",27); + check(!doc.querySelector(".excalidraw-drawing-preview-popover")&&JSON.stringify(view.getViewElements())===before,"Escape wrote draft image settings"); + view=await env.saveReopen(view); + c.caseTrace.imageLinks = { expected: savedLinks, after: [first,"shared-copy",variant].map(link) }; + check(JSON.stringify([first,"shared-copy",variant].map(link))===JSON.stringify(savedLinks),"reopen lost image preview links or anchoring"); + for(const id of [first,"shared-copy",variant])check(view.excalidrawData.getFile(get(id).fileId).file===drawing&&get(id).customData.isAnchored,"reopen changed image source or anchoring"); + check(view.getViewElements().filter(el=>el.type==='image').length===3,"settings created duplicate image elements"); + return { assertions: ["selected drawing image opens owner-window configuration", "native frame/padding controls prompt once for all three source copies", "only-this-image isolates its link and preserves image area/center", "one native undo/redo restores references and geometry", "apply-all changes only edited fields across shared and distinct references", "100% persists in links and uses intrinsic dimensions", "Escape cancels drafts", "save/reopen preserves all links and three scene elements"] }; +} diff --git a/scripts/testing/host/embedRegressions.mjs b/scripts/testing/host/embedRegressions.mjs index ca558136..928ca9c2 100644 --- a/scripts/testing/host/embedRegressions.mjs +++ b/scripts/testing/host/embedRegressions.mjs @@ -86,7 +86,7 @@ async function exercise(c, env, template, modifier, context) { await c.waitFor(() => images().length === 3 && images().every(decoded), "padding images decoded"); const frames = () => [...root().querySelectorAll(".excalidraw-embed-controls-frame")]; await c.waitFor(() => frames().length === 3, "padding toolbar bindings"); - check(!frames()[2].querySelector('[data-excalidraw-embed-action="padding"]'), "padding shown on a whole drawing"); + check(frames()[2].querySelector('[data-excalidraw-embed-action="padding"] .lucide-box-select'), "whole drawing outer-padding icon absent"); const launch = async () => { const frame = frames()[1]; frame.scrollIntoView({ block: "center" }); const button = frame.querySelector('[data-excalidraw-embed-action="padding"]'); button.focus(); @@ -107,6 +107,6 @@ async function exercise(c, env, template, modifier, context) { check(leaf.view.editor.getValue() === source, "Escape changed padding source"); check(!doc.querySelector(".excalidraw-embed-padding-popover"), "padding popup leaked after Escape"); await leaf.view.save(); check(await app.vault.read(drawing) === bytes, "padding modified the destination drawing"); - return { assertions: ["padding action is absent on a whole drawing", "native slider keys create a live export preview without writing", "Enter changes only the second repeated area reference", "one native undo restores the complete original source", "Escape cancels and removes the popup", "the drawing bytes are unchanged"] }; + return { assertions: ["whole drawing exposes the outer-padding icon", "native slider keys create a live export preview without writing", "Enter changes only the second repeated area reference", "one native undo restores the complete original source", "Escape cancels and removes the popup", "the drawing bytes are unchanged"] }; }); } diff --git a/scripts/testing/host/frameSemantics.mjs b/scripts/testing/host/frameSemantics.mjs index 7f83d528..b7620d67 100644 --- a/scripts/testing/host/frameSemantics.mjs +++ b/scripts/testing/host/frameSemantics.mjs @@ -2,12 +2,13 @@ import assert from "node:assert/strict"; import { readFileSync } from "node:fs"; import { runInAppTask } from "./inAppTask.mjs"; +import { exerciseDrawingImagePreview } from "./drawingImagePreview.mjs"; import { behaviorEnvironment } from "./behaviorEnvironment.mjs"; import { behaviorInputDriver, collectBehaviorCases } from "./behaviorMatrix.mjs"; import { completeConsoleErrors } from "./debuggerSession.mjs"; import { settleBrowserDiagnostics, splitWindowErrors } from "./browserDiagnostics.mjs"; -const kinds = ["metadata", "navigation", "previews", "controls"]; +const kinds = ["metadata", "navigation", "previews", "controls", "outer-padding", "scene-images"]; export const frameSemanticsCaseIds = ["main", "popout"].flatMap(context => kinds.map(kind => `native:frames:${context}:${kind}`)).concat("native:frames:settings-reload"); export const frameSemanticsDeviceCaseIds = ["phone", "tablet"].flatMap(context => kinds.map(kind => `native:frames:${context}:${kind}`)); @@ -20,6 +21,7 @@ export async function runFrameSemanticsScenario({ cli, drawingPath, contexts = [ { ...base, id: "frame-marker", type: "frame", frameRole: "marker", name: "Marker,padding=50", x: 300, width: 100, height: 160, index: "a2" }, { ...base, id: "frame-unnamed", type: "frame", name: null, x: 500, index: "a3" }, { ...base, id: "frame-literal", type: "frame", name: "Frame", x: 650, index: "a4" }, + { ...base, id: "outside-crop", x: 210, y: 20, width: 10, height: 10, backgroundColor: "#ff0000", index: "a4V" }, { ...base, id: "outside", x: 900, y: 300, index: "a5" }, ]; template = template.replace(/```json\n[\s\S]*?\n```/, "```json\n" + JSON.stringify(scene, null, 2) + "\n```"); @@ -29,7 +31,7 @@ export async function runFrameSemanticsScenario({ cli, drawingPath, contexts = [ const env=await (${behaviorEnvironment.toString()})(c,path,context,template,${completeConsoleErrors.toString()},${settleBrowserDiagnostics.toString()}); c.diagnostics=env.diagnostics; (${collectBehaviorCases.toString()})(c); - await (${exercise.toString()})(c,env,template,modifier,context.id); + await (${exercise.toString()})(c,env,template,modifier,context.id,(${exerciseDrawingImagePreview.toString()})); return {tests:c.tests,consoleErrors:c.externalConsoleErrors||[],windowErrors:env.windowErrors,browserIdle:env.browserIdle}; }`)(); const result = await runInAppTask({ cli, execute, args: [drawingPath, { id, input: inputMode }, template, process.platform === "darwin" ? 4 : 2], @@ -74,12 +76,12 @@ async function reloadSettings(c) { return { tests: c.tests }; } -async function exercise(c, env, template, modifier, context) { +async function exercise(c, env, template, modifier, context, sceneExercise) { const { p, leaf, doc, win, check, click, key } = env; const nativeWindow = win.require("@electron/remote").getCurrentWindow(); const minimized = nativeWindow.isMinimized(); nativeWindow.restore(); nativeWindow.show(); nativeWindow.focus(); if (minimized) c.defer(() => { if (!nativeWindow.isDestroyed()) nativeWindow.minimize(); }); - let view = await env.openDrawing("Frames", { "excalidraw-thumbnail": "Main, α", "retained-property": "untouched" }); + let view = await env.openDrawing("Frames", { "excalidraw-thumbnail": "Main, α", "excalidraw-export-padding": 0, "retained-property": "untouched" }); const drawing = view.file; const customData = () => JSON.stringify(view.getViewElements().filter(element => element.type === "frame").map(element => [element.id, element.customData]).sort((a, b) => a[0].localeCompare(b[0]))); const yaml = async () => p.ea.obsidian.parseYaml((await app.vault.read(drawing)).match(/^---\n([\s\S]*?)\n---/)[1]); @@ -233,4 +235,23 @@ async function exercise(c, env, template, modifier, context) { check((await yaml())["excalidraw-thumbnail"] === "Main, α", "embed frame picker changed drawing thumbnail"); return { assertions: ["scan-eye dropdown has defaults and all frames including unnamed", "marker name generates unambiguous ID reference", "only owning occurrence changes with one Undo", "frame padding preview and cancel leave source unchanged", "destination thumbnail unchanged"] }; }); + await c.case(`native:frames:${context}:outer-padding`, ["P02","P05"], async () => { + const outer = await env.create("Outer-padding.md", `![[${drawing.path}#^as-image,padding=0|200]]\n\n![[${drawing.path}#^as-image,padding=30|200]]\n\n![[${drawing.path}#^frame=,padding=30|200]]\n\nEnd`); + for(const type of ["SVG","SVGIMG","PNG"]){ + p.settings.previewImageType=type;await leaf.setViewState({type:"empty",state:{}}); + await leaf.setViewState({type:"markdown",state:{file:outer.path,mode:"source",source:false}}); + app.workspace.setActiveLeaf(leaf,{focus:true});leaf.view.editor.setCursor({line:leaf.view.editor.lastLine(),ch:0}); + await c.waitFor(()=>images().length===3&&images().every(decoded),"outer padding images decoded"); + check(Math.abs(ratio(images()[0])-200/120)<.01,type+" zero padding changed frame bounds"); + check(Math.abs(ratio(images()[1])-260/180)<.01,type+" thumbnail outer padding dimensions incorrect: "+ratio(images()[1])); + check(ratio(images()[2])>2,type+" padded whole-scene became a thumbnail"); + const image=images()[1], svg=image.querySelector("svg"); + const source=svg?"data:image/svg+xml;charset=utf-8,"+encodeURIComponent(svg.outerHTML):image.src; + const pixels=await env.decode(source); + check(pixels.green>0&&pixels.red===0,type+" outer padding revealed the red element outside the frame"); + } + return {assertions:["default-thumbnail and explicit whole-scene padding persist independently", "all three render formats add the requested outer dimensions", "frame contents remain clipped; outer padding never reveals neighboring elements"]}; + }); + await c.case(`native:frames:${context}:scene-images`, ["P02","P05"], () => sceneExercise(c,env,template,drawing,context,modifier)); + } diff --git a/src/constants/constants.ts b/src/constants/constants.ts index bb800b7e..07d5b09d 100644 --- a/src/constants/constants.ts +++ b/src/constants/constants.ts @@ -107,6 +107,7 @@ export let { getBoundTextMaxWidth, exportToSvg, exportToBlob, + exportScene, mutateElement, restoreElements, restoreLibraryItems, @@ -168,6 +169,7 @@ export function updateExcalidrawLib() { getBoundTextMaxWidth, exportToSvg, exportToBlob, + exportScene, mutateElement, restoreElements, restoreLibraryItems, diff --git a/src/core/editor/embedFrame.ts b/src/core/editor/embedFrame.ts index 494e3d0f..596b40c4 100644 --- a/src/core/editor/embedFrame.ts +++ b/src/core/editor/embedFrame.ts @@ -1,24 +1,12 @@ import { readDrawingEmbedToken } from "./embedDimensions"; -import { getEmbeddedFilenameParts } from "src/utils/embeddedFilenameParts"; +import { rewriteDrawingPreviewLink } from "src/utils/drawingPreviewLink"; /** Rewrite only one embed's region override; paths, aliases, titles and table escapes stay byte-identical. */ export function rewriteEmbedFrame(text: string, reference: string | null): string | null { const token = readDrawingEmbedToken(text); if (!token || token.text !== text || reference !== null && reference !== "" && !/^[A-Za-z0-9_-]+$/.test(reference)) return null; - const target = token.target, hash = target.includes("#") ? target.indexOf("#") : target.search(/%23/i); - const path = hash < 0 ? target : target.slice(0, hash); - const raw = hash < 0 ? "" : target.slice(hash); - let decoded: string; - try { decoded = decodeURIComponent(raw); } catch { return null; } - const parts = getEmbeddedFilenameParts(decoded); - const suffix = reference && parts.padding !== undefined - ? raw.match(/(?:,|%2c)padding(?:=|%3d)(?:\d+(?:(?:\.|%2e)\d+)?|(?:\.|%2e)\d+)$/i)?.[0] ?? "" - : ""; - const marker = raw.startsWith("%23") ? "%23" : "#"; - const caret = raw.match(/^(?:#|%23)(%5e)/i)?.[1] ?? "^"; - const kind = reference && parts.hasClippedFrameref ? "clippedframe" : "frame"; - const equals = raw.match(/(?:clippedframe|frame)(%3d|=)/i)?.[1] ?? "="; - const next = reference === null ? path : path + marker + caret + kind + equals + reference + suffix; + const target = token.target, next = rewriteDrawingPreviewLink(target, { frame: reference }); + if (next === null) return null; const from = token.wiki ? 3 : text.indexOf(target, token.aliasTo + 2); return from < 0 ? null : text.slice(0, from) + next + text.slice(from + target.length); } diff --git a/src/core/editor/embedPadding.ts b/src/core/editor/embedPadding.ts index 2c72ae4e..7a8744b1 100644 --- a/src/core/editor/embedPadding.ts +++ b/src/core/editor/embedPadding.ts @@ -1,23 +1,9 @@ import { readDrawingEmbedToken } from "./embedDimensions"; -import { getEmbeddedFilenameParts } from "src/utils/embeddedFilenameParts"; +import { rewriteDrawingPreviewLink } from "src/utils/drawingPreviewLink"; -const PADDING_SUFFIX = /(?:,|%2c)padding(?:=|%3d)(?:\d+(?:(?:\.|%2e)\d+)?|(?:\.|%2e)\d+)$/i; - -/** Rewrite only a region reference's terminal padding, preserving raw paths and encoding. */ +/** Rewrite a drawing preview's padding; retained name supports existing callers. */ export function withAreaPadding(target: string, padding: number | null): string | null { - const hash = target.includes("#") ? target.indexOf("#") : target.search(/%23/i); - if (hash < 0) return null; - let decoded: string; - // A canonical vault filename may contain a literal %. Only the reference - // needs URI decoding; destination paths must retain their exact spelling. - try { decoded = target.slice(0, hash) + decodeURIComponent(target.slice(hash)); } catch { return null; } - const parts = getEmbeddedFilenameParts(decoded); - if (!(parts.hasArearef || parts.hasFrameref || parts.hasClippedFrameref) || !(parts.blockref || parts.sectionref) || - padding !== null && (!Number.isFinite(padding) || padding < 0 || padding > 2000)) return null; - const bare = target.replace(PADDING_SUFFIX, ""); - // Malformed/duplicate parameters must never be mistaken for the area id. - if (parts.hasArearef && /,padding=/i.test(decodeURIComponent(bare.slice(hash)))) return null; - return bare + (padding === null ? "" : `,padding=${padding}`); + return rewriteDrawingPreviewLink(target, { padding }); } /** Edit the destination parameter of one owned wiki/Markdown/table embed token. */ diff --git a/src/core/managers/DrawingEmbedControls.ts b/src/core/managers/DrawingEmbedControls.ts index ca48030e..d0623330 100644 --- a/src/core/managers/DrawingEmbedControls.ts +++ b/src/core/managers/DrawingEmbedControls.ts @@ -78,7 +78,7 @@ export class DrawingEmbedControls extends MarkdownRenderChild { const menu = this.frameMenu = new Menu(); menu.setUseNativeMenu(false); const parts = getEmbeddedFilenameParts(this.actions.target), ref = parts.blockref ?? parts.sectionref; const choose = (reference: string | null) => { if (!this.current() || !this.source.replaceFrame(reference)) this.changed(); }; - menu.addItem(item => item.setTitle(t("FRAME_DEFAULT")).setChecked(!parts.hasBlockref && !parts.hasSectionref).onClick(() => choose(null))); + menu.addItem(item => item.setTitle(t("FRAME_DEFAULT")).setChecked(!parts.hasBlockref && !parts.hasSectionref || ref === "as-image").onClick(() => choose(null))); menu.addItem(item => item.setTitle(t("FRAME_WHOLE")).setChecked(parts.hasFrameref && ref === "").onClick(() => choose(""))); menu.addSeparator(); for (const frame of this.actions.frames) { @@ -90,7 +90,8 @@ export class DrawingEmbedControls extends MarkdownRenderChild { }); } if (this.actions.padding && this.source.replacePadding) { - const padding = button("padding", "square-dot", t("EMBED_ADJUST_PADDING"), () => { + const area = getEmbeddedFilenameParts(this.actions.target).hasArearef; + const padding = button("padding", area ? "square-dot" : "box-select", t(area ? "PREVIEW_AREA_EXPANSION" : "PREVIEW_OUTER_PADDING"), () => { if (this.padding) { this.padding.close(true); return; } if (!this.current()) return; this.finish(false); diff --git a/src/core/managers/DrawingEmbedPaddingControl.ts b/src/core/managers/DrawingEmbedPaddingControl.ts index fce2a315..626ae607 100644 --- a/src/core/managers/DrawingEmbedPaddingControl.ts +++ b/src/core/managers/DrawingEmbedPaddingControl.ts @@ -2,6 +2,7 @@ import { Component, Notice, SliderComponent, setIcon, setTooltip } from "obsidia import type { DrawingEmbedActions, EmbedSourceBinding } from "src/types/drawingEmbedTypes"; import { t } from "src/lang/helpers"; import { setStyle } from "src/utils/styleUtils"; +import { getDrawingPreviewParts } from "src/utils/drawingPreviewLink"; const VALUES = [0, 10, ...Array.from({ length: 40 }, (_, index) => (index + 1) * 50)]; @@ -33,12 +34,16 @@ export class DrawingEmbedPaddingControl extends Component { this.frame.addClass("excalidraw-embed-padding-open"); this.opener.setAttribute("aria-expanded", "true"); const doc = this.frame.ownerDocument, win = doc.defaultView; - this.popup = doc.body.createDiv({ cls: "excalidraw-embed-padding-popover", attr: { role: "dialog", "aria-label": t("EMBED_ADJUST_PADDING") } }); + const area = getDrawingPreviewParts(this.actions.target ?? "")?.hasArearef; + const label = t(area ? "PREVIEW_AREA_EXPANSION" : "PREVIEW_OUTER_PADDING"); + this.popup = doc.body.createDiv({ cls: "excalidraw-embed-padding-popover", attr: { role: "dialog", "aria-label": label } }); + this.popup.createDiv({ cls: "excalidraw-embed-padding-heading", text: label }); + this.popup.createDiv({ cls: "excalidraw-embed-padding-help", text: t(area ? "PREVIEW_AREA_HELP" : "PREVIEW_PADDING_HELP") }); const track = this.popup.createDiv({ cls: "excalidraw-embed-padding-track" }); const nearest = VALUES.reduce((best, value, index) => Math.abs(value - this.value) < Math.abs(VALUES[best] - this.value) ? index : best, 0); const control = new SliderComponent(track).setLimits(0, VALUES.length - 1, 1).setValue(nearest); const slider = control.sliderEl; - slider.setAttribute("aria-label", t("EMBED_ADJUST_PADDING")); + slider.setAttribute("aria-label", label); slider.setAttribute("aria-valuetext", String(this.value)); const output = this.popup.createEl("output", { text: String(this.value), attr: { "aria-live": "polite" } }); const update = () => { diff --git a/src/core/managers/MarkdownPostProcessor.ts b/src/core/managers/MarkdownPostProcessor.ts index 4afa894c..447139a4 100644 --- a/src/core/managers/MarkdownPostProcessor.ts +++ b/src/core/managers/MarkdownPostProcessor.ts @@ -179,7 +179,7 @@ const _getPNG = async ({ const cacheKey = { ...filenameParts, - cacheId: "frame-thumbnail-v1", + cacheId: "frame-thumbnail-v2", isDark: theme === "dark", previewImageType: PreviewImageType.PNG, scale, @@ -197,14 +197,15 @@ const _getPNG = async ({ } } - const quickPNG = !isImagePartRef(filenameParts) + const hasImageReference = isExplicitImageEmbed(imgAttributes.fname); + const quickPNG = !hasImageReference ? await getQuickImagePreview(plugin, file.path, "png") : undefined; const png = quickPNG ?? (await createPNG( - isImagePartRef(filenameParts) + hasImageReference ? filenameParts.filepath + filenameParts.linkpartReference : file.path, scale, @@ -328,7 +329,7 @@ const _getSVGIMG = async ({ exportSettings.skipInliningFonts = false; const cacheKey = { ...filenameParts, - cacheId: "frame-thumbnail-v1", + cacheId: "frame-thumbnail-v2", isDark: theme === "dark", previewImageType: PreviewImageType.SVGIMG, scale: 1, @@ -424,7 +425,7 @@ const _getSVGNative = async ({ exportSettings.skipInliningFonts = false; const cacheKey = { ...filenameParts, - cacheId: "frame-thumbnail-v1", + cacheId: "frame-thumbnail-v2", isDark: theme === "dark", previewImageType: PreviewImageType.SVG, scale: 1, diff --git a/src/lang/locale/en.ts b/src/lang/locale/en.ts index 28b5f6fe..6a56aed3 100644 --- a/src/lang/locale/en.ts +++ b/src/lang/locale/en.ts @@ -16,6 +16,21 @@ declare const PLUGIN_VERSION: string; // English export default { + PREVIEW_OUTER_PADDING: "Outer padding", + PREVIEW_AREA_EXPANSION: "Area expansion", + PREVIEW_PADDING_HELP: "Adds space around the preview without including additional elements.", + PREVIEW_AREA_HELP: "Includes more of the surrounding drawing.", + PREVIEW_CONFIGURE: "Configure drawing preview", + PREVIEW_CONFIGURE_HELP: "Choose the view, padding, and original-size behavior. If this drawing appears more than once, you'll choose which images to update.", + PREVIEW_VIEW: "View", + PREVIEW_ANCHOR: "Anchor at original size (100%)", + PREVIEW_ANCHOR_HELP: "Follows source dimensions and disables manual resizing.", + PREVIEW_SHARED_TITLE: "Change this image or all copies?", + PREVIEW_SHARED_HELP: "\"{drawing}\" appears in {count} images in this scene. Apply your changes to all of them?", + PREVIEW_ALL: "All {count} images", + PREVIEW_ONLY: "Only this image", + PREVIEW_APPLY: "Apply", + PREVIEW_CURRENT: "Current reference", FRAME_NAVIGATE: "Navigate to frame", FRAME_PICK: "Choose frame", FRAME_DEFAULT: "Default thumbnail", diff --git a/src/lang/locale/es.ts b/src/lang/locale/es.ts index 9bf08f97..d60a6934 100644 --- a/src/lang/locale/es.ts +++ b/src/lang/locale/es.ts @@ -16,6 +16,21 @@ declare const PLUGIN_VERSION: string; // Español export default { + PREVIEW_OUTER_PADDING: "Margen exterior", + PREVIEW_AREA_EXPANSION: "Ampliación del área", + PREVIEW_PADDING_HELP: "Añade espacio alrededor de la vista previa sin incluir elementos adicionales.", + PREVIEW_AREA_HELP: "Incluye más contenido del dibujo circundante.", + PREVIEW_CONFIGURE: "Configurar vista previa del dibujo", + PREVIEW_CONFIGURE_HELP: "Elige la vista, el margen y el tamaño original. Si el dibujo aparece varias veces, podrás elegir qué imágenes actualizar.", + PREVIEW_VIEW: "Vista", + PREVIEW_ANCHOR: "Anclar al tamaño original (100%)", + PREVIEW_ANCHOR_HELP: "Sigue las dimensiones del origen y desactiva el cambio de tamaño manual.", + PREVIEW_SHARED_TITLE: "¿Cambiar esta imagen o todas las copias?", + PREVIEW_SHARED_HELP: "«{drawing}» aparece en {count} imágenes de esta escena. ¿Aplicar los cambios a todas?", + PREVIEW_ALL: "Las {count} imágenes", + PREVIEW_ONLY: "Solo esta imagen", + PREVIEW_APPLY: "Aplicar", + PREVIEW_CURRENT: "Referencia actual", FRAME_NAVIGATE: "Ir al marco", FRAME_PICK: "Elegir marco", FRAME_DEFAULT: "Miniatura predeterminada", diff --git a/src/lang/locale/ru.ts b/src/lang/locale/ru.ts index e28ccb38..0059fb09 100644 --- a/src/lang/locale/ru.ts +++ b/src/lang/locale/ru.ts @@ -14,6 +14,21 @@ import { // русский export default { + PREVIEW_OUTER_PADDING: "Внешние поля", + PREVIEW_AREA_EXPANSION: "Расширение области", + PREVIEW_PADDING_HELP: "Добавляет поля вокруг предпросмотра, не включая дополнительные элементы.", + PREVIEW_AREA_HELP: "Включает больше содержимого вокруг выбранной области.", + PREVIEW_CONFIGURE: "Настроить предпросмотр рисунка", + PREVIEW_CONFIGURE_HELP: "Выберите вид, поля и исходный размер. Если рисунок используется несколько раз, вы сможете выбрать изображения для обновления.", + PREVIEW_VIEW: "Вид", + PREVIEW_ANCHOR: "Закрепить исходный размер (100%)", + PREVIEW_ANCHOR_HELP: "Следует размерам источника и отключает ручное изменение размера.", + PREVIEW_SHARED_TITLE: "Изменить это изображение или все копии?", + PREVIEW_SHARED_HELP: "«{drawing}» используется в {count} изображениях этой сцены. Применить изменения ко всем?", + PREVIEW_ALL: "Все изображения ({count})", + PREVIEW_ONLY: "Только это изображение", + PREVIEW_APPLY: "Применить", + PREVIEW_CURRENT: "Текущая ссылка", FRAME_NAVIGATE: "Перейти к рамке", FRAME_PICK: "Выбрать рамку", FRAME_DEFAULT: "Миниатюра по умолчанию", diff --git a/src/lang/locale/zh-cn.ts b/src/lang/locale/zh-cn.ts index c2d83f27..3040be73 100644 --- a/src/lang/locale/zh-cn.ts +++ b/src/lang/locale/zh-cn.ts @@ -11,6 +11,21 @@ declare const PLUGIN_VERSION: string; // 简体中文 export default { + PREVIEW_OUTER_PADDING: "外部留白", + PREVIEW_AREA_EXPANSION: "扩展区域", + PREVIEW_PADDING_HELP: "在预览周围添加留白,不显示额外元素。", + PREVIEW_AREA_HELP: "包含所选区域周围更多的绘图内容。", + PREVIEW_CONFIGURE: "配置绘图预览", + PREVIEW_CONFIGURE_HELP: "选择视图、留白和原始大小。如果此绘图多次出现,你可以选择要更新的图像。", + PREVIEW_VIEW: "视图", + PREVIEW_ANCHOR: "锁定为原始大小(100%)", + PREVIEW_ANCHOR_HELP: "跟随源图尺寸,并禁用手动调整大小。", + PREVIEW_SHARED_TITLE: "修改此图像还是所有副本?", + PREVIEW_SHARED_HELP: "“{drawing}”在此场景中用于 {count} 个图像。将更改应用于所有图像吗?", + PREVIEW_ALL: "全部 {count} 个图像", + PREVIEW_ONLY: "仅此图像", + PREVIEW_APPLY: "应用", + PREVIEW_CURRENT: "当前引用", FRAME_NAVIGATE: "跳转到画框", FRAME_PICK: "选择画框", FRAME_DEFAULT: "默认缩略图", diff --git a/src/lang/locale/zh-tw.ts b/src/lang/locale/zh-tw.ts index 4fbb4b2d..c564091b 100644 --- a/src/lang/locale/zh-tw.ts +++ b/src/lang/locale/zh-tw.ts @@ -11,6 +11,21 @@ declare const PLUGIN_VERSION: string; // 繁體中文 export default { + PREVIEW_OUTER_PADDING: "外部留白", + PREVIEW_AREA_EXPANSION: "擴展區域", + PREVIEW_PADDING_HELP: "在預覽周圍加入留白,不顯示額外元素。", + PREVIEW_AREA_HELP: "包含所選區域周圍更多的繪圖內容。", + PREVIEW_CONFIGURE: "設定繪圖預覽", + PREVIEW_CONFIGURE_HELP: "選擇檢視、留白和原始大小。如果此繪圖多次出現,你可以選擇要更新的影像。", + PREVIEW_VIEW: "檢視", + PREVIEW_ANCHOR: "鎖定為原始大小(100%)", + PREVIEW_ANCHOR_HELP: "跟隨來源尺寸,並停用手動調整大小。", + PREVIEW_SHARED_TITLE: "修改此影像還是所有副本?", + PREVIEW_SHARED_HELP: "「{drawing}」在此場景中用於 {count} 個影像。將變更套用至所有影像嗎?", + PREVIEW_ALL: "全部 {count} 個影像", + PREVIEW_ONLY: "僅此影像", + PREVIEW_APPLY: "套用", + PREVIEW_CURRENT: "目前參照", FRAME_NAVIGATE: "跳至畫框", FRAME_PICK: "選擇畫框", FRAME_DEFAULT: "預設縮圖", diff --git a/src/shared/Dialogs/DrawingImagePreviewPopover.ts b/src/shared/Dialogs/DrawingImagePreviewPopover.ts new file mode 100644 index 00000000..5e7bb45d --- /dev/null +++ b/src/shared/Dialogs/DrawingImagePreviewPopover.ts @@ -0,0 +1,130 @@ +import { Component, Setting, SliderComponent, setIcon } from "obsidian"; +import type { ExcalidrawFrameElement } from "@zsviczian/excalidraw/types/element/src/types"; +import type ExcalidrawView from "src/view/ExcalidrawView"; +import type { EmbeddedFile } from "src/shared/EmbeddedFileLoader"; +import { getDrawingPreviewParts, rewriteDrawingPreviewLink, type DrawingPreviewChanges } from "src/utils/drawingPreviewLink"; +import { setStyle } from "src/utils/styleUtils"; +import { t } from "src/lang/helpers"; + +/** Draft image-link controls: preview locally, then commit once after choosing scope. */ +export class DrawingImagePreviewPopover extends Component { + private popup: HTMLElement; + private image: HTMLImageElement; + private timer: number | null = null; + private generation = 0; + private active = false; + private applying = false; + private readonly original: string; + private readonly changes: DrawingPreviewChanges = {}; + + constructor(private readonly view: ExcalidrawView, private readonly source: EmbeddedFile, + private readonly frames: readonly ExcalidrawFrameElement[], private readonly defaultPadding: number, private readonly isCurrent: () => boolean, + private readonly render: (link: string) => Promise<{ image: { dataURL: string } }>, + private readonly commit: (changes: DrawingPreviewChanges) => Promise, private readonly closed: () => void) { + super(); this.original = source.linkParts.original; + } + + /** Mount in the selected image's owning window, outside canvas paint containment. */ + onload(): void { + this.active = true; + const doc = this.view.ownerDocument, win = doc.defaultView; + this.popup = doc.body.createDiv({ cls: "excalidraw-drawing-preview-popover", attr: { role: "dialog", "aria-label": t("PREVIEW_CONFIGURE") } }); + this.popup.createEl("strong", { text: t("PREVIEW_CONFIGURE") }); + this.popup.createDiv({ cls: "setting-item-description", text: t("PREVIEW_CONFIGURE_HELP") }); + this.image = this.popup.createEl("img", { attr: { alt: t("PREVIEW_VIEW") } }); + const parts = getDrawingPreviewParts(this.original), ref = parts.blockref ?? parts.sectionref; + const initialFrame = parts.hasFrameref && ref === "" ? "whole" : + !(parts.hasBlockref || parts.hasSectionref) || ref === "as-image" ? "default" : + (parts.hasFrameref || parts.hasClippedFrameref) && this.frames.some(frame => frame.id === ref || frame.name === ref) + ? "frame:" + this.frames.find(frame => frame.id === ref || frame.name === ref).id : "current"; + const paddingSetting = new Setting(this.popup); + const updatePaddingLabel = () => { + const next = getDrawingPreviewParts(rewriteDrawingPreviewLink(this.original, this.changes)); + const area = next.hasArearef; + paddingSetting.setName(t(area ? "PREVIEW_AREA_EXPANSION" : "PREVIEW_OUTER_PADDING")) + .setDesc(t(area ? "PREVIEW_AREA_HELP" : "PREVIEW_PADDING_HELP")); + paddingSetting.nameEl.empty(); + setIcon(paddingSetting.nameEl, area ? "square-dot" : "box-select"); + paddingSetting.nameEl.appendText(" " + t(area ? "PREVIEW_AREA_EXPANSION" : "PREVIEW_OUTER_PADDING")); + }; + const viewSetting = new Setting(this.popup).setName(t("PREVIEW_VIEW")).addDropdown(dropdown => { + dropdown.addOption("default", t("FRAME_DEFAULT")).addOption("whole", t("FRAME_WHOLE")); + if (initialFrame === "current") dropdown.addOption("current", t("PREVIEW_CURRENT")); + for (const frame of this.frames) dropdown.addOption("frame:" + frame.id, + frame.name?.trim() ? frame.name : `${t(frame.frameRole === "marker" ? "FRAME_UNNAMED_MARKER" : "FRAME_UNNAMED")} (${frame.id})`); + dropdown.setValue(initialFrame).onChange(value => { + if (value === initialFrame) delete this.changes.frame; + else this.changes.frame = value === "default" ? null : value === "whole" ? "" : value.slice(6); + updatePaddingLabel(); this.queuePreview(); + }); + }); + this.popup.insertBefore(viewSetting.settingEl, paddingSetting.settingEl); + const defaultPadding = this.defaultPadding, initialPadding = parts.padding; + let slider: SliderComponent; + const output = paddingSetting.controlEl.createEl("output", { text: String(initialPadding ?? defaultPadding) }); + paddingSetting.addSlider(control => { + slider = control; control.setLimits(0, 2000, 10).setValue(initialPadding ?? defaultPadding).onChange(value => { + if (value === (initialPadding ?? defaultPadding)) delete this.changes.padding; else this.changes.padding = value; + output.setText(String(value)); this.queuePreview(); + }); control.sliderEl.setAttribute("aria-label", t("PREVIEW_OUTER_PADDING")); + }).addExtraButton(button => button.setIcon("rotate-ccw").setTooltip(t("EMBED_RESET_PADDING")).onClick(() => { + if (initialPadding === undefined) delete this.changes.padding; else this.changes.padding = null; + slider.setValue(defaultPadding); output.setText(String(defaultPadding)); this.queuePreview(); + })); + updatePaddingLabel(); + const anchored = this.original.endsWith("|100%"); + new Setting(this.popup).setName(t("PREVIEW_ANCHOR")).setDesc(t("PREVIEW_ANCHOR_HELP")).addToggle(toggle => + toggle.setValue(anchored).onChange(value => { if (value === anchored) delete this.changes.anchored; else this.changes.anchored = value; })); + const buttons = this.popup.createDiv({ cls: "excalidraw-drawing-preview-buttons" }); + const cancel = buttons.createEl("button", { text: t("PROMPT_BUTTON_CANCEL"), attr: { type: "button" } }); + const apply = buttons.createEl("button", { text: t("PREVIEW_APPLY"), cls: "mod-cta", attr: { type: "button" } }); + this.registerDomEvent(cancel, "click", () => { if (!this.applying) this.unload(); }); + const save = async () => { + if (this.applying || !this.current()) return; + if (!Object.keys(this.changes).length) { this.unload(); return; } + this.applying = true; apply.disabled = true; + try { if (await this.commit({ ...this.changes })) this.unload(); } + finally { this.applying = false; apply.disabled = false; } + }; + this.registerDomEvent(apply, "click", () => { void save(); }); + this.registerDomEvent(this.popup, "pointerdown", event => event.stopPropagation()); + this.registerDomEvent(this.popup, "wheel", event => event.stopPropagation()); + this.registerDomEvent(doc, "pointerdown", event => { if (!this.applying && !event.composedPath().includes(this.popup)) this.unload(); }); + this.registerDomEvent(doc, "keydown", event => { + if (event.key === "Escape" && !this.applying) { event.preventDefault(); event.stopPropagation(); this.unload(); } + }, true); + this.registerDomEvent(win, "resize", () => this.place()); + this.registerDomEvent(win, "blur", () => { if (!this.applying) this.unload(); }); + this.place(); this.queuePreview(); this.popup.querySelector("select")?.focus(); + } + + private current(): boolean { return this.active && this.isCurrent(); } + + private place(): void { + if (!this.current()) { this.unload(); return; } + const anchor = this.view.excalidrawContainer.querySelector(".excalidraw-selected-element-menu") ?? this.view.excalidrawContainer; + const bounds = anchor.getBoundingClientRect(), popup = this.popup.getBoundingClientRect(), win = this.popup.ownerDocument.defaultView; + setStyle(this.popup, { left: `${Math.max(8, Math.min(bounds.left, win.innerWidth - popup.width - 8))}px`, + top: `${Math.max(8, Math.min(bounds.bottom + 4, win.innerHeight - popup.height - 8))}px` }); + } + + private queuePreview(): void { + const generation = ++this.generation; + if (this.timer !== null) window.clearTimeout(this.timer); + this.timer = window.setTimeout(() => { this.timer = null; void (async () => { + const link = rewriteDrawingPreviewLink(this.original, this.changes); + if (!link || !this.current()) return; + try { + const result = await this.render(link); + if (this.current() && generation === this.generation) { this.image.src = result.image.dataURL; this.place(); } + } catch { /* The owned controller reports apply failures; a stale draft never writes. */ } + })(); }, 300); + } + + /** Cancel delayed renders and release this window's controls without a scene write. */ + onunload(): void { + this.active = false; this.generation++; + if (this.timer !== null) window.clearTimeout(this.timer); + this.timer = null; this.popup?.remove(); this.closed(); + } +} diff --git a/src/shared/Dialogs/Messages.ts b/src/shared/Dialogs/Messages.ts index 564d5d29..193ec23a 100644 --- a/src/shared/Dialogs/Messages.ts +++ b/src/shared/Dialogs/Messages.ts @@ -19,8 +19,9 @@ I build this plugin as a labor of love. Curious about the philosophy behind it? `, "2.29.3": ` ## New and improved -- Choose a named frame or marker frame as the drawing thumbnail, pick frames from embed controls, and use **Navigate to frame** to jump within a drawing. Named frames are listed in the document?s \`excalidraw-anchors\` property. [#3042](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/3042). -- Adjust the padding of \`area=\`, \`frame=\` and \`clippedframe=\` drawing embeds from their Live Preview toolbar. Preview changes with the slider, then close it to save; Escape cancels. Inspired by 🙏[Evgene-Kopylov](${URLs.GITHUB_COM}/Evgene-Kopylov) [#2868](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2868). +- Configure drawing images directly in the scene: choose a view, padding and original-size anchoring, then update one image or all copies of the same drawing. +- Choose a named frame or marker frame as the drawing thumbnail, pick frames from embed controls, and use **Navigate to frame** to jump within a drawing. Named frames are listed in the document's \`excalidraw-anchors\` property. [#3042](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/3042). +- Adjust outer padding for thumbnails, whole scenes and frames, or expand the captured area of \`area=\` drawing embeds from their Live Preview toolbar. Preview changes with the slider, then close it to save; Escape cancels. Inspired by 🙏[Evgene-Kopylov](${URLs.GITHUB_COM}/Evgene-Kopylov) [#2868](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2868). ## Fixed - Drawing embeds render reliably in long notes in Reading view and with relative links in Live Preview. [#3039](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/3039), [#3040](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/3040). diff --git a/src/shared/EmbeddedDataRegistries.ts b/src/shared/EmbeddedDataRegistries.ts index c14c3cd5..39f1d4f4 100644 --- a/src/shared/EmbeddedDataRegistries.ts +++ b/src/shared/EmbeddedDataRegistries.ts @@ -13,6 +13,7 @@ import type { FileId } from "@zsviczian/excalidraw/types/element/src/types"; import type { MarkdownImageData } from "src/types/markdownImageTypes"; import type { EmbeddedFile } from "./EmbeddedFileLoader"; import type { ExcalidrawData, EquationItem, MermaidItem } from "./ExcalidrawData"; +import { getEmbeddedFileMasterLink } from "src/utils/linkUtils"; export class EmbeddedDataRegistries { /** @@ -79,9 +80,7 @@ export class EmbeddedDataRegistries { embeddedFile = new this.embeddedFileCtor( this.host.plugin, this.host.file.path, - masterFile.blockrefData - ? `${masterFile.path}#${masterFile.blockrefData}` - : masterFile.path, + getEmbeddedFileMasterLink(masterFile.path, masterFile.blockrefData), masterFile.colorMapJSON, ); this.host.files.set(fileId, embeddedFile); @@ -125,9 +124,7 @@ export class EmbeddedDataRegistries { const embeddedFile = new this.embeddedFileCtor( this.host.plugin, this.host.file.path, - (masterFile.blockrefData - ? `${path}#${masterFile.blockrefData}` - : path) + (fixScale ? "|100%" : ""), + getEmbeddedFileMasterLink(path + (fixScale ? "|100%" : ""), masterFile.blockrefData), masterFile.colorMapJSON, ); this.host.files.set(fileId, embeddedFile); diff --git a/src/shared/EmbeddedFileLoader.ts b/src/shared/EmbeddedFileLoader.ts index a842a2d1..6b2f9eac 100644 --- a/src/shared/EmbeddedFileLoader.ts +++ b/src/shared/EmbeddedFileLoader.ts @@ -674,7 +674,8 @@ export class EmbeddedFile { this.filenameparts.hasGroupref || this.filenameparts.hasArearef || this.filenameparts.hasFrameref || - this.filenameparts.hasClippedFrameref + this.filenameparts.hasClippedFrameref || + this.filenameparts.blockref === "as-image" && this.plugin.isExcalidrawFile(this.file) ); this.filenameparts.filepath = this.file.path; } @@ -953,7 +954,7 @@ export class EmbeddedFilesLoader { ? (inFile as EmbeddedFile).filenameparts : null; const cacheKey: ImageKey = { - cacheId: "frame-thumbnail-v1", + cacheId: "frame-thumbnail-v2", ...(hasFilenameParts ? { ...filenameParts, diff --git a/src/types/excalidrawLib.d.ts b/src/types/excalidrawLib.d.ts index 498bad6b..565f41d9 100644 --- a/src/types/excalidrawLib.d.ts +++ b/src/types/excalidrawLib.d.ts @@ -78,6 +78,7 @@ type EmbeddedLink = | null; export declare namespace ExcalidrawLib { + const exportScene: typeof import("@zsviczian/excalidraw").exportScene; type ObsidianCommonHostUIMode = "full" | "compact" | "tray" | "mobile"; type ObsidianCommonHostAdapter = Readonly<{ diff --git a/src/utils/drawingPreviewLink.ts b/src/utils/drawingPreviewLink.ts new file mode 100644 index 00000000..38bf770b --- /dev/null +++ b/src/utils/drawingPreviewLink.ts @@ -0,0 +1,51 @@ +import { getEmbeddedFilenameParts } from "./embeddedFilenameParts"; + +/** Persisted preview overrides live in the embedded-file link, including |100%. */ +export interface DrawingPreviewChanges { + frame?: string | null; + padding?: number | null; + anchored?: boolean; +} + +const PADDING_SUFFIX = /(?:,|%2c)padding(?:=|%3d)(?:\d+(?:(?:\.|%2e)\d+)?|(?:\.|%2e)\d+)$/i; + +/** Read the reference without decoding a vault filename that may contain a literal %. */ +export function getDrawingPreviewParts(link: string) { + const target = link.split("|")[0], hash = target.includes("#") ? target.indexOf("#") : target.search(/%23/i); + try { return getEmbeddedFilenameParts(hash < 0 ? target : target.slice(0, hash) + decodeURIComponent(target.slice(hash))); } + catch { return getEmbeddedFilenameParts(target); } +} + +/** Apply only changed fields while retaining raw paths, aliases and unrelated overrides. */ +export function rewriteDrawingPreviewLink(link: string, changes: DrawingPreviewChanges): string | null { + const pipe = link.indexOf("|"), target = pipe < 0 ? link : link.slice(0, pipe); + let alias = pipe < 0 ? "" : link.slice(pipe); + const parts = getDrawingPreviewParts(target); + if (!parts) return null; + const hash = target.includes("#") ? target.indexOf("#") : target.search(/%23/i); + const path = hash < 0 ? target : target.slice(0, hash), raw = hash < 0 ? "" : target.slice(hash); + const marker = raw.startsWith("%23") ? "%23" : "#", caret = raw.match(/^(?:#|%23)(%5e)/i)?.[1] ?? "^"; + let reference = raw; + if (changes.frame !== undefined) { + const frame = changes.frame; + if (frame !== null && frame !== "" && !/^[A-Za-z0-9_-]+$/.test(frame)) return null; + const padding = parts.padding === undefined ? "" : raw.match(PADDING_SUFFIX)?.[0] ?? ""; + const kind = frame && parts.hasClippedFrameref ? "clippedframe" : "frame"; + const equals = raw.match(/(?:clippedframe|frame)(%3d|=)/i)?.[1] ?? "="; + reference = frame === null ? (padding ? marker + caret + "as-image" + padding : "") : marker + caret + kind + equals + frame + padding; + } + if (changes.padding !== undefined) { + const padding = changes.padding, ref = parts.blockref ?? parts.sectionref; + if (padding !== null && (!Number.isFinite(padding) || padding < 0 || padding > 2000)) return null; + if (changes.frame === undefined && !( + !raw || ref === "as-image" || parts.hasFrameref || (parts.hasArearef || parts.hasGroupref || parts.hasClippedFrameref) && !!ref + )) return null; + let bare = raw.replace(PADDING_SUFFIX, ""); + try { bare = decodeURIComponent(bare); } catch { /* Literal percent signs remain valid names. */ } + if (parts.hasArearef && /,padding=/i.test(bare)) return null; + reference = reference.replace(PADDING_SUFFIX, ""); + if (padding !== null) reference = (reference || marker + caret + "as-image") + `,padding=${padding}`; + } + if (changes.anchored !== undefined) alias = alias.replace(/\|100%$/, "") + (changes.anchored ? "|100%" : ""); + return path + reference + alias; +} diff --git a/src/utils/embeddedFilenameParts.ts b/src/utils/embeddedFilenameParts.ts index 0fbd1aaa..0e3d525b 100644 --- a/src/utils/embeddedFilenameParts.ts +++ b/src/utils/embeddedFilenameParts.ts @@ -41,7 +41,7 @@ export function getEmbeddedFilenameParts(fname: string): FILENAMEPARTS { const hasSectionref = Boolean(parts[6]); const prefix = parts[4] ?? parts[7]; const rawReference = hasBlockref ? parts[5] : parts[8]; - const paddingMatch = IMAGE_REFERENCE_PREFIXES.has(prefix) + const paddingMatch = (IMAGE_REFERENCE_PREFIXES.has(prefix) || rawReference?.startsWith("as-image,padding=")) ? rawReference?.match(PADDING_PARAMETER_REGEX) : null; const parsedPadding = paddingMatch ? Number(paddingMatch[1]) : undefined; diff --git a/src/utils/excalidrawAutomateUtils.ts b/src/utils/excalidrawAutomateUtils.ts index 80a6c8fc..9fb4282c 100644 --- a/src/utils/excalidrawAutomateUtils.ts +++ b/src/utils/excalidrawAutomateUtils.ts @@ -762,7 +762,7 @@ export async function createSVG( } if ( - !(filenameParts.hasGroupref || filenameParts.hasClippedFrameref) && + !(filenameParts.hasGroupref || filenameParts.hasClippedFrameref) && filenameParts.blockref !== "as-image" && (filenameParts.hasBlockref || filenameParts.hasSectionref) ) { let el = filenameParts.hasSectionref diff --git a/src/utils/linkUtils.ts b/src/utils/linkUtils.ts index 51c287f2..0cdf4861 100644 --- a/src/utils/linkUtils.ts +++ b/src/utils/linkUtils.ts @@ -12,6 +12,13 @@ export type LinkParts = { page: number; }; +/** Restore a master-map reference with |100% after its fragment, exactly once. */ +export function getEmbeddedFileMasterLink(path: string, reference: string | null): string { + if (!reference) return path; + const anchored = path.endsWith("|100%"); + return path.replace(/\|100%$/, "") + "#" + reference + (anchored && !reference.endsWith("|100%") ? "|100%" : ""); +} + /** * Splits a drawing or embedded-file link into its path, reference, dimensions, * and optional PDF page. diff --git a/src/utils/thumbnailPadding.ts b/src/utils/thumbnailPadding.ts new file mode 100644 index 00000000..aad254e6 --- /dev/null +++ b/src/utils/thumbnailPadding.ts @@ -0,0 +1,15 @@ +import type { ExportSceneConfig } from "@zsviczian/excalidraw/types/excalidraw/scene/export"; +import type { AppState } from "@zsviczian/excalidraw/types/excalidraw/types"; +import type { ExportSettings } from "src/types/exportUtilTypes"; + +/** A larger export viewport adds outer space while the original frame remains the clip. */ +export function getThumbnailPaddingConfig(settings: ExportSettings, state: Partial, padding: number, scale = 1): ExportSceneConfig { + const frame = settings.exportingFrame; + return { + exportingFrame: frame, padding: 0, scale, fit: "none", origin: "canvas", + x: frame.x - padding, y: frame.y - padding, + width: frame.width + 2 * padding, height: frame.height + 2 * padding, + theme: settings.withTheme && state.theme === "dark" ? "dark" : "light", + canvasBackgroundColor: settings.withBackground ? state.viewBackgroundColor ?? "#ffffff" : false, + }; +} diff --git a/src/utils/utils.ts b/src/utils/utils.ts index 47b51882..412d6e53 100644 --- a/src/utils/utils.ts +++ b/src/utils/utils.ts @@ -1,5 +1,6 @@ import { App, Notice, request, requestUrl, TFile } from "obsidian"; import { readFrameProperty } from "./frameMetadata"; +import { getThumbnailPaddingConfig } from "./thumbnailPadding"; import { Random } from "roughjs/bin/math"; import { AppState, @@ -11,6 +12,7 @@ import { errorlog } from "./coreUtils"; import { exportToSvg, exportToBlob, + exportScene, IMAGE_TYPES, FRONTMATTER_KEYS, EXCALIDRAW_PLUGIN, @@ -247,7 +249,12 @@ export async function getSVG( el.isDeleted !== true, ); } - svg = await exportToSvg({ + if (exportSettings.exportingFrame && padding > 0) { + svg = await exportScene({ type: "svg", data: { elements: exportElements, appState: scene.appState, files }, config: { + ...getThumbnailPaddingConfig(exportSettings, scene.appState, padding), + ...(exportSettings.skipInliningFonts ? { skipInliningFonts: true } : {}), renderEmbeddables: true, + } }); + } else svg = await exportToSvg({ elements: exportElements, appState: { ...scene.appState, @@ -336,6 +343,10 @@ export async function getPNG( ); } + if (exportSettings.exportingFrame && padding > 0) { + return await exportScene({ type: "png", data: { elements, appState: scene.appState, files: filterFiles(files) }, + config: getThumbnailPaddingConfig(exportSettings, scene.appState, padding, scale) }); + } return await exportToBlob({ elements, appState: { diff --git a/src/view/ExcalidrawView.ts b/src/view/ExcalidrawView.ts index 5e291847..9a560c15 100644 --- a/src/view/ExcalidrawView.ts +++ b/src/view/ExcalidrawView.ts @@ -1,5 +1,6 @@ import { syncFrameAnchors, readFrameProperty, resolveThumbnailFrame } from "src/utils/frameMetadata"; import { FrameThumbnailController } from "./managers/FrameThumbnailController"; +import { DrawingImagePreviewController } from "./managers/DrawingImagePreviewController"; import { Editor, TextFileView, @@ -303,6 +304,7 @@ import { EphemeralIncrement, } from "@zsviczian/excalidraw/types/element/src"; import { + getTemplate, getTextElementsMatchingQuery, getFrameElementsMatchingQuery, getElementsWithLinkMatchingQuery, @@ -476,6 +478,7 @@ export default class ExcalidrawView private excalidrawExtensionRenderer: ViewExcalidrawExtensionRenderer; private markdownImageController: MarkdownImageController; public readonly frameThumbnail: FrameThumbnailController; + public readonly drawingImagePreview: DrawingImagePreviewController; private sceneFileManager: ViewSceneFileManager; private saveCoordinator: ViewSaveCoordinator; private sameFileEditGate: SameFileEditGate; @@ -731,6 +734,11 @@ export default class ExcalidrawView ); this.frameThumbnail = new FrameThumbnailController(this, MultiOptionConfirmationPrompt); this.register(() => this.frameThumbnail.reset()); + this.drawingImagePreview = new DrawingImagePreviewController(this, { + Prompt: MultiOptionConfirmationPrompt, EmbeddedFile, EmbeddedFilesLoader, + getTemplate, scaleLoadedImage, getExportPadding, + }); + this.register(() => this.drawingImagePreview.reset()); this.markdownImageController = new MarkdownImageController(this, { isMarkdownImageElement, getMarkdownImageCustomData, @@ -2390,6 +2398,7 @@ export default class ExcalidrawView async onUnloadFile(): Promise { this.frameThumbnail.reset(); + this.drawingImagePreview.reset(); //deliberately not calling super.onUnloadFile() to avoid autosave (saved in unload) this.invalidateSetViewDataLoad(); this.markdownImageController.cancelPendingConversion(); diff --git a/src/view/components/ExcalidrawRoot.ts b/src/view/components/ExcalidrawRoot.ts index 46fd0715..b4f1cb97 100644 --- a/src/view/components/ExcalidrawRoot.ts +++ b/src/view/components/ExcalidrawRoot.ts @@ -71,6 +71,12 @@ export function createExcalidrawRootElement( view.selectedElementActionsMenu = new SelectedElementActionsMenu( () => view.excalidrawContainer, ); + view.selectedElementActionsMenu.registerProvider({ + id: "drawing-image-preview", + getActions: element => element.type === "image" && !view.excalidrawAPI?.getAppState().viewModeEnabled && view.drawingImagePreview.getSource(element) + ? [{ id: "configure-drawing-preview", title: t("PREVIEW_CONFIGURE"), icon: "scan-eye", + action: () => { void view.drawingImagePreview.open(element.id); } }] : [], + }); view.selectedElementActionsMenu.registerProvider({ id: "markdown-image", getActions: (element) => @@ -101,6 +107,7 @@ export function createExcalidrawRootElement( } view.plugin.scriptEngine.runAutostartScripts(view); return () => { + view.drawingImagePreview.reset(); view.obsidianMenu.destroy(); view.obsidianMenu = null; view.embeddableMenu.destroy(); diff --git a/src/view/components/menu/SelectedElementActionsMenu.ts b/src/view/components/menu/SelectedElementActionsMenu.ts index 743b41f1..97c421ec 100644 --- a/src/view/components/menu/SelectedElementActionsMenu.ts +++ b/src/view/components/menu/SelectedElementActionsMenu.ts @@ -42,6 +42,7 @@ export class SelectedElementActionsMenu { private actionElementType: ExcalidrawElement["type"] | null = null; private actionElementFileId: string | null = null; private actionElementCustomData: ExcalidrawElement["customData"] | null = null; + private actionViewMode: boolean | null = null; private positionKey = ""; constructor(private readonly getHost: () => HTMLElement | null | undefined) {} @@ -108,11 +109,13 @@ export class SelectedElementActionsMenu { selectionChanged || element.type !== this.actionElementType || fileId !== this.actionElementFileId || + appState.viewModeEnabled !== this.actionViewMode || element.customData !== this.actionElementCustomData; if (actionTargetChanged) { this.actionElementType = element.type; this.actionElementFileId = fileId; this.actionElementCustomData = element.customData; + this.actionViewMode = appState.viewModeEnabled; const actions = this.providers.flatMap((provider) => provider.getActions(element), ); @@ -158,6 +161,7 @@ export class SelectedElementActionsMenu { // A title attribute adds a native browser tooltip alongside the // styled Excalidraw tooltip. Keep the accessible name only. "aria-label": action.title, + "data-excalidraw-element-action": action.id, }, }); const iconEl = button.createDiv({ @@ -237,6 +241,7 @@ export class SelectedElementActionsMenu { } private clearActionTarget(): void { + this.actionViewMode = null; this.actionElementType = null; this.actionElementFileId = null; this.actionElementCustomData = null; diff --git a/src/view/managers/DrawingImagePreviewController.ts b/src/view/managers/DrawingImagePreviewController.ts new file mode 100644 index 00000000..863ef890 --- /dev/null +++ b/src/view/managers/DrawingImagePreviewController.ts @@ -0,0 +1,145 @@ +import { Notice } from "obsidian"; +import type { ExcalidrawImageElement, FileId } from "@zsviczian/excalidraw/types/element/src/types"; +import type { MultiOptionConfirmationPrompt } from "src/shared/Dialogs/Prompt"; +import type ExcalidrawView from "../ExcalidrawView"; +import type { EmbeddedFile, EmbeddedFilesLoader } from "src/shared/EmbeddedFileLoader"; +import { DrawingImagePreviewPopover } from "src/shared/Dialogs/DrawingImagePreviewPopover"; +import { CaptureUpdateAction, fileid } from "src/constants/constants"; +import { getSceneFrames } from "src/utils/frameMetadata"; +import { rewriteDrawingPreviewLink, type DrawingPreviewChanges } from "src/utils/drawingPreviewLink"; +import type { FileData } from "src/types/embeddedFileLoaderTypes"; +import { t } from "src/lang/helpers"; +import { errorlog } from "src/utils/coreUtils"; + +/** Constructor injection keeps the existing view/export/loader import graph intact. */ +export interface DrawingImagePreviewDependencies { + Prompt: typeof MultiOptionConfirmationPrompt; + EmbeddedFile: typeof import("src/shared/EmbeddedFileLoader").EmbeddedFile; + EmbeddedFilesLoader: typeof import("src/shared/EmbeddedFileLoader").EmbeddedFilesLoader; + getTemplate: typeof import("src/utils/excalidrawAutomateUtils").getTemplate; + scaleLoadedImage: typeof import("src/utils/utils").scaleLoadedImage; + getExportPadding: typeof import("src/utils/utils").getExportPadding; +} + +/** View-owned drawing-image settings; copy-on-write references make settings undoable. */ +export class DrawingImagePreviewController { + private popover: DrawingImagePreviewPopover | null = null; + private prompt: MultiOptionConfirmationPrompt | null = null; + private readonly loaders = new Set(); + private generation = 0; + private busy = false; + + constructor(private readonly view: ExcalidrawView, private readonly dependencies: DrawingImagePreviewDependencies) {} + + /** Resolve actual drawing-backed image elements, including shared references. */ + getSource(element: ExcalidrawImageElement): EmbeddedFile | null { + const source = this.view.excalidrawData?.getFile(element.fileId); + return source?.file && !source.isMarkdownSection && this.view.plugin.isExcalidrawFile(source.file) ? source : null; + } + + /** Open one selected-image popover, rechecking the view after reading frame names. */ + async open(elementId: string): Promise { + if (this.busy) return; + this.reset(); + const view = this.view, api = view.excalidrawAPI, file = view.file, generation = this.generation; + if (!api || !file) return; + const current = () => generation === this.generation && view.file === file && view.excalidrawAPI === api && + view.plugin._loaded && !view.isClosingOrMigrating() && !api.getAppState().viewModeEnabled; + const element = view.getViewElements().find((el): el is ExcalidrawImageElement => el.type === "image" && el.id === elementId); + const source = element && this.getSource(element); + if (!source || !current()) return; + const originalLink = source.linkParts.original; + const ownsImage = () => current() && source.linkParts.original === originalLink && + view.excalidrawData.getFile(element.fileId) === source && + view.getViewElements().some(el => el.id === elementId && el.type === "image" && el.fileId === element.fileId); + try { + const loader = new this.dependencies.EmbeddedFilesLoader(view.plugin); this.loaders.add(loader); + let scene: Awaited>; + try { scene = await this.dependencies.getTemplate(view.plugin, source.file.path, false, loader, 0); } + finally { this.loaders.delete(loader); loader.terminate = true; } + if (!ownsImage()) return; + this.popover = new DrawingImagePreviewPopover(view, source, getSceneFrames(scene.elements), this.dependencies.getExportPadding(view.plugin, source.file), + ownsImage, + link => this.load(source, link), + changes => this.apply(elementId, source, changes, ownsImage), + () => { this.popover = null; }); + this.popover.load(); + } catch (error: unknown) { if (current()) { errorlog({ where: "DrawingImagePreviewController.open", error }); new Notice(t("ERROR_TRY_AGAIN")); } } + } + + private async load(source: EmbeddedFile, link: string) { + const descriptor = new this.dependencies.EmbeddedFile(this.view.plugin, this.view.file.path, link, source.colorMap ? JSON.stringify(source.colorMap) : undefined); + const loader = new this.dependencies.EmbeddedFilesLoader(this.view.plugin, this.view.excalidrawAPI.getAppState().theme === "dark"); + this.loaders.add(loader); + try { + const image = await loader.getObsidianImage(descriptor, 0); + if (!image || loader.terminate) throw Error("Drawing preview was retired"); + return { descriptor, image }; + } finally { this.loaders.delete(loader); loader.terminate = true; } + } + + private async apply(elementId: string, source: EmbeddedFile, changes: DrawingPreviewChanges, current: () => boolean): Promise { + if (this.busy || !current()) return false; + const view = this.view, api = view.excalidrawAPI; + const copies = view.getViewElements().filter((el): el is ExcalidrawImageElement => + el.type === "image" && this.getSource(el)?.file === source.file); + let targets = copies.filter(el => el.id === elementId); + this.busy = true; + try { + if (copies.length > 1) { + const message = t("PREVIEW_SHARED_HELP").replace("{drawing}", source.file.basename).replace("{count}", String(copies.length)); + const escaped = message.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">"); + const prompt = new this.dependencies.Prompt<"all" | "one" | null>(view.plugin, escaped, new Map([ + [t("PREVIEW_ALL").replace("{count}", String(copies.length)), "all"], [t("PREVIEW_ONLY"), "one"], [t("PROMPT_BUTTON_CANCEL"), null], + ]), t("PREVIEW_ONLY")); + prompt.titleEl.setText(t("PREVIEW_SHARED_TITLE")); + this.prompt = prompt; const choice = await prompt.waitForClose; this.prompt = null; + if (!choice || !current()) return false; + if (choice === "all") targets = copies; + } + const snapshots = targets.map(el => ({ element: el, source: this.getSource(el), version: el.version, nonce: el.versionNonce })); + const prepared = new Map> & { id: FileId }>(); + const replacements = new Map(), files: FileData[] = []; + for (const snapshot of snapshots) { + if (!current()) return false; + const link = rewriteDrawingPreviewLink(snapshot.source.linkParts.original, changes); + if (link === null) throw Error("Invalid drawing preview link"); + if (link === snapshot.source.linkParts.original) continue; + const group = link + "\n" + JSON.stringify(snapshot.source.colorMap); + let data = prepared.get(group); + if (!data) { + const loaded = await this.load(snapshot.source, link); + if (!current()) return false; + data = { ...loaded, id: fileid() as FileId }; prepared.set(group, data); + files.push({ ...loaded.image, id: data.id, shouldScale: loaded.descriptor.shouldScale() }); + } + const element = structuredClone(snapshot.element); + replacements.set(element.id, { ...element, fileId: data.id, version: element.version + 1 }); + } + if (!current()) return false; + const elements = view.getViewElements(); + if (!snapshots.every(snapshot => elements.some(el => el.id === snapshot.element.id && el.type === "image" && + el.fileId === snapshot.element.fileId && el.version === snapshot.version && el.versionNonce === snapshot.nonce && + view.excalidrawData.getFile(el.fileId) === snapshot.source))) throw Error("Drawing image changed during configuration"); + const resized = this.dependencies.scaleLoadedImage({ elements: elements.map(el => replacements.get(el.id) ?? el) }, files); + // No await after registration: scene IDs, intrinsic data and geometry form one undo step. + for (const data of prepared.values()) { + data.descriptor.setImage({ imgBase64: data.image.dataURL, mimeType: data.image.mimeType, size: data.image.size, + isDark: api.getAppState().theme === "dark", isSVGwithBitmap: data.image.hasSVGwithBitmap }); + view.excalidrawData.setFile(data.id, data.descriptor); + } + api.addFiles({ files, skipSvgNormalization: new Set(files.map(file => file.id)) }); + view.updateScene({ elements: resized.scene.elements, captureUpdate: CaptureUpdateAction.IMMEDIATELY }); + view.setDirty(); return true; + } catch (error: unknown) { if (current()) { errorlog({ where: "DrawingImagePreviewController.apply", error }); new Notice(t("ERROR_TRY_AGAIN")); } return false; } + finally { this.busy = false; } + } + + /** Retire pending renders, prompts and controls on file change, migration or unload. */ + reset(): void { + this.generation++; this.popover?.unload(); this.popover = null; + this.prompt?.close(); this.prompt = null; + for (const loader of this.loaders) loader.terminate = true; + this.loaders.clear(); + } +} diff --git a/styles.css b/styles.css index 37f236ab..500eb38d 100644 --- a/styles.css +++ b/styles.css @@ -2649,6 +2649,50 @@ button.excalidraw-font-picker { box-shadow: var(--shadow-s); font-size: var(--font-ui-small); } +.excalidraw-embed-padding-heading, +.excalidraw-embed-padding-help { + flex-basis: 100%; +} +.excalidraw-embed-padding-heading { + font-weight: var(--font-semibold); +} +.excalidraw-embed-padding-help { + color: var(--text-muted); + font-size: var(--font-ui-smaller); +} +.excalidraw-drawing-preview-popover { + position: fixed; + z-index: var(--layer-popover); + width: 340px; + max-width: calc(100vw - 16px); + max-height: calc(100vh - 16px); + overflow: auto; + padding: 12px; + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-m); + background: var(--background-primary); + box-shadow: var(--shadow-s); +} +.excalidraw-drawing-preview-popover > img { + display: block; + width: 100%; + height: 120px; + margin: 8px auto; + object-fit: contain; +} +.excalidraw-drawing-preview-popover .setting-item { + display: block; + padding: 8px 0; +} +.excalidraw-drawing-preview-popover .setting-item-control { + justify-content: flex-start; + margin-top: 6px; +} +.excalidraw-drawing-preview-buttons { + display: flex; + justify-content: flex-end; + gap: 8px; +} .excalidraw-embed-padding-track { display: flex; align-items: center; diff --git a/tests/features.json b/tests/features.json index 3f81b106..9c087206 100644 --- a/tests/features.json +++ b/tests/features.json @@ -106,6 +106,22 @@ { "path": "src/core/editor/embedFrame.ts", "symbol": "export function rewriteEmbedFrame" + }, + { + "path": "src/view/managers/DrawingImagePreviewController.ts", + "symbol": "export class DrawingImagePreviewController" + }, + { + "path": "src/shared/Dialogs/DrawingImagePreviewPopover.ts", + "symbol": "export class DrawingImagePreviewPopover" + }, + { + "path": "src/utils/drawingPreviewLink.ts", + "symbol": "export function rewriteDrawingPreviewLink" + }, + { + "path": "src/utils/thumbnailPadding.ts", + "symbol": "export function getThumbnailPaddingConfig" } ], "tests": [ @@ -212,19 +228,54 @@ "native:frames:main:navigation", "native:frames:main:previews", "native:frames:main:controls", + "native:frames:main:outer-padding", + "native:frames:main:scene-images", "native:frames:popout:metadata", "native:frames:popout:navigation", "native:frames:popout:previews", "native:frames:popout:controls", + "native:frames:popout:outer-padding", + "native:frames:popout:scene-images", "native:frames:settings-reload", "native:frames:phone:metadata", "native:frames:phone:navigation", "native:frames:phone:previews", "native:frames:phone:controls", + "native:frames:phone:outer-padding", + "native:frames:phone:scene-images", "native:frames:tablet:metadata", "native:frames:tablet:navigation", "native:frames:tablet:previews", - "native:frames:tablet:controls" + "native:frames:tablet:controls", + "native:frames:tablet:outer-padding", + "native:frames:tablet:scene-images" + ] + }, + { + "layer": "source", + "path": "scripts/testing/drawingPreviewLink.source.test.mjs", + "cases": [ + "node:scripts/testing/drawingPreviewLink.source.test.mjs::thumbnail and whole-scene padding remain independent of frame selection and anchoring", + "node:scripts/testing/drawingPreviewLink.source.test.mjs::preview changes preserve raw encoding, padding, other aliases and the shared master-map link", + "node:scripts/testing/drawingPreviewLink.source.test.mjs::outer thumbnail padding enlarges the viewport while retaining the original frame clip" + ] + }, + { + "layer": "source", + "path": "scripts/testing/drawingImagePreview.source.test.mjs", + "cases": [ + "node:scripts/testing/drawingImagePreview.source.test.mjs::only this image gets a new persisted link and uses real external-update geometry; undo retains the original reference", + "node:scripts/testing/drawingImagePreview.source.test.mjs::apply to all copies changes only edited fields, preserving distinct views, anchoring and each image center", + "node:scripts/testing/drawingImagePreview.source.test.mjs::100% anchoring follows rendered intrinsic dimensions and remains in the link", + "node:scripts/testing/drawingImagePreview.source.test.mjs::cancel, stale scene changes and retired views do not register partial links or write a scene" + ] + }, + { + "layer": "source", + "path": "scripts/testing/drawingPreviewLoader.source.test.mjs", + "cases": [ + "node:scripts/testing/drawingPreviewLoader.source.test.mjs::embedded drawing loader recognizes padded default and whole-scene links while retaining 100%", + "node:scripts/testing/drawingPreviewLoader.source.test.mjs::an ordinary Markdown block named as-image keeps its section-transclusion behavior" ] } ], @@ -519,6 +570,22 @@ { "path": "src/core/editor/embedFrame.ts", "symbol": "export function rewriteEmbedFrame" + }, + { + "path": "src/view/managers/DrawingImagePreviewController.ts", + "symbol": "export class DrawingImagePreviewController" + }, + { + "path": "src/shared/Dialogs/DrawingImagePreviewPopover.ts", + "symbol": "export class DrawingImagePreviewPopover" + }, + { + "path": "src/utils/drawingPreviewLink.ts", + "symbol": "export function rewriteDrawingPreviewLink" + }, + { + "path": "src/utils/thumbnailPadding.ts", + "symbol": "export function getThumbnailPaddingConfig" } ], "tests": [ @@ -888,19 +955,54 @@ "native:frames:main:navigation", "native:frames:main:previews", "native:frames:main:controls", + "native:frames:main:outer-padding", + "native:frames:main:scene-images", "native:frames:popout:metadata", "native:frames:popout:navigation", "native:frames:popout:previews", "native:frames:popout:controls", + "native:frames:popout:outer-padding", + "native:frames:popout:scene-images", "native:frames:settings-reload", "native:frames:phone:metadata", "native:frames:phone:navigation", "native:frames:phone:previews", "native:frames:phone:controls", + "native:frames:phone:outer-padding", + "native:frames:phone:scene-images", "native:frames:tablet:metadata", "native:frames:tablet:navigation", "native:frames:tablet:previews", - "native:frames:tablet:controls" + "native:frames:tablet:controls", + "native:frames:tablet:outer-padding", + "native:frames:tablet:scene-images" + ] + }, + { + "layer": "source", + "path": "scripts/testing/drawingPreviewLink.source.test.mjs", + "cases": [ + "node:scripts/testing/drawingPreviewLink.source.test.mjs::thumbnail and whole-scene padding remain independent of frame selection and anchoring", + "node:scripts/testing/drawingPreviewLink.source.test.mjs::preview changes preserve raw encoding, padding, other aliases and the shared master-map link", + "node:scripts/testing/drawingPreviewLink.source.test.mjs::outer thumbnail padding enlarges the viewport while retaining the original frame clip" + ] + }, + { + "layer": "source", + "path": "scripts/testing/drawingImagePreview.source.test.mjs", + "cases": [ + "node:scripts/testing/drawingImagePreview.source.test.mjs::only this image gets a new persisted link and uses real external-update geometry; undo retains the original reference", + "node:scripts/testing/drawingImagePreview.source.test.mjs::apply to all copies changes only edited fields, preserving distinct views, anchoring and each image center", + "node:scripts/testing/drawingImagePreview.source.test.mjs::100% anchoring follows rendered intrinsic dimensions and remains in the link", + "node:scripts/testing/drawingImagePreview.source.test.mjs::cancel, stale scene changes and retired views do not register partial links or write a scene" + ] + }, + { + "layer": "source", + "path": "scripts/testing/drawingPreviewLoader.source.test.mjs", + "cases": [ + "node:scripts/testing/drawingPreviewLoader.source.test.mjs::embedded drawing loader recognizes padded default and whole-scene links while retaining 100%", + "node:scripts/testing/drawingPreviewLoader.source.test.mjs::an ordinary Markdown block named as-image keeps its section-transclusion behavior" ] } ], diff --git a/tests/inventory.json b/tests/inventory.json index 80008ee6..6a79d2c8 100644 --- a/tests/inventory.json +++ b/tests/inventory.json @@ -2155,132 +2155,132 @@ { "name": "excalidraw-anchors", "path": "src/constants/constants.ts", - "line": 314 + "line": 316 }, { "name": "excalidraw-thumbnail", "path": "src/constants/constants.ts", - "line": 315 + "line": 317 }, { "name": "excalidraw-plugin", "path": "src/constants/constants.ts", - "line": 316 + "line": 318 }, { "name": "excalidraw-export-transparent", "path": "src/constants/constants.ts", - "line": 317 + "line": 319 }, { "name": "excalidraw-mask", "path": "src/constants/constants.ts", - "line": 322 + "line": 324 }, { "name": "excalidraw-export-dark", "path": "src/constants/constants.ts", - "line": 323 + "line": 325 }, { "name": "excalidraw-export-svgpadding", "path": "src/constants/constants.ts", - "line": 328 + "line": 330 }, { "name": "excalidraw-export-padding", "path": "src/constants/constants.ts", - "line": 333 + "line": 335 }, { "name": "excalidraw-export-pngscale", "path": "src/constants/constants.ts", - "line": 338 + "line": 340 }, { "name": "excalidraw-export-embed-scene", "path": "src/constants/constants.ts", - "line": 343 + "line": 345 }, { "name": "excalidraw-export-internal-links", "path": "src/constants/constants.ts", - "line": 348 + "line": 350 }, { "name": "excalidraw-link-prefix", "path": "src/constants/constants.ts", - "line": 353 + "line": 355 }, { "name": "excalidraw-url-prefix", "path": "src/constants/constants.ts", - "line": 358 + "line": 360 }, { "name": "excalidraw-link-brackets", "path": "src/constants/constants.ts", - "line": 363 + "line": 365 }, { "name": "excalidraw-onload-script", "path": "src/constants/constants.ts", - "line": 368 + "line": 370 }, { "name": "excalidraw-linkbutton-opacity", "path": "src/constants/constants.ts", - "line": 373 + "line": 375 }, { "name": "excalidraw-default-mode", "path": "src/constants/constants.ts", - "line": 378 + "line": 380 }, { "name": "excalidraw-font", "path": "src/constants/constants.ts", - "line": 383 + "line": 385 }, { "name": "excalidraw-font-color", "path": "src/constants/constants.ts", - "line": 384 + "line": 386 }, { "name": "excalidraw-border-color", "path": "src/constants/constants.ts", - "line": 389 + "line": 391 }, { "name": "excalidraw-css", "path": "src/constants/constants.ts", - "line": 394 + "line": 396 }, { "name": "excalidraw-autoexport", "path": "src/constants/constants.ts", - "line": 395 + "line": 397 }, { "name": "excalidraw-iframe-theme", "path": "src/constants/constants.ts", - "line": 400 + "line": 402 }, { "name": "excalidraw-embeddable-theme", "path": "src/constants/constants.ts", - "line": 405 + "line": 407 }, { "name": "excalidraw-open-md", "path": "src/constants/constants.ts", - "line": 410 + "line": 412 }, { "name": "excalidraw-embed-md", "path": "src/constants/constants.ts", - "line": 415 + "line": 417 } ], "cliCommands": [ @@ -2464,10 +2464,22 @@ "path": "scripts/testing/drawingCreationIntegration.test.mjs", "mode": "isolated-or-extracted" }, + { + "path": "scripts/testing/drawingImagePreview.source.test.mjs", + "mode": "isolated-or-extracted" + }, { "path": "scripts/testing/drawingLoadError.test.mjs", "mode": "isolated-or-extracted" }, + { + "path": "scripts/testing/drawingPreviewLink.source.test.mjs", + "mode": "direct-module-or-tooling" + }, + { + "path": "scripts/testing/drawingPreviewLoader.source.test.mjs", + "mode": "isolated-or-extracted" + }, { "path": "scripts/testing/dropActions.test.mjs", "mode": "isolated-or-extracted"