diff --git a/docs/DRAWING_EMBED_CONTROLS.md b/docs/DRAWING_EMBED_CONTROLS.md index 1ea9c48e..63bc1941 100644 --- a/docs/DRAWING_EMBED_CONTROLS.md +++ b/docs/DRAWING_EMBED_CONTROLS.md @@ -5,8 +5,9 @@ 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=` reference such as `![[Drawing#^area=abcdefgh|300]]`, the toolbar -also offers **Adjust area padding**, using the square-dot icon. A compact +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 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 @@ -19,11 +20,40 @@ 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 an `area=` -reference. They are absent for whole drawings, text/group/frame references, +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, Reading view, read-only editors, nested Markdown transclusions, and Canvas. Reading view retains preview and open-drawing actions. +## Frames and drawing thumbnails + +Select a named frame or marker frame and use **Set as drawing thumbnail** in its +context menu. The document property `excalidraw-thumbnail` stores its exact name +and can also be edited manually. Names must be unique. Implicit previews in +notes, hover previews and other drawings crop to the frame rectangle, without +its outline or title. A missing, invalid or ambiguous name falls back to the +whole scene. PNG/SVG autoexports continue to export the full scene. + +On save, `excalidraw-anchors` lists unique named frames and marker frames in +scene order. Unnamed frames are omitted; a frame deliberately named `Frame` +is included. New properties appear at the top of frontmatter and existing +properties retain their positions. Unrelated properties are preserved. + +The first rename of a thumbnail frame asks whether to always update its document +property, ask on each rename or leave it unchanged. Change this preference later +in the saving settings. Deleting the frame leaves a stale name and the preview +falls back to the whole scene. + +For editable Live Preview embeds whose drawing has frames, the **scan-eye** +button opens a frame picker. **Default thumbnail** removes the explicit override; +**Whole scene** writes `#^frame=` and ignores the thumbnail property. Other items +choose a frame by ID, including unnamed frames and names ending in `,padding=N`. +Existing explicit `frame=` and `clippedframe=` rendering remains unchanged. + +Use **Excalidraw: Navigate to frame** to fuzzy-search regular and marker frames +in the current drawing. It uses the existing viewport navigation and selection +behavior, preserving editing mode and Search text. + ## Focused validation Source checks cover detached Reading sections, relative paths, source ownership, @@ -43,6 +73,25 @@ The prepared test vault must be open, trusted, and CLI-enabled. See host prerequisite is not a native test pass. Physical touch devices and other desktop operating systems remain separate manual environments. +For frame metadata, thumbnails, navigation and source controls, run +`node scripts/testing/host/verify.mjs --frame-semantics`. Add +`--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. + +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. + ## Investigation checkpoint: 2026-11-10 Baseline: plugin `master@2ef81a5d`; implementation branch diff --git a/docs/agent-handoffs/issue-3042.md b/docs/agent-handoffs/issue-3042.md deleted file mode 100644 index 5c812ae8..00000000 --- a/docs/agent-handoffs/issue-3042.md +++ /dev/null @@ -1,17 +0,0 @@ -# Temporary handoff: issue #3042 — semantic frame anchors - -**Plan-only placeholder. Not a feature implementation.** - -- Issue and agreed specification: https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/3042 -- Baseline: `master@83c35ffffea56db7c833c8fe5b3831968083c5a1` -- Working branch: `2026-11-11-issue-3042-frame-anchors-thumbnails` -- Owning repository: `zsviczian/obsidian-excalidraw-plugin` **only**. Do not change the Excalidraw fork, Extras, or K-Plex. -- Implement both regular frames and marker frames; null/blank frame names are not anchors. -- Follow current persisted frontmatter placement/order rules. The YAML thumbnail is a frame **name**; no customData. -- Rename preference: always update, ask each time, or ignore; leverage existing scene-change detection. -- Markdown embeds: implicit thumbnail, explicit empty `#^frame=` for whole scene, frame dropdown with `scan-box` only when frames exist; padding slider for area/frame/clippedframe. -- Navigate to frame with fuzzy modal using existing `setEphemeralState` / `zoomToElementId` behavior. -- Keep current full-scene autoexports; no generated thumbnail artifacts or Bases-specific UI. -- Read the associated **draft PR description** for the detailed plan and tests. - -**Implementation agent: remove this temporary file before the PR is marked ready for review.** diff --git a/scripts/testing/embedControls.source.test.mjs b/scripts/testing/embedControls.source.test.mjs index b9ce331d..7f1e83b4 100644 --- a/scripts/testing/embedControls.source.test.mjs +++ b/scripts/testing/embedControls.source.test.mjs @@ -3,10 +3,16 @@ import test from "node:test"; import { sourceHarness } from "./sourceHarness.mjs"; import { embedTestDOM } from "./embedTestDOM.mjs"; -async function fixture(text = "![[Map|Alias|180x130|left]]", padding = false, paddingSource = true) { - const dom = embedTestDOM(), notices = [], modals = [], writes = []; +async function fixture(text = "![[Map|Alias|180x130|left]]", padding = false, paddingSource = true, frames = []) { + const dom = embedTestDOM(), notices = [], modals = [], writes = [], menus = []; + class Menu { + items = []; constructor() { menus.push(this); } + setUseNativeMenu() { return this; } addSeparator() { return this; } + addItem(callback) { const item = { setTitle(value) { this.title = value; return this; }, setChecked(value) { this.checked = value; return this; }, onClick(callback) { this.click = callback; return this; } }; callback(item); this.items.push(item); return this; } + onHide(callback) { this.onHidden = callback; } showAtPosition(position, doc) { this.position = position; this.doc = doc; } hide() { this.hidden = true; this.onHidden?.(); } + } let current = true, sourceCurrent = true, selects = 0, opens = 0; - const graph = sourceHarness({ obsidian: { Component: dom.Component, MarkdownRenderChild: dom.MarkdownRenderChild, SliderComponent: class {}, Notice: class { constructor(text) { notices.push(text); } }, setIcon(element, icon) { element.icon = icon; }, setTooltip() {} }, + const graph = sourceHarness({ obsidian: { Menu, Component: dom.Component, MarkdownRenderChild: dom.MarkdownRenderChild, SliderComponent: class {}, Notice: class { constructor(text) { notices.push(text); } }, setIcon(element, icon) { element.icon = icon; }, setTooltip() {} }, "src/lang/helpers": { t: key => key }, "src/utils/styleUtils": { setStyle: (el, values) => Object.assign(el.style, values), removeStyle: (el, keys) => { for (const key of keys) delete el.style[key]; } }, "src/shared/Dialogs/DrawingEmbedPreviewModal": { DrawingEmbedPreviewModal: class { constructor(_app, _preview, _opener, close) { this.onClosed = close; modals.push(this); } open() { this.active = true; } close() { this.active = false; this.onClosed(); } } }, @@ -16,15 +22,34 @@ async function fixture(text = "![[Map|Alias|180x130|left]]", padding = false, pa const image = frame.createEl("img", { cls: "excalidraw-embedded-img" }); image.bounds = { left: 0, top: 0, right: 180, bottom: 130, width: 180, height: 130 }; const source = { text, isCurrent: () => sourceCurrent, replace: value => { if (!sourceCurrent) return false; writes.push(value); return true; }, select: () => { selects++; return sourceCurrent; } }; if (paddingSource) source.replacePadding = () => true; - const controls = new DrawingEmbedControls(frame, { app: {}, target: "Map", isCurrent: () => current, openDrawing: () => opens++, getOpenTooltip: () => "configured open shortcuts", ...(padding ? { padding: { value: 10 } } : {}) }, source); controls.load(); + if (paddingSource) source.replaceFrame = reference => { if (!sourceCurrent) return false; writes.push(["frame", reference]); return true; }; + const controls = new DrawingEmbedControls(frame, { app: {}, target: "Map", frames, isCurrent: () => current, openDrawing: () => opens++, getOpenTooltip: () => "configured open shortcuts", ...(padding ? { padding: { value: 10 } } : {}) }, source); controls.load(); const handle = frame.querySelector(".excalidraw-embed-resize-handle"), toolbar = frame.querySelector(".excalidraw-embed-toolbar"); handle.bounds = { left: 156, top: 106, right: 178, bottom: 128, width: 22, height: 22 }; const buttons = toolbar.children.filter(element => element.tagName === "BUTTON"); - return { ...dom, frame, image, handle, toolbar, buttons, controls, writes, source, notices, modals, current: value => current = value, sourceCurrent: value => sourceCurrent = value, selects: () => selects, opens: () => opens, + return { ...dom, frame, image, handle, toolbar, buttons, controls, writes, source, notices, modals, menus, current: value => current = value, sourceCurrent: value => sourceCurrent = value, selects: () => selects, opens: () => opens, close: () => { controls.unload(); graph.close(); assert.equal(dom.listenerCount(), 0); assert.ok(dom.observers.every(observer => !observer.connected)); } }; } function start(f) { f.handle.fire("pointerdown", { button: 0, pointerId: 1, clientX: 180, clientY: 130 }); } +test("frame picker requires editable ownership, offers unnamed frames by ID, and owns its menu document", async () => { + const frames = [{ id: "frame-a", reference: "frame-a", name: "中心,padding=50" }, { id: "frame-b", reference: "frame-b", name: null, marker: true }]; + for (const writable of [true, false]) { + const f = await fixture(undefined, false, writable, frames); + try { + const trigger = f.buttons.find(button => button.getAttribute("data-excalidraw-embed-action") === "frame"); + assert.equal(!!trigger, writable); + if (!trigger) continue; + assert.equal(trigger.icon, "scan-eye"); trigger.fire("click"); + const menu = f.menus[0]; assert.equal(menu.doc, f.document); + assert.deepEqual(menu.items.map(item => item.title), ["FRAME_DEFAULT", "FRAME_WHOLE", "中心,padding=50", "FRAME_UNNAMED_MARKER (frame-b)"]); + assert.deepEqual(f.writes, []); menu.items[3].click(); assert.deepEqual(f.writes, [["frame", "frame-b"]]); + f.sourceCurrent(false); menu.items[1].click(); assert.equal(f.writes.length, 1); + } finally { f.close(); } + if (writable) assert.equal(f.menus[0].hidden, true); + } +}); + test("padding toolbar action requires both an area-rendering capability and a writable source", async () => { for (const area of [false, true]) for (const writable of [false, true]) { const f = await fixture(undefined, area, writable); diff --git a/scripts/testing/embedFrame.source.test.mjs b/scripts/testing/embedFrame.source.test.mjs new file mode 100644 index 00000000..19cfd9e7 --- /dev/null +++ b/scripts/testing/embedFrame.source.test.mjs @@ -0,0 +1,32 @@ +import assert from "node:assert/strict"; +import test, { after } from "node:test"; +import { EditorState, Transaction } from "@codemirror/state"; +import { history, undo } from "@codemirror/commands"; +import { sourceHarness } from "./sourceHarness.mjs"; +const graph = sourceHarness(); +const { rewriteEmbedFrame } = await graph.importModule("src/core/editor/embedFrame.ts"); +const { DrawingEmbedSource } = await graph.importModule("src/core/editor/embedSource.ts"); +after(() => graph.close()); + +test("frame selection preserves raw paths, clipping, dimensions, titles, padding and escaped table aliases", () => { + for (const [text, expected] of [ + ["![[../Drawing|Caption|200x100|left]]", "![[../Drawing#^frame=frame-id|Caption|200x100|left]]"], + ["![[Map#^clippedframe=Part, One,padding=50\\|200\\|right]]", "![[Map#^clippedframe=frame-id,padding=50\\|200\\|right]]"], + ['![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]]'); + for (const ref of ['../Other', 'frame#evil', 'Name,padding=20']) assert.equal(rewriteEmbedFrame('![[Map]]', ref), null); +}); + +test("frame selection edits only the owned occurrence and is one undo step", () => { + const token = '![[Map|200]]', doc = token + '\n' + token; + let state = EditorState.create({ doc, extensions: [history()] }); + const view = { get state() { return state; }, dispatch(spec) { state = (spec instanceof Transaction ? spec : state.update(spec)).state; } }; + const source = new DrawingEmbedSource(view, token.length + 1, doc.length, token, () => true); + assert.equal(source.replaceFrame('frame-id'), true); + assert.equal(state.doc.toString(), token + '\n![[Map#^frame=frame-id|200]]'); + assert.equal(undo(view), true); assert.equal(state.doc.toString(), doc); + assert.equal(source.replaceFrame('other'), false); +}); diff --git a/scripts/testing/embedLocales.test.mjs b/scripts/testing/embedLocales.test.mjs index 78f732ab..d0e564e8 100644 --- a/scripts/testing/embedLocales.test.mjs +++ b/scripts/testing/embedLocales.test.mjs @@ -26,3 +26,24 @@ test("embed controls have complete maintained translations without lossy shell e } } }); + +test("frame controls have complete 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("// Drawing embed controls (#3036)") && node.name.text?.startsWith("FRAME_")) { + assert.ok(ts.isStringLiteral(node.initializer)); strings.set(node.name.text, node.initializer.text); + } + ts.forEachChild(node, visit); + }; + visit(tree); assert.equal(strings.size, 17, 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); + } + } +}); diff --git a/scripts/testing/embedPadding.source.test.mjs b/scripts/testing/embedPadding.source.test.mjs index 019f5e4f..c30a45a0 100644 --- a/scripts/testing/embedPadding.source.test.mjs +++ b/scripts/testing/embedPadding.source.test.mjs @@ -21,9 +21,11 @@ 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=Frame", "Map#^clippedframe=Frame", "Map#^area=", "Map#^area=abc,padding=-1", "Map#^area=abc,padding=1,padding=2"]) + 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"]) 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"); + assert.equal(withAreaPadding("Map#^clippedframe=Part,padding=20, Two", 50), "Map#^clippedframe=Part,padding=20, Two,padding=50"); }); test("padding changes only the owned repeated occurrence in one undo step and preserves target guards", () => { diff --git a/scripts/testing/frameMetadata.source.test.mjs b/scripts/testing/frameMetadata.source.test.mjs new file mode 100644 index 00000000..40a48850 --- /dev/null +++ b/scripts/testing/frameMetadata.source.test.mjs @@ -0,0 +1,39 @@ +import assert from "node:assert/strict"; +import test, { after } from "node:test"; +import { load } from "js-yaml"; +import { sourceHarness } from "./sourceHarness.mjs"; +const graph = sourceHarness({ obsidian: { parseYaml: load } }); +const { getFrameAnchors, resolveThumbnailFrame, syncFrameAnchors, writeFrameProperty, readFrameProperty } = await graph.importModule("src/utils/frameMetadata.ts"); +after(() => graph.close()); +const frame = (id, name, frameRole) => ({ id, name, type: "frame", x: 10, y: 20, width: 200, height: 100, frameRole }); + +test("frame anchors include actual regular and marker names, preserving order and punctuation", () => { + const scene = [frame("a", null), frame("b", " "), frame("c", "Frame"), frame("d", "中心, padding=20", "marker"), frame("e", "Frame"), { ...frame("f", "Deleted"), isDeleted: true }]; + assert.deepEqual(getFrameAnchors(scene), ["Frame", "中心, padding=20"]); + const source = '---\ncustom: "keep"\nnested:\n value: yes\n---\nBody\n'; + const result = syncFrameAnchors(source, scene); + assert.deepEqual(readFrameProperty(result, "excalidraw-anchors"), ["Frame", "中心, padding=20"]); + assert.ok(result.includes('custom: "keep"\nnested:\n value: yes\n')); assert.ok(result.endsWith("---\nBody\n")); + assert.equal(syncFrameAnchors(result, scene), result); + assert.ok(syncFrameAnchors(source, scene, false).indexOf("excalidraw-anchors:") > source.indexOf("nested:")); +}); + +test("frame metadata replaces only its own multiline property and leaves invalid YAML untouched", () => { + const source = '---\nfirst: 1\nexcalidraw-anchors:\n - Old\n# Keep this comment\nlast: 2\n---\nText\n'; + const result = syncFrameAnchors(source, [frame("a", "A: \"quote\"")]); + assert.equal(result, '---\nfirst: 1\nexcalidraw-anchors:\n - "A: \\"quote\\""\n# Keep this comment\nlast: 2\n---\nText\n'.replaceAll('\\\\"','\\"')); + assert.equal(syncFrameAnchors('---\nbroken: [\n---\n', [frame("a", "A")]), '---\nbroken: [\n---\n'); + assert.equal(syncFrameAnchors('---\ncustom: 1\n---\n', []), '---\ncustom: 1\n---\n'); + assert.equal(writeFrameProperty(source, "other", "no"), source); + assert.equal(syncFrameAnchors('---\n---\nBody', [frame("a", "A")]), '---\nexcalidraw-anchors:\n - "A"\n---\nBody'); + assert.equal(syncFrameAnchors('---\r\nkeep: yes\r\n---\r\nBody', [frame("a", "A")]), '---\r\nexcalidraw-anchors:\r\n - "A"\r\nkeep: yes\r\n---\r\nBody'); +}); + +test("thumbnail YAML uses exact unique names and supports manual edits, commas and suffixes", () => { + const scene = [frame("a", "Main,padding=10"), frame("b", "Dupe"), frame("c", "Dupe", "marker")]; + assert.equal(resolveThumbnailFrame(scene, "Main,padding=10")?.id, "a"); + for (const name of [null, "", "Dupe", "a", "missing", []]) assert.equal(resolveThumbnailFrame(scene, name), null); + const doc = writeFrameProperty('---\nfoo: yes\n---\nBody', "excalidraw-thumbnail", "Main,padding=10"); + assert.equal(readFrameProperty(doc), "Main,padding=10"); + assert.equal(readFrameProperty(writeFrameProperty(doc, "excalidraw-thumbnail", undefined)), undefined); +}); diff --git a/scripts/testing/frameNavigator.source.test.mjs b/scripts/testing/frameNavigator.source.test.mjs new file mode 100644 index 00000000..7dd9f073 --- /dev/null +++ b/scripts/testing/frameNavigator.source.test.mjs @@ -0,0 +1,21 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { load } from "js-yaml"; +import { sourceHarness } from "./sourceHarness.mjs"; + +test("frame navigation preserves search and mode, distinguishes unnamed frames and rejects retired owners", async () => { + const calls = [], graph = sourceHarness({ obsidian: { parseYaml: load, FuzzySuggestModal: class { setPlaceholder() {} onClose() {} } }, "src/lang/helpers": { t: key => key } }); + try { + const { FrameNavigator } = await graph.importModule("src/shared/Dialogs/FrameNavigator.ts"); + const elements = [{ type: "frame", id: "regular", name: null }, { type: "frame", frameRole: "marker", id: "marker", name: null }, { type: "rectangle", id: "other" }]; + const view = { app: {}, file: {}, excalidrawAPI: {}, getViewElements: () => elements, isClosingOrMigrating: () => false, zoomToElementId: (...args) => calls.push(args), search: "existing search", mode: "edit" }; + const picker = new FrameNavigator(view, () => calls.push("closed")); + assert.deepEqual(picker.getItems(), elements.slice(0, 2)); + assert.equal(picker.getItemText(elements[0]), "FRAME_UNNAMED (regular)"); + assert.equal(picker.getItemText(elements[1]), "FRAME_UNNAMED_MARKER (marker)"); + picker.onChooseItem(elements[1]); assert.deepEqual(calls, [["marker", false]]); + assert.equal(view.search, "existing search"); assert.equal(view.mode, "edit"); + view.excalidrawAPI = {}; picker.onChooseItem(elements[0]); assert.equal(calls.length, 1); + picker.onClose(); assert.equal(calls.at(-1), "closed"); + } finally { graph.close(); } +}); diff --git a/scripts/testing/framePreview.source.test.mjs b/scripts/testing/framePreview.source.test.mjs new file mode 100644 index 00000000..f3706ef5 --- /dev/null +++ b/scripts/testing/framePreview.source.test.mjs @@ -0,0 +1,68 @@ +/** Execute the full production template/export module with only host/export boundaries substituted. */ +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 { load } from "js-yaml"; + +function fixture(property = '"Main,padding=20"') { + let source = `---\nexcalidraw-plugin: parsed\nexcalidraw-thumbnail: ${property}\n---\n## Drawing\n`; + const frame = { id: "frame-id", type: "frame", name: "Main,padding=20", x: 10, y: 20, width: 120, height: 80, isDeleted: false }; + let elements = [frame, { id: "in", type: "rectangle", x: 20, y: 30, width: 5, height: 5, frameId: "frame-id" }, { id: "out", type: "rectangle", x: 1000, y: 1000, width: 5, height: 5 }]; + class TFile { path = "Drawing.md"; extension = "md"; } + const file = new TFile(), requests = []; + const context = vm.createContext({ console, PLUGIN_VERSION: "test" }); + const compile = (path, mocks) => { + 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.runInContext(`(function(require,exports){${code}\n})`, context)(name => mocks[name] ?? {}, exports); return exports; + }; + const parts = compile('src/utils/embeddedFilenameParts.ts', {}); + const metadata = compile('src/utils/frameMetadata.ts', { obsidian: { parseYaml: load } }); + const api = compile('src/utils/excalidrawAutomateUtils.ts', { + './frameMetadata': metadata, + obsidian: { TFile, normalizePath: value => value }, + 'src/shared/TextMode': { getTextMode: () => 'parsed' }, + 'src/shared/ExcalidrawData': { ExcalidrawData: class { + scene = { elements: structuredClone(elements), appState: { theme: 'light' }, files: {} }; + async loadData() {} destroy() {} + }, getExcalidrawMarkdownHeaderSection: value => value }, + 'src/utils/utils': { ...parts, getPNG: async (_scene, options) => { requests.push(options); return options; }, getSVG: async (_scene, options) => { requests.push(options); return { viewBox: { baseVal: {} }, setAttribute() {} }; } }, + './excalidrawViewUtils': { getFrameBasedOnFrameNameOrId: name => elements.find(frame => frame.type === 'frame' && (frame.id === name || frame.name === name)) }, + './excalidrawElementUtils': { cloneElement: element => ({ ...element }) }, + 'src/constants/safeUrls': { URLs: {} }, + }); + const plugin = { app: { vault: { read: async () => source }, metadataCache: { getFirstLinkpathDest: () => file } }, settings: { exportPaddingSVG: 10 }, ea: { getElementsInFrame: frame => frame ? elements.filter(element => element.id === frame.id || element.frameId === frame.id) : [] } }; + const loader = { loadSceneFiles: async () => {} }, options = { withBackground: false, withTheme: false, isMask: false, drawingThumbnail: true }; + return { api, plugin, loader, options, requests, frame, source: value => { source = value; }, elements: value => { elements = value; } }; +} + +test("default thumbnails resolve exact YAML names while explicit whole/frame and ordinary exports retain precedence", async () => { + const f = fixture(); + const get = (target, preview) => f.api.getTemplate(f.plugin, target, false, f.loader, 0, false, undefined, preview); + assert.equal((await get('Drawing.md', true)).thumbnailFrame.id, 'frame-id'); + assert.equal((await get('Drawing.md#^as-image', true)).thumbnailFrame.id, 'frame-id'); + assert.equal((await get('Drawing.md', false)).thumbnailFrame, undefined); + const whole = await get('Drawing.md#^frame=', true); + assert.equal(whole.thumbnailFrame, undefined); assert.equal(whole.elements.length, 3); + const explicit = await get('Drawing.md#^frame=frame-id', true); + assert.equal(explicit.thumbnailFrame, undefined); assert.equal(explicit.elements.length, 2); +}); + +test("missing, ambiguous and invalid thumbnails fall back to the complete scene", async () => { + for (const value of ['Missing', 'null', '[]', '""']) { + const f = fixture(value), scene = await f.api.getTemplate(f.plugin, 'Drawing.md', false, f.loader, 0, false, undefined, true); + assert.equal(scene.thumbnailFrame, undefined); assert.equal(scene.elements.length, 3); + } + const f = fixture(); f.elements([f.frame, { ...f.frame, id: 'other', frameRole: 'marker' }]); + assert.equal((await f.api.getTemplate(f.plugin, 'Drawing.md', false, f.loader, 0, false, undefined, true)).thumbnailFrame, undefined); +}); + +test("PNG and SVG preview exports forward strict frame cropping without changing full-scene export defaults", async () => { + const f = fixture(); + await f.api.createPNG('Drawing.md', 1, f.options, f.loader, 'light', undefined, undefined, [], f.plugin, 0); + await f.api.createSVG('Drawing.md', false, f.options, f.loader, 'light', undefined, undefined, [], f.plugin, 0); + assert.deepEqual(f.requests.map(options => options.exportingFrame.id), ['frame-id', 'frame-id']); + await f.api.createPNG('Drawing.md', 1, { ...f.options, drawingThumbnail: false }, f.loader, 'light', undefined, undefined, [], f.plugin, 0); + assert.equal(f.requests.at(-1).exportingFrame, undefined); +}); diff --git a/scripts/testing/frameThumbnailController.source.test.mjs b/scripts/testing/frameThumbnailController.source.test.mjs new file mode 100644 index 00000000..b88439e6 --- /dev/null +++ b/scripts/testing/frameThumbnailController.source.test.mjs @@ -0,0 +1,95 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { load } from "js-yaml"; +import { sourceHarness } from "./sourceHarness.mjs"; + +async function fixture(policy = "always") { + const prompts = [], errors = [], settingsWrites = []; + class Prompt { + constructor(_plugin, message, buttons) { this.message = message; this.buttons = buttons; this.waitForClose = new Promise(resolve => { this.resolve = resolve; }); prompts.push(this); } + close() { this.resolve(null); } choose(value) { this.resolve(value); } + } + const graph = sourceHarness({ obsidian: { Notice: class {}, parseYaml: load }, + "src/shared/Dialogs/FrameNavigator": { FrameNavigator: class { open() {} close() {} } }, + "src/lang/helpers": { t: key => key }, "src/utils/coreUtils": { errorlog: value => errors.push(value) } }); + const { FrameThumbnailController } = await graph.importModule("src/view/managers/FrameThumbnailController.ts"); + const { readFrameProperty } = await graph.importModule("src/utils/frameMetadata.ts"); + const file = { path: "Drawing.md" }, api = {}; + let disk = '---\nexcalidraw-plugin: parsed\nexcalidraw-thumbnail: A\nunknown: sentinel\n---\nBody', closed = false, saves = 0; + let elements = [{ id: "frame-id", type: "frame", name: "A", x: 0, y: 0, width: 100, height: 80 }]; + const view = { file, excalidrawAPI: api, data: disk, compatibilityMode: false, + app: { vault: { read: async () => disk, getFileByPath: path => path === file.path ? file : null } }, + plugin: { _loaded: true, settings: { thumbnailRenamePolicy: policy, unknown: "sentinel" }, saveSettings: async () => settingsWrites.push(structuredClone(view.plugin.settings)) }, + getViewElements: () => elements, isClosingOrMigrating: () => closed, setDirty() {}, + forceSave: async () => { saves++; view.data = disk = controller.applyHeader(view.data, elements); }, + }; + const controller = new FrameThumbnailController(view, Prompt); controller.update(elements, true); + const flush = () => new Promise(resolve => setImmediate(resolve)); + const rename = name => { elements = [{ ...elements[0], name }]; controller.update(elements); }; + return { controller, view, file, api, prompts, errors, settingsWrites, rename, flush, yaml: () => readFrameProperty(disk), saves: () => saves, + scene: value => { elements = value; controller.update(elements); }, + external: name => { disk = disk.replace(/excalidraw-thumbnail:.*\n/, 'excalidraw-thumbnail: ' + JSON.stringify(name) + '\n'); }, + close: () => { closed = true; controller.reset(); graph.close(); } }; +} + +test("thumbnail rename follows always policy and undo/redo without replacing user hooks or unknown settings", async () => { + const f = await fixture(); + try { + const hook = () => {}; f.view.onSceneChangeHook = hook; + f.rename("B"); await f.flush(); assert.equal(f.yaml(), "B"); + f.rename("A"); await f.flush(); assert.equal(f.yaml(), "A"); + f.rename("B"); await f.flush(); assert.equal(f.yaml(), "B"); + assert.equal(f.prompts.length, 0); assert.equal(f.saves(), 3); assert.equal(f.view.onSceneChangeHook, hook); + assert.equal(f.view.plugin.settings.unknown, "sentinel"); + } finally { f.close(); } +}); + +test("first rename persists a selected policy and ask allows a different decision on subsequent renames", async () => { + const f = await fixture("unset"); + try { + f.rename("B"); assert.equal(f.prompts.length, 1); f.prompts[0].choose("ask"); await f.flush(); + assert.equal(f.settingsWrites[0].thumbnailRenamePolicy, "ask"); assert.equal(f.settingsWrites[0].unknown, "sentinel"); + f.prompts[1].choose(false); await f.flush(); assert.equal(f.yaml(), "A"); + f.rename("C"); f.prompts[2].choose(true); await f.flush(); assert.equal(f.yaml(), "C"); + } finally { f.close(); } +}); + +test("cancelling first-rename policy does not reopen a prompt on unchanged selection or scene updates", async () => { + const f = await fixture("unset"); + try { f.rename("B"); f.prompts[0].close(); await f.flush(); f.rename("B"); await f.flush(); assert.equal(f.prompts.length, 1); assert.equal(f.yaml(), "A"); } + finally { f.close(); } +}); + +test("a rename reverted while its own YAML write settles keeps tracking the same frame", async () => { + const f = await fixture(); + try { + const save = f.view.forceSave; let first = true; + f.view.forceSave = async () => { await save(); if (first) { first = false; f.rename("A"); } }; + f.rename("B"); await f.flush(); await f.flush(); + assert.equal(f.yaml(), "A"); assert.equal(f.saves(), 2); + } finally { f.close(); } +}); + +test("a context-menu thumbnail choice establishes identity before the next scene event renames it", async () => { + const f = await fixture(); + try { + f.scene([{ id: "other", type: "frame", name: "Other", x: 0, y: 0, width: 100, height: 80 }]); + assert.equal(await f.controller.setThumbnail("Other"), true); + f.rename("Renamed"); await f.flush(); + assert.equal(f.yaml(), "Renamed"); + } finally { f.close(); } +}); + +test("external YAML changes, blank names and retired views cannot be overwritten by a pending rename", async () => { + for (const kind of ["external", "blank", "retired"]) { + const f = await fixture("ask"); + try { + f.rename("B"); const prompt = f.prompts[0]; + if (kind === "external") f.external("Manual"); + if (kind === "blank") f.rename(""); + if (kind === "retired") f.controller.reset(); + prompt.choose(true); await f.flush(); + assert.equal(f.yaml(), kind === "external" ? "Manual" : "A"); assert.equal(f.saves(), 0); + } finally { f.close(); } + } +}); diff --git a/scripts/testing/host/devices.mjs b/scripts/testing/host/devices.mjs index 72780722..89b29ef5 100644 --- a/scripts/testing/host/devices.mjs +++ b/scripts/testing/host/devices.mjs @@ -16,6 +16,7 @@ import { mainWindowExpression, restoreDeviceState } from "./deviceRecovery.mjs"; import { runBehaviorMatrix } from "./behaviorMatrix.mjs"; import { runKplexOntologyScenario } from "./kplexOntology.mjs"; import { runEmbedControlsScenario } from "./embedControls.mjs"; +import { runFrameSemanticsScenario } from "./frameSemantics.mjs"; import {acquireBrowserDiagnostics,classifyCLIErrorText,splitWindowErrors} from './browserDiagnostics.mjs'; import { constrainedViewportMetrics, viewportInput } from "./deviceViewport.mjs"; import { retryReadOnly } from "./readOnlyTransport.mjs"; @@ -33,6 +34,7 @@ export async function runDeviceMatrix({ featureCases, kplexOntology = false, embedControls = false, + frameSemantics = false, }) { reportDir = resolve(reportDir); const target = validateTarget({ @@ -211,6 +213,11 @@ export async function runDeviceMatrix({ embeds = await runEmbedControlsScenario({ cli, drawingPath: path, contexts: [profile.id.startsWith("phone-") ? "phone" : "tablet"], inputMode: "touch", viewportScale: viewportMetrics?.scale ?? 1 }); report.tests.push(...embeds.tests); } + let frames; + if (frameSemantics && ["phone-portrait-light", "tablet-portrait-full-light"].includes(profile.id)) { + frames = await runFrameSemanticsScenario({ cli, drawingPath: path, contexts: [profile.id.startsWith("phone-") ? "phone" : "tablet"], inputMode: "touch", viewportScale: viewportMetrics?.scale ?? 1 }); + report.tests.push(...frames.tests); + } // Clearing viewport emulation resizes the real host again. Include that // teardown in the quiet/error gate before starting the next profile. if (viewportMetrics) {cli("dev:cdp", "method=Emulation.clearDeviceMetricsOverride", "params={}");viewportMetrics=null;} @@ -220,13 +227,14 @@ export async function runDeviceMatrix({ ...(workflows?.consoleErrors || []), ...(ontology?.consoleErrors || []), ...(embeds?.consoleErrors || []), + ...(frames?.consoleErrors || []), ]; const unexpected = unexpectedConsoleErrors(errors, expectedConsoleErrors), windowErrorText = cli("dev:errors").trim(); const windowEvents=browserSession.read(),classified=splitWindowErrors(windowEvents),cliErrors=classifyCLIErrorText(windowErrorText); const errorGatePassed = unexpected.length === 0 && - classified.unexpected.length===0 && cliErrors.unexpected.length===0 && browserIdle.status==='passed' && (!workflows||workflows.status==='passed') && (!ontology||ontology.status==='passed') && (!embeds||embeds.status==='passed'); + classified.unexpected.length===0 && cliErrors.unexpected.length===0 && browserIdle.status==='passed' && (!workflows||workflows.status==='passed') && (!ontology||ontology.status==='passed') && (!embeds||embeds.status==='passed') && (!frames||frames.status==='passed'); browserSession.dispose();browserSession=null; if(debuggerSession.transportDiagnostics?.length)report.transportDiagnostics.push(...debuggerSession.transportDiagnostics.map(item=>({profile:profile.id,...item}))); debuggerSession.dispose(); diff --git a/scripts/testing/host/frameSemantics.mjs b/scripts/testing/host/frameSemantics.mjs new file mode 100644 index 00000000..7f83d528 --- /dev/null +++ b/scripts/testing/host/frameSemantics.mjs @@ -0,0 +1,236 @@ +/** Focused #3042 metadata, thumbnail rendering, source controls and navigation. */ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { runInAppTask } from "./inAppTask.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"]; +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}`)); + +export async function runFrameSemanticsScenario({ cli, drawingPath, contexts = ["main", "popout"], inputMode = "mouse", viewportScale = 1 }) { + let template = readFileSync(new URL("../../../tests/vault/Drawings/Uncompressed.excalidraw.md", import.meta.url), "utf8"); + const scene = JSON.parse(template.match(/```json\n([\s\S]*?)\n```/)[1]), base = scene.elements[0]; + scene.elements = [ + { ...base, id: "frame-main", type: "frame", name: "Main, α", width: 200, height: 120, index: "a0", customData: undefined }, + { ...base, id: "inside", x: 20, y: 20, width: 60, height: 40, frameId: "frame-main", index: "a1", backgroundColor: "#00ff00" }, + { ...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", x: 900, y: 300, index: "a5" }, + ]; + template = template.replace(/```json\n[\s\S]*?\n```/, "```json\n" + JSON.stringify(scene, null, 2) + "\n```"); + const tests = [], consoleErrors = [], windowErrors = [], browserIdle = []; + for (const id of contexts) { + const execute = new Function(`return async function(c,path,context,template,modifier){ + const env=await (${behaviorEnvironment.toString()})(c,path,context,template,${completeConsoleErrors.toString()},${settleBrowserDiagnostics.toString()}); + c.diagnostics=env.diagnostics; + (${collectBehaviorCases.toString()})(c); + await (${exercise.toString()})(c,env,template,modifier,context.id); + 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], + timeoutMs: 240000, cleanupMs: 60000, onRequest: behaviorInputDriver(cli, viewportScale), + onProgress: phase => { if (phase) process.stdout.write("Frames: " + phase + "\n"); }, + }); + tests.push(...result.tests); consoleErrors.push(...result.consoleErrors); windowErrors.push(...result.windowErrors); browserIdle.push(...result.browserIdle); + } + if (contexts.includes("main")) { + const result = await runInAppTask({ cli, execute: reloadSettings, args: [], timeoutMs: 90000, cleanupMs: 60000 }); + tests.push(...result.tests); + } + assert.equal(consoleErrors.length, 0); assert.equal(splitWindowErrors(windowErrors).unexpected.length, 0); + assert.ok(browserIdle.every(item => item.status === "passed")); + if (tests.some(test => test.status !== "passed")) { + const error = Error("Focused frame cases failed: " + tests.filter(test => test.status !== "passed").map(test => test.testId).join(", ")); + error.evidence = tests; throw error; + } + return { id: "frame-semantics", status: "passed", tests, consoleErrors, windowErrors, browserIdle }; +} + +async function reloadSettings(c) { + await c.case("native:frames:settings-reload", ["P01", "P02"], async () => { + const id = "obsidian-excalidraw-plugin", old = app.plugins.plugins[id], key = "__framePolicyFutureSetting"; + const original = old.settings.thumbnailRenamePolicy; + const settingsPath = app.vault.configDir + "/plugins/" + id + "/data.json"; + c.defer(async () => { + if (!app.plugins.plugins[id]) await app.plugins.enablePlugin(id); + await c.waitForCleanup(() => app.plugins.plugins[id]?.isReady, "restored plugin readiness"); + const live = app.plugins.plugins[id]; live.settings.thumbnailRenamePolicy = original; delete live.settings[key]; await live.saveSettings(); + }); + old.settings.thumbnailRenamePolicy = "ask"; old.settings[key] = { zero: 0, enabled: false }; + await old.saveSettings(); + const before = JSON.parse(await app.vault.adapter.read(settingsPath)); + if (before.thumbnailRenamePolicy !== "ask" || before[key]?.enabled !== false) throw Error("policy not persisted before unload"); + await app.plugins.disablePlugin(id); await app.plugins.enablePlugin(id); + await c.waitFor(() => app.plugins.plugins[id]?.isReady, "replacement plugin readiness"); + const live = app.plugins.plugins[id], after = JSON.parse(await app.vault.adapter.read(settingsPath)); + if (live === old || live.settings.thumbnailRenamePolicy !== "ask" || live.settings[key]?.zero !== 0 || live.settings[key]?.enabled !== false || after.thumbnailRenamePolicy !== "ask") throw Error("reload lost non-default policy or unknown settings"); + return { assertions: ["non-default rename policy saved on disk", "actual unload/startup creates new plugin instance", "new policy and unknown zero/false settings survive on disk and in memory"] }; + }); + return { tests: c.tests }; +} + +async function exercise(c, env, template, modifier, context) { + 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" }); + 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]); + const thumbnailIs = async name => { + const property = (await yaml())["excalidraw-thumbnail"]; + c.caseTrace = { ...c.caseTrace, thumbnail: { property, tracked: view.frameThumbnail.tracked, patch: !!view.frameThumbnail.patch, running: view.frameThumbnail.running, scene: view.getViewElements().filter(element => element.type === "frame").map(element => [element.id, element.name]) } }; + return property === name; + }; + const rename = name => { + const api = view.excalidrawAPI; + api.updateScene({ elements: api.getSceneElements().map(element => element.id === "frame-main" ? { ...element, name, version: element.version + 1, versionNonce: element.versionNonce + 1 } : element), captureUpdate: "IMMEDIATELY" }); + }; + await c.case(`native:frames:${context}:metadata`, ["P02", "P05"], async () => { + view.setDirty(); await view.forceSave(true, true); + const originalCustomData = customData(); + check(JSON.stringify((await yaml())["excalidraw-anchors"]) === JSON.stringify(["Main, α", "Marker,padding=50", "Frame"]), "actual frame names not saved as ordered YAML list"); + check((await yaml())["retained-property"] === "untouched", "unrelated YAML changed"); + check(await view.frameThumbnail.setThumbnail("Marker,padding=50"), "marker thumbnail write failed"); + check((await yaml())["excalidraw-thumbnail"] === "Marker,padding=50", "thumbnail name parsed as padding"); + await view.zoomToElementId("frame-main", false); + const state = view.excalidrawAPI.getAppState(), x = (100 + state.scrollX) * state.zoom.value + state.offsetLeft, y = state.scrollY * state.zoom.value + state.offsetTop + 1; + await env.input("Input.dispatchMouseEvent", { type: "mousePressed", x, y, button: "right", buttons: 2, clickCount: 1 }); + await env.input("Input.dispatchMouseEvent", { type: "mouseReleased", x, y, button: "right", buttons: 0, clickCount: 1 }); + await c.waitFor(() => doc.querySelector('[data-testid="drawingThumbnail"] button'), "selected frame thumbnail context action"); + const action = doc.querySelector('[data-testid="drawingThumbnail"] button'); + check(action.title.includes("excalidraw-thumbnail"), "thumbnail context help absent"); await click(action); + await c.waitFor(async () => (await yaml())["excalidraw-thumbnail"] === "Main, α", "context action saves exact frame name"); + p.settings.thumbnailRenamePolicy = "always"; await p.saveSettings(); + rename("Renamed, β"); + await c.waitFor(() => thumbnailIs("Renamed, β"), "rename policy saves YAML"); + rename("Main, α"); + await c.waitFor(() => thumbnailIs("Main, α"), "reverted frame name saves YAML"); + check(customData() === originalCustomData, "thumbnail changed scene metadata: " + originalCustomData + " -> " + customData()); + view = await env.saveReopen(view); + check((await yaml())["excalidraw-thumbnail"] === "Main, α", "thumbnail lost after reopen"); + p.settings.autoexportSVG = true; p.settings.autoexportPNG = true; p.settings.displayExportedImageIfAvailable = true; + view.setDirty(); await view.forceSave(true, true); + const exportBase = drawing.path.slice(0, -3); + await c.waitFor(() => app.vault.getFileByPath(exportBase + ".svg") && app.vault.getFileByPath(exportBase + ".png"), "full-scene autoexports created"); + const svg = new win.DOMParser().parseFromString(await app.vault.read(app.vault.getFileByPath(exportBase + ".svg")), "image/svg+xml").documentElement; + check(svg.viewBox.baseVal.width > 900, "SVG autoexport inherited thumbnail crop"); + const png = new win.Blob([await app.vault.readBinary(app.vault.getFileByPath(exportBase + ".png"))], { type: "image/png" }), url = win.URL.createObjectURL(png); + try { const image = new win.Image(); image.src = url; await image.decode(); check(image.naturalWidth / image.naturalHeight > 2, "PNG autoexport inherited thumbnail crop"); } finally { win.URL.revokeObjectURL(url); } + p.settings.autoexportSVG = false; p.settings.autoexportPNG = false; + return { assertions: ["regular, marker and literal Frame names form an ordered YAML list; unnamed excluded", "unrelated YAML survives", "exact marker name with padding-looking suffix round trips", "always policy follows rename and revert", "no thumbnail customData", "save/reopen retains metadata"] }; + }); + await c.case(`native:frames:${context}:navigation`, ["P02"], async () => { + const api = view.excalidrawAPI, mode = api.getAppState().viewModeEnabled; + api.toggleSidebar({ name: "default", tab: "search", force: true }); + await c.waitFor(() => view.contentEl.querySelector('.layer-ui__search-inputWrapper input'), "Search input opens"); + const search = view.contentEl.querySelector('.layer-ui__search-inputWrapper input'); await click(search); + await key("a", "KeyA", 65, modifier); + await env.input("Input.insertText", { text: "retained needle" }); + await c.waitFor(() => search.value === "retained needle", "Search sentinel entered"); + const before = search.value, scene = JSON.stringify(api.getSceneElements()); + app.commands.executeCommandById("obsidian-excalidraw-plugin:navigate-to-frame"); + await c.waitFor(() => doc.querySelector(".prompt .suggestion-item"), "frame fuzzy picker opens in owner window"); + const items = [...doc.querySelectorAll(".prompt .suggestion-item")]; + check(items.length === 4 && items.some(item => item.textContent.includes("frame-unnamed")), "navigator omitted unnamed frame"); + await click(items.find(item => item.textContent.includes("Marker,padding=50"))); + await c.waitFor(() => !doc.querySelector(".prompt"), "frame picker closes"); + check(api.getAppState().viewModeEnabled === mode, "navigation changed drawing mode"); + check(JSON.stringify(api.getSceneElements()) === scene, "navigation mutated scene"); + check(search.value === before, "navigation changed Search text"); + check(api.getAppState().selectedElementIds["frame-marker"], "existing navigation did not select target frame"); + api.toggleSidebar({ name: "default", tab: "search", force: false }); + return { assertions: ["owner-window fuzzy picker contains regular, marker and unnamed frames", "native selection navigates to marker ID", "editing mode, scene and Search text unchanged"] }; + }); + const note = await env.create("Embeds.md", `![[${drawing.path}|240]]\n\n![[${drawing.path}#^frame=|240]]\n\n![[${drawing.path}#^frame=frame-marker,padding=0|240]]\n\nEnd`); + const readingNote = await env.create("Reading.md", `![[${drawing.path}|240]]\n\nEnd`); + const root = () => [...leaf.view.contentEl.querySelectorAll(leaf.view.getMode?.() === "preview" ? ".markdown-preview-view" : ".markdown-source-view")].find(element => element.getBoundingClientRect().height > 0 && !element.closest(".internal-embed")); + const images = () => [...root()?.querySelectorAll(".excalidraw-embedded-img") || []]; + const decoded = image => image.getBoundingClientRect().height > 0 && (image.tagName !== "IMG" || image.complete && image.naturalWidth > 0); + const open = async mode => { + if (leaf.view === view) view.exitFullscreen(); + await leaf.setViewState({ type: "empty", state: {} }); + await leaf.setViewState({ type: "markdown", state: { file: mode === "preview" ? readingNote.path : note.path, mode, source: false } }); + app.workspace.setActiveLeaf(leaf, { focus: true }); win.focus(); + if (mode === "source") leaf.view.editor.setCursor({ line: leaf.view.editor.lastLine(), ch: 0 }); + await c.waitFor(() => { + if (mode === "preview" && root()) root().scrollTop = 0; + c.caseTrace = { ...c.caseTrace, format: p.settings.previewImageType, mode, images: images().map(image => ({ tag: image.tagName, bounds: image.getBoundingClientRect().toJSON(), html: image.outerHTML.slice(0, 300) })) }; + return images().length === (mode === "preview" ? 1 : 3) && images().every(decoded); + }, mode + " thumbnail images decoded"); + }; + const ratio = image => { + if (image.tagName === "IMG") return image.naturalWidth / image.naturalHeight; + const svg = image.tagName.toLowerCase() === "svg" ? image : image.querySelector("svg"); + return svg.viewBox.baseVal.width / svg.viewBox.baseVal.height; + }; + await c.case(`native:frames:${context}:previews`, ["P05"], async () => { + for (const type of ["SVG", "SVGIMG", "PNG"]) { + p.settings.previewImageType = type; + await open("source"); + check(Math.abs(ratio(images()[0]) - 200 / 120) < .01, type + " implicit thumbnail crop differs from frame rectangle"); + check(ratio(images()[1]) > 2, type + " explicit whole scene retained thumbnail crop"); + check(ratio(images()[2]) < 1, type + " explicit marker reference ignored"); + await open("preview"); + check(Math.abs(ratio(images()[0]) - 200 / 120) < .01, type + " Reading preview ignored thumbnail"); + } + await app.fileManager.processFrontMatter(drawing, fm => { fm["excalidraw-thumbnail"] = "Missing frame"; }); + await open("source"); + check(ratio(images()[0]) > 2, "manual stale YAML did not fall back to full scene"); + await app.fileManager.processFrontMatter(drawing, fm => { fm["excalidraw-thumbnail"] = "Main, α"; }); + await open("source"); + check(Math.abs(ratio(images()[0]) - 200 / 120) < .01, "manual YAML edit did not invalidate cached preview"); + const { Component, MarkdownRenderer } = p.ea.obsidian, component = new Component(); component.load(); + const hover = doc.body.createDiv({ cls: "hover-popover markdown-preview-view" }); + try { + await MarkdownRenderer.render(app, `![[${drawing.path}]]`, hover, note.path, component); + await c.waitFor(() => hover.querySelector(".excalidraw-embedded-img") && decoded(hover.querySelector(".excalidraw-embedded-img")), "hover thumbnail decodes"); + check(Math.abs(ratio(hover.querySelector(".excalidraw-embedded-img")) - 200 / 120) < .01, "hover ignored thumbnail"); + } finally { component.unload(); hover.remove(); } + const ea = p.ea.getAPI(); + try { + const id = await ea.addImage(0, 0, drawing, false, false), element = ea.getElement(id); + check(Math.abs(element.width / element.height - 200 / 120) < .01, "nested drawing ignored thumbnail"); + ea.reset(); + const svg = await ea.createSVG(drawing.path); + check(svg.viewBox.baseVal.width > 900, "ordinary full-scene export inherited thumbnail crop"); + } finally { ea.destroy(); } + return { assertions: ["PNG, SVG image and native SVG use strict implicit frame bounds in Live Preview and Reading", "empty frame means whole scene and explicit marker overrides default", "hover and nested drawing use thumbnail", "ordinary SVG export remains whole scene"] }; + }); + await c.case(`native:frames:${context}:controls`, ["P02", "P05"], async () => { + p.settings.previewImageType = "SVG"; await open("source"); + const drawingBytes = await app.vault.read(drawing); + const frames = () => [...root().querySelectorAll(".excalidraw-embed-controls-frame")]; + await c.waitFor(() => frames().length === 3, "frame toolbars bound"); + const source = leaf.view.editor.getValue(); + const picker = frames()[1].querySelector('[data-excalidraw-embed-action="frame"]'); + check(picker?.querySelector(".lucide-scan-eye"), "frame picker does not use scan-eye"); + picker.focus(); await click(picker); + await c.waitFor(() => doc.querySelector(".menu .menu-item"), "frame dropdown opens"); + const items = [...doc.querySelectorAll(".menu .menu-item")]; + check(items.length === 6 && items.some(item => item.textContent.includes("frame-unnamed")), "frame menu omitted defaults or unnamed"); + await click(items.find(item => item.textContent.includes("Marker,padding=50"))); + const changed = source.replace("#^frame=|240", "#^frame=frame-marker|240"); + await c.waitFor(() => leaf.view.editor.getValue() === changed, "frame picker writes exact source occurrence using ID"); + leaf.view.editor.cm.focus(); await key("z", "KeyZ", 90, modifier); + await c.waitFor(() => leaf.view.editor.getValue() === source, "frame picker single undo"); + await c.waitFor(() => frames()[2]?.querySelector('[data-excalidraw-embed-action="padding"]'), "frame padding control"); + frames()[2].querySelector('[data-excalidraw-embed-action="padding"]').focus(); + await click(frames()[2].querySelector('[data-excalidraw-embed-action="padding"]')); + await c.waitFor(() => doc.querySelector(".excalidraw-embed-padding-popover input"), "frame padding slider opens"); + await key("Home", "Home", 36); await key("ArrowUp", "ArrowUp", 38); + await c.waitFor(() => frames()[2].querySelector(".excalidraw-embed-padding-preview svg"), "frame padding export preview"); + await key("Escape", "Escape", 27); + check(leaf.view.editor.getValue() === source, "canceling frame padding changed source"); + await leaf.view.save(); + check(await app.vault.read(drawing) === drawingBytes, "embed controls mutated destination drawing"); + 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"] }; + }); +} diff --git a/scripts/testing/host/verify.mjs b/scripts/testing/host/verify.mjs index fbe1eade..f2b93a50 100644 --- a/scripts/testing/host/verify.mjs +++ b/scripts/testing/host/verify.mjs @@ -12,6 +12,7 @@ import { runNativeCLIScenario } from "./nativeCLI.mjs"; import { runEmbedRecoveryScenario } from "./embedRecovery.mjs"; import { runEmbedControlsScenario } from "./embedControls.mjs"; import { runEmbedRegressionsScenario } from "./embedRegressions.mjs"; +import { runFrameSemanticsScenario } from "./frameSemantics.mjs"; import { runGroupedLinkClickScenario } from "./groupedLinkClick.mjs"; import { runLatexInputScenario } from "./latexInput.mjs"; import { runImageGeometryScenario } from "./imageGeometry.mjs"; @@ -91,6 +92,7 @@ const nativeCLI = coreScenarios || process.argv.includes("--native-cli"); const embedRecovery = coreScenarios || process.argv.includes("--embed-recovery"); const embedControls = coreScenarios || process.argv.includes("--embed-controls"); const embedRegressions = coreScenarios || process.argv.includes("--embed-regressions"); +const frameSemantics = coreScenarios || process.argv.includes("--frame-semantics"); const groupedLinkClick = coreScenarios || process.argv.includes("--grouped-link-click"); const latexInput = coreScenarios || process.argv.includes("--latex-input"); @@ -166,6 +168,7 @@ const flags = [ "--embed-recovery", "--embed-controls", "--embed-regressions", + "--frame-semantics", "--grouped-link-click", "--latex-input", "--latex-preview", @@ -358,6 +361,7 @@ try { ...(embedRecovery ? [runEmbedRecoveryScenario] : []), ...(embedControls ? [runEmbedControlsScenario] : []), ...(embedRegressions ? [runEmbedRegressionsScenario] : []), + ...(frameSemantics ? [runFrameSemanticsScenario] : []), ...(groupedLinkClick ? [runGroupedLinkClickScenario] : []), ...(latexInput ? [runLatexInputScenario] : []), ...(latexPreview @@ -422,6 +426,7 @@ try { featureCases:focusedCases, kplexOntology, embedControls, + frameSemantics, }); deviceReport.source = combination?.manifests.plugin || source; deviceReport.artifacts = report.artifacts.installedHashes; diff --git a/scripts/testing/regression.mjs b/scripts/testing/regression.mjs index 97529751..9d9e3cf9 100644 --- a/scripts/testing/regression.mjs +++ b/scripts/testing/regression.mjs @@ -23,12 +23,13 @@ import { textSaveShortcutCaseIds } from "./host/textSaveShortcut.mjs"; import { codeCardCaseIds } from "./host/codeCards.mjs"; import { embedControlCaseIds, embedControlDeviceCaseIds } from "./host/embedControls.mjs"; import { embedRegressionCaseIds } from "./host/embedRegressions.mjs"; +import { frameSemanticsCaseIds, frameSemanticsDeviceCaseIds } from "./host/frameSemantics.mjs"; import { kplexOntologyCaseIds, kplexOntologyDeviceCaseIds } from "./host/kplexOntology.mjs"; export const requiredDeviceCases = [ ...deviceProfiles(), ...breakpointProfiles(), -].map((profile) => "native:device:" + profile.id).concat(kplexOntologyDeviceCaseIds, embedControlDeviceCaseIds); +].map((profile) => "native:device:" + profile.id).concat(kplexOntologyDeviceCaseIds, embedControlDeviceCaseIds, frameSemanticsDeviceCaseIds); export const requiredNativeCases = [ ...workflowBundleCaseIds, @@ -36,6 +37,7 @@ export const requiredNativeCases = [ ...codeCardCaseIds, ...embedControlCaseIds, ...embedRegressionCaseIds, + ...frameSemanticsCaseIds, ...kplexOntologyCaseIds, ...behavioralCases().map((row) => row.testId), ...["image-url", "image-import"].flatMap((action) => diff --git a/src/constants/constants.ts b/src/constants/constants.ts index bb46fb7b..bb800b7e 100644 --- a/src/constants/constants.ts +++ b/src/constants/constants.ts @@ -311,6 +311,8 @@ export const AUDIO_TYPES = [ export const CODE_TYPES = ["json", "css", "js"]; export const FRONTMATTER_KEYS = { + anchors: { name: "excalidraw-anchors", type: "multitext", depricated: false }, + thumbnail: { name: "excalidraw-thumbnail", type: "text", depricated: false }, plugin: { name: "excalidraw-plugin", type: "text", depricated: false }, "export-transparent": { name: "excalidraw-export-transparent", diff --git a/src/core/editor/embedFrame.ts b/src/core/editor/embedFrame.ts new file mode 100644 index 00000000..494e3d0f --- /dev/null +++ b/src/core/editor/embedFrame.ts @@ -0,0 +1,24 @@ +import { readDrawingEmbedToken } from "./embedDimensions"; +import { getEmbeddedFilenameParts } from "src/utils/embeddedFilenameParts"; + +/** 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 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 b7b4dc16..2c72ae4e 100644 --- a/src/core/editor/embedPadding.ts +++ b/src/core/editor/embedPadding.ts @@ -3,7 +3,7 @@ import { getEmbeddedFilenameParts } from "src/utils/embeddedFilenameParts"; const PADDING_SUFFIX = /(?:,|%2c)padding(?:=|%3d)(?:\d+(?:(?:\.|%2e)\d+)?|(?:\.|%2e)\d+)$/i; -/** Rewrite only an area reference's padding, preserving raw paths and encoding. */ +/** Rewrite only a region reference's terminal padding, preserving raw paths and encoding. */ 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; @@ -12,11 +12,11 @@ export function withAreaPadding(target: string, padding: number | null): string // 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.blockref || parts.sectionref) || + 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 (/,padding=/i.test(decodeURIComponent(bare.slice(hash)))) return null; + if (parts.hasArearef && /,padding=/i.test(decodeURIComponent(bare.slice(hash)))) return null; return bare + (padding === null ? "" : `,padding=${padding}`); } diff --git a/src/core/editor/embedSource.ts b/src/core/editor/embedSource.ts index 04d0eafc..9d020b64 100644 --- a/src/core/editor/embedSource.ts +++ b/src/core/editor/embedSource.ts @@ -3,6 +3,7 @@ import { ChangeDesc, EditorSelection, Transaction } from "@codemirror/state"; import type { EditorView } from "@codemirror/view"; import { readDrawingEmbedToken } from "./embedDimensions"; import { rewriteEmbedPadding } from "./embedPadding"; +import { rewriteEmbedFrame } from "./embedFrame"; import type { EmbedSourceBinding } from "src/types/drawingEmbedTypes"; /** @@ -67,6 +68,14 @@ export class DrawingEmbedSource implements EmbedSourceBinding { return true; } + /** Frame choices can change a region reference without exposing arbitrary destination writes. */ + replaceFrame(reference: string | null): boolean { + const text = rewriteEmbedFrame(this.text, reference); + if (!text || !this.isCurrent() || this.validateRange && !this.validateRange(this.from, this.to)) return false; + if (text === this.text) return true; + return this.commit(text, "input.excalidraw-embed-frame"); + } + /** Select the containing-note syntax, allowing Live Preview to reveal it. */ select(): boolean { if (!this.isCurrent() || this.validateRange && !this.validateRange(this.from, this.to)) return false; diff --git a/src/core/managers/CommandManager.ts b/src/core/managers/CommandManager.ts index c9181fff..1f6b6464 100644 --- a/src/core/managers/CommandManager.ts +++ b/src/core/managers/CommandManager.ts @@ -807,6 +807,17 @@ export class CommandManager { }, }); + this.addCommand({ + id: "navigate-to-frame", name: t("FRAME_NAVIGATE"), + checkCallback: (checking: boolean) => { + const view = this.app.workspace.getActiveViewOfType(ExcalidrawView); + const available = !!view?.getViewElements().some(element => element.type === "frame" && !element.isDeleted); + if (checking) return available; + if (available) view.frameThumbnail.navigate(); + return available; + }, + }); + this.addCommand({ id: "fullscreen", name: t("TOGGLE_FULLSCREEN"), diff --git a/src/core/managers/DrawingEmbedControls.ts b/src/core/managers/DrawingEmbedControls.ts index 0c8af926..ca48030e 100644 --- a/src/core/managers/DrawingEmbedControls.ts +++ b/src/core/managers/DrawingEmbedControls.ts @@ -1,4 +1,5 @@ -import { Component, MarkdownRenderChild, Notice, setIcon, setTooltip } from "obsidian"; +import { Component, MarkdownRenderChild, Menu, Notice, setIcon, setTooltip } from "obsidian"; +import { getEmbeddedFilenameParts } from "src/utils/embeddedFilenameParts"; import { getEmbedDimensions, rewriteEmbedDimensions } from "../editor/embedDimensions"; import type { DrawingEmbedActions, EmbedSourceBinding } from "src/types/drawingEmbedTypes"; import { DrawingEmbedPreviewModal } from "src/shared/Dialogs/DrawingEmbedPreviewModal"; @@ -30,6 +31,7 @@ export class DrawingEmbedControls extends MarkdownRenderChild { private active = false; private modals = new Set(); private padding: DrawingEmbedPaddingControl | null = null; + private frameMenu: Menu | null = null; constructor( frame: HTMLElement, @@ -69,6 +71,24 @@ export class DrawingEmbedControls extends MarkdownRenderChild { this.registerDomEvent(open, "pointerenter", () => setTooltip(open, this.actions.getOpenTooltip())); this.registerDomEvent(open, "focus", () => setTooltip(open, this.actions.getOpenTooltip())); if (this.source) { + if (this.actions.frames?.length && this.source.replaceFrame) { + const picker = button("frame", "scan-eye", t("FRAME_PICK"), () => { + if (!this.current()) return; + this.padding?.close(false); this.finish(false); this.frameMenu?.hide(); + 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_WHOLE")).setChecked(parts.hasFrameref && ref === "").onClick(() => choose(""))); + menu.addSeparator(); + for (const frame of this.actions.frames) { + const label = frame.name?.trim() ? frame.name : `${t(frame.marker ? "FRAME_UNNAMED_MARKER" : "FRAME_UNNAMED")} (${frame.id})`; + menu.addItem(item => item.setTitle(label).setChecked((parts.hasFrameref || parts.hasClippedFrameref) && (ref === frame.id || ref === frame.name)).onClick(() => choose(frame.reference))); + } + menu.onHide(() => { if (this.frameMenu === menu) this.frameMenu = null; }); + const bounds = picker.getBoundingClientRect(); menu.showAtPosition({ x: bounds.left, y: bounds.bottom }, doc); + }); + } if (this.actions.padding && this.source.replacePadding) { const padding = button("padding", "square-dot", t("EMBED_ADJUST_PADDING"), () => { if (this.padding) { this.padding.close(true); return; } @@ -168,6 +188,7 @@ export class DrawingEmbedControls extends MarkdownRenderChild { private start(kind: ResizeGesture["kind"], x = 0, id?: number, y = 0): boolean { if (!this.source || !this.current() || !this.visual) return false; this.padding?.close(false); + this.frameMenu?.hide(); this.frameMenu = null; this.finish(false); const bounds = this.visual.getBoundingClientRect(); if (bounds.width <= 0 || bounds.height <= 0) return false; @@ -246,6 +267,7 @@ export class DrawingEmbedControls extends MarkdownRenderChild { onunload(): void { this.active = false; this.finish(false); this.padding?.close(false); + this.frameMenu?.hide(); this.frameMenu = null; for (const modal of [...this.modals]) modal.close(); this.modals.clear(); this.toolbar?.remove(); this.handle?.remove(); this.containerEl.removeClass("excalidraw-embed-controls-frame", "excalidraw-embed-controls-below"); diff --git a/src/core/managers/MarkdownPostProcessor.ts b/src/core/managers/MarkdownPostProcessor.ts index 0d5dfe8e..4afa894c 100644 --- a/src/core/managers/MarkdownPostProcessor.ts +++ b/src/core/managers/MarkdownPostProcessor.ts @@ -16,7 +16,9 @@ import { RERENDER_EVENT, } from "../../constants/constants"; import { EmbeddedFilesLoader } from "../../shared/EmbeddedFileLoader"; -import { createPNG, createSVG } from "../../utils/excalidrawAutomateUtils"; +import { createPNG, createSVG, getTemplate } from "../../utils/excalidrawAutomateUtils"; +import { getSceneFrames } from "src/utils/frameMetadata"; +import type { DrawingFrameChoice } from "src/types/frameTypes"; import type ExcalidrawPlugin from "../main"; import { getIMGFilename } from "../../utils/fileUtils"; import { @@ -67,6 +69,24 @@ let app: App; let vault: Vault; let metadataCache: MetadataCache; let readingControls: Set | null = null; +let drawingFrames: Map }> | null = null; + +const getDrawingFrames = (file: TFile): Promise => { + const entries = drawingFrames; + if (!entries) return Promise.resolve([]); + const mtime = file.stat.mtime, cached = entries.get(file); + if (cached?.mtime === mtime) return cached.frames; + const frames = getTemplate(plugin, file.path, false, new EmbeddedFilesLoader(plugin), 0).then(scene => + file.stat.mtime !== mtime ? [] : getSceneFrames(scene.elements).map(frame => ({ + id: frame.id, name: frame.name, marker: frame.frameRole === "marker", reference: frame.id, + }))); + entries.set(file, { mtime, frames }); + if (entries.size > 128) { + const oldest = [...entries.keys()][0]; + if (oldest) entries.delete(oldest); + } + return frames; +}; const getDefaultWidth = (plugin: ExcalidrawPlugin): string => { const width = parseInt(plugin.settings.width); @@ -116,10 +136,13 @@ export const initializeMarkdownPostProcessor = (p: ExcalidrawPlugin) => { // their controls/viewers; context cleanup removes completed owners promptly. const owners = new Set(); readingControls = owners; + const frames = new Map }>(); + drawingFrames = frames; p.register(() => { for (const controls of [...owners]) controls.unload(); owners.clear(); if (readingControls === owners) readingControls = null; + frames.clear(); if (drawingFrames === frames) drawingFrames = null; }); }; @@ -156,6 +179,7 @@ const _getPNG = async ({ const cacheKey = { ...filenameParts, + cacheId: "frame-thumbnail-v1", isDark: theme === "dark", previewImageType: PreviewImageType.PNG, scale, @@ -304,6 +328,7 @@ const _getSVGIMG = async ({ exportSettings.skipInliningFonts = false; const cacheKey = { ...filenameParts, + cacheId: "frame-thumbnail-v1", isDark: theme === "dark", previewImageType: PreviewImageType.SVGIMG, scale: 1, @@ -399,6 +424,7 @@ const _getSVGNative = async ({ exportSettings.skipInliningFonts = false; const cacheKey = { ...filenameParts, + cacheId: "frame-thumbnail-v1", isDark: theme === "dark", previewImageType: PreviewImageType.SVG, scale: 1, @@ -508,6 +534,7 @@ const getIMG = async ( withBackground: getWithBackground(plugin, file), withTheme: forceTheme ? true : plugin.settings.exportWithTheme, isMask: isMaskFile(plugin, file), + drawingThumbnail: true, }; const theme = @@ -787,8 +814,11 @@ const createImgElement = async ( const drawingFile = attr.file ?? vault.getFileByPath(drawingPath); const isCurrent = () => currentPlugin._loaded && vault.getFileByPath(drawingPath) === drawingFile && (!isRenderActive || isRenderActive()); + const frames = !onCanvas && drawingFile ? await getDrawingFrames(drawingFile) : []; + if (!isCurrent()) { discardImage(imgOrDiv); return null; } if (!onCanvas && drawingFile) setDrawingEmbedActions(imgOrDiv, { app: app, target: attr.fname, isCurrent, + frames, openDrawing: event => openDrawingEmbed(currentPlugin, attr.fname, event, imgOrDiv), getOpenTooltip: () => getDrawingEmbedOpenTooltip(currentPlugin.settings), // A fullscreen viewer owns a fresh payload and must never revoke an inline diff --git a/src/core/settings.ts b/src/core/settings.ts index 4ccda484..84d43eea 100644 --- a/src/core/settings.ts +++ b/src/core/settings.ts @@ -1902,6 +1902,16 @@ export class ExcalidrawSettingTab extends PluginSettingTab { private getSavingSpecs(): SettingSpec[] { return [ + { + name: t("FRAME_RENAME_POLICY"), desc: t("FRAME_RENAME_DESC"), + aliases: ["thumbnail frame rename", "excalidraw-thumbnail"], + control: { type: "dropdown", key: "thumbnailRenamePolicy", options: [ + { value: "unset", label: t("FRAME_RENAME_UNSET") }, + { value: "always", label: t("FRAME_RENAME_ALWAYS") }, + { value: "ask", label: t("FRAME_RENAME_ASK") }, + { value: "never", label: t("FRAME_RENAME_NEVER") }, + ] }, + }, { name: t("COMPRESS_NAME"), desc: fragWithHTML(t("COMPRESS_DESC")), diff --git a/src/core/settingsDefaults.ts b/src/core/settingsDefaults.ts index bd38b999..951ab60a 100644 --- a/src/core/settingsDefaults.ts +++ b/src/core/settingsDefaults.ts @@ -10,6 +10,7 @@ * array binds directly against these same keys and defaults. */ import { Modifier } from "obsidian"; +import type { ThumbnailRenamePolicy } from "src/types/frameTypes"; import type { CodeBlockInsertionPreference } from "src/types/codeBlockTypes"; import { PenStyle } from "src/types/penTypes"; import { DynamicStyle, GridSettings } from "src/types/types"; @@ -43,6 +44,7 @@ import type { declare const PLUGIN_VERSION: string; export interface ExcalidrawSettings { + thumbnailRenamePolicy: ThumbnailRenamePolicy; showTabTitlebarButtons: boolean; copyLinkToElemenetAnchorTo100: boolean; copyFrameLinkByName: boolean; @@ -491,6 +493,7 @@ export const cloneModelConfigs = ( ) as Record; export const DEFAULT_SETTINGS: ExcalidrawSettings = { + thumbnailRenamePolicy: "unset", showTabTitlebarButtons: true, copyLinkToElemenetAnchorTo100: false, copyFrameLinkByName: false, diff --git a/src/lang/locale/en.ts b/src/lang/locale/en.ts index 5bdbba4a..28b5f6fe 100644 --- a/src/lang/locale/en.ts +++ b/src/lang/locale/en.ts @@ -16,10 +16,27 @@ declare const PLUGIN_VERSION: string; // English export default { + FRAME_NAVIGATE: "Navigate to frame", + FRAME_PICK: "Choose frame", + FRAME_DEFAULT: "Default thumbnail", + FRAME_WHOLE: "Whole scene", + FRAME_UNNAMED: "Unnamed frame", + FRAME_UNNAMED_MARKER: "Unnamed marker frame", + FRAME_SET_THUMBNAIL: "Set as drawing thumbnail", + FRAME_CLEAR_THUMBNAIL: "Clear drawing thumbnail", + FRAME_THUMBNAIL_HELP: "Use this frame for drawing previews. Its name is saved in the excalidraw-thumbnail document property.", + FRAME_NEEDS_NAME: "Give this frame a unique name first.", + FRAME_RENAME_POLICY: "When the thumbnail frame is renamed", + FRAME_RENAME_DESC: "Choose whether to update the excalidraw-thumbnail document property when its frame is renamed.", + FRAME_RENAME_UNSET: "Ask on first rename", + FRAME_RENAME_ALWAYS: "Always update the thumbnail property", + FRAME_RENAME_ASK: "Ask each time", + FRAME_RENAME_NEVER: "Do nothing", + FRAME_RENAME_CONFIRM: "Update the drawing thumbnail property to the frame's new name?", // Drawing embed controls (#3036) EMBED_OPEN_MODIFIER: "{keys}+click: {action}", EMBED_ACTIONS: "Drawing embed actions", - EMBED_ADJUST_PADDING: "Adjust area padding", + EMBED_ADJUST_PADDING: "Adjust padding", EMBED_RESET_PADDING: "Use default padding", EMBED_OPEN_DRAWING: "Open drawing", EMBED_EDIT_SOURCE: "Edit embed syntax", diff --git a/src/lang/locale/es.ts b/src/lang/locale/es.ts index 246e9dbe..9bf08f97 100644 --- a/src/lang/locale/es.ts +++ b/src/lang/locale/es.ts @@ -16,10 +16,27 @@ declare const PLUGIN_VERSION: string; // Español export default { + FRAME_NAVIGATE: "Ir al marco", + FRAME_PICK: "Elegir marco", + FRAME_DEFAULT: "Miniatura predeterminada", + FRAME_WHOLE: "Escena completa", + FRAME_UNNAMED: "Marco sin nombre", + FRAME_UNNAMED_MARKER: "Marco marcador sin nombre", + FRAME_SET_THUMBNAIL: "Usar como miniatura del dibujo", + FRAME_CLEAR_THUMBNAIL: "Quitar miniatura del dibujo", + FRAME_THUMBNAIL_HELP: "Usa este marco en las vistas previas. Su nombre se guarda en la propiedad excalidraw-thumbnail del documento.", + FRAME_NEEDS_NAME: "Asigna primero un nombre único a este marco.", + FRAME_RENAME_POLICY: "Al renombrar el marco de la miniatura", + FRAME_RENAME_DESC: "Elige si se actualiza la propiedad excalidraw-thumbnail cuando se renombra su marco.", + FRAME_RENAME_UNSET: "Preguntar al renombrar por primera vez", + FRAME_RENAME_ALWAYS: "Actualizar siempre la propiedad de miniatura", + FRAME_RENAME_ASK: "Preguntar cada vez", + FRAME_RENAME_NEVER: "No hacer nada", + FRAME_RENAME_CONFIRM: "¿Actualizar la propiedad de miniatura con el nuevo nombre del marco?", // Drawing embed controls (#3036) EMBED_OPEN_MODIFIER: "{keys}+clic: {action}", EMBED_ACTIONS: "Acciones del dibujo incrustado", - EMBED_ADJUST_PADDING: "Ajustar el margen del área", + EMBED_ADJUST_PADDING: "Ajustar el margen", EMBED_RESET_PADDING: "Usar el margen predeterminado", EMBED_OPEN_DRAWING: "Abrir dibujo", EMBED_EDIT_SOURCE: "Editar sintaxis de la inserción", diff --git a/src/lang/locale/ru.ts b/src/lang/locale/ru.ts index 64b435c4..e28ccb38 100644 --- a/src/lang/locale/ru.ts +++ b/src/lang/locale/ru.ts @@ -14,10 +14,27 @@ import { // русский export default { + FRAME_NAVIGATE: "Перейти к рамке", + FRAME_PICK: "Выбрать рамку", + FRAME_DEFAULT: "Миниатюра по умолчанию", + FRAME_WHOLE: "Вся сцена", + FRAME_UNNAMED: "Рамка без имени", + FRAME_UNNAMED_MARKER: "Рамка-маркер без имени", + FRAME_SET_THUMBNAIL: "Использовать как миниатюру рисунка", + FRAME_CLEAR_THUMBNAIL: "Убрать миниатюру рисунка", + FRAME_THUMBNAIL_HELP: "Использовать эту рамку для предпросмотра. Её имя сохраняется в свойстве документа excalidraw-thumbnail.", + FRAME_NEEDS_NAME: "Сначала задайте рамке уникальное имя.", + FRAME_RENAME_POLICY: "При переименовании рамки миниатюры", + FRAME_RENAME_DESC: "Обновлять ли свойство excalidraw-thumbnail при переименовании его рамки.", + FRAME_RENAME_UNSET: "Спросить при первом переименовании", + FRAME_RENAME_ALWAYS: "Всегда обновлять свойство миниатюры", + FRAME_RENAME_ASK: "Спрашивать каждый раз", + FRAME_RENAME_NEVER: "Ничего не делать", + FRAME_RENAME_CONFIRM: "Заменить имя рамки в свойстве миниатюры новым именем?", // Drawing embed controls (#3036) EMBED_OPEN_MODIFIER: "{keys}+щелчок: {action}", EMBED_ACTIONS: "Действия со встроенным рисунком", - EMBED_ADJUST_PADDING: "Изменить отступ области", + EMBED_ADJUST_PADDING: "Изменить отступ", EMBED_RESET_PADDING: "Использовать отступ по умолчанию", EMBED_OPEN_DRAWING: "Открыть рисунок", EMBED_EDIT_SOURCE: "Изменить синтаксис вставки", diff --git a/src/lang/locale/zh-cn.ts b/src/lang/locale/zh-cn.ts index d9b53c3c..c2d83f27 100644 --- a/src/lang/locale/zh-cn.ts +++ b/src/lang/locale/zh-cn.ts @@ -11,10 +11,27 @@ declare const PLUGIN_VERSION: string; // 简体中文 export default { + FRAME_NAVIGATE: "跳转到画框", + FRAME_PICK: "选择画框", + FRAME_DEFAULT: "默认缩略图", + FRAME_WHOLE: "完整场景", + FRAME_UNNAMED: "未命名画框", + FRAME_UNNAMED_MARKER: "未命名标记画框", + FRAME_SET_THUMBNAIL: "设为绘图缩略图", + FRAME_CLEAR_THUMBNAIL: "清除绘图缩略图", + FRAME_THUMBNAIL_HELP: "使用此画框预览绘图。其名称保存在文档的 excalidraw-thumbnail 属性中。", + FRAME_NEEDS_NAME: "请先为此画框设置唯一名称。", + FRAME_RENAME_POLICY: "重命名缩略图画框时", + FRAME_RENAME_DESC: "选择重命名画框时是否更新 excalidraw-thumbnail 文档属性。", + FRAME_RENAME_UNSET: "首次重命名时询问", + FRAME_RENAME_ALWAYS: "始终更新缩略图属性", + FRAME_RENAME_ASK: "每次询问", + FRAME_RENAME_NEVER: "不执行操作", + FRAME_RENAME_CONFIRM: "将绘图缩略图属性更新为画框的新名称吗?", // Drawing embed controls (#3036) EMBED_OPEN_MODIFIER: "{keys}+单击:{action}", EMBED_ACTIONS: "嵌入绘图操作", - EMBED_ADJUST_PADDING: "调整区域边距", + EMBED_ADJUST_PADDING: "调整边距", EMBED_RESET_PADDING: "使用默认边距", EMBED_OPEN_DRAWING: "打开绘图", EMBED_EDIT_SOURCE: "编辑嵌入语法", diff --git a/src/lang/locale/zh-tw.ts b/src/lang/locale/zh-tw.ts index a493db47..4fbb4b2d 100644 --- a/src/lang/locale/zh-tw.ts +++ b/src/lang/locale/zh-tw.ts @@ -11,10 +11,27 @@ declare const PLUGIN_VERSION: string; // 繁體中文 export default { + FRAME_NAVIGATE: "跳至畫框", + FRAME_PICK: "選擇畫框", + FRAME_DEFAULT: "預設縮圖", + FRAME_WHOLE: "完整場景", + FRAME_UNNAMED: "未命名畫框", + FRAME_UNNAMED_MARKER: "未命名標記畫框", + FRAME_SET_THUMBNAIL: "設為繪圖縮圖", + FRAME_CLEAR_THUMBNAIL: "清除繪圖縮圖", + FRAME_THUMBNAIL_HELP: "使用此畫框預覽繪圖。其名稱儲存在文件的 excalidraw-thumbnail 屬性中。", + FRAME_NEEDS_NAME: "請先為此畫框設定唯一名稱。", + FRAME_RENAME_POLICY: "重新命名縮圖畫框時", + FRAME_RENAME_DESC: "選擇重新命名畫框時是否更新 excalidraw-thumbnail 文件屬性。", + FRAME_RENAME_UNSET: "首次重新命名時詢問", + FRAME_RENAME_ALWAYS: "一律更新縮圖屬性", + FRAME_RENAME_ASK: "每次詢問", + FRAME_RENAME_NEVER: "不執行操作", + FRAME_RENAME_CONFIRM: "將繪圖縮圖屬性更新為畫框的新名稱嗎?", // Drawing embed controls (#3036) EMBED_OPEN_MODIFIER: "{keys}+按一下:{action}", EMBED_ACTIONS: "嵌入繪圖操作", - EMBED_ADJUST_PADDING: "調整區域邊距", + EMBED_ADJUST_PADDING: "調整邊距", EMBED_RESET_PADDING: "使用預設邊距", EMBED_OPEN_DRAWING: "開啟繪圖", EMBED_EDIT_SOURCE: "編輯嵌入語法", diff --git a/src/shared/Dialogs/FrameNavigator.ts b/src/shared/Dialogs/FrameNavigator.ts new file mode 100644 index 00000000..5b9eef5a --- /dev/null +++ b/src/shared/Dialogs/FrameNavigator.ts @@ -0,0 +1,30 @@ +import { FuzzySuggestModal } from "obsidian"; +import type { ExcalidrawFrameElement } from "@zsviczian/excalidraw/types/element/src/types"; +import type ExcalidrawView from "src/view/ExcalidrawView"; +import { getSceneFrames } from "src/utils/frameMetadata"; +import { t } from "src/lang/helpers"; + +/** Fuzzy frame navigation keeps the existing viewport/selection semantics and drawing mode. */ +export class FrameNavigator extends FuzzySuggestModal { + private readonly file: ExcalidrawView["file"]; + private readonly api: ExcalidrawView["excalidrawAPI"]; + + constructor(private readonly view: ExcalidrawView, private readonly onClosed: () => void) { + super(view.app); this.file = view.file; this.api = view.excalidrawAPI; + this.setPlaceholder(t("FRAME_NAVIGATE")); + } + + getItems(): ExcalidrawFrameElement[] { return getSceneFrames(this.view.getViewElements()); } + + getItemText(frame: ExcalidrawFrameElement): string { + return frame.name?.trim() ? frame.name : `${t(frame.frameRole === "marker" ? "FRAME_UNNAMED_MARKER" : "FRAME_UNNAMED")} (${frame.id})`; + } + + onChooseItem(frame: ExcalidrawFrameElement): void { + if (this.view.file !== this.file || this.view.excalidrawAPI !== this.api || this.view.isClosingOrMigrating()) return; + if (!getSceneFrames(this.view.getViewElements()).some(current => current.id === frame.id)) return; + void this.view.zoomToElementId(frame.id, false); + } + + onClose(): void { super.onClose(); this.onClosed(); } +} diff --git a/src/shared/Dialogs/Messages.ts b/src/shared/Dialogs/Messages.ts index 1313f738..564d5d29 100644 --- a/src/shared/Dialogs/Messages.ts +++ b/src/shared/Dialogs/Messages.ts @@ -19,7 +19,8 @@ I build this plugin as a labor of love. Curious about the philosophy behind it? `, "2.29.3": ` ## New and improved -- Adjust the padding 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). +- 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). ## 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/EmbeddedFileLoader.ts b/src/shared/EmbeddedFileLoader.ts index 752c7b32..a842a2d1 100644 --- a/src/shared/EmbeddedFileLoader.ts +++ b/src/shared/EmbeddedFileLoader.ts @@ -933,6 +933,7 @@ export class EmbeddedFilesLoader { withTheme: !!forceTheme, isMask, skipInliningFonts: false, + drawingThumbnail: true, }; const hasColorMap = Boolean( @@ -952,6 +953,7 @@ export class EmbeddedFilesLoader { ? (inFile as EmbeddedFile).filenameparts : null; const cacheKey: ImageKey = { + cacheId: "frame-thumbnail-v1", ...(hasFilenameParts ? { ...filenameParts, diff --git a/src/types/drawingEmbedTypes.ts b/src/types/drawingEmbedTypes.ts index d988afc4..b32275dd 100644 --- a/src/types/drawingEmbedTypes.ts +++ b/src/types/drawingEmbedTypes.ts @@ -1,5 +1,6 @@ /** Narrow renderer, dialog and editor capabilities for drawing embed controls. */ import type { App } from "obsidian"; +import type { DrawingFrameChoice } from "./frameTypes"; export interface LocatedDrawingEmbed { from: number; @@ -18,6 +19,7 @@ export interface DrawingEmbedActions extends DrawingEmbedPreview { openDrawing: (event: MouseEvent) => void; getOpenTooltip: () => string; isCurrent: () => boolean; + frames?: readonly DrawingFrameChoice[]; padding?: { value: number; create: (padding: number | null, isCurrent: () => boolean) => Promise; @@ -29,5 +31,6 @@ export interface EmbedSourceBinding { isCurrent(): boolean; replace(text: string): boolean; replacePadding?(padding: number | null): boolean; + replaceFrame?(reference: string | null): boolean; select(): boolean; } diff --git a/src/types/exportUtilTypes.ts b/src/types/exportUtilTypes.ts index 762eb6d6..9db63229 100644 --- a/src/types/exportUtilTypes.ts +++ b/src/types/exportUtilTypes.ts @@ -1,4 +1,5 @@ import { FrameRenderingOptions } from "./utilTypes"; +import type { ExcalidrawFrameElement, NonDeleted } from "@zsviczian/excalidraw/types/element/src/types"; export type PDFPageAlignment = | "center" @@ -63,6 +64,9 @@ export interface ExportSettings { isMask: boolean; frameRendering?: FrameRenderingOptions; //optional, overrides relevant appState settings for rendering the frame skipInliningFonts?: boolean; + /** Preview-only opt-in; ordinary scene exports must ignore the document thumbnail. */ + drawingThumbnail?: boolean; + exportingFrame?: NonDeleted; } // Electron IPC interfaces diff --git a/src/types/frameTypes.ts b/src/types/frameTypes.ts new file mode 100644 index 00000000..f7ca33f1 --- /dev/null +++ b/src/types/frameTypes.ts @@ -0,0 +1,10 @@ +/** Frame UI data contains no editor or plugin capability. */ +export interface DrawingFrameChoice { + id: string; + name: string | null; + marker: boolean; + reference: string; +} + +/** The first applicable rename asks the user to select a durable policy. */ +export type ThumbnailRenamePolicy = "unset" | "always" | "ask" | "never"; diff --git a/src/utils/excalidrawAutomateUtils.ts b/src/utils/excalidrawAutomateUtils.ts index 91fa1904..80a6c8fc 100644 --- a/src/utils/excalidrawAutomateUtils.ts +++ b/src/utils/excalidrawAutomateUtils.ts @@ -1,4 +1,5 @@ import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate"; +import { readFrameProperty, resolveThumbnailFrame } from "./frameMetadata"; import { BinaryFileData, DataURL, @@ -305,6 +306,7 @@ export async function getTemplate( depth: number, convertMarkdownLinksToObsidianURLs: boolean = false, cliFileIdAllowList?: Set, // #3004 -- CLI export may load only images needed by its preview policy + drawingThumbnail = false, ): Promise<{ elements: ExcalidrawElement[]; appState: Partial; @@ -312,6 +314,7 @@ export async function getTemplate( files: BinaryFiles; hasSVGwithBitmap: boolean; plaintext: string; //markdown data above Excalidraw data and below YAML frontmatter + thumbnailFrame?: ExportSettings["exportingFrame"]; }> { const app = plugin.app; const vault = app.vault; @@ -351,6 +354,8 @@ export async function getTemplate( } let scene = excalidrawData.scene; + const implicit = !(filenameParts.hasBlockref || filenameParts.hasSectionref) || filenameParts.blockref === "as-image"; + const thumbnail = drawingThumbnail && implicit ? resolveThumbnailFrame(scene.elements, readFrameProperty(data)) : null; let groupElements: ExcalidrawElement[] = scene.elements; if (filenameParts.hasGroupref) { @@ -371,7 +376,7 @@ export async function getTemplate( ); } } - if (filenameParts.hasFrameref || filenameParts.hasClippedFrameref) { + if ((filenameParts.hasFrameref || filenameParts.hasClippedFrameref) && !(filenameParts.hasFrameref && (filenameParts.blockref ?? filenameParts.sectionref) === "")) { const el = getFrameBasedOnFrameNameOrId( filenameParts.blockref, scene.elements, @@ -500,6 +505,7 @@ export async function getTemplate( : "", files, hasSVGwithBitmap, + thumbnailFrame: thumbnail ? { ...thumbnail, isDeleted: false } : undefined, }; } return { @@ -541,7 +547,7 @@ export async function createPNG( const filenameParts = getEmbeddedFilenameParts(templatePath); padding = filenameParts.padding ?? padding ?? plugin.settings.exportPaddingSVG; const template = templatePath - ? await getTemplate(plugin, templatePath, true, loader, depth) + ? await getTemplate(plugin, templatePath, true, loader, depth, false, undefined, exportSettings?.drawingThumbnail) : null; let elements = template?.elements ?? []; elements = elements.concat(automateElements); @@ -578,6 +584,7 @@ export async function createPNG( ...(exportSettings?.frameRendering ? { frameRendering: exportSettings.frameRendering } : {}), + exportingFrame: template?.thumbnailFrame, }, padding, scale, @@ -691,6 +698,8 @@ export async function createSVG( loader, depth, convertMarkdownLinksToObsidianURLs, + undefined, + exportSettings?.drawingThumbnail, ) : null; let elements = template?.elements ?? []; @@ -730,6 +739,7 @@ export async function createSVG( exportSettings?.withBackground ?? plugin.settings.exportWithBackground, withTheme, isMask: exportSettings?.isMask ?? false, + exportingFrame: template?.thumbnailFrame, ...(filenameParts?.hasClippedFrameref ? { frameRendering: { diff --git a/src/utils/excalidrawViewUtils.ts b/src/utils/excalidrawViewUtils.ts index cf91187d..85e1c18b 100644 --- a/src/utils/excalidrawViewUtils.ts +++ b/src/utils/excalidrawViewUtils.ts @@ -763,17 +763,21 @@ export function renderContextMenuAction( onClose: (callback?: () => void) => void, actionId?: string, checked: boolean = false, + description?: string, + disabled = false, ) { return React.createElement( "li", { key: nanoid(), - onClick: () => onClose(action), + onClick: () => { if (!disabled) onClose(action); }, "data-testid": actionId, }, React.createElement( "button", { + disabled, + title: description, className: checked ? "context-menu-item checkmark" : "context-menu-item", diff --git a/src/utils/frameMetadata.ts b/src/utils/frameMetadata.ts new file mode 100644 index 00000000..c0136011 --- /dev/null +++ b/src/utils/frameMetadata.ts @@ -0,0 +1,75 @@ +/** Named frame metadata is Markdown-owned; scene IDs are used only for live navigation. */ +import type { ExcalidrawElement, ExcalidrawFrameElement } from "@zsviczian/excalidraw/types/element/src/types"; +import { parseYaml } from "obsidian"; + +export const FRAME_ANCHORS_PROPERTY = "excalidraw-anchors"; +export const FRAME_THUMBNAIL_PROPERTY = "excalidraw-thumbnail"; + +/** Return both regular and marker frames in scene order, excluding deleted elements. */ +export function getSceneFrames(elements: readonly ExcalidrawElement[]): ExcalidrawFrameElement[] { + return elements.filter((element): element is ExcalidrawFrameElement => element.type === "frame" && !element.isDeleted); +} + +/** Preserve actual names verbatim; the editor's unnamed-frame fallback is not metadata. */ +export function getFrameAnchors(elements: readonly ExcalidrawElement[]): string[] { + return [...new Set(getSceneFrames(elements).map(frame => frame.name).filter(name => typeof name === "string" && name.trim().length > 0))]; +} + +/** Resolve a YAML name exactly, with no arbitrary choice between duplicates. */ +export function resolveThumbnailFrame(elements: readonly ExcalidrawElement[], name: unknown): ExcalidrawFrameElement | null { + if (typeof name !== "string" || !name.trim()) return null; + const frames = getSceneFrames(elements).filter(frame => frame.name === name); + const frame = frames.length === 1 ? frames[0] : null; + return frame && [frame.x, frame.y, frame.width, frame.height].every(Number.isFinite) && frame.width > 0 && frame.height > 0 ? frame : null; +} + +function frontmatter(text: string): { from: number; to: number; content: string; values: Record; newline: string } | null { + const open = text.match(/^(?:\uFEFF)?---(\r?\n)/); + if (!open) return null; + const closing = /^---(?:\r?\n|$)/gm; closing.lastIndex = open[0].length; + const end = closing.exec(text); + if (!end) return null; + const content = text.slice(open[0].length, end.index).replace(/\r?\n$/, ""); + try { + const values: unknown = parseYaml(content) ?? {}; + if (typeof values !== "object" || Array.isArray(values)) return null; + return { from: open[0].length, to: end.index, content, values: values as Record, newline: open[1] }; + } catch { return null; } +} + +/** Read saved YAML directly when a cache entry may still describe an earlier write. */ +export function readFrameProperty(text: string, key = FRAME_THUMBNAIL_PROPERTY): unknown { + return frontmatter(text)?.values[key]; +} + +/** + * Change only one frame property block, preserving all other YAML bytes and order. + * Existing keys stay in place. New keys follow the current writer's prepend rule; + * the optional placement argument also supports callers with an append policy. + */ +export function writeFrameProperty(text: string, key: string, value: string | readonly string[] | undefined, prepend = true): string { + if (key !== FRAME_ANCHORS_PROPERTY && key !== FRAME_THUMBNAIL_PROPERTY) return text; + const fm = frontmatter(text); + if (!fm || JSON.stringify(fm.values[key]) === JSON.stringify(value)) return text; + const lines = fm.content ? fm.content.split(fm.newline) : []; + const start = lines.findIndex(line => new RegExp(`^(?:${key}|"${key}"|'${key}')\\s*:`).test(line)); + const serialized = value === undefined ? [] : Array.isArray(value) + ? [key + ":", ...value.map(name => " - " + JSON.stringify(name))] + : [key + ": " + JSON.stringify(value)]; + if (start >= 0) { + let end = start + 1; + while (end < lines.length && (/^\s+\S/.test(lines[end]) || /^-\s/.test(lines[end]) || !lines[end].trim())) end++; + lines.splice(start, end - start, ...serialized); + } else { + if (value === undefined || Object.hasOwn(fm.values, key)) return text; + if (prepend) lines.unshift(...serialized); else lines.push(...serialized); + } + const content = lines.join(fm.newline); + return text.slice(0, fm.from) + content + (content ? fm.newline : "") + text.slice(fm.to); +} + +/** Synchronize the captured save scene without introducing empty properties on plain drawings. */ +export function syncFrameAnchors(text: string, elements: readonly ExcalidrawElement[], prepend = true): string { + const names = getFrameAnchors(elements); + return writeFrameProperty(text, FRAME_ANCHORS_PROPERTY, names.length ? names : undefined, prepend); +} diff --git a/src/utils/obsidianUtils.ts b/src/utils/obsidianUtils.ts index b214263b..402a4239 100644 --- a/src/utils/obsidianUtils.ts +++ b/src/utils/obsidianUtils.ts @@ -699,6 +699,7 @@ export function strictArrayBuffer( // 1. Map your custom 'type' strings to actual TypeScript types type FrontmatterTypeMap = { text: string; + multitext: string[]; checkbox: boolean; number: number; }; diff --git a/src/utils/utils.ts b/src/utils/utils.ts index cddcece8..47b51882 100644 --- a/src/utils/utils.ts +++ b/src/utils/utils.ts @@ -1,4 +1,5 @@ import { App, Notice, request, requestUrl, TFile } from "obsidian"; +import { readFrameProperty } from "./frameMetadata"; import { Random } from "roughjs/bin/math"; import { AppState, @@ -263,7 +264,7 @@ export async function getSVG( exportSettings.frameRendering?.enabled && !allowFramePadding ? 0 : padding, - exportingFrame: null, + exportingFrame: exportSettings.exportingFrame ?? null, renderEmbeddables: true, skipInliningFonts: exportSettings.skipInliningFonts, }); @@ -348,6 +349,7 @@ export async function getPNG( : {}), } as AppState, files: filterFiles(files), + exportingFrame: exportSettings.exportingFrame ?? null, exportPadding: exportSettings.frameRendering?.enabled && !allowFramePadding ? 0 @@ -384,6 +386,11 @@ export async function getQuickImagePreview( if (!plugin.settings.displayExportedImageIfAvailable) { return null; } + const source = plugin.app.vault.getFileByPath(path); + if (source) { + const thumbnail = readFrameProperty(await plugin.app.vault.cachedRead(source)); + if (typeof thumbnail === "string" && thumbnail.trim()) return null; + } const imagePath = getIMGFilename(path, extension); const file = plugin.app.vault.getAbstractFileByPath(imagePath); if (!file || !(file instanceof TFile)) { diff --git a/src/view/ExcalidrawView.ts b/src/view/ExcalidrawView.ts index cb2fbd7e..5e291847 100644 --- a/src/view/ExcalidrawView.ts +++ b/src/view/ExcalidrawView.ts @@ -1,3 +1,5 @@ +import { syncFrameAnchors, readFrameProperty, resolveThumbnailFrame } from "src/utils/frameMetadata"; +import { FrameThumbnailController } from "./managers/FrameThumbnailController"; import { Editor, TextFileView, @@ -473,6 +475,7 @@ export default class ExcalidrawView private linkNavigationManager: ViewLinkNavigationManager; private excalidrawExtensionRenderer: ViewExcalidrawExtensionRenderer; private markdownImageController: MarkdownImageController; + public readonly frameThumbnail: FrameThumbnailController; private sceneFileManager: ViewSceneFileManager; private saveCoordinator: ViewSaveCoordinator; private sameFileEditGate: SameFileEditGate; @@ -726,6 +729,8 @@ export default class ExcalidrawView openExportImageDialog: () => this.actionOpenExportImageDialog(), }, ); + this.frameThumbnail = new FrameThumbnailController(this, MultiOptionConfirmationPrompt); + this.register(() => this.frameThumbnail.reset()); this.markdownImageController = new MarkdownImageController(this, { isMarkdownImageElement, getMarkdownImageCustomData, @@ -1434,9 +1439,15 @@ export default class ExcalidrawView this.exportDialog.dirty = false; } - const header = syncMarkdownImagesInHeader( - getExcalidrawMarkdownHeaderSection(sourceTextSnapshot, keys), - this.excalidrawData.markdownImages, + const header = this.frameThumbnail.applyHeader( + syncFrameAnchors( + syncMarkdownImagesInHeader( + getExcalidrawMarkdownHeaderSection(sourceTextSnapshot, keys), + this.excalidrawData.markdownImages, + ), + scene.elements, + ), + scene.elements, ); const tail = this.plugin.settings.zoteroCompatibility ? (RE_TAIL.exec(sourceTextSnapshot)?.[1] ?? "") @@ -2378,6 +2389,7 @@ export default class ExcalidrawView } async onUnloadFile(): Promise { + this.frameThumbnail.reset(); //deliberately not calling super.onUnloadFile() to avoid autosave (saved in unload) this.invalidateSetViewDataLoad(); this.markdownImageController.cancelPendingConversion(); @@ -6111,6 +6123,7 @@ export default class ExcalidrawView } this.previousSceneVersion = this.getSceneVersion(et); this.setTrackedAppStateBaseline(st); + this.frameThumbnail.update(et, true); this.canvasColorChangeHook(st); return; } @@ -6154,6 +6167,7 @@ export default class ExcalidrawView this.checkSceneVersion(et); } + this.frameThumbnail.update(et); handleMarkdownImageEditorSelection(this, et, st.selectedElementIds); this.triggerSceneChangeHooks(et, st, files); } @@ -7168,6 +7182,21 @@ export default class ExcalidrawView ); const areElementsSelected = selectedElementIds.length > 0; + if (!appState.viewModeEnabled && !this.compatibilityMode && selectedElementIds.length === 1) { + const frame = elements.find(element => element.id === selectedElementIds[0] && element.type === "frame" && !element.isDeleted); + if (frame?.type === "frame") { + const thumbnail = resolveThumbnailFrame(elements, readFrameProperty(this.data)); + const clear = thumbnail?.id === frame.id; + const enabled = clear || resolveThumbnailFrame(elements, frame.name)?.id === frame.id; + contextMenuActions.push([renderContextMenuAction( + React, t(clear ? "FRAME_CLEAR_THUMBNAIL" : "FRAME_SET_THUMBNAIL"), + () => { void this.frameThumbnail.setThumbnail(clear ? undefined : frame.name, readFrameProperty(this.data), clear ? undefined : frame.id); }, + onClose, "drawingThumbnail", clear, + enabled ? t("FRAME_THUMBNAIL_HELP") : t("FRAME_NEEDS_NAME"), !enabled, + )]); + } + } + if (this.isLinkSelected()) { const isFormula = !this.getSelectedTextElement()?.id && diff --git a/src/view/managers/FrameThumbnailController.ts b/src/view/managers/FrameThumbnailController.ts new file mode 100644 index 00000000..d2eccacf --- /dev/null +++ b/src/view/managers/FrameThumbnailController.ts @@ -0,0 +1,147 @@ +import { Notice, type TFile } from "obsidian"; +import type { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types"; +import type ExcalidrawView from "../ExcalidrawView"; +import type { MultiOptionConfirmationPrompt } from "src/shared/Dialogs/Prompt"; +import { t } from "src/lang/helpers"; +import { getSceneFrames, readFrameProperty, resolveThumbnailFrame, writeFrameProperty, FRAME_THUMBNAIL_PROPERTY } from "src/utils/frameMetadata"; +import type { ThumbnailRenamePolicy } from "src/types/frameTypes"; +import { errorlog } from "src/utils/coreUtils"; +import { FrameNavigator } from "src/shared/Dialogs/FrameNavigator"; + +/** View-owned name tracking, prompts and save-time YAML edits; never owns a scene hook. */ +export class FrameThumbnailController { + private file: TFile | null = null; + private tracked: { id: string; expected: string; ignored?: string } | null = null; + private signature = ""; + private generation = 0; + private running = false; + private prompt: MultiOptionConfirmationPrompt | null = null; + private patch: { file: TFile; expected: unknown; name: string | undefined; id?: string } | null = null; + private navigator: FrameNavigator | null = null; + + constructor(private readonly view: ExcalidrawView, private readonly Prompt: typeof MultiOptionConfirmationPrompt) {} + + /** Seed on load; thereafter only actual frame/name or YAML changes invalidate a prompt. */ + update(elements: readonly ExcalidrawElement[], initial = false): void { + const view = this.view, yaml = readFrameProperty(view.data), frames = getSceneFrames(elements); + const signature = JSON.stringify([yaml, frames.map(frame => [frame.id, frame.name])]); + if (initial || this.file !== view.file) { + this.reset(); this.file = view.file; this.signature = signature; + const frame = resolveThumbnailFrame(elements, yaml); + if (frame) this.tracked = { id: frame.id, expected: frame.name }; + return; + } + if (signature === this.signature) return; + this.signature = signature; this.generation++; this.prompt?.close(); + // A Vault write can become visible before forceSave settles. Keep the live + // frame identity across our own property transition, including rapid undo. + const ownTransition = this.patch?.file === view.file && + (yaml === this.patch.expected || yaml === this.patch.name); + if (ownTransition) return; + if (!this.tracked || yaml !== this.tracked.expected) { + const frame = resolveThumbnailFrame(elements, yaml); + this.tracked = frame ? { id: frame.id, expected: frame.name } : null; + return; + } + const frame = frames.find(frame => frame.id === this.tracked.id); + if (!frame) { this.tracked = null; return; } + void this.reconcile(); + } + + private current(file: TFile, api: ExcalidrawView["excalidrawAPI"]): boolean { + return this.view.file === file && this.view.excalidrawAPI === api && !this.view.isClosingOrMigrating() && + this.view.plugin._loaded && this.view.app.vault.getFileByPath(file.path) === file; + } + + private async reconcile(): Promise { + if (this.running || !this.tracked || !this.file) return; + const track = this.tracked, file = this.file, api = this.view.excalidrawAPI; + const frame = getSceneFrames(this.view.getViewElements()).find(frame => frame.id === track.id); + if (!frame?.name?.trim() || frame.name === track.expected || frame.name === track.ignored || !this.current(file, api)) return; + const generation = this.generation, name = frame.name; + this.running = true; + try { + let policy = this.view.plugin.settings.thumbnailRenamePolicy; + if (policy === "unset") { + const prompt = new this.Prompt(this.view.plugin, t("FRAME_RENAME_POLICY"), new Map([ + [t("FRAME_RENAME_ALWAYS"), "always"], [t("FRAME_RENAME_ASK"), "ask"], [t("FRAME_RENAME_NEVER"), "never"], + ])); + this.prompt = prompt; + policy = await prompt.waitForClose; + this.prompt = null; + if (!policy) { if (generation === this.generation) track.ignored = name; return; } + if (generation !== this.generation || !this.current(file, api)) return; + this.view.plugin.settings.thumbnailRenamePolicy = policy; + await this.view.plugin.saveSettings(); + } + if (generation !== this.generation || !this.current(file, api)) return; + let update = policy === "always"; + if (policy === "ask") { + const prompt = new this.Prompt(this.view.plugin, t("FRAME_RENAME_CONFIRM")); + this.prompt = prompt; update = await prompt.waitForClose === true; this.prompt = null; + } + if (generation !== this.generation || !this.current(file, api)) return; + track.ignored = name; + if (update && await this.setThumbnail(name, track.expected, track.id)) { + track.expected = name; track.ignored = undefined; + } + } catch (error: unknown) { + track.ignored = name; + errorlog({ where: "FrameThumbnailController.rename", error }); + } finally { + this.running = false; + void this.reconcile(); + } + } + + /** Queue a conditional header edit through this view's existing save coordinator. */ + async setThumbnail(name: string | undefined, expected: unknown = readFrameProperty(this.view.data), id?: string): Promise { + const view = this.view, file = view.file, api = view.excalidrawAPI; + if (!file || view.compatibilityMode || this.patch || !this.current(file, api)) return false; + const frame = name === undefined ? null : resolveThumbnailFrame(view.getViewElements(), name); + if (name !== undefined && !frame) { new Notice(t("FRAME_NEEDS_NAME")); return false; } + const source = await view.app.vault.read(file); + if (!this.current(file, api) || source !== view.data || readFrameProperty(source) !== expected) return false; + const patch = { file, expected, name, id: id ?? frame?.id }; + this.patch = patch; + try { + view.setDirty(); await view.forceSave(true, true); + if (!this.current(file, api)) return false; + const saved = readFrameProperty(await view.app.vault.read(file)) === name; + if (saved && this.current(file, api)) { + if (name === undefined) this.tracked = null; + else if (this.tracked?.id === patch.id) this.tracked.expected = name; + else if (patch.id) this.tracked = { id: patch.id, expected: name }; + } + return saved; + } finally { + if (this.patch === patch) this.patch = null; + void this.reconcile(); + } + } + + /** Called only with the scene and header captured by the same save operation. */ + applyHeader(header: string, elements: readonly ExcalidrawElement[]): string { + const patch = this.patch; + if (!patch || patch.file !== this.view.file || readFrameProperty(header) !== patch.expected) return header; + if (patch.name !== undefined) { + const frame = resolveThumbnailFrame(elements, patch.name); + if (!frame || patch.id && frame.id !== patch.id) return header; + } + return writeFrameProperty(header, FRAME_THUMBNAIL_PROPERTY, patch.name); + } + + /** File changes, migration and unload retire prompts without a late write. */ + reset(): void { + this.generation++; this.file = null; this.tracked = null; this.patch = null; this.signature = ""; + this.prompt?.close(); this.prompt = null; + this.navigator?.close(); this.navigator = null; + } + + /** Open one owned frame navigator in the drawing's active window. */ + navigate(): void { + this.navigator?.close(); + this.navigator = new FrameNavigator(this.view, () => { this.navigator = null; }); + this.navigator.open(); + } +} diff --git a/tests/features.json b/tests/features.json index fe26a0b8..3f81b106 100644 --- a/tests/features.json +++ b/tests/features.json @@ -90,6 +90,22 @@ { "path": "src/view/managers/ViewSaveCoordinator.ts", "symbol": "export class ViewSaveCoordinator" + }, + { + "path": "src/utils/frameMetadata.ts", + "symbol": "export function syncFrameAnchors" + }, + { + "path": "src/view/managers/FrameThumbnailController.ts", + "symbol": "export class FrameThumbnailController" + }, + { + "path": "src/shared/Dialogs/FrameNavigator.ts", + "symbol": "export class FrameNavigator" + }, + { + "path": "src/core/editor/embedFrame.ts", + "symbol": "export function rewriteEmbedFrame" } ], "tests": [ @@ -142,6 +158,74 @@ "cases": [ "native:cold-durable-restoration" ] + }, + { + "layer": "source", + "path": "scripts/testing/frameMetadata.source.test.mjs", + "cases": [ + "node:scripts/testing/frameMetadata.source.test.mjs::frame anchors include actual regular and marker names, preserving order and punctuation", + "node:scripts/testing/frameMetadata.source.test.mjs::frame metadata replaces only its own multiline property and leaves invalid YAML untouched", + "node:scripts/testing/frameMetadata.source.test.mjs::thumbnail YAML uses exact unique names and supports manual edits, commas and suffixes" + ] + }, + { + "layer": "source", + "path": "scripts/testing/framePreview.source.test.mjs", + "cases": [ + "node:scripts/testing/framePreview.source.test.mjs::default thumbnails resolve exact YAML names while explicit whole/frame and ordinary exports retain precedence", + "node:scripts/testing/framePreview.source.test.mjs::missing, ambiguous and invalid thumbnails fall back to the complete scene", + "node:scripts/testing/framePreview.source.test.mjs::PNG and SVG preview exports forward strict frame cropping without changing full-scene export defaults" + ] + }, + { + "layer": "source", + "path": "scripts/testing/frameThumbnailController.source.test.mjs", + "cases": [ + "node:scripts/testing/frameThumbnailController.source.test.mjs::thumbnail rename follows always policy and undo/redo without replacing user hooks or unknown settings", + "node:scripts/testing/frameThumbnailController.source.test.mjs::first rename persists a selected policy and ask allows a different decision on subsequent renames", + "node:scripts/testing/frameThumbnailController.source.test.mjs::cancelling first-rename policy does not reopen a prompt on unchanged selection or scene updates", + "node:scripts/testing/frameThumbnailController.source.test.mjs::a rename reverted while its own YAML write settles keeps tracking the same frame", + "node:scripts/testing/frameThumbnailController.source.test.mjs::a context-menu thumbnail choice establishes identity before the next scene event renames it", + "node:scripts/testing/frameThumbnailController.source.test.mjs::external YAML changes, blank names and retired views cannot be overwritten by a pending rename" + ] + }, + { + "layer": "source", + "path": "scripts/testing/frameNavigator.source.test.mjs", + "cases": [ + "node:scripts/testing/frameNavigator.source.test.mjs::frame navigation preserves search and mode, distinguishes unnamed frames and rejects retired owners" + ] + }, + { + "layer": "source", + "path": "scripts/testing/embedFrame.source.test.mjs", + "cases": [ + "node:scripts/testing/embedFrame.source.test.mjs::frame selection preserves raw paths, clipping, dimensions, titles, padding and escaped table aliases", + "node:scripts/testing/embedFrame.source.test.mjs::frame selection edits only the owned occurrence and is one undo step" + ] + }, + { + "layer": "native", + "path": "scripts/testing/host/frameSemantics.mjs", + "cases": [ + "native:frames:main:metadata", + "native:frames:main:navigation", + "native:frames:main:previews", + "native:frames:main:controls", + "native:frames:popout:metadata", + "native:frames:popout:navigation", + "native:frames:popout:previews", + "native:frames:popout:controls", + "native:frames:settings-reload", + "native:frames:phone:metadata", + "native:frames:phone:navigation", + "native:frames:phone:previews", + "native:frames:phone:controls", + "native:frames:tablet:metadata", + "native:frames:tablet:navigation", + "native:frames:tablet:previews", + "native:frames:tablet:controls" + ] } ], "fixtures": [ @@ -419,6 +503,22 @@ { "path": "src/core/managers/DrawingEmbedPaddingControl.ts", "symbol": "DrawingEmbedPaddingControl" + }, + { + "path": "src/utils/frameMetadata.ts", + "symbol": "export function syncFrameAnchors" + }, + { + "path": "src/view/managers/FrameThumbnailController.ts", + "symbol": "export class FrameThumbnailController" + }, + { + "path": "src/shared/Dialogs/FrameNavigator.ts", + "symbol": "export class FrameNavigator" + }, + { + "path": "src/core/editor/embedFrame.ts", + "symbol": "export function rewriteEmbedFrame" } ], "tests": [ @@ -734,6 +834,74 @@ "native:embed-regressions:popout:detached", "native:embed-regressions:popout:padding" ] + }, + { + "layer": "source", + "path": "scripts/testing/frameMetadata.source.test.mjs", + "cases": [ + "node:scripts/testing/frameMetadata.source.test.mjs::frame anchors include actual regular and marker names, preserving order and punctuation", + "node:scripts/testing/frameMetadata.source.test.mjs::frame metadata replaces only its own multiline property and leaves invalid YAML untouched", + "node:scripts/testing/frameMetadata.source.test.mjs::thumbnail YAML uses exact unique names and supports manual edits, commas and suffixes" + ] + }, + { + "layer": "source", + "path": "scripts/testing/framePreview.source.test.mjs", + "cases": [ + "node:scripts/testing/framePreview.source.test.mjs::default thumbnails resolve exact YAML names while explicit whole/frame and ordinary exports retain precedence", + "node:scripts/testing/framePreview.source.test.mjs::missing, ambiguous and invalid thumbnails fall back to the complete scene", + "node:scripts/testing/framePreview.source.test.mjs::PNG and SVG preview exports forward strict frame cropping without changing full-scene export defaults" + ] + }, + { + "layer": "source", + "path": "scripts/testing/frameThumbnailController.source.test.mjs", + "cases": [ + "node:scripts/testing/frameThumbnailController.source.test.mjs::thumbnail rename follows always policy and undo/redo without replacing user hooks or unknown settings", + "node:scripts/testing/frameThumbnailController.source.test.mjs::first rename persists a selected policy and ask allows a different decision on subsequent renames", + "node:scripts/testing/frameThumbnailController.source.test.mjs::cancelling first-rename policy does not reopen a prompt on unchanged selection or scene updates", + "node:scripts/testing/frameThumbnailController.source.test.mjs::a rename reverted while its own YAML write settles keeps tracking the same frame", + "node:scripts/testing/frameThumbnailController.source.test.mjs::a context-menu thumbnail choice establishes identity before the next scene event renames it", + "node:scripts/testing/frameThumbnailController.source.test.mjs::external YAML changes, blank names and retired views cannot be overwritten by a pending rename" + ] + }, + { + "layer": "source", + "path": "scripts/testing/frameNavigator.source.test.mjs", + "cases": [ + "node:scripts/testing/frameNavigator.source.test.mjs::frame navigation preserves search and mode, distinguishes unnamed frames and rejects retired owners" + ] + }, + { + "layer": "source", + "path": "scripts/testing/embedFrame.source.test.mjs", + "cases": [ + "node:scripts/testing/embedFrame.source.test.mjs::frame selection preserves raw paths, clipping, dimensions, titles, padding and escaped table aliases", + "node:scripts/testing/embedFrame.source.test.mjs::frame selection edits only the owned occurrence and is one undo step" + ] + }, + { + "layer": "native", + "path": "scripts/testing/host/frameSemantics.mjs", + "cases": [ + "native:frames:main:metadata", + "native:frames:main:navigation", + "native:frames:main:previews", + "native:frames:main:controls", + "native:frames:popout:metadata", + "native:frames:popout:navigation", + "native:frames:popout:previews", + "native:frames:popout:controls", + "native:frames:settings-reload", + "native:frames:phone:metadata", + "native:frames:phone:navigation", + "native:frames:phone:previews", + "native:frames:phone:controls", + "native:frames:tablet:metadata", + "native:frames:tablet:navigation", + "native:frames:tablet:previews", + "native:frames:tablet:controls" + ] } ], "fixtures": [ diff --git a/tests/inventory.json b/tests/inventory.json index 7236a447..80008ee6 100644 --- a/tests/inventory.json +++ b/tests/inventory.json @@ -147,239 +147,244 @@ "line": 793 }, { - "name": "fullscreen", + "name": "navigate-to-frame", "path": "src/core/managers/CommandManager.ts", "line": 811 }, + { + "name": "fullscreen", + "path": "src/core/managers/CommandManager.ts", + "line": 822 + }, { "name": "disable-binding", "path": "src/core/managers/CommandManager.ts", - "line": 833 + "line": 844 }, { "name": "disable-framerendering", "path": "src/core/managers/CommandManager.ts", - "line": 851 + "line": 862 }, { "name": "frame-settings", "path": "src/core/managers/CommandManager.ts", - "line": 869 + "line": 880 }, { "name": "copy-link-to-drawing", "path": "src/core/managers/CommandManager.ts", - "line": 887 + "line": 898 }, { "name": "disable-frameclipping", "path": "src/core/managers/CommandManager.ts", - "line": 905 + "line": 916 }, { "name": "export-image", "path": "src/core/managers/CommandManager.ts", - "line": 923 + "line": 934 }, { "name": "save", "path": "src/core/managers/CommandManager.ts", - "line": 944 + "line": 955 }, { "name": "toggle-lock", "path": "src/core/managers/CommandManager.ts", - "line": 957 + "line": 968 }, { "name": "scriptengine-store", "path": "src/core/managers/CommandManager.ts", - "line": 978 + "line": 989 }, { "name": "delete-file", "path": "src/core/managers/CommandManager.ts", - "line": 992 + "line": 1003 }, { "name": "convert-text2MD", "path": "src/core/managers/CommandManager.ts", - "line": 1023 + "line": 1034 }, { "name": "insert-link", "path": "src/core/managers/CommandManager.ts", - "line": 1054 + "line": 1065 }, { "name": "insert-cmd", "path": "src/core/managers/CommandManager.ts", - "line": 1077 + "line": 1088 }, { "name": "insert-link-to-element", "path": "src/core/managers/CommandManager.ts", - "line": 1099 + "line": 1110 }, { "name": "insert-link-to-element-group", "path": "src/core/managers/CommandManager.ts", - "line": 1117 + "line": 1128 }, { "name": "insert-link-to-element-frame", "path": "src/core/managers/CommandManager.ts", - "line": 1135 + "line": 1146 }, { "name": "insert-link-to-element-frame-clipped", "path": "src/core/managers/CommandManager.ts", - "line": 1153 + "line": 1164 }, { "name": "insert-link-to-element-area", "path": "src/core/managers/CommandManager.ts", - "line": 1171 + "line": 1182 }, { "name": "toggle-lefthanded-mode", "path": "src/core/managers/CommandManager.ts", - "line": 1189 + "line": 1200 }, { "name": "toggle-enable-context-menu", "path": "src/core/managers/CommandManager.ts", - "line": 1218 + "line": 1229 }, { "name": "flip-image", "path": "src/core/managers/CommandManager.ts", - "line": 1233 + "line": 1244 }, { "name": "duplicate-image", "path": "src/core/managers/CommandManager.ts", - "line": 1293 + "line": 1304 }, { "name": "reset-image-to-100", "path": "src/core/managers/CommandManager.ts", - "line": 1358 + "line": 1369 }, { "name": "reset-image-ar", "path": "src/core/managers/CommandManager.ts", - "line": 1413 + "line": 1424 }, { "name": "open-link-props", "path": "src/core/managers/CommandManager.ts", - "line": 1456 + "line": 1467 }, { "name": "convert-card-to-file", "path": "src/core/managers/CommandManager.ts", - "line": 1499 + "line": 1510 }, { "name": "insert-active-pdfpage", "path": "src/core/managers/CommandManager.ts", - "line": 1536 + "line": 1547 }, { "name": "crop-image", "path": "src/core/managers/CommandManager.ts", - "line": 1602 + "line": 1613 }, { "name": "annotate-image", "path": "src/core/managers/CommandManager.ts", - "line": 1937 + "line": 1948 }, { "name": "insert-editable-markdown-image", "path": "src/core/managers/CommandManager.ts", - "line": 2233 + "line": 2244 }, { "name": "edit-selected-markdown-image", "path": "src/core/managers/CommandManager.ts", - "line": 2248 + "line": 2259 }, { "name": "refresh-scene-images", "path": "src/core/managers/CommandManager.ts", - "line": 2271 + "line": 2282 }, { "name": "insert-image", "path": "src/core/managers/CommandManager.ts", - "line": 2297 + "line": 2308 }, { "name": "import-svg", "path": "src/core/managers/CommandManager.ts", - "line": 2315 + "line": 2326 }, { "name": "release-notes", "path": "src/core/managers/CommandManager.ts", - "line": 2333 + "line": 2344 }, { "name": "view-autostart-scripts", "path": "src/core/managers/CommandManager.ts", - "line": 2347 + "line": 2358 }, { "name": "tray-mode", "path": "src/core/managers/CommandManager.ts", - "line": 2355 + "line": 2366 }, { "name": "insert-md", "path": "src/core/managers/CommandManager.ts", - "line": 2380 + "line": 2391 }, { "name": "insert-pdf", "path": "src/core/managers/CommandManager.ts", - "line": 2398 + "line": 2409 }, { "name": "insert-pdf", "path": "src/core/managers/CommandManager.ts", - "line": 2417 + "line": 2428 }, { "name": "universal-add-file", "path": "src/core/managers/CommandManager.ts", - "line": 2448 + "line": 2459 }, { "name": "universal-card", "path": "src/core/managers/CommandManager.ts", - "line": 2470 + "line": 2481 }, { "name": "insert-LaTeX-symbol", "path": "src/core/managers/CommandManager.ts", - "line": 2488 + "line": 2499 }, { "name": "toggle-excalidraw-view", "path": "src/core/managers/CommandManager.ts", - "line": 2506 + "line": 2517 }, { "name": "convert-to-excalidraw", "path": "src/core/managers/CommandManager.ts", - "line": 2539 + "line": 2550 }, { "name": "convert-excalidraw", "path": "src/core/managers/CommandManager.ts", - "line": 2571 + "line": 2582 } ], "publicEA": [ @@ -1201,1066 +1206,1081 @@ ], "settings": [ { - "name": "showTabTitlebarButtons", - "path": "src/core/settingsDefaults.ts", - "line": 46 - }, - { - "name": "copyLinkToElemenetAnchorTo100", + "name": "thumbnailRenamePolicy", "path": "src/core/settingsDefaults.ts", "line": 47 }, { - "name": "copyFrameLinkByName", + "name": "showTabTitlebarButtons", "path": "src/core/settingsDefaults.ts", "line": 48 }, { - "name": "disableDoubleClickTextEditing", + "name": "copyLinkToElemenetAnchorTo100", "path": "src/core/settingsDefaults.ts", "line": 49 }, { - "name": "phoneFooterSafeAreaPadding", + "name": "copyFrameLinkByName", "path": "src/core/settingsDefaults.ts", "line": 50 }, { - "name": "tabletFooterSafeAreaPadding", + "name": "disableDoubleClickTextEditing", "path": "src/core/settingsDefaults.ts", "line": 51 }, { - "name": "folder", + "name": "phoneFooterSafeAreaPadding", "path": "src/core/settingsDefaults.ts", "line": 52 }, { - "name": "libraryFolderPath", + "name": "tabletFooterSafeAreaPadding", "path": "src/core/settingsDefaults.ts", "line": 53 }, { - "name": "libraryFileName", + "name": "folder", "path": "src/core/settingsDefaults.ts", "line": 54 }, { - "name": "libraryStorageMode", + "name": "libraryFolderPath", "path": "src/core/settingsDefaults.ts", "line": 55 }, { - "name": "libraryMigrationStatus", + "name": "libraryFileName", "path": "src/core/settingsDefaults.ts", "line": 56 }, { - "name": "libraryMigrationSnoozeUntil", + "name": "libraryStorageMode", "path": "src/core/settingsDefaults.ts", "line": 57 }, { - "name": "cropFolder", + "name": "libraryMigrationStatus", "path": "src/core/settingsDefaults.ts", "line": 58 }, { - "name": "annotateFolder", + "name": "libraryMigrationSnoozeUntil", "path": "src/core/settingsDefaults.ts", "line": 59 }, { - "name": "embedUseExcalidrawFolder", + "name": "cropFolder", "path": "src/core/settingsDefaults.ts", "line": 60 }, { - "name": "templateFilePath", + "name": "annotateFolder", "path": "src/core/settingsDefaults.ts", "line": 61 }, { - "name": "scriptFolderPath", + "name": "embedUseExcalidrawFolder", "path": "src/core/settingsDefaults.ts", "line": 62 }, { - "name": "allowJavaScriptFiles", + "name": "templateFilePath", "path": "src/core/settingsDefaults.ts", "line": 63 }, { - "name": "storeScriptFilesAsJavaScript", + "name": "scriptFolderPath", "path": "src/core/settingsDefaults.ts", "line": 64 }, { - "name": "fontAssetsPath", + "name": "allowJavaScriptFiles", "path": "src/core/settingsDefaults.ts", "line": 65 }, { - "name": "loadChineseFonts", + "name": "storeScriptFilesAsJavaScript", "path": "src/core/settingsDefaults.ts", "line": 66 }, { - "name": "loadJapaneseFonts", + "name": "fontAssetsPath", "path": "src/core/settingsDefaults.ts", "line": 67 }, { - "name": "loadKoreanFonts", + "name": "loadChineseFonts", "path": "src/core/settingsDefaults.ts", "line": 68 }, { - "name": "compress", + "name": "loadJapaneseFonts", "path": "src/core/settingsDefaults.ts", "line": 69 }, { - "name": "decompressForMDView", + "name": "loadKoreanFonts", "path": "src/core/settingsDefaults.ts", "line": 70 }, { - "name": "onceOffCompressFlagReset", + "name": "compress", "path": "src/core/settingsDefaults.ts", "line": 71 }, { - "name": "autosaveIntervalDesktop", + "name": "decompressForMDView", "path": "src/core/settingsDefaults.ts", "line": 72 }, { - "name": "autosaveIntervalMobile", + "name": "onceOffCompressFlagReset", "path": "src/core/settingsDefaults.ts", "line": 73 }, { - "name": "drawingFilenamePrefix", + "name": "autosaveIntervalDesktop", "path": "src/core/settingsDefaults.ts", "line": 74 }, { - "name": "drawingEmbedPrefixWithFilename", + "name": "autosaveIntervalMobile", "path": "src/core/settingsDefaults.ts", "line": 75 }, { - "name": "drawingFilnameEmbedPostfix", + "name": "drawingFilenamePrefix", "path": "src/core/settingsDefaults.ts", "line": 76 }, { - "name": "drawingFilenameDateTime", + "name": "drawingEmbedPrefixWithFilename", "path": "src/core/settingsDefaults.ts", "line": 77 }, { - "name": "useExcalidrawExtension", + "name": "drawingFilnameEmbedPostfix", "path": "src/core/settingsDefaults.ts", "line": 78 }, { - "name": "cropSuffix", + "name": "drawingFilenameDateTime", "path": "src/core/settingsDefaults.ts", "line": 79 }, { - "name": "cropPrefix", + "name": "useExcalidrawExtension", "path": "src/core/settingsDefaults.ts", "line": 80 }, { - "name": "annotateSuffix", + "name": "cropSuffix", "path": "src/core/settingsDefaults.ts", "line": 81 }, { - "name": "annotatePrefix", + "name": "cropPrefix", "path": "src/core/settingsDefaults.ts", "line": 82 }, { - "name": "annotatePreserveSize", + "name": "annotateSuffix", "path": "src/core/settingsDefaults.ts", "line": 83 }, { - "name": "displaySVGInPreview", + "name": "annotatePrefix", "path": "src/core/settingsDefaults.ts", "line": 84 }, { - "name": "previewImageType", + "name": "annotatePreserveSize", "path": "src/core/settingsDefaults.ts", "line": 85 }, { - "name": "renderingConcurrency", + "name": "displaySVGInPreview", "path": "src/core/settingsDefaults.ts", "line": 86 }, { - "name": "imageCacheRetentionDays", + "name": "previewImageType", "path": "src/core/settingsDefaults.ts", "line": 87 }, { - "name": "allowImageCache", + "name": "renderingConcurrency", "path": "src/core/settingsDefaults.ts", "line": 88 }, { - "name": "allowImageCacheInScene", + "name": "imageCacheRetentionDays", "path": "src/core/settingsDefaults.ts", "line": 89 }, { - "name": "displayExportedImageIfAvailable", + "name": "allowImageCache", "path": "src/core/settingsDefaults.ts", "line": 90 }, { - "name": "previewMatchObsidianTheme", + "name": "allowImageCacheInScene", "path": "src/core/settingsDefaults.ts", "line": 91 }, { - "name": "width", + "name": "displayExportedImageIfAvailable", "path": "src/core/settingsDefaults.ts", "line": 92 }, { - "name": "height", + "name": "previewMatchObsidianTheme", "path": "src/core/settingsDefaults.ts", "line": 93 }, { - "name": "overrideObsidianFontSize", + "name": "width", "path": "src/core/settingsDefaults.ts", "line": 94 }, { - "name": "dynamicStyling", + "name": "height", "path": "src/core/settingsDefaults.ts", "line": 95 }, { - "name": "isLeftHanded", + "name": "overrideObsidianFontSize", "path": "src/core/settingsDefaults.ts", "line": 96 }, { - "name": "desktopUIMode", + "name": "dynamicStyling", "path": "src/core/settingsDefaults.ts", "line": 97 }, { - "name": "tabletUIMode", + "name": "isLeftHanded", "path": "src/core/settingsDefaults.ts", "line": 98 }, { - "name": "phoneUIMode", + "name": "desktopUIMode", "path": "src/core/settingsDefaults.ts", "line": 99 }, { - "name": "iframeMatchExcalidrawTheme", + "name": "tabletUIMode", "path": "src/core/settingsDefaults.ts", "line": 100 }, { - "name": "matchTheme", + "name": "phoneUIMode", "path": "src/core/settingsDefaults.ts", "line": 101 }, { - "name": "matchThemeAlways", + "name": "iframeMatchExcalidrawTheme", "path": "src/core/settingsDefaults.ts", "line": 102 }, { - "name": "matchThemeTrigger", + "name": "matchTheme", "path": "src/core/settingsDefaults.ts", "line": 103 }, { - "name": "defaultMode", + "name": "matchThemeAlways", "path": "src/core/settingsDefaults.ts", "line": 104 }, { - "name": "defaultPenMode", + "name": "matchThemeTrigger", "path": "src/core/settingsDefaults.ts", "line": 105 }, { - "name": "penModeDoubleTapEraser", + "name": "defaultMode", "path": "src/core/settingsDefaults.ts", "line": 106 }, { - "name": "penModeSingleFingerPanning", + "name": "defaultPenMode", "path": "src/core/settingsDefaults.ts", "line": 107 }, { - "name": "penModeCrosshairVisible", + "name": "penModeDoubleTapEraser", "path": "src/core/settingsDefaults.ts", "line": 108 }, { - "name": "renderImageInMarkdownReadingMode", + "name": "penModeSingleFingerPanning", "path": "src/core/settingsDefaults.ts", "line": 109 }, { - "name": "renderImageInHoverPreviewForMDNotes", + "name": "penModeCrosshairVisible", "path": "src/core/settingsDefaults.ts", "line": 110 }, { - "name": "renderImageInMarkdownToPDF", + "name": "renderImageInMarkdownReadingMode", "path": "src/core/settingsDefaults.ts", "line": 111 }, { - "name": "allowPinchZoom", + "name": "renderImageInHoverPreviewForMDNotes", "path": "src/core/settingsDefaults.ts", "line": 112 }, { - "name": "allowWheelZoom", + "name": "renderImageInMarkdownToPDF", "path": "src/core/settingsDefaults.ts", "line": 113 }, { - "name": "zoomToFitOnOpen", + "name": "allowPinchZoom", "path": "src/core/settingsDefaults.ts", "line": 114 }, { - "name": "zoomToFitOnResize", + "name": "allowWheelZoom", "path": "src/core/settingsDefaults.ts", "line": 115 }, { - "name": "zoomToFitMaxLevel", + "name": "zoomToFitOnOpen", "path": "src/core/settingsDefaults.ts", "line": 116 }, { - "name": "zoomStep", + "name": "zoomToFitOnResize", "path": "src/core/settingsDefaults.ts", "line": 117 }, { - "name": "zoomMin", + "name": "zoomToFitMaxLevel", "path": "src/core/settingsDefaults.ts", "line": 118 }, { - "name": "zoomMax", + "name": "zoomStep", "path": "src/core/settingsDefaults.ts", "line": 119 }, { - "name": "openInAdjacentPane", + "name": "zoomMin", "path": "src/core/settingsDefaults.ts", "line": 120 }, { - "name": "showSecondOrderLinks", + "name": "zoomMax", "path": "src/core/settingsDefaults.ts", "line": 121 }, { - "name": "focusOnFileTab", + "name": "openInAdjacentPane", "path": "src/core/settingsDefaults.ts", "line": 122 }, { - "name": "openInMainWorkspace", + "name": "showSecondOrderLinks", "path": "src/core/settingsDefaults.ts", "line": 123 }, { - "name": "showLinkBrackets", + "name": "focusOnFileTab", "path": "src/core/settingsDefaults.ts", "line": 124 }, { - "name": "syncElementLinkWithText", + "name": "openInMainWorkspace", "path": "src/core/settingsDefaults.ts", "line": 125 }, { - "name": "linkPrefix", + "name": "showLinkBrackets", "path": "src/core/settingsDefaults.ts", "line": 126 }, { - "name": "urlPrefix", + "name": "syncElementLinkWithText", "path": "src/core/settingsDefaults.ts", "line": 127 }, { - "name": "parseTODO", + "name": "linkPrefix", "path": "src/core/settingsDefaults.ts", "line": 128 }, { - "name": "todo", + "name": "urlPrefix", "path": "src/core/settingsDefaults.ts", "line": 129 }, { - "name": "done", + "name": "parseTODO", "path": "src/core/settingsDefaults.ts", "line": 130 }, { - "name": "hoverPreviewWithoutCTRL", + "name": "todo", "path": "src/core/settingsDefaults.ts", "line": 131 }, { - "name": "linkOpacity", + "name": "done", "path": "src/core/settingsDefaults.ts", "line": 132 }, { - "name": "allowCtrlClick", + "name": "hoverPreviewWithoutCTRL", "path": "src/core/settingsDefaults.ts", "line": 133 }, { - "name": "forceWrap", + "name": "linkOpacity", "path": "src/core/settingsDefaults.ts", "line": 134 }, { - "name": "pageTransclusionCharLimit", + "name": "allowCtrlClick", "path": "src/core/settingsDefaults.ts", "line": 135 }, { - "name": "wordWrappingDefault", + "name": "forceWrap", "path": "src/core/settingsDefaults.ts", "line": 136 }, { - "name": "removeTransclusionQuoteSigns", + "name": "pageTransclusionCharLimit", "path": "src/core/settingsDefaults.ts", "line": 137 }, { - "name": "oEmbedAllowed", + "name": "wordWrappingDefault", "path": "src/core/settingsDefaults.ts", "line": 138 }, { - "name": "pngExportScale", + "name": "removeTransclusionQuoteSigns", "path": "src/core/settingsDefaults.ts", "line": 139 }, { - "name": "exportWithTheme", + "name": "oEmbedAllowed", "path": "src/core/settingsDefaults.ts", "line": 140 }, { - "name": "exportWithBackground", + "name": "pngExportScale", "path": "src/core/settingsDefaults.ts", "line": 141 }, { - "name": "exportPaddingSVG", + "name": "exportWithTheme", "path": "src/core/settingsDefaults.ts", "line": 142 }, { - "name": "exportEmbedScene", + "name": "exportWithBackground", "path": "src/core/settingsDefaults.ts", "line": 143 }, { - "name": "keepInSync", + "name": "exportPaddingSVG", "path": "src/core/settingsDefaults.ts", "line": 144 }, { - "name": "autoexportSVG", + "name": "exportEmbedScene", "path": "src/core/settingsDefaults.ts", "line": 145 }, { - "name": "autoexportPNG", + "name": "keepInSync", "path": "src/core/settingsDefaults.ts", "line": 146 }, { - "name": "autoExportLightAndDark", + "name": "autoexportSVG", "path": "src/core/settingsDefaults.ts", "line": 147 }, { - "name": "autoexportExcalidraw", + "name": "autoexportPNG", "path": "src/core/settingsDefaults.ts", "line": 148 }, { - "name": "embedType", + "name": "autoExportLightAndDark", "path": "src/core/settingsDefaults.ts", "line": 149 }, { - "name": "embedMarkdownCommentLinks", + "name": "autoexportExcalidraw", "path": "src/core/settingsDefaults.ts", "line": 150 }, { - "name": "embedWikiLink", + "name": "embedType", "path": "src/core/settingsDefaults.ts", "line": 151 }, + { + "name": "embedMarkdownCommentLinks", + "path": "src/core/settingsDefaults.ts", + "line": 152 + }, + { + "name": "embedWikiLink", + "path": "src/core/settingsDefaults.ts", + "line": 153 + }, { "name": "embedPlaceholderImage", "path": "src/core/settingsDefaults.ts", - "line": 155 - }, - { - "name": "syncExcalidraw", - "path": "src/core/settingsDefaults.ts", - "line": 156 - }, - { - "name": "compatibilityMode", - "path": "src/core/settingsDefaults.ts", "line": 157 }, { - "name": "experimentalFileType", + "name": "syncExcalidraw", "path": "src/core/settingsDefaults.ts", "line": 158 }, { - "name": "experimentalFileTag", + "name": "compatibilityMode", "path": "src/core/settingsDefaults.ts", "line": 159 }, { - "name": "experimentalLivePreview", + "name": "experimentalFileType", "path": "src/core/settingsDefaults.ts", "line": 160 }, { - "name": "fadeOutExcalidrawMarkup", + "name": "experimentalFileTag", "path": "src/core/settingsDefaults.ts", "line": 161 }, { - "name": "loadPropertySuggestions", + "name": "experimentalLivePreview", "path": "src/core/settingsDefaults.ts", "line": 162 }, { - "name": "experimentalEnableFourthFont", + "name": "fadeOutExcalidrawMarkup", "path": "src/core/settingsDefaults.ts", "line": 163 }, { - "name": "experimantalFourthFont", + "name": "loadPropertySuggestions", "path": "src/core/settingsDefaults.ts", "line": 164 }, { - "name": "addDummyTextElement", + "name": "experimentalEnableFourthFont", "path": "src/core/settingsDefaults.ts", "line": 165 }, { - "name": "zoteroCompatibility", + "name": "experimantalFourthFont", "path": "src/core/settingsDefaults.ts", "line": 166 }, { - "name": "fieldSuggester", + "name": "addDummyTextElement", "path": "src/core/settingsDefaults.ts", "line": 167 }, { - "name": "enableOnloadScripts", + "name": "zoteroCompatibility", "path": "src/core/settingsDefaults.ts", "line": 168 }, { - "name": "enableCommandLinks", + "name": "fieldSuggester", "path": "src/core/settingsDefaults.ts", "line": 169 }, { - "name": "drawingOpenCount", + "name": "enableOnloadScripts", + "path": "src/core/settingsDefaults.ts", + "line": 170 + }, + { + "name": "enableCommandLinks", "path": "src/core/settingsDefaults.ts", "line": 171 }, { - "name": "library", - "path": "src/core/settingsDefaults.ts", - "line": 172 - }, - { - "name": "library2", + "name": "drawingOpenCount", "path": "src/core/settingsDefaults.ts", "line": 173 }, { - "name": "imageElementNotice", + "name": "library", + "path": "src/core/settingsDefaults.ts", + "line": 174 + }, + { + "name": "library2", "path": "src/core/settingsDefaults.ts", "line": 175 }, + { + "name": "imageElementNotice", + "path": "src/core/settingsDefaults.ts", + "line": 177 + }, { "name": "mdSVGwidth", "path": "src/core/settingsDefaults.ts", - "line": 178 - }, - { - "name": "mdSVGmaxHeight", - "path": "src/core/settingsDefaults.ts", - "line": 179 - }, - { - "name": "mdFont", - "path": "src/core/settingsDefaults.ts", "line": 180 }, { - "name": "mdFontColor", + "name": "mdSVGmaxHeight", "path": "src/core/settingsDefaults.ts", "line": 181 }, { - "name": "mdBorderColor", + "name": "mdFont", "path": "src/core/settingsDefaults.ts", "line": 182 }, { - "name": "mdCSS", + "name": "mdFontColor", "path": "src/core/settingsDefaults.ts", "line": 183 }, { - "name": "markdownImageSettings", + "name": "mdBorderColor", "path": "src/core/settingsDefaults.ts", "line": 184 }, { - "name": "markdownImageDeletionPreference", + "name": "mdCSS", "path": "src/core/settingsDefaults.ts", "line": 185 }, { - "name": "pasteCodeBlockAs", + "name": "markdownImageSettings", "path": "src/core/settingsDefaults.ts", "line": 186 }, { - "name": "scriptEngineSettings", + "name": "markdownImageDeletionPreference", "path": "src/core/settingsDefaults.ts", "line": 187 }, + { + "name": "pasteCodeBlockAs", + "path": "src/core/settingsDefaults.ts", + "line": 188 + }, + { + "name": "scriptEngineSettings", + "path": "src/core/settingsDefaults.ts", + "line": 189 + }, { "name": "autostartScripts", "path": "src/core/settingsDefaults.ts", - "line": 195 + "line": 197 }, { "name": "autostartScriptFailures", "path": "src/core/settingsDefaults.ts", - "line": 202 + "line": 204 }, { "name": "previousRelease", "path": "src/core/settingsDefaults.ts", - "line": 205 + "line": 207 }, { "name": "showReleaseNotes", "path": "src/core/settingsDefaults.ts", - "line": 206 + "line": 208 }, { "name": "useDeclarativeSettings", "path": "src/core/settingsDefaults.ts", - "line": 207 + "line": 209 }, { "name": "excalidrawMasteryPromoCollapsed", "path": "src/core/settingsDefaults.ts", - "line": 208 + "line": 210 }, { "name": "compareManifestToPluginVersion", "path": "src/core/settingsDefaults.ts", - "line": 209 + "line": 211 }, { "name": "showNewVersionNotification", "path": "src/core/settingsDefaults.ts", - "line": 210 + "line": 212 }, { "name": "latexBoilerplate", "path": "src/core/settingsDefaults.ts", - "line": 212 + "line": 214 }, { "name": "latexPreambleLocation", "path": "src/core/settingsDefaults.ts", - "line": 213 + "line": 215 }, { "name": "taskboneEnabled", "path": "src/core/settingsDefaults.ts", - "line": 214 + "line": 216 }, { "name": "taskboneAPIkey", "path": "src/core/settingsDefaults.ts", - "line": 215 + "line": 217 }, { "name": "pinnedScripts", "path": "src/core/settingsDefaults.ts", - "line": 216 + "line": 218 }, { "name": "sidepanelTabs", "path": "src/core/settingsDefaults.ts", - "line": 217 + "line": 219 }, { "name": "customPens", "path": "src/core/settingsDefaults.ts", - "line": 218 + "line": 220 }, { "name": "numberOfCustomPens", "path": "src/core/settingsDefaults.ts", - "line": 219 + "line": 221 }, { "name": "pdfScale", "path": "src/core/settingsDefaults.ts", - "line": 220 + "line": 222 }, { "name": "pdfBorderBox", "path": "src/core/settingsDefaults.ts", - "line": 221 + "line": 223 }, { "name": "pdfFrame", "path": "src/core/settingsDefaults.ts", - "line": 222 + "line": 224 }, { "name": "pdfGapSize", "path": "src/core/settingsDefaults.ts", - "line": 223 + "line": 225 }, { "name": "pdfGroupPages", "path": "src/core/settingsDefaults.ts", - "line": 224 + "line": 226 }, { "name": "pdfLockAfterImport", "path": "src/core/settingsDefaults.ts", - "line": 225 + "line": 227 }, { "name": "pdfNumColumns", "path": "src/core/settingsDefaults.ts", - "line": 226 + "line": 228 }, { "name": "pdfNumRows", "path": "src/core/settingsDefaults.ts", - "line": 227 + "line": 229 }, { "name": "pdfDirection", "path": "src/core/settingsDefaults.ts", - "line": 228 + "line": 230 }, { "name": "pdfImportScale", "path": "src/core/settingsDefaults.ts", - "line": 229 + "line": 231 }, { "name": "gridSettings", "path": "src/core/settingsDefaults.ts", - "line": 230 + "line": 232 }, { "name": "laserSettings", "path": "src/core/settingsDefaults.ts", - "line": 231 + "line": 233 }, { "name": "embeddableMarkdownDefaults", "path": "src/core/settingsDefaults.ts", - "line": 236 + "line": 238 }, { "name": "markdownNodeOneClickEditing", "path": "src/core/settingsDefaults.ts", - "line": 237 + "line": 239 }, { "name": "canvasImmersiveEmbed", "path": "src/core/settingsDefaults.ts", - "line": 238 + "line": 240 }, { "name": "startupScriptPath", "path": "src/core/settingsDefaults.ts", - "line": 239 + "line": 241 }, { "name": "aiEnabled", "path": "src/core/settingsDefaults.ts", - "line": 240 + "line": 242 }, { "name": "aiVerboseLogging", "path": "src/core/settingsDefaults.ts", - "line": 241 + "line": 243 }, { "name": "aiProviderProfiles", "path": "src/core/settingsDefaults.ts", - "line": 242 + "line": 244 }, { "name": "aiTextModelConfigs", "path": "src/core/settingsDefaults.ts", - "line": 243 + "line": 245 }, { "name": "aiImageModelConfigs", "path": "src/core/settingsDefaults.ts", - "line": 244 + "line": 246 }, { "name": "aiDefaultTextModel", "path": "src/core/settingsDefaults.ts", - "line": 245 + "line": 247 }, { "name": "aiDefaultMultimodalModel", "path": "src/core/settingsDefaults.ts", - "line": 246 + "line": 248 }, { "name": "aiDefaultImageGenerationModel", "path": "src/core/settingsDefaults.ts", - "line": 247 + "line": 249 }, { "name": "aiDefaultMaxOutgoingTokens", "path": "src/core/settingsDefaults.ts", - "line": 248 + "line": 250 }, { "name": "aiDefaultMaxResponseTokens", "path": "src/core/settingsDefaults.ts", - "line": 249 + "line": 251 }, { "name": "modifierKeyConfig", "path": "src/core/settingsDefaults.ts", - "line": 250 + "line": 252 }, { "name": "slidingPanesSupport", "path": "src/core/settingsDefaults.ts", - "line": 254 + "line": 256 }, { "name": "areaZoomLimit", "path": "src/core/settingsDefaults.ts", - "line": 255 + "line": 257 }, { "name": "longPressDesktop", "path": "src/core/settingsDefaults.ts", - "line": 256 + "line": 258 }, { "name": "longPressMobile", "path": "src/core/settingsDefaults.ts", - "line": 257 + "line": 259 }, { "name": "doubleClickLinkOpenViewMode", "path": "src/core/settingsDefaults.ts", - "line": 258 + "line": 260 }, { "name": "rank", "path": "src/core/settingsDefaults.ts", - "line": 259 + "line": 261 }, { "name": "modifierKeyOverrides", "path": "src/core/settingsDefaults.ts", - "line": 260 + "line": 262 }, { "name": "showSplashscreen", "path": "src/core/settingsDefaults.ts", - "line": 261 + "line": 263 }, { "name": "pdfSettings", "path": "src/core/settingsDefaults.ts", - "line": 262 + "line": 264 }, { "name": "disableContextMenu", "path": "src/core/settingsDefaults.ts", - "line": 263 + "line": 265 } ], "frontmatter": [ { - "name": "excalidraw-plugin", + "name": "excalidraw-anchors", "path": "src/constants/constants.ts", "line": 314 }, { - "name": "excalidraw-export-transparent", + "name": "excalidraw-thumbnail", "path": "src/constants/constants.ts", "line": 315 }, + { + "name": "excalidraw-plugin", + "path": "src/constants/constants.ts", + "line": 316 + }, + { + "name": "excalidraw-export-transparent", + "path": "src/constants/constants.ts", + "line": 317 + }, { "name": "excalidraw-mask", "path": "src/constants/constants.ts", - "line": 320 + "line": 322 }, { "name": "excalidraw-export-dark", "path": "src/constants/constants.ts", - "line": 321 + "line": 323 }, { "name": "excalidraw-export-svgpadding", "path": "src/constants/constants.ts", - "line": 326 + "line": 328 }, { "name": "excalidraw-export-padding", "path": "src/constants/constants.ts", - "line": 331 + "line": 333 }, { "name": "excalidraw-export-pngscale", "path": "src/constants/constants.ts", - "line": 336 + "line": 338 }, { "name": "excalidraw-export-embed-scene", "path": "src/constants/constants.ts", - "line": 341 + "line": 343 }, { "name": "excalidraw-export-internal-links", "path": "src/constants/constants.ts", - "line": 346 + "line": 348 }, { "name": "excalidraw-link-prefix", "path": "src/constants/constants.ts", - "line": 351 + "line": 353 }, { "name": "excalidraw-url-prefix", "path": "src/constants/constants.ts", - "line": 356 + "line": 358 }, { "name": "excalidraw-link-brackets", "path": "src/constants/constants.ts", - "line": 361 + "line": 363 }, { "name": "excalidraw-onload-script", "path": "src/constants/constants.ts", - "line": 366 + "line": 368 }, { "name": "excalidraw-linkbutton-opacity", "path": "src/constants/constants.ts", - "line": 371 + "line": 373 }, { "name": "excalidraw-default-mode", "path": "src/constants/constants.ts", - "line": 376 + "line": 378 }, { "name": "excalidraw-font", "path": "src/constants/constants.ts", - "line": 381 + "line": 383 }, { "name": "excalidraw-font-color", "path": "src/constants/constants.ts", - "line": 382 + "line": 384 }, { "name": "excalidraw-border-color", "path": "src/constants/constants.ts", - "line": 387 + "line": 389 }, { "name": "excalidraw-css", "path": "src/constants/constants.ts", - "line": 392 + "line": 394 }, { "name": "excalidraw-autoexport", "path": "src/constants/constants.ts", - "line": 393 + "line": 395 }, { "name": "excalidraw-iframe-theme", "path": "src/constants/constants.ts", - "line": 398 + "line": 400 }, { "name": "excalidraw-embeddable-theme", "path": "src/constants/constants.ts", - "line": 403 + "line": 405 }, { "name": "excalidraw-open-md", "path": "src/constants/constants.ts", - "line": 408 + "line": 410 }, { "name": "excalidraw-embed-md", "path": "src/constants/constants.ts", - "line": 413 + "line": 415 } ], "cliCommands": [ @@ -2464,6 +2484,10 @@ "path": "scripts/testing/embedDimensions.source.test.mjs", "mode": "direct-module-or-tooling" }, + { + "path": "scripts/testing/embedFrame.source.test.mjs", + "mode": "direct-module-or-tooling" + }, { "path": "scripts/testing/embedLocales.test.mjs", "mode": "isolated-or-extracted" @@ -2492,6 +2516,22 @@ "path": "scripts/testing/features.test.mjs", "mode": "direct-module-or-tooling" }, + { + "path": "scripts/testing/frameMetadata.source.test.mjs", + "mode": "direct-module-or-tooling" + }, + { + "path": "scripts/testing/frameNavigator.source.test.mjs", + "mode": "direct-module-or-tooling" + }, + { + "path": "scripts/testing/framePreview.source.test.mjs", + "mode": "isolated-or-extracted" + }, + { + "path": "scripts/testing/frameThumbnailController.source.test.mjs", + "mode": "direct-module-or-tooling" + }, { "path": "scripts/testing/frontmatter.source.test.mjs", "mode": "direct-module-or-tooling"