diff --git a/docs/testing-evidence/embed-controls-2026-11-06.md b/docs/testing-evidence/embed-controls-2026-11-06.md index 783c97a3..4c4f07fc 100644 --- a/docs/testing-evidence/embed-controls-2026-11-06.md +++ b/docs/testing-evidence/embed-controls-2026-11-06.md @@ -15,7 +15,10 @@ The editor bridge uses public `editorInfoField`, `editorLivePreviewField` and CodeMirror DOM/source boundaries. It checks the complete source token, owning file/editor and canonical drawing/reference. It does not depend on native private widget fields, the active note, a global occurrence index or whole-file replacement. -Bindings map through prefix edits and retire on edits inside their token. +Bindings map through prefix edits and retire on edits inside their token. Native +table widgets use their public source boundary and the physical table cell; +rectangular shape, delimiter row, complete token and row/column identity must +agree before a write. Escaped table aliases also retain their displayed size. Movement changes CSS only. A completed resize uses one isolated editor history transaction. Unchanged or cancelled gestures preserve the original source bytes. @@ -27,9 +30,10 @@ unchanged. Existing wrapper layout remains responsible for alignment and percent sizing. Controls follow the visible image bounds. Cancellation restores control placement immediately; scrolling and viewport -changes remeasure it. Hover toolbars touch the image boundary so pointer travel -does not cross a disappearing hover gap. Always-visible touch toolbars occupy -normal document flow below the image. A full-width no-op keeps percentage syntax +changes and image decoding remeasure it through an owned ResizeObserver. Hover +toolbars sit inside the image because native widgets use paint containment. +Small images and always-visible touch toolbars use normal flow below the image. +A full-width no-op keeps percentage syntax instead of shrinking solely to create space for the handle. Fullscreen uses the existing exporter with the same drawing/reference and theme, @@ -41,7 +45,8 @@ prompts and modifier/reference behavior. Reading-mode controls have one plugin-owned registry in addition to their render context lifetime. Context cleanup removes each owner from the registry, and -plugin unload closes any remaining controls/viewers. A Reading export completing +plugin unload closes any remaining controls/viewers. Hidden Live Preview controls +retire when switching to Reading mode. A Reading export completing after plugin unload is discarded before touching the document. No dependency, release version, fork or Extras change is required. The unmerged @@ -86,13 +91,37 @@ loop after resizing. The latter starved the renderer's replacement timer and CLI The bridge now rejects stale generations before mounting; a bounded production bridge test reproduces and prevents the loop. A recovery build was hash-verified in the owned test vault. The stalled run remains failed, including cleanup. -It is not acceptance evidence. A restart was requested because other vaults were -open and the owned window did not respond to a normal reload. +It is not acceptance evidence. The maintainer restarted Obsidian; acknowledged +CLI recovery removed only the failed run's owned fixtures and restored the +declared baseline. Recovery evidence is retained under +`.test-work/recovery/pr3037-stale-renderer/restarted-baseline.json`. -Full native acceptance must be rerun after recovery. Exact table-widget source -mapping, same-note split panes, popout input with the main window minimized, -touch, minimum Obsidian 1.8.7, macOS, physical Android/iOS and hosted CodeScanner -remain explicit review/validation gates until actual evidence is recorded. +The focused desktop matrix passed on Windows / Obsidian 1.14.5 after recovery: +all 15 embed cases across main, split and popout contexts, with clean console, +source stability, cleanup and baseline restoration. It covers all three image +modes, repeated/same-line tokens, table cells, same-note split synchronization, +history, source selection, fullscreen keyboard controls/focus, Reading mode and +popout input with the main window minimized. Evidence: +`.test-work/reports/pr3037-controls-focused-10/report.json`. + +Trusted touch initially exposed the host's `body.emulate-mobile .clickable-icon` +rule overriding the resize handle's touch action. A scoped selector now outranks +that rule. All ten phone/tablet embed cases, including resize/history/reset, +tables, fullscreen pinch and pan, passed against the fresh frozen build: +`.test-work/reports/pr3037-phone-probe-3/report.json`. + +A repeated popout run exposed the native table cell editor activating underneath +a toolbar mouse press and retaining an extra rendered copy. Toolbar compatibility +mouse/touch events are now isolated from the table; button default activation is +preserved. Source tests and the focused popout roundtrip passed after the fix: +`.test-work/reports/pr3037-table-input-smoke/popout-probe.json`. + +Latest source suite before the event-isolation checkpoint: 716 tests in 87 files +passed. Modified embed modules have zero targeted lint or TypeScript diagnostics. +The production bundle is 5,088,586 bytes before that final small checkpoint. +Complete native and portable acceptance, minimum Obsidian 1.8.7, macOS, physical +Android/iOS and hosted CodeScanner remain explicit gates until actual evidence +is recorded. `npm run code` reports 118 existing errors outside the modified production modules; targeted lint and targeted TypeScript diagnostics pass. Production diff --git a/scripts/testing/embedBridge.source.test.mjs b/scripts/testing/embedBridge.source.test.mjs index ceea67c9..4e3066d9 100644 --- a/scripts/testing/embedBridge.source.test.mjs +++ b/scripts/testing/embedBridge.source.test.mjs @@ -10,11 +10,13 @@ test("invalid render generations cannot remount controls or starve the renderer let generation = true, loaded = 0, unloaded = 0, retireWhileMapping = false; globalThis.queueMicrotask = callback => pending.push(callback); const file = { path: "Source.md" }, drawing = { path: "Map.excalidraw.md" }, text = "![[Map.excalidraw.md|180]]"; - const editorInfoField = StateField.define({ create: () => ({ file }), update: value => value }); + class MarkdownView { mode = "source"; file = file; getMode() { return this.mode; } } + const info = new MarkdownView(), sourceContainer = { style: { display: "" } }; + const editorInfoField = StateField.define({ create: () => info, update: value => value }); const editorLivePreviewField = StateField.define({ create: () => true, update: value => value }); const doc = { defaultView: { MutationObserver: class { constructor(callback) { this.callback = callback; observers.push(this); } - observe() { this.connected = true; } + observe(target) { this.connected = true; (this.targets ??= []).push(target); } disconnect() { this.connected = false; } } } }; const frame = { isConnected: true, ownerDocument: doc }, parent = { childNodes: [] }; @@ -24,7 +26,7 @@ test("invalid render generations cannot remount controls or starve the renderer const actions = { target: drawing.path, isCurrent: () => generation }; const mutation = () => { for (const observer of observers) if (observer.connected) observer.callback(); }; const graph = sourceHarness({ - obsidian: { editorInfoField, editorLivePreviewField }, + obsidian: { editorInfoField, editorLivePreviewField, MarkdownView }, "@codemirror/view": { ...cmView, ViewPlugin: { fromClass: value => value } }, "../managers/DrawingEmbedControls": { DrawingEmbedControls: class { load() { loaded++; mutation(); } unload() { unloaded++; mutation(); } } }, "../managers/drawingEmbedActions": { getDrawingEmbedActions: () => actions }, @@ -33,14 +35,18 @@ test("invalid render generations cannot remount controls or starve the renderer const { createDrawingEmbedExtension } = await graph.importModule("src/core/editor/drawingEmbedExtension.ts"); const plugin = { isExcalidrawFile: value => value === drawing, app: { metadataCache: { getFirstLinkpathDest: () => drawing } } }; const bridge = createDrawingEmbedExtension(plugin); - const view = { dom: { ownerDocument: doc }, contentDOM, state: EditorState.create({ doc: text + "\n", extensions: [editorInfoField, editorLivePreviewField] }), + const view = { dom: { ownerDocument: doc, closest: () => sourceContainer }, contentDOM, state: EditorState.create({ doc: text + "\n", extensions: [editorInfoField, editorLivePreviewField] }), posAtDOM(el, offset) { if (retireWhileMapping) generation = false; return el === parent && offset === 1 ? text.length + 1 : 0; } }; const drain = () => { for (let i = 0; pending.length && i < 10; i++) pending.shift()(); assert.equal(pending.length, 0, "unbounded remount/mutation loop"); }; new bridge.extension(view); drain(); assert.equal(loaded, 1); - generation = false; mutation(); drain(); assert.equal(loaded, 1); assert.equal(unloaded, 1); - generation = true; mutation(); drain(); assert.equal(loaded, 2); + assert.ok(observers[0].targets.includes(sourceContainer), "source visibility changes must schedule ownership sync"); + info.mode = "preview"; mutation(); drain(); assert.equal(loaded, 1); assert.equal(unloaded, 1); + info.mode = "source"; sourceContainer.style.display = "none"; mutation(); drain(); assert.equal(loaded, 1); + sourceContainer.style.display = ""; mutation(); drain(); assert.equal(loaded, 2); + generation = false; mutation(); drain(); assert.equal(loaded, 2); assert.equal(unloaded, 2); + generation = true; mutation(); drain(); assert.equal(loaded, 3); generation = false; mutation(); drain(); - generation = true; retireWhileMapping = true; mutation(); drain(); assert.equal(loaded, 2, "source invalidated during DOM mapping was mounted"); + generation = true; retireWhileMapping = true; mutation(); drain(); assert.equal(loaded, 3, "source invalidated during DOM mapping was mounted"); bridge.dispose(); drain(); assert.ok(observers.every(observer => !observer.connected)); } finally { graph.close(); globalThis.queueMicrotask = originalQueue; } }); diff --git a/scripts/testing/embedControls.source.test.mjs b/scripts/testing/embedControls.source.test.mjs index ba077f4d..4c120b70 100644 --- a/scripts/testing/embedControls.source.test.mjs +++ b/scripts/testing/embedControls.source.test.mjs @@ -22,6 +22,19 @@ async function fixture(text = "![[Map|Alias|180x130|left]]") { } function start(f) { f.handle.fire("pointerdown", { button: 0, pointerId: 1, clientX: 180, clientY: 130 }); } +test("toolbar compatibility events cannot activate the surrounding native table cell", async () => { + const f = await fixture(); + try { + for (const name of ["mousedown", "touchstart"]) { + let stopped = false; + const event = f.toolbar.fire(name, { stopPropagation() { stopped = true; } }); + assert.equal(stopped, true); assert.equal(event.prevented, undefined); + } + assert.deepEqual(f.writes, []); assert.equal(f.selects(), 0); + f.toolbar.children[2].fire("click"); assert.equal(f.selects(), 1); + } finally { f.close(); } +}); + test("resize previews proportionally without writing, then commits once on the owned pointer release", async () => { const f = await fixture(); try { @@ -99,3 +112,18 @@ test("a full-width no-op retains percentage syntax and a replacement gesture use f.fire(f.window, "pointerup", { pointerId: 2 }); assert.deepEqual(f.writes, ["![[Map|188]]"]); } finally { f.close(); } }); + +test("late image sizing leaves the toolbar inside paint containment and remeasures the changed frame", async () => { + const f = await fixture(); + try { + f.toolbar.bounds = { ...f.toolbar.bounds, width: 142, height: 40 }; + f.frame.getBoundingClientRect = () => ({ ...f.frame.bounds, bottom: f.frame.hasClass("excalidraw-embed-controls-below") ? 170 : 130 }); + f.image.bounds = { ...f.image.bounds, bottom: 0, height: 0 }; + f.frame.fire("load"); assert.equal(f.frame.hasClass("excalidraw-embed-controls-below"), true); + f.image.bounds = { ...f.image.bounds, bottom: 130, height: 130 }; + const observer = f.observers.find(observer => observer.resize); assert.equal(observer.target, f.image); + observer.fire(); assert.equal(f.frame.hasClass("excalidraw-embed-controls-below"), false); + assert.equal(f.frame.style["--excalidraw-embed-control-top"], "0px"); + assert.equal(f.frame.style["--excalidraw-embed-control-bottom"], "-8px"); + } finally { f.close(); } +}); diff --git a/scripts/testing/embedPreview.source.test.mjs b/scripts/testing/embedPreview.source.test.mjs index 3b04cb9a..14fea3f3 100644 --- a/scripts/testing/embedPreview.source.test.mjs +++ b/scripts/testing/embedPreview.source.test.mjs @@ -63,9 +63,9 @@ test("fullscreen zoom, fit, pan and pinch own their handlers and private image l const f = fixture(), image = new Element(); f.resolve(image); await flush(); const stage = f.modal.contentEl.find("excalidraw-embed-preview-stage"), surface = stage.find("excalidraw-embed-preview-surface"); assert.ok(surface.children.includes(image)); - stage.fire("keydown", { key: "+" }); assert.equal(Number(stage.getAttribute("data-zoom")), 1.25); - stage.fire("keydown", { key: "ArrowRight" }); assert.match(surface.style.transform, /-24px/); - stage.fire("keydown", { key: "0" }); assert.equal(stage.getAttribute("data-zoom"), "1"); + f.modal.modalEl.fire("keydown", { key: "+", target: f.modal.contentEl.find("excalidraw-embed-preview-toolbar").children[0] }); assert.equal(Number(stage.getAttribute("data-zoom")), 1.25); + f.modal.modalEl.fire("keydown", { key: "ArrowRight", target: stage }); assert.match(surface.style.transform, /-24px/); + f.modal.modalEl.fire("keydown", { key: "0", target: stage }); assert.equal(stage.getAttribute("data-zoom"), "1"); stage.fire("pointerdown", { button: 0, pointerId: 1, clientX: 10, clientY: 10 }); stage.fire("pointerdown", { button: 0, pointerId: 2, clientX: 30, clientY: 10 }); stage.fire("pointermove", { pointerId: 2, clientX: 50, clientY: 10 }); diff --git a/scripts/testing/embedSource.source.test.mjs b/scripts/testing/embedSource.source.test.mjs index d0c0f7d4..b61de33b 100644 --- a/scripts/testing/embedSource.source.test.mjs +++ b/scripts/testing/embedSource.source.test.mjs @@ -6,6 +6,16 @@ import {sourceHarness} from './sourceHarness.mjs'; const graph=sourceHarness(); const {DrawingEmbedSource}=await graph.importModule('src/core/editor/embedSource.ts'); after(()=>graph.close()); + +test('a physical-cell range validator blocks stale resize and source selection without history entries',()=>{ + let state=EditorState.create({doc:'![[Map|100]]',extensions:[history()]}),allowed=false,validations=0,focused=false; + const view={get state(){return state;},dispatch(spec){state=state.update(spec).state;},focus(){focused=true;}}; + const binding=new DrawingEmbedSource(view,0,state.doc.length,state.doc.toString(),()=>true,(from,to)=>{validations++;assert.equal(state.sliceDoc(from,to),'![[Map|100]]');return allowed;}); + assert.equal(binding.replace('![[Map|108]]'),false);assert.equal(binding.select(),false);assert.equal(focused,false);assert.equal(undo(view),false); + const transaction=state.update({changes:{from:0,insert:'prefix '}});state=transaction.state;binding.map(transaction.changes); + assert.equal(validations,2,'range validation must not read pre-update DOM while mapping'); + allowed=true;assert.equal(binding.replace('![[Map|108]]'),true);assert.equal(state.doc.toString(),'prefix ![[Map|108]]'); +}); function fixture(doc='before ![[Map|200]] after ![[Map|200]]',occurrence=1){ let state=EditorState.create({doc,extensions:[history()]});let owner=true,focused=false,writes=0; const text='![[Map|200]]',from=doc.indexOf(text,occurrence===0?0:doc.indexOf(text)+1); diff --git a/scripts/testing/embedTestDOM.mjs b/scripts/testing/embedTestDOM.mjs index 2aaf55af..7c1fef5a 100644 --- a/scripts/testing/embedTestDOM.mjs +++ b/scripts/testing/embedTestDOM.mjs @@ -7,6 +7,10 @@ export function embedTestDOM() { disconnect() { this.connected = false; } fire() { if (this.connected) this.callback(); } } }; + window.ResizeObserver = class extends window.MutationObserver { + constructor(callback) { super(callback); this.resize = true; } + observe(target) { super.observe(); this.target = target; } + }; const document = { defaultView: window, activeElement: null }; class Element { constructor(options = {}) { this.children = []; this.attrs = { ...options.attr }; this.classes = new Set((options.cls || "").split(" ")); this.events = new Map(); this.style = {}; this.ownerDocument = document; this.isConnected = true; this.captures = new Set(); this.bounds = { left: 0, top: 0, right: 700, bottom: 130, width: 700, height: 130 }; } diff --git a/scripts/testing/host/embedControls.mjs b/scripts/testing/host/embedControls.mjs index 240d410a..82f58853 100644 --- a/scripts/testing/host/embedControls.mjs +++ b/scripts/testing/host/embedControls.mjs @@ -7,7 +7,7 @@ import { behaviorInputDriver } from "./behaviorMatrix.mjs"; import { completeConsoleErrors } from "./debuggerSession.mjs"; import { settleBrowserDiagnostics, splitWindowErrors } from "./browserDiagnostics.mjs"; -const casesFor = ids => ids.flatMap(id => [...["PNG", "SVGIMG", "SVG"].map(mode => `native:embed-controls:${id}:${mode}`), `native:embed-ownership:${id}`]); +const casesFor = ids => ids.flatMap(id => [...["PNG", "SVGIMG", "SVG"].map(mode => `native:embed-controls:${id}:${mode}`), `native:embed-ownership:${id}`, `native:embed-table:${id}`]); export const embedControlCaseIds = casesFor(["main", "split", "popout"]); export const embedControlDeviceCaseIds = casesFor(["phone", "tablet"]); @@ -58,32 +58,60 @@ async function exerciseEmbedControls(c, env, template, modifier) { await leaf.setViewState({ type: "markdown", state: { file: file.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(() => leaf.view.contentEl.querySelectorAll(".excalidraw-embed-toolbar").length === 3, "three owned embed toolbars"); + await c.waitFor(() => activeRoot()?.querySelectorAll(".excalidraw-embed-toolbar").length === 3, "three active owned embed toolbars"); await c.waitFor(() => frames().every(frame => { const image = frame.querySelector(".excalidraw-embedded-img"); return image?.getBoundingClientRect().height > 0 && (image.tagName !== "IMG" || image.complete && image.naturalWidth > 0); }), "decoded drawing previews with positive dimensions"); }; - const frames = () => [...leaf.view.contentEl.querySelectorAll(".excalidraw-embed-controls-frame")]; + const activeRoot = () => leaf.view.contentEl.querySelector(leaf.view.getMode?.() === "preview" ? ".markdown-preview-view" : ".markdown-source-view"); + const frames = () => [...activeRoot()?.querySelectorAll(".excalidraw-embed-controls-frame") || []]; const action = async (index, name) => { const frame = frames()[index]; check(frame, "missing embed frame " + index); frame.scrollIntoView({ block: "center" }); - const rect = frame.getBoundingClientRect(); + let rect, signature, stableSince; + await c.waitFor(() => { + rect = frames()[index]?.getBoundingClientRect(); + if (!rect?.height) return false; + const current = [rect.x, rect.y, rect.width, rect.height].map(value => Math.round(value * 10)).join(":"); + if (signature !== current) { signature = current; stableSince = Date.now(); } + return Date.now() - stableSince >= 120; + }, "embed scroll settled before hover"); if (!touch) await input("Input.dispatchMouseEvent", { type: "mouseMoved", x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 }); await click(() => frames()[index]?.querySelector(`[data-excalidraw-embed-action="${name}"]`)); }; const drag = async (index, delta, cancel = false) => { - const frame = frames()[index], handle = frame.querySelector('[data-excalidraw-embed-action="resize"]'); + let frame = frames()[index], handle = frame.querySelector('[data-excalidraw-embed-action="resize"]'); handle.focus(); handle.scrollIntoView({ block: "center" }); - const r = handle.getBoundingClientRect(), x = r.x + r.width / 2, y = r.y + r.height / 2; - const events = [], observe = event => events.push({ type: event.type, target: event.target.className, trusted: event.isTrusted, x: event.clientX, y: event.clientY }); - for (const name of ["pointerdown", "pointermove", "pointerup", "blur", "lostpointercapture"]) win.addEventListener(name, observe, true); - c.defer(() => { for (const name of ["pointerdown", "pointermove", "pointerup", "blur", "lostpointercapture"]) win.removeEventListener(name, observe, true); }); + let r, x, y, signature, stableSince; + await c.waitFor(() => { + const nextFrame = frames()[index], next = nextFrame?.querySelector('[data-excalidraw-embed-action="resize"]'); + if (!next) return false; + if (next !== handle) { frame = nextFrame; handle = next; handle.focus(); handle.scrollIntoView({ block: "center" }); } + r = handle.getBoundingClientRect(); x = r.x + r.width / 2; y = r.y + r.height / 2; + if (!handle.contains(doc.elementFromPoint(x, y))) { signature = null; return false; } + const current = [r.x, r.y, r.width, r.height].map(value => Math.round(value * 10)).join(":"); + if (signature !== current) { signature = current; stableSince = Date.now(); } + return Date.now() - stableSince >= 120; + }, "stable uncovered resize handle"); + const events = [], eventNames = ["pointerdown", "pointermove", "pointerup", "pointercancel", "touchstart", "touchmove", "blur", "lostpointercapture"]; + const observe = event => events.push({ type: event.type, target: event.target.className, trusted: event.isTrusted, x: event.clientX, y: event.clientY, prevented: event.defaultPrevented, cancelable: event.cancelable }); + for (const name of eventNames) win.addEventListener(name, observe, true); + c.defer(() => { for (const name of eventNames) win.removeEventListener(name, observe, true); }); c.observations = { ...c.observations, drag: { handle: handle.outerHTML, bounds: r.toJSON(), image: frame.querySelector(".excalidraw-embedded-img").getBoundingClientRect().toJSON(), hit: doc.elementFromPoint(x, y)?.outerHTML.slice(0, 500), events } }; + const touchRules = []; + const inspectRules = rules => { for (const rule of rules) { + if (rule.style?.touchAction && rule.selectorText && handle.matches(rule.selectorText)) touchRules.push({ selector: rule.selectorText, value: rule.style.touchAction, priority: rule.style.getPropertyPriority("touch-action") }); + if (rule.cssRules) inspectRules(rule.cssRules); + } }; + for (const sheet of doc.styleSheets) { try { inspectRules(sheet.cssRules); } catch { /* Cross-origin sheets cannot be inspected. */ } } + c.observations.drag.touchRules = touchRules; const send = (phase, point) => touch ? input("Input.dispatchTouchEvent", { type: phase === "down" ? "touchStart" : phase === "move" ? "touchMove" : "touchEnd", touchPoints: phase === "up" ? [] : [{ x: point, y, id: 1 }] }) : input("Input.dispatchMouseEvent", { type: phase === "down" ? "mousePressed" : phase === "move" ? "mouseMoved" : "mouseReleased", x: point, y, button: "left", buttons: phase === "up" ? 0 : 1, clickCount: 1 }); try { - await send("down", x); await send("move", x + delta / 2); await send("move", x + delta); + const states = c.observations.drag.states = []; + const snapshot = () => states.push({ connected: frame.isConnected, current: frame === frames()[index], classes: frame.className, handleAction: win.getComputedStyle(handle).touchAction, selection: leaf.view.editor.cm.state.selection.main.toJSON() }); + await send("down", x); snapshot(); await send("move", x + delta / 2); snapshot(); await send("move", x + delta); snapshot(); check(leaf.view.editor.getValue() === content, "pointer movement wrote source before commit"); check(frame.hasClass("excalidraw-embed-resizing"), "real pointer did not start CSS resize preview"); if (cancel) await key("Escape", "Escape", 27); @@ -135,19 +163,42 @@ async function exerciseEmbedControls(c, env, template, modifier) { let modal, stage; await c.waitFor(() => (modal = doc.querySelector(".excalidraw-embed-preview-modal")) && (stage = modal.querySelector(".excalidraw-embed-preview-stage")) && modal.querySelector(".excalidraw-embedded-img"), "fresh fullscreen payload"); check(modal.querySelector("[fileSource]")?.getAttribute("fileSource") === drawing.path, "fullscreen changed drawing identity"); + const keys = [], recordKey = event => keys.push({ key: event.key, code: event.code, target: event.target.className, trusted: event.isTrusted }); + doc.addEventListener("keydown", recordKey, true); c.defer(() => doc.removeEventListener("keydown", recordKey, true)); + c.observations = { ...c.observations, fullscreen: { focus: doc.activeElement?.outerHTML.slice(0, 500), connected: modal.isConnected, keys } }; await key("+", "Equal", 187, 8); + c.observations.fullscreen.zoom = stage.getAttribute("data-zoom"); + c.observations.fullscreen.stageConnected = stage.isConnected; check(Number(stage.getAttribute("data-zoom")) > 1, "fullscreen keyboard zoom failed"); await key("ArrowRight", "ArrowRight", 39); check(modal.querySelector(".excalidraw-embed-preview-surface").style.transform.includes("-24px"), "fullscreen keyboard pan failed"); await key("0", "Digit0", 48); check(Number(stage.getAttribute("data-zoom")) === 1, "fullscreen fit failed"); + if (touch) { + const r = stage.getBoundingClientRect(), x = r.x + r.width / 2, y = r.y + r.height / 2; + const points = distance => [{ x: x - distance, y, id: 1 }, { x: x + distance, y, id: 2 }]; + try { + await input("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: points(20) }); + await input("Input.dispatchTouchEvent", { type: "touchMove", touchPoints: points(40) }); + check(Number(stage.getAttribute("data-zoom")) > 1.25, "fullscreen trusted pinch failed"); + } finally { await input("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] }); } + await key("0", "Digit0", 48); + try { + await input("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [{ x, y, id: 1 }] }); + await input("Input.dispatchTouchEvent", { type: "touchMove", touchPoints: [{ x: x + 20, y: y + 12, id: 1 }] }); + check(modal.querySelector(".excalidraw-embed-preview-surface").style.transform.includes("20px, 12px"), "fullscreen trusted touch pan failed"); + } finally { await input("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] }); } + await key("0", "Digit0", 48); + } await key("Escape", "Escape", 27); await c.waitFor(() => !modal.isConnected, "fullscreen closes on Escape"); + doc.removeEventListener("keydown", recordKey, true); check(doc.activeElement?.getAttribute("data-excalidraw-embed-action") === "preview", "fullscreen did not restore opener focus"); check(inline.isConnected && (mode === "SVG" ? !!inline.querySelector("svg") : inline.complete && inline.naturalWidth > 0), "closing fullscreen invalidated inline payload"); check(!leaf.view.contentEl.querySelector(`.internal-embed[src="${plain.path}"] [data-excalidraw-embed-action]`), "ordinary image acquired drawing controls"); await open("preview"); - check(!leaf.view.contentEl.querySelector('[data-excalidraw-embed-action="resize"], [data-excalidraw-embed-action="edit"], [data-excalidraw-embed-action="reset"]'), "Reading mode acquired source mutation controls"); + check(!activeRoot().querySelector('[data-excalidraw-embed-action="resize"], [data-excalidraw-embed-action="edit"], [data-excalidraw-embed-action="reset"]'), "Reading mode acquired source mutation controls"); + check(!leaf.view.contentEl.querySelector('.markdown-source-view [data-excalidraw-embed-action="resize"]'), "hidden source retained editable controls after mode switch"); await action(2, "preview"); await c.waitFor(() => doc.querySelector(".excalidraw-embed-preview-modal [fileSource]")?.getAttribute("fileSource") === drawing.path + "#^as-image", "Reading fullscreen preserves reference"); await key("Escape", "Escape", 27); @@ -196,4 +247,46 @@ async function exerciseEmbedControls(c, env, template, modifier) { check(await app.vault.read(drawing) === drawingBytes, "ownership tests changed drawing content"); return { assertions: ["same-line repeated embeds target only their own token", "inline/fenced examples have no controls", "independent note and pane stay unchanged", "one-step undo", "refresh remounts controls exactly once", "switching source unloads controls and fullscreen", "drawing bytes unchanged"], actual: geometry() }; }); + + await c.case(`native:embed-table:${context}`, ["P03", "P04", "P05"], async () => { + const token = `![[${drawing.path}\\|Caption\\|100\\|left]]`; + const markdown = `![Label\\|120](<${drawing.path}#^as-image> "Keep title")`; + const source = `# Table source\n\n| Drawing | Cell |\n| --- | --- |\n| ${token} | first |\n| ${token} | second |\n| ${markdown} | third |\n\nFooter\n`; + const file = await create("Table-source.md", source); + await leaf.setViewState({ type: "markdown", state: { file: file.path, mode: "source", source: false } }); + app.workspace.setActiveLeaf(leaf, { focus: true }); + leaf.view.editor.setCursor({ line: leaf.view.editor.lastLine(), ch: 0 }); + const cm = leaf.view.editor.cm; + const ready = () => { + const current = frames(); + c.observations = { ...c.observations, table: { selection: cm.state.selection.main.toJSON(), frames: current.map(frame => ({ connected: frame.isConnected, width: frame.querySelector(".excalidraw-embedded-img")?.getAttribute("w") })), html: cm.contentDOM.querySelector(".cm-table-widget")?.outerHTML.slice(0, 10000) } }; + return current.length === 3 && current.every((frame, i) => frame.querySelector(".excalidraw-embedded-img")?.getAttribute("w") === (i === 2 ? "120" : "100")); + }; + await c.waitFor(ready, "three authoritative table cells and escaped display dimensions"); + let other; + if (!touch) { + other = app.workspace.getLeaf("split", "vertical"); env.owned.add(other); + await other.setViewState({ type: "markdown", state: { file: file.path, mode: "source", source: false } }); + other.view.editor.setCursor({ line: other.view.editor.lastLine(), ch: 0 }); + app.workspace.setActiveLeaf(other, { focus: true }); + } + frames()[1].querySelector('[data-excalidraw-embed-action="resize"]').focus(); + await key("ArrowRight", "ArrowRight", 39); + const changed = source.replace(token + " | second", token.replace("100", "108") + " | second"); + await c.waitFor(() => cm.state.doc.toString() === changed, "only the second identical physical table cell resized"); + if (other) await c.waitFor(() => other.view.editor.getValue() === changed, "same-note split receives the exact table transaction"); + cm.focus(); await key("z", "KeyZ", 90, modifier); + await c.waitFor(() => cm.state.doc.toString() === source && ready(), "one undo restores table source and rendered dimensions"); + await action(2, "edit"); + check(cm.state.sliceDoc(cm.state.selection.main.from, cm.state.selection.main.to) === markdown, "table source edit selected the wrong syntax or cell"); + leaf.view.editor.setCursor({ line: leaf.view.editor.lastLine(), ch: 0 }); + await c.waitFor(ready, "table syntax edit roundtrip"); + await action(1, "reset"); + const reset = source.replace(token + " | second", token.replace("\\|100", "") + " | second"); + await c.waitFor(() => cm.state.doc.toString() === reset, "table reset preserves escaped aliases, style, title and other cells"); + cm.focus(); await key("z", "KeyZ", 90, modifier); + await c.waitFor(() => cm.state.doc.toString() === source, "table reset is one undo step"); + check(await app.vault.read(drawing) === drawingBytes, "table controls changed the drawing file"); + return { assertions: ["native table widget public boundaries and physical cell ownership", "escaped wiki and Markdown-image dimensions render", "only second identical row changes", "same-note split synchronization", "one-step undo/reset", "exact Markdown syntax selection", "aliases/styles/title and other cells preserved", "drawing bytes unchanged"], actual: geometry() }; + }); } diff --git a/scripts/testing/markdownEmbeds.test.mjs b/scripts/testing/markdownEmbeds.test.mjs index 4cee6da6..306b8195 100644 --- a/scripts/testing/markdownEmbeds.test.mjs +++ b/scripts/testing/markdownEmbeds.test.mjs @@ -201,6 +201,14 @@ test("Reading controls are read-only and absent in nested, print, hover, Canvas } }); +test("native table alt text retains escaped caption, size and style through image generation", async () => { + const f = fixture(), parent = new f.Element(), embed = parent.appendChild(new f.Element("internal-embed")); + embed.setAttribute("src", "target.excalidraw.md"); embed.setAttribute("alt", "Caption\\|100\\|left"); + const rendered = f.processor.processReadingMode([embed], f.ctx), job = f.start(); + assert.equal(f.requests[0].attr.fwidth, "100"); assert.deepEqual([...f.requests[0].attr.imgstyle], ["excalidraw-svg-left"]); + await f.settle(); await job; await rendered; +}); + test("ready follows successful insertion; repeated callbacks preserve the image", async () => { const f = fixture(); const first = f.render(); const repeat = f.render(); assert.equal(f.container.hasAttribute("ready"), false); assert.equal(f.jobs.length, 1); assert.equal(f.children.length, 1); diff --git a/scripts/testing/tableEmbedSource.source.test.mjs b/scripts/testing/tableEmbedSource.source.test.mjs new file mode 100644 index 00000000..0c9d3ae7 --- /dev/null +++ b/scripts/testing/tableEmbedSource.source.test.mjs @@ -0,0 +1,40 @@ +import assert from "node:assert/strict"; +import test, { after } from "node:test"; +import { sourceHarness } from "./sourceHarness.mjs"; +const graph = sourceHarness(); +const { readTableEmbedToken: locate } = await graph.importModule("src/core/editor/tableEmbedSource.ts"); +const { rewriteEmbedDimensions, parseEmbedAlias } = await graph.importModule("src/core/editor/embedDimensions.ts"); +after(() => graph.close()); + +test("physical table cells locate repeated escaped embeds without global occurrence matching", () => { + const token = "![[Drawings/Map.excalidraw.md#^frame=Frame name\\|Caption\\|100\\|left]]"; + const table = `| Drawing | Note |\n| :--- | ---: |\n| ${token} | first |\n| ${token} | second |\n`; + const first = locate(table, 25, 1, 0, 3, 2), second = locate(table, 25, 2, 0, 3, 2); + assert.equal(first.from, 25 + table.indexOf(token)); assert.equal(second.from, 25 + table.lastIndexOf(token)); + assert.equal(second.text, token); assert.equal(second.target, "Drawings/Map.excalidraw.md#^frame=Frame name"); + const edited = rewriteEmbedDimensions(second.text, { width: 108 }); + assert.equal(edited, token.replace("100", "108")); + assert.equal(table.slice(0, second.from - 25) + edited + table.slice(second.from - 25 + token.length), table.replace(token + " | second", edited + " | second")); + assert.deepEqual(parseEmbedAlias("Caption\\|100\\|left"), { alias: "Caption", width: "100", style: "left" }); +}); + +test("Markdown titles, Unicode, optional outer pipes and escaped code pipes retain exact source", () => { + const token = '![图例\\|50%](<绘图/地图.excalidraw.md#^group=abcdefgh> "Keep title")'; + const table = `Drawing | Code\n--- | ---\n ${token} | \`x\\|y\`\n`; + assert.equal(locate(table, 0, 1, 0, 2, 2).text, token); + const header = `| ![[Header\\|80]] | Name |\n| --- | --- |\n`; + assert.equal(locate(header, 10, 0, 0, 1, 2).from, 12); + const slashes = `| Code | Drawing |\n| --- | --- |\n| \\ | ![[Map\\|100]] |\n`; + assert.equal(locate(slashes, 0, 1, 1, 2, 2).text, "![[Map\\|100]]"); +}); + +test("ragged, mismatched, ambiguous, nested and non-embed cells never acquire editable ranges", () => { + const table = "| Image | Note |\n| --- | --- |\n| ![[Map]] | keep |\n"; + for (const args of [[0,1,0,3,2], [0,1,0,2,3], [0,2,0,2,2], [-1,1,0,2,2], [0,1,2,2,2]]) assert.equal(locate(table, ...args), null); + for (const source of [ + table.replace("--- | ---", "text | ---"), table.replace("| keep |", "| keep | extra |"), + table.replace("![[Map]]", "![[Map]] ![[Map]]"), table.replace("![[Map]]", "`![[Map]]`"), + table.replaceAll("|", "> |"), table + "not part of the table\n", + ]) assert.equal(locate(source, 0, 1, 0, 2, 2), null); + assert.equal(locate(table, 0, 1, 1, 2, 2), null); +}); diff --git a/src/core/editor/drawingEmbedExtension.ts b/src/core/editor/drawingEmbedExtension.ts index acb0a0fa..d8e520a0 100644 --- a/src/core/editor/drawingEmbedExtension.ts +++ b/src/core/editor/drawingEmbedExtension.ts @@ -1,11 +1,13 @@ import { EditorState, type Extension } from "@codemirror/state"; import { EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view"; -import { editorInfoField, editorLivePreviewField } from "obsidian"; +import { editorInfoField, editorLivePreviewField, MarkdownView } from "obsidian"; import type ExcalidrawPlugin from "../main"; import { DrawingEmbedControls } from "../managers/DrawingEmbedControls"; import { getDrawingEmbedActions } from "../managers/drawingEmbedActions"; import { DrawingEmbedSource } from "./embedSource"; import { readDrawingEmbedToken } from "./embedDimensions"; +import { readTableEmbedToken } from "./tableEmbedSource"; +import type { LocatedDrawingEmbed } from "src/types/drawingEmbedTypes"; interface OwnedEmbed { image: HTMLElement; @@ -13,12 +15,18 @@ interface OwnedEmbed { controls: DrawingEmbedControls; } +function isSourceMode(view: EditorView): boolean { + const info = view.state.field(editorInfoField, false); + return (!(info instanceof MarkdownView) || info.getMode() === "source") && + view.dom.closest(".markdown-source-view")?.style.display !== "none"; +} + function decodeTarget(target: string): string { const unescaped = target.replace(/\\([\\[\]()<>!| ])/g, "$1"); try { return decodeURI(unescaped); } catch { return unescaped; } } -function readWidgetToken(view: EditorView, element: HTMLElement): { from: number; text: string; target: string } | null { +function widgetRange(view: EditorView, element: HTMLElement): { from: number; to: number } | null { const parent = element.parentNode; if (!parent) return null; let from: number, boundaryFrom: number, boundaryTo: number; @@ -32,10 +40,26 @@ function readWidgetToken(view: EditorView, element: HTMLElement): { from: number return null; } if (from !== boundaryFrom || boundaryTo <= from || boundaryTo - from > 16384) return null; - const rangeText = view.state.doc.sliceString(from, boundaryTo), token = readDrawingEmbedToken(rangeText); + return { from, to: boundaryTo }; +} + +function readWidgetToken(view: EditorView, element: HTMLElement): LocatedDrawingEmbed | null { + const range = widgetRange(view, element); + if (!range) return null; + const { from, to } = range; + const rangeText = view.state.doc.sliceString(from, to), token = readDrawingEmbedToken(rangeText); return token && !rangeText.slice(token.text.length).trim() ? { from, text: token.text, target: token.target } : null; } +function readTableWidgetToken(view: EditorView, root: HTMLElement, table: HTMLTableElement, cell: HTMLTableCellElement): LocatedDrawingEmbed | null { + if (!cell || cell.closest("table") !== table || cell.colSpan !== 1 || cell.rowSpan !== 1) return null; + const row = cell.parentElement as HTMLTableRowElement; + if (row.parentElement?.parentElement !== table) return null; + const range = widgetRange(view, root); + if (!range) return null; + return readTableEmbedToken(view.state.doc.sliceString(range.from, range.to), range.from, row.rowIndex, cell.cellIndex, table.rows.length, table.rows[0]?.cells.length ?? 0); +} + /** * Public CodeMirror DOM boundaries locate a complete parsed token. Both the * source file/editor and the renderer's canonical drawing reference must agree. @@ -56,6 +80,8 @@ export function createDrawingEmbedExtension(plugin: ExcalidrawPlugin): { extensi const win = view.dom.ownerDocument.defaultView; this.observer = new win.MutationObserver(() => this.schedule()); this.observer.observe(view.contentDOM, { childList: true, subtree: true }); + const source = view.dom.closest(".markdown-source-view"); + if (source) this.observer.observe(source, { attributes: true, attributeFilter: ["class", "style"] }); this.schedule(); } @@ -78,21 +104,25 @@ export function createDrawingEmbedExtension(plugin: ExcalidrawPlugin): { extensi private sync(): void { const view = this.view, info = view.state.field(editorInfoField, false), sourceFile = info?.file; - if (!sourceFile || !view.state.field(editorLivePreviewField, false) || + if (!sourceFile || !isSourceMode(view) || !view.state.field(editorLivePreviewField, false) || view.state.facet(EditorState.readOnly) || !view.state.facet(EditorView.editable) || plugin.isExcalidrawFile(sourceFile)) { this.clear(); return; } const seen = new Set(); for (const image of view.contentDOM.querySelectorAll(".excalidraw-embedded-img")) { const nativeEmbed = image.closest(".internal-embed"), frame = image.parentElement; + const table = nativeEmbed ? null : image.closest("table.table-editor"); + const cell = table && image.closest("td, th"); + const root = nativeEmbed ?? table?.closest(".cm-table-widget"); + const key = nativeEmbed ?? frame; const actions = getDrawingEmbedActions(image); - if (!nativeEmbed || !frame || !actions || !actions.isCurrent() || image.closest(".cm-content") !== view.contentDOM || - nativeEmbed.closest(".markdown-embed, .hover-popover, .canvas-node-content, .print, .cm-preview-code-block")) continue; - seen.add(nativeEmbed); - const existing = this.entries.get(nativeEmbed); + if (!root || !frame || !actions || !actions.isCurrent() || image.closest(".cm-content") !== view.contentDOM || + root.closest(".markdown-embed, .hover-popover, .canvas-node-content, .print, .cm-preview-code-block")) continue; + seen.add(key); + const existing = this.entries.get(key); if (existing?.image === image && existing.source.isCurrent()) continue; - if (existing) { existing.source.invalidate(); existing.controls.unload(); this.entries.delete(nativeEmbed); } - const token = readWidgetToken(view, nativeEmbed); + if (existing) { existing.source.invalidate(); existing.controls.unload(); this.entries.delete(key); } + const token = table ? readTableWidgetToken(view, root, table, cell) : readWidgetToken(view, root); if (!token) continue; const from = token.from; const target = decodeTarget(token.target), hash = target.indexOf("#"); @@ -100,12 +130,20 @@ export function createDrawingEmbedExtension(plugin: ExcalidrawPlugin): { extensi const drawing = plugin.app.metadataCache.getFirstLinkpathDest(path, sourceFile.path); if (!drawing || !plugin.isExcalidrawFile(drawing) || decodeTarget(drawing.path + reference) !== decodeTarget(actions.target)) continue; const sourcePath = sourceFile.path, ownerDocument = view.dom.ownerDocument; + const row = cell?.parentElement as HTMLTableRowElement | undefined; + const rowIndex = row?.rowIndex, columnIndex = cell?.cellIndex; const source = new DrawingEmbedSource(view, from, from + token.text.length, token.text, () => this.active && !disposed && sourceFile.path === sourcePath && view.state.field(editorInfoField, false)?.file === sourceFile && + isSourceMode(view) && !!view.state.field(editorLivePreviewField, false) && !view.state.facet(EditorState.readOnly) && view.state.facet(EditorView.editable) && - frame.isConnected && view.contentDOM.contains(frame) && nativeEmbed.contains(frame) && - frame.ownerDocument === ownerDocument && view.dom.ownerDocument === ownerDocument && actions.isCurrent()); + frame.isConnected && view.contentDOM.contains(frame) && root.contains(frame) && + (!table || cell?.parentElement === row && row.rowIndex === rowIndex && cell.cellIndex === columnIndex) && + frame.ownerDocument === ownerDocument && view.dom.ownerDocument === ownerDocument && actions.isCurrent(), + table ? (from, to) => { + const current = readTableWidgetToken(view, root, table, cell); + return current?.from === from && from + current.text.length === to && current.text === token.text; + } : undefined); // A renderer may invalidate its generation before replacing the DOM. // Do not mount a stale binding: mounting/unloading it would schedule // another DOM sync and starve the renderer's debounce timer. @@ -113,7 +151,7 @@ export function createDrawingEmbedExtension(plugin: ExcalidrawPlugin): { extensi const controls = new DrawingEmbedControls(frame, actions, source); try { controls.load(); } catch (error) { source.invalidate(); controls.unload(); throw error; } - this.entries.set(nativeEmbed, { image, source, controls }); + this.entries.set(key, { image, source, controls }); } for (const [element, entry] of this.entries) if (!seen.has(element)) { entry.source.invalidate(); entry.controls.unload(); this.entries.delete(element); diff --git a/src/core/editor/embedDimensions.ts b/src/core/editor/embedDimensions.ts index ac30b447..598b0d12 100644 --- a/src/core/editor/embedDimensions.ts +++ b/src/core/editor/embedDimensions.ts @@ -32,7 +32,7 @@ export function getDimensionsFromAliasString(data: string): EmbedDimensions | nu /** Preserve the existing renderer's alias/style precedence. */ export function parseEmbedAlias(input: string): EmbedAliasParts { - const parts = input.split("|").map(part => part.trim()); + const parts = input.replace(/\\\|/g, "|").split("|").map(part => part.trim()); const first = getDimensionsFromAliasString(parts[0]); const second = parts.length > 1 ? getDimensionsFromAliasString(parts[1]) : null; let result: EmbedAliasParts; diff --git a/src/core/editor/embedSource.ts b/src/core/editor/embedSource.ts index ed4398ec..6f0f3012 100644 --- a/src/core/editor/embedSource.ts +++ b/src/core/editor/embedSource.ts @@ -18,6 +18,7 @@ export class DrawingEmbedSource implements EmbedSourceBinding { private to: number, public readonly text: string, private readonly ownsSource: () => boolean, + private readonly validateRange?: (from: number, to: number) => boolean, ) {} /** Track edits before the token; edits inside it retire this binding. */ @@ -41,7 +42,7 @@ export class DrawingEmbedSource implements EmbedSourceBinding { /** Commit a single isolated undoable transaction, retaining the destination. */ replace(text: string): boolean { - if (!this.isCurrent()) return false; + if (!this.isCurrent() || this.validateRange && !this.validateRange(this.from, this.to)) return false; if (text === this.text) return true; const original = readDrawingEmbedToken(this.text), next = readDrawingEmbedToken(text); if (!original || !next || next.text !== text || next.target !== original.target || next.wiki !== original.wiki) return false; @@ -55,7 +56,7 @@ export class DrawingEmbedSource implements EmbedSourceBinding { /** Select the containing-note syntax, allowing Live Preview to reveal it. */ select(): boolean { - if (!this.isCurrent()) return false; + if (!this.isCurrent() || this.validateRange && !this.validateRange(this.from, this.to)) return false; this.view.dispatch({ selection: EditorSelection.range(this.from, this.to), scrollIntoView: true }); this.view.focus(); return true; diff --git a/src/core/editor/tableEmbedSource.ts b/src/core/editor/tableEmbedSource.ts new file mode 100644 index 00000000..ad261d43 --- /dev/null +++ b/src/core/editor/tableEmbedSource.ts @@ -0,0 +1,49 @@ +import { readDrawingEmbedToken } from "./embedDimensions"; +import type { LocatedDrawingEmbed } from "src/types/drawingEmbedTypes"; + +interface CellRange { from: number; to: number } + +/** Table delimiters are unescaped pipes, including inside inline code. */ +function cells(line: string): CellRange[] { + const result: CellRange[] = []; + let from = 0, slashes = 0, pipes = 0; + for (let i = 0; i < line.length; i++) { + const char = line[i]; + if (char === "|" && slashes % 2 === 0) { + result.push({ from, to: i }); from = i + 1; pipes++; + } + slashes = char === "\\" ? slashes + 1 : 0; + } + if (!pipes) return []; + result.push({ from, to: line.length }); + if (!line.slice(result[0].from, result[0].to).trim()) result.shift(); + const last = result.at(-1); + if (last && !line.slice(last.from, last.to).trim()) result.pop(); + return result; +} + +/** + * Locate one complete token in a physical cell of a publicly mapped native + * table widget. Validate the entire rectangular table/DOM shape first; never + * infer the cell from a filename or a document-wide occurrence number. + */ +export function readTableEmbedToken( + source: string, tableFrom: number, row: number, column: number, + rowCount: number, columnCount: number, +): LocatedDrawingEmbed | null { + if (![tableFrom, row, column, rowCount, columnCount].every(Number.isInteger) || + tableFrom < 0 || row < 0 || row >= rowCount || column < 0 || column >= columnCount || + rowCount < 1 || columnCount < 1 || source.length > 16384) return null; + const lines = source.split("\n"); + while (lines.length && !lines.at(-1).trim()) lines.pop(); + if (lines.length !== rowCount + 1) return null; + const rows = lines.map(cells); + if (rows.some(cells => cells.length !== columnCount) || + !rows[1].every(cell => /^:?-+:?$/.test(lines[1].slice(cell.from, cell.to).trim()))) return null; + const lineIndex = row === 0 ? 0 : row + 1, cell = rows[lineIndex][column]; + const raw = lines[lineIndex].slice(cell.from, cell.to), text = raw.trim(); + const token = readDrawingEmbedToken(text); + if (!token || token.text !== text) return null; + const offset = lines.slice(0, lineIndex).reduce((length, line) => length + line.length + 1, 0); + return { from: tableFrom + offset + cell.from + raw.search(/\S/), text, target: token.target }; +} diff --git a/src/core/managers/DrawingEmbedControls.ts b/src/core/managers/DrawingEmbedControls.ts index ed4dbd99..27708539 100644 --- a/src/core/managers/DrawingEmbedControls.ts +++ b/src/core/managers/DrawingEmbedControls.ts @@ -23,6 +23,7 @@ export class DrawingEmbedControls extends MarkdownRenderChild { private toolbar: HTMLElement; private handle: HTMLButtonElement | null = null; private visual: HTMLElement | SVGElement | null = null; + private resizeObserver: ResizeObserver | null = null; private gesture: ResizeGesture | null = null; private active = false; private modals = new Set(); @@ -41,6 +42,10 @@ export class DrawingEmbedControls extends MarkdownRenderChild { const frame = this.containerEl, doc = frame.ownerDocument, win = doc.defaultView; frame.addClass("excalidraw-embed-controls-frame"); this.toolbar = frame.createDiv({ cls: "excalidraw-embed-toolbar", attr: { role: "toolbar", "aria-label": t("EMBED_ACTIONS") } }); + // Native table cells also handle compatibility mouse/touch events. A + // toolbar press must not activate the cell editor underneath our action. + this.registerDomEvent(this.toolbar, "mousedown", event => event.stopPropagation()); + this.registerDomEvent(this.toolbar, "touchstart", event => event.stopPropagation()); const button = (action: string, icon: string, label: string, callback: (event: MouseEvent) => void) => { const element = this.toolbar.createEl("button", { cls: "clickable-icon", attr: { type: "button", "aria-label": label, "data-excalidraw-embed-action": action } }); setIcon(element, icon); setTooltip(element, label); @@ -71,6 +76,11 @@ export class DrawingEmbedControls extends MarkdownRenderChild { const observer = new win.MutationObserver(() => this.refresh()); observer.observe(frame, { childList: true, subtree: true }); this.register(() => observer.disconnect()); + if (typeof win.ResizeObserver === "function") { + this.resizeObserver = new win.ResizeObserver(() => this.placeToolbar()); + this.register(() => { this.resizeObserver?.disconnect(); this.resizeObserver = null; }); + } + this.registerDomEvent(frame, "load", () => this.placeToolbar(), true); this.registerDomEvent(frame, "pointerenter", () => this.placeToolbar()); this.registerDomEvent(frame, "focusin", () => this.placeToolbar()); this.registerDomEvent(win, "resize", () => this.placeToolbar()); @@ -90,7 +100,11 @@ export class DrawingEmbedControls extends MarkdownRenderChild { private refresh(): void { const image = this.containerEl.querySelector(".excalidraw-embedded-img"); const visual = image?.querySelector("img, svg") ?? image; - if (visual !== this.visual) { this.finish(false); this.visual = visual; } + if (visual !== this.visual) { + this.finish(false); this.visual = visual; + this.resizeObserver?.disconnect(); + if (visual) this.resizeObserver?.observe(visual); + } if (!image) return; if (this.toolbar.parentElement !== this.containerEl) this.containerEl.append(this.toolbar); if (this.handle && this.handle.parentElement !== this.containerEl) this.containerEl.append(this.handle); @@ -98,18 +112,23 @@ export class DrawingEmbedControls extends MarkdownRenderChild { } private placeToolbar(): void { - const frame = this.containerEl, bounds = frame.getBoundingClientRect(); + const frame = this.containerEl; if (!this.active || !frame.isConnected) return; - const visual = this.visual?.getBoundingClientRect() ?? bounds; - const editor = frame.closest(".cm-scroller"); + let visual = this.visual?.getBoundingClientRect() ?? frame.getBoundingClientRect(); + const editor = frame.closest(".cm-scroller, .markdown-preview-view"); const top = editor?.getBoundingClientRect().top ?? 0; - frame.toggleClass("excalidraw-embed-controls-below", visual.top < top + 48 || visual.width < 160); + // Obsidian's image widget uses contain: paint. Keep the normal toolbar + // inside its image; small previews need an in-flow row below instead. + const toolbar = this.toolbar.getBoundingClientRect(); + frame.toggleClass("excalidraw-embed-controls-below", visual.width < Math.max(160, toolbar.width) || visual.height < Math.max(48, toolbar.height)); + // Switching to/from an in-flow row changes the frame's height immediately. + const bounds = frame.getBoundingClientRect(); + visual = this.visual?.getBoundingClientRect() ?? bounds; const right = frame.closest(".cm-content, .markdown-preview-view")?.getBoundingClientRect().right ?? frame.ownerDocument.defaultView.innerWidth; setStyle(frame, { "--excalidraw-embed-toolbar-width": `${Math.max(44, right - visual.left - 16)}px`, "--excalidraw-embed-control-left": `${visual.left - bounds.left}px`, - "--excalidraw-embed-control-top": `${visual.top - bounds.top}px`, - "--excalidraw-embed-control-below": `${visual.bottom - bounds.top}px`, + "--excalidraw-embed-control-top": `${Math.max(visual.top, top) - bounds.top}px`, "--excalidraw-embed-control-right": `${bounds.right - visual.right - 8}px`, "--excalidraw-embed-control-bottom": `${bounds.bottom - visual.bottom - 8}px`, }); @@ -197,6 +216,6 @@ export class DrawingEmbedControls extends MarkdownRenderChild { 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"); - removeStyle(this.containerEl, ["--excalidraw-embed-toolbar-width", "--excalidraw-embed-resize-width", "--excalidraw-embed-resize-height", "--excalidraw-embed-control-left", "--excalidraw-embed-control-top", "--excalidraw-embed-control-below", "--excalidraw-embed-control-right", "--excalidraw-embed-control-bottom"]); + removeStyle(this.containerEl, ["--excalidraw-embed-toolbar-width", "--excalidraw-embed-resize-width", "--excalidraw-embed-resize-height", "--excalidraw-embed-control-left", "--excalidraw-embed-control-top", "--excalidraw-embed-control-right", "--excalidraw-embed-control-bottom"]); } } diff --git a/src/shared/Dialogs/DrawingEmbedPreviewModal.ts b/src/shared/Dialogs/DrawingEmbedPreviewModal.ts index 77776747..41f4ac04 100644 --- a/src/shared/Dialogs/DrawingEmbedPreviewModal.ts +++ b/src/shared/Dialogs/DrawingEmbedPreviewModal.ts @@ -75,7 +75,9 @@ export class DrawingEmbedPreviewModal extends Modal { this.owner.registerDomEvent(this.stage, "pointerup", release); this.owner.registerDomEvent(this.stage, "pointercancel", release); this.owner.registerDomEvent(this.stage, "lostpointercapture", release); - this.owner.registerDomEvent(this.stage, "keydown", event => { + // Obsidian may focus its close button after onOpen(), and users can Tab to + // our toolbar. Viewer shortcuts belong to the whole modal, not just the pan surface. + this.owner.registerDomEvent(this.modalEl, "keydown", event => { if (event.ctrlKey || event.metaKey || event.altKey) return; if (["+", "=", "-", "0", "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) { event.preventDefault(); diff --git a/src/types/drawingEmbedTypes.ts b/src/types/drawingEmbedTypes.ts index a74e4a8c..e5119991 100644 --- a/src/types/drawingEmbedTypes.ts +++ b/src/types/drawingEmbedTypes.ts @@ -1,6 +1,12 @@ /** Narrow renderer, dialog and editor capabilities for drawing embed controls. */ import type { App } from "obsidian"; +export interface LocatedDrawingEmbed { + from: number; + text: string; + target: string; +} + export interface DrawingEmbedPreview { create: (isCurrent: () => boolean) => Promise; discard: (element: HTMLElement) => void; diff --git a/styles.css b/styles.css index e9aa6cfa..43035d4f 100644 --- a/styles.css +++ b/styles.css @@ -2537,7 +2537,7 @@ button.excalidraw-font-picker { .excalidraw-embed-toolbar { position: absolute; left: var(--excalidraw-embed-control-left, 0px); - bottom: calc(100% - var(--excalidraw-embed-control-top, 0px)); + top: var(--excalidraw-embed-control-top, 0px); z-index: 10; display: flex; flex-wrap: wrap; @@ -2553,8 +2553,9 @@ button.excalidraw-font-picker { pointer-events: none; } .excalidraw-embed-controls-below > .excalidraw-embed-toolbar { + position: relative; bottom: auto; - top: var(--excalidraw-embed-control-below, 100%); + top: auto; } .excalidraw-embed-toolbar button, .excalidraw-embed-preview-toolbar button { @@ -2572,10 +2573,13 @@ button.excalidraw-font-picker { background: var(--background-primary); border: 1px solid var(--background-modifier-border); cursor: nwse-resize; - touch-action: none; opacity: 0; pointer-events: none; } +/* Outrank the host's body.emulate-mobile .clickable-icon touch rule. */ +.excalidraw-embed-controls-frame > .excalidraw-embed-resize-handle.clickable-icon { + touch-action: none; +} .excalidraw-embed-controls-frame:hover > .excalidraw-embed-toolbar, .excalidraw-embed-controls-frame:focus-within > .excalidraw-embed-toolbar, .excalidraw-embed-controls-frame:hover > .excalidraw-embed-resize-handle, diff --git a/tests/features.json b/tests/features.json index 2669c241..0fda0b78 100644 --- a/tests/features.json +++ b/tests/features.json @@ -618,6 +618,13 @@ "node:scripts/testing/embedPreview.source.test.mjs::closing during fullscreen export cancels ownership and discards only the late private payload" ] }, + { + "layer": "source", + "path": "scripts/testing/tableEmbedSource.source.test.mjs", + "cases": [ + "node:scripts/testing/tableEmbedSource.source.test.mjs::physical table cells locate repeated escaped embeds without global occurrence matching" + ] + }, { "layer": "native", "path": "scripts/testing/host/embedControls.mjs", @@ -626,22 +633,27 @@ "native:embed-controls:main:SVGIMG", "native:embed-controls:main:SVG", "native:embed-ownership:main", + "native:embed-table:main", "native:embed-controls:split:PNG", "native:embed-controls:split:SVGIMG", "native:embed-controls:split:SVG", "native:embed-ownership:split", + "native:embed-table:split", "native:embed-controls:popout:PNG", "native:embed-controls:popout:SVGIMG", "native:embed-controls:popout:SVG", "native:embed-ownership:popout", + "native:embed-table:popout", "native:embed-controls:phone:PNG", "native:embed-controls:phone:SVGIMG", "native:embed-controls:phone:SVG", "native:embed-ownership:phone", + "native:embed-table:phone", "native:embed-controls:tablet:PNG", "native:embed-controls:tablet:SVGIMG", "native:embed-controls:tablet:SVG", - "native:embed-ownership:tablet" + "native:embed-ownership:tablet", + "native:embed-table:tablet" ] }, { @@ -663,6 +675,7 @@ "path": "scripts/testing/embedControls.source.test.mjs", "cases": [ "node:scripts/testing/embedControls.source.test.mjs::resize previews proportionally without writing, then commits once on the owned pointer release", + "node:scripts/testing/embedControls.source.test.mjs::toolbar compatibility events cannot activate the surrounding native table cell", "node:scripts/testing/embedControls.source.test.mjs::Escape, lost capture, stale source and visual replacement cancel without stale writes" ] } diff --git a/tests/inventory.json b/tests/inventory.json index 9fdfb9bd..5ea7be9b 100644 --- a/tests/inventory.json +++ b/tests/inventory.json @@ -2704,6 +2704,10 @@ "path": "scripts/testing/svgText.test.mjs", "mode": "direct-module-or-tooling" }, + { + "path": "scripts/testing/tableEmbedSource.source.test.mjs", + "mode": "direct-module-or-tooling" + }, { "path": "scripts/testing/templateWorkflow.test.mjs", "mode": "isolated-or-extracted"