diff --git a/scripts/testing/codeBlockInsertion.source.test.mjs b/scripts/testing/codeBlockInsertion.source.test.mjs index db39e2c3..41329870 100644 --- a/scripts/testing/codeBlockInsertion.source.test.mjs +++ b/scripts/testing/codeBlockInsertion.source.test.mjs @@ -15,7 +15,7 @@ const harness = sourceHarness({ } }, }, - "../../shared/MarkdownImage": { insertMarkdownImage: async (...args) => fixture.images.push(args) }, + "../../shared/MarkdownImage": { insertCodeBlockMarkdownImage: async (...args) => fixture.images.push(args) }, "../../utils/excalidrawViewUtils": { addBackOfTheNoteCard: async (...args) => { fixture.cards.push(args); return "card"; } }, "../../constants/constants": { CaptureUpdateAction: { EVENTUALLY: "EVENTUALLY" } }, "./pastedCodeCardSizing": { fitPastedCodeBlockCard: async (...args) => fixture.fits.push(args) }, diff --git a/scripts/testing/codeBlockMarkdownImageSizing.source.test.mjs b/scripts/testing/codeBlockMarkdownImageSizing.source.test.mjs new file mode 100644 index 00000000..f867f66c --- /dev/null +++ b/scripts/testing/codeBlockMarkdownImageSizing.source.test.mjs @@ -0,0 +1,27 @@ +/** Bound natural DOM measurements and clean the temporary style in its owning document. */ +import assert from "node:assert/strict"; +import test from "node:test"; +import { sourceHarness } from "./sourceHarness.mjs"; +const harness = sourceHarness({ "./htmlUtils": { setStyleText: (element, text) => element.textContent = text } }); +const { getCodeBlockMarkdownImageWidth } = await harness.importModule("src/utils/codeBlockMarkdownImageUtils.ts"); +test.after(() => harness.close()); +test("code width uses natural layout plus border, bounded to compact and maximum sizes", () => { + const before = globalThis.deliberateCreateElement; + try { + for (const [natural, border, expected] of [[40, 0, 180], [301.2, 4, 306], [790, 4, 794], [16000, 4, 800]]) { + const classes = new Set(), styles = new Set(); + const doc = { head: { appendChild: element => styles.add(element) } }; + const container = { ownerDocument: doc, classList: { add: name => classes.add(name), remove: name => classes.delete(name) }, + getBoundingClientRect() { assert.equal(classes.size, 1); assert.equal(styles.size, 1); return { width: natural }; } }; + globalThis.deliberateCreateElement = (owner, tag) => { assert.equal(owner, doc); assert.equal(tag, "style"); const element = { remove: () => styles.delete(element) }; return element; }; + assert.equal(getCodeBlockMarkdownImageWidth(container, 800, border), expected); + assert.equal(classes.size, 0); assert.equal(styles.size, 0); + container.getBoundingClientRect = () => { throw Error("retired frame"); }; + assert.throws(() => getCodeBlockMarkdownImageWidth(container, 800, border), /retired frame/); + assert.equal(classes.size, 0); assert.equal(styles.size, 0); + } + } finally { + if (before === undefined) delete globalThis.deliberateCreateElement; + else globalThis.deliberateCreateElement = before; + } +}); diff --git a/scripts/testing/host/codeBlockImageLayout.mjs b/scripts/testing/host/codeBlockImageLayout.mjs new file mode 100644 index 00000000..fc9aaac9 --- /dev/null +++ b/scripts/testing/host/codeBlockImageLayout.mjs @@ -0,0 +1,109 @@ +/** Measure the built SVG's actual code layout, independently of canvas zoom. */ +export async function exerciseCodeBlockImageLayout(c, env) { + const { p, doc, win, check, openDrawing, saveReopen, geometry } = env; + await c.case("native:code-block-image-layout:" + geometry().requested.id, ["P02", "P05"], async () => { + p.settings.pasteCodeBlockAs = "markdown-image"; + p.settings.markdownImageSettings.defaults.width = 180; + let view = await openDrawing("code-image-layout"); + view.excalidrawAPI.updateScene({ elements: [], captureUpdate: "NEVER" }); + const bodies = [ + { name: "medium", body: "console.log('A moderately long line needs more than 180 pixels');" }, + { name: "short", body: "const x = 1;" }, + { name: "long", body: "const token = '" + "x".repeat(260) + "';\nconsole.log(token);", wrapped: true }, + { name: "tabs-unicode", body: "\t// Unicode: 漢字 Ελληνικά café\n\tconsole.log('" + "long text ".repeat(22) + "');", wrapped: true }, + ]; + const records = [], images = []; + const inspect = async (element, variant) => { + const svg = await (await win.fetch(view.excalidrawAPI.getFiles()[element.fileId].dataURL)).text(); + const iframe = doc.createElement("iframe"); + iframe.style.cssText = "position:fixed;left:-100000px;top:0;width:" + element.customData.markdownImage.render.width + "px;height:10000px;border:0;visibility:hidden"; + doc.body.appendChild(iframe); + let record; + try { + const frameDoc = iframe.contentDocument, frameWin = iframe.contentWindow; + const parsed = new win.DOMParser().parseFromString(svg, "image/svg+xml"); + frameDoc.body.style.margin = "0"; + frameDoc.body.appendChild(frameDoc.importNode(parsed.documentElement, true)); + await frameDoc.fonts.ready; + const pre = frameDoc.querySelector("pre"), code = pre?.querySelector("code"); + check(code, "exported SVG has no code"); + const codeStyle = frameWin.getComputedStyle(code), preStyle = frameWin.getComputedStyle(pre); + record = { name: variant.name, width: element.width, flowWidth: element.customData.markdownImage.render.width, + svgWidth: parsed.documentElement.getAttribute("width"), height: element.height, + codeHeight: code.getBoundingClientRect().height, lineHeight: Number.parseFloat(codeStyle.lineHeight), + pre: { clientWidth: pre.clientWidth, scrollWidth: pre.scrollWidth, clientHeight: pre.clientHeight, scrollHeight: pre.scrollHeight, whiteSpace: preStyle.whiteSpace, overflowX: preStyle.overflowX }, + code: { clientWidth: code.clientWidth, scrollWidth: code.scrollWidth, whiteSpace: codeStyle.whiteSpace, overflowX: codeStyle.overflowX } }; + c.observations = { ...c.observations, codeImageLayout: [...records, record], codeImageSVG: svg }; + check(element.width >= 180 && element.width <= 800 && record.flowWidth === element.width, "code image width is outside adaptive bounds or differs from its layout width"); + if (variant.name === "medium") check(element.width > 180 && element.width < 800, "medium code still inherits the narrow 180-pixel Markdown default"); + if (variant.name === "short") check(element.width < records[0].width, "short code is not narrower than medium code"); + check(code.textContent.trimEnd() === variant.body.trimEnd(), "wrapping changed code, indentation or Unicode"); + check(["pre-wrap", "break-spaces"].includes(preStyle.whiteSpace) && ["pre-wrap", "break-spaces"].includes(codeStyle.whiteSpace), "code does not wrap in the exported image"); + check(!["auto", "scroll"].includes(preStyle.overflowX) && !["auto", "scroll"].includes(codeStyle.overflowX), "a static horizontal scrollbar is still exported"); + check(pre.scrollWidth <= pre.clientWidth + 1 && code.scrollWidth <= code.clientWidth + 1 && pre.scrollHeight <= pre.clientHeight + 1, "code is clipped instead of wrapping and growing"); + if (variant.wrapped) { + check(element.width === (variant.expectedWidth ?? 800), "long code differs from its capped or explicit layout width"); + check(record.codeHeight > record.lineHeight * variant.body.split("\n").length + 1, "long code did not grow into additional visual lines"); + } + } finally { iframe.remove(); } + return { svg, record }; + }; + for (const variant of bodies) { + const api = view.excalidrawAPI, before = new Set(api.getSceneElements().map(element => element.id)); + const source = "```js\n" + variant.body + "\n```"; + await view.pasteCodeBlock(source); + const element = api.getSceneElements().find(element => !before.has(element.id) && element.type === "image"); + check(element, "pasted code image missing"); + let { svg, record } = await inspect(element, variant); + images.push({ name: variant.name, svg }); records.push(record); + if (variant.name === "long") { + app.workspace.setActiveLeaf(view.leaf, { focus: true }); + api.updateScene({ appState: { selectedElementIds: { [element.id]: true } }, captureUpdate: "NEVER", forceFlushSync: true }); + const panel = await p.openSidepanel(false), previousTabs = new Set(panel.tabs.keys()); + await view.openMarkdownImageEditor(element.id); + const tab = [...panel.tabs.values()].find(tab => !previousTabs.has(tab.id)); + check(tab, "Markdown editor tab missing for width change"); + c.defer(() => { if (tab.contentEl.isConnected) tab.close(); }); + try { + await c.waitFor(() => tab.contentEl.querySelector(".excalidraw-markdown-image-editor__markdown-view .cm-content"), "Markdown width editor source readiness"); + let widthInput; + await c.waitFor(() => { + widthInput = tab.contentEl.querySelector('input[type="number"]'); + c.observations.widthEditor = { width: widthInput?.value, selected: view.excalidrawAPI.getAppState().selectedElementIds, html: tab.contentEl.outerHTML.slice(0, 1200) }; + return widthInput?.value === "800"; + }, "Markdown layout width control targets the selected code image"); + widthInput.value = "600"; + widthInput.dispatchEvent(new tab.contentEl.ownerDocument.defaultView.Event("input", { bubbles: true })); + await c.waitFor(() => { + const current = view.excalidrawAPI.getSceneElements().find(item => item.id === element.id); + const status = tab.contentEl.querySelector(".excalidraw-markdown-image-editor__status"); + c.observations.widthEditor = { ...c.observations.widthEditor, input: widthInput.value, width: current?.width, flow: current?.customData?.markdownImage?.render.width, sameAPI: view.excalidrawAPI === api, status: status?.outerHTML }; + return current?.customData?.markdownImage?.render.width === 600 && !status?.classList.contains("is-updating"); + }, "Markdown editor renders at explicit width 600"); + } finally { + tab.close(); + await c.waitForCleanup(() => !view.isSameFileEditingActive() && !view.isSaveInProgress() && view.isLoaded && view.excalidrawAPI && !view.semaphores.justLoaded, "Markdown width editor close persistence and save-grace release"); + app.workspace.setActiveLeaf(view.leaf, { focus: true }); + } + const resized = view.excalidrawAPI.getSceneElements().find(item => item.id === element.id); + const result = await inspect(resized, { ...variant, name: "long-at-600", expectedWidth: 600 }); + svg = result.svg; record = result.record; + images.push({ name: "long-at-600", svg }); records.push(record); + } + const expected = { id: element.id, width: record.width, height: record.height, flowWidth: record.flowWidth }; + // Closing the same-file editor queues one final Vault synchronization. + // Its acquisition wait can outlive the owner grace period; do not race it + // with the save whose physical acknowledgment is asserted by saveReopen. + await c.waitFor(() => { + c.observations.layoutSaveReadiness = { busy: view.isPersistenceBusy(), editing: view.isSameFileEditingActive(), pendingPath: view.pendingExternalSyncPath, pendingLoop: !!view.externalSyncLoopPromise, loaded: view.isLoaded }; + return !view.isPersistenceBusy() && !view.isSameFileEditingActive() && !view.pendingExternalSyncPath && !view.externalSyncLoopPromise && view.isLoaded; + }, "code image editor's pending file synchronization settles before save/reopen"); + view = await saveReopen(view); + const restored = view.excalidrawAPI.getSceneElements().find(element => element.id === expected.id); + check(restored?.width === expected.width && restored?.height === expected.height && restored.customData.markdownImage.render.width === expected.flowWidth, "adaptive image dimensions changed on reopen"); + check(view.excalidrawData.getMarkdownImage(restored.fileId)?.markdown === source, "reopen lost editable code source"); + } + check(p.settings.markdownImageSettings.defaults.width === 180, "code insertion changed the general Markdown image default"); + return { assertions: ["initial code width adapts to actual rendered content from a 180px global default", "short code remains compact; long lines cap at 800px", "long tokens, tabs and Unicode wrap without exported scrollbars or clipping", "explicit editor width 600 reflows existing code without clipping or scrollbars", "editable source and adaptive/manual dimensions survive save/reopen", "general Markdown image defaults remain unchanged"], records, images }; + }); +} diff --git a/scripts/testing/host/codeCards.mjs b/scripts/testing/host/codeCards.mjs index a0ce9f14..4735e0da 100644 --- a/scripts/testing/host/codeCards.mjs +++ b/scripts/testing/host/codeCards.mjs @@ -7,8 +7,9 @@ import { behaviorInputDriver } from "./behaviorMatrix.mjs"; import { completeConsoleErrors } from "./debuggerSession.mjs"; import { settleBrowserDiagnostics, splitWindowErrors } from "./browserDiagnostics.mjs"; import { exerciseCodeBlockFormats } from "./codeBlockFormats.mjs"; +import { exerciseCodeBlockImageLayout } from "./codeBlockImageLayout.mjs"; -export const codeCardCaseIds = ["main", "popout"].flatMap(context => ["native:workflow-code-card-2894:" + context, "native:code-block-format:" + context]); +export const codeCardCaseIds = ["main", "popout"].flatMap(context => ["native:workflow-code-card-2894:" + context, "native:code-block-format:" + context, "native:code-block-image-layout:" + context]); export async function runCodeCardScenario({ cli, drawingPath }) { const template = readFileSync(new URL("../../../tests/vault/Drawings/Uncompressed.excalidraw.md", import.meta.url), "utf8"); @@ -16,6 +17,7 @@ export async function runCodeCardScenario({ cli, drawingPath }) { for (const id of ["main", "popout"]) { const execute = new Function(`return async function(c,path,context,template,modifier){ const env=await (${behaviorEnvironment.toString()})(c,path,context,template,${completeConsoleErrors.toString()},${settleBrowserDiagnostics.toString()}); + await (${exerciseCodeBlockImageLayout.toString()})(c,env); await (${exerciseCodeCards.toString()})(c,env,modifier); await (${exerciseCodeBlockFormats.toString()})(c,env,modifier); return {tests:c.tests,consoleErrors:c.externalConsoleErrors||[],windowErrors:env.windowErrors,browserIdle:env.browserIdle}; diff --git a/scripts/testing/markdownImageInsertion.source.test.mjs b/scripts/testing/markdownImageInsertion.source.test.mjs index e0a69a10..87f591ce 100644 --- a/scripts/testing/markdownImageInsertion.source.test.mjs +++ b/scripts/testing/markdownImageInsertion.source.test.mjs @@ -9,24 +9,28 @@ const harness = sourceHarness({ "src/core": { getEA: () => f.ea }, "src/constants/constants": { fileid: () => "source-id", MD_EX_SECTIONS: {} }, "src/shared/EmbeddedFileLoader": { EmbeddedFile: class {}, EmbeddedFilesLoader: class { - async renderMarkdownToSVG() { f.onRender(); return { dataURL: "data:image/svg+xml,test", size: { width: 400, height: 140 } }; } + async renderMarkdownToSVG(file, markdown, settings, autoFit) { + f.renders.push({ file, markdown, settings: structuredClone(settings), autoFit }); + f.onRender(); return { dataURL: "data:image/svg+xml,test", size: { width: autoFit ? f.fittedWidth : settings.width, height: 140 } }; + } } }, "src/shared/ExcalidrawData": { getTransclusion() {}, REGEX_LINK: {} }, "src/utils/elementCustomDataUtils": { addAppendUpdateCustomData: (el, data) => el.customData = { ...el.customData, ...data }, setMarkdownImageRenderedSize() {} }, "src/types/markdownImageTypes": { MARKDOWN_IMAGE_CUSTOM_DATA_KEY: "markdownImage", MARKDOWN_IMAGE_SCHEMA_VERSION: 1 }, - "src/utils/markdownImageUtils": { resolveMarkdownImageRenderSettings: () => render, getMarkdownImageDisplayGeometry() {}, getMarkdownImageCropGeometry() {} }, + "src/utils/markdownImageUtils": { resolveMarkdownImageRenderSettings: defaults => structuredClone(defaults), getMarkdownImageDisplayGeometry() {}, getMarkdownImageCropGeometry() {} }, + "src/utils/codeBlockMarkdownImageUtils": { CODE_BLOCK_IMAGE_MAX_WIDTH: 800 }, "src/utils/pathUtils": { cleanSectionHeading: s => s }, "src/utils/coreUtils": { errorlog: error => { throw error; } }, }); -const { insertMarkdownImage } = await harness.importModule("src/shared/MarkdownImage.ts"); +const { insertMarkdownImage, insertCodeBlockMarkdownImage } = await harness.importModule("src/shared/MarkdownImage.ts"); test.after(() => harness.close()); function setup() { - f = { commits: 0, destroyed: 0, dirty: 0, selected: 0, sources: new Map(), onRender() {}, onAddImage() {} }; + f = { commits: 0, destroyed: 0, dirty: 0, selected: 0, sources: new Map(), renders: [], fittedWidth: 640, onRender() {}, onAddImage() {} }; const el = { id: "element", type: "image", fileId: "temporary" }; f.ea = { imagesDict: {}, async addImage() { f.onAddImage(); return el.id; }, getElement: () => el, async addElementsToView() { f.commits++; return true; }, destroy() { f.destroyed++; } }; f.view = { file: {}, excalidrawAPI: { selectElements() { f.selected++; } }, currentPosition: { x: 1, y: 2 }, - isClosingOrMigrating: () => false, plugin: { settings: { markdownImageSettings: { defaults: render } } }, + isClosingOrMigrating: () => false, plugin: { settings: { markdownImageSettings: { defaults: structuredClone(render) } } }, excalidrawData: { setMarkdownImage: (id, source) => f.sources.set(id, source) }, getViewElements: () => [el], rememberMarkdownImageRender() {}, setDirty() { f.dirty++; } }; return f; @@ -38,12 +42,23 @@ test("Markdown image insertion retains editable local text and commits once", as assert.equal(state.commits, 1); assert.equal(state.destroyed, 1); assert.equal(state.dirty, 1); assert.equal(state.selected, 1); }); test("Markdown image render and decode cannot insert into a replaced file, API or migrating view", async () => { - for (const phase of ["onRender", "onAddImage"]) { + for (const insert of [insertMarkdownImage, insertCodeBlockMarkdownImage]) for (const phase of ["onRender", "onAddImage"]) { for (const retire of [view => view.file = {}, view => view.excalidrawAPI = { selectElements() {} }, view => view.isClosingOrMigrating = () => true]) { const state = setup(); state[phase] = () => retire(state.view); - assert.equal(await insertMarkdownImage(state.view, "```js\nx();\n```"), null); + assert.equal(await insert(state.view, "```js\nx();\n```"), null); assert.equal(state.commits, 0); assert.equal(state.sources.size, 0); assert.equal(state.dirty, 0); assert.equal(state.destroyed, phase === "onAddImage" ? 1 : 0); } } }); +test("pasted code requests adaptive width once and persists the actual flow width without changing general defaults", async () => { + const state = setup(); state.view.plugin.settings.markdownImageSettings.defaults.width = 180; + const code = "```js\nconsole.log('adaptive');\n```"; + const element = await insertCodeBlockMarkdownImage(state.view, code); + assert.equal(state.renders[0].autoFit, true); assert.equal(state.renders[0].settings.width, 800); + assert.equal(element.width, 640); assert.equal(element.customData.markdownImage.render.width, 640); + assert.equal(state.view.plugin.settings.markdownImageSettings.defaults.width, 180); + assert.equal(state.sources.get(element.fileId).markdown, code); assert.equal(state.commits, 1); + await insertMarkdownImage(state.view, code); + assert.equal(state.renders[1].autoFit, false); assert.equal(state.renders[1].settings.width, 180); +}); diff --git a/src/shared/Dialogs/Messages.ts b/src/shared/Dialogs/Messages.ts index 2ba869d2..a77f3f28 100644 --- a/src/shared/Dialogs/Messages.ts +++ b/src/shared/Dialogs/Messages.ts @@ -19,7 +19,7 @@ I build this plugin as a labor of love. Curious about the philosophy behind it? `, "2.29.2": ` ## New and improved -- Paste code blocks as interactive embeddables or editable Markdown images, and optionally remember your choice in Excalidraw settings. +- Paste code blocks as interactive embeddables or editable Markdown images, and optionally remember your choice. Code images adapt to their content up to 800 px wide and wrap long lines without scrollbars. ## Fixed - Empty settings records now trigger recovery instead of silently resetting preferences and script settings. diff --git a/src/shared/EmbeddedFileLoader.ts b/src/shared/EmbeddedFileLoader.ts index bdbc1656..752c7b32 100644 --- a/src/shared/EmbeddedFileLoader.ts +++ b/src/shared/EmbeddedFileLoader.ts @@ -90,6 +90,10 @@ import { type MarkdownImageRenderCacheEntry, } from "src/utils/markdownImageUtils"; import { addAppendUpdateCustomData } from "src/utils/elementCustomDataUtils"; +import { + getCodeBlockMarkdownImageWidth, + MARKDOWN_IMAGE_CODE_WRAP_CSS, +} from "src/utils/codeBlockMarkdownImageUtils"; //declared in rollup.config.mjs declare const deliberateFetch: ( @@ -178,6 +182,7 @@ type MarkdownRenderOverrides = { render: MarkdownImageRenderSettings; fullHeight: boolean; isTransclusion?: boolean; + autoFitCodeBlockWidth?: boolean; }; const waitForMarkdownPostProcessors = ( @@ -834,6 +839,7 @@ export class EmbeddedFilesLoader { sourceFile: TFile, markdown: string, render: MarkdownImageRenderSettings, + autoFitCodeBlockWidth = false, ): Promise { if (this.isDark !== false) { const lightThemeLoader = new EmbeddedFilesLoader(this.plugin, false); @@ -842,6 +848,7 @@ export class EmbeddedFilesLoader { sourceFile, markdown, render, + autoFitCodeBlockWidth, ); } finally { lightThemeLoader.terminate = true; @@ -855,7 +862,7 @@ export class EmbeddedFilesLoader { this.plugin, sourceFile, linkParts, - { markdown, render, fullHeight: true }, + { markdown, render, fullHeight: true, autoFitCodeBlockWidth }, ); return result; } finally { @@ -2469,7 +2476,7 @@ export class EmbeddedFilesLoader { ? `.excalidraw-md-host.theme-light{color-scheme:light;--background-primary:#ffffff;--background-secondary:#f5f5f5;--text-normal:#2e3338;--text-muted:#6b6b6b;--link-color:#086ddd}.excalidraw-md-host.theme-light a{color:var(--link-color)}.excalidraw-md-host.theme-light th{background-color:#dedede}.excalidraw-md-host.theme-light pre[class*=language-],.excalidraw-md-host.theme-light :not(pre)>code[class*=language-]{color:#393a34;background-color:#f5f5f5;border-color:#ddd}.excalidraw-md-host.theme-light blockquote{background-color:rgba(0,0,0,.06)}` : ""; let style: string = overrides - ? `${DEFAULT_MD_EMBED_CSS}\n${ISOLATED_MARKDOWN_RENDER_CSS}\n${markdownImageThemeCSS}\n${overrides.render.css}` + ? `${DEFAULT_MD_EMBED_CSS}\n${ISOLATED_MARKDOWN_RENDER_CSS}\n${markdownImageThemeCSS}\n${overrides.render.css}\n${MARKDOWN_IMAGE_CODE_WRAP_CSS}` : (safeFrontmatter[FRONTMATTER_KEYS["md-css"].name] ?? ""); let frontmatterCSSisAfile = false; @@ -2802,7 +2809,10 @@ export class EmbeddedFilesLoader { // FIX: Force the iframe's body to respect the target width and prevent text inflation // Removed `overflow: hidden !important` so we don't accidentally clip valid heights on iOS measurement. const bodyReset = deliberateCreateElement(iframeDoc, "style") as HTMLStyleElement; - setStyleText(bodyReset, ` + const resetIframeWidth = () => { + setStyle(iframeHost, { width: `${linkParts.width}px` }); + setStyle(iframe, { width: `${linkParts.width}px` }); + setStyleText(bodyReset, ` html, body { margin: 0 !important; padding: 0 !important; @@ -2813,6 +2823,8 @@ export class EmbeddedFilesLoader { text-size-adjust: none !important; } `); + }; + resetIframeWidth(); iframeDoc.head.appendChild(bodyReset); if (style) { @@ -2843,6 +2855,15 @@ export class EmbeddedFilesLoader { iframeDoc.body.appendChild(footerDIV); await waitForDocumentFonts(iframeDoc); + if (overrides?.autoFitCodeBlockWidth) { + linkParts.width = getCodeBlockMarkdownImageWidth( + stylingDIV, + overrides.render.width, + drawBorder ? 4 : 0, + ); + resetIframeWidth(); + } + iframeDoc.body.querySelectorAll("*").forEach((el: HTMLElement) => { const elementStyle = el.style; const computedStyle = iframeWindow.getComputedStyle(el); diff --git a/src/shared/MarkdownImage.ts b/src/shared/MarkdownImage.ts index 84ddfba6..e40e12e1 100644 --- a/src/shared/MarkdownImage.ts +++ b/src/shared/MarkdownImage.ts @@ -33,6 +33,7 @@ import { } from "src/utils/markdownImageUtils"; import { cleanSectionHeading } from "src/utils/pathUtils"; import { errorlog } from "src/utils/coreUtils"; +import { CODE_BLOCK_IMAGE_MAX_WIDTH } from "src/utils/codeBlockMarkdownImageUtils"; export type MarkdownImageSourceData = { markdown: string; @@ -199,9 +200,10 @@ async function renderMarkdown( markdown: string, render: MarkdownImageRenderSettings, sourceFile = view.file, + autoFitCodeBlockWidth = false, ) { const loader = new EmbeddedFilesLoader(view.plugin, false); - return loader.renderMarkdownToSVG(sourceFile, markdown, render); + return loader.renderMarkdownToSVG(sourceFile, markdown, render, autoFitCodeBlockWidth); } const rememberRenderedMarkdownImage = ( @@ -458,6 +460,24 @@ export async function insertMarkdownImage( view: ExcalidrawView, source: string | TFile | EmbeddedFile = "", position: { x: number; y: number } = view.currentPosition, +): Promise { + return insertMarkdownImageWithLayout(view, source, position); +} + +/** Inserts clipboard code at its natural width, capped before line wrapping. */ +export async function insertCodeBlockMarkdownImage( + view: ExcalidrawView, + markdown: string, + position: { x: number; y: number } = view.currentPosition, +): Promise { + return insertMarkdownImageWithLayout(view, markdown, position, true); +} + +async function insertMarkdownImageWithLayout( + view: ExcalidrawView, + source: string | TFile | EmbeddedFile, + position: { x: number; y: number }, + autoFitCodeBlockWidth = false, ): Promise { const { file, excalidrawAPI: api } = view; const isCurrent = () => file && api && view.file === file && @@ -473,16 +493,19 @@ export async function insertMarkdownImage( return null; } const render = getMarkdownImageRenderSettings(view.plugin); + if (autoFitCodeBlockWidth) render.width = CODE_BLOCK_IMAGE_MAX_WIDTH; const sourceFile = sourceData.embeddedFile?.file ?? view.file; const rendered = await renderMarkdown( view, sourceData.markdown, render, sourceFile, + autoFitCodeBlockWidth, ); if (!isCurrent() || !rendered.dataURL || rendered.size.height <= 0) { return null; } + if (autoFitCodeBlockWidth) render.width = rendered.size.width; const ea = getEA(view); const fileId = fileid() as FileId; const id = await ea.addImage( diff --git a/src/utils/codeBlockMarkdownImageUtils.ts b/src/utils/codeBlockMarkdownImageUtils.ts new file mode 100644 index 00000000..88fc5be6 --- /dev/null +++ b/src/utils/codeBlockMarkdownImageUtils.ts @@ -0,0 +1,52 @@ +import { setStyleText } from "./htmlUtils"; + +declare const deliberateCreateElement: (document: Document, tagName: string) => HTMLElement; + +export const CODE_BLOCK_IMAGE_MAX_WIDTH = 800; + +/** Static images cannot expose scrolling: retain whitespace and wrap long tokens. */ +export const MARKDOWN_IMAGE_CODE_WRAP_CSS = ` +.excalidraw-md-host pre, +.excalidraw-md-host pre code { + max-width: 100% !important; + height: auto !important; + max-height: none !important; + white-space: pre-wrap !important; + overflow-wrap: anywhere !important; + word-break: break-word !important; + overflow: visible !important; +} +.excalidraw-md-host pre code { display: block !important; } +.excalidraw-md-host pre code * { + white-space: inherit !important; + overflow-wrap: inherit !important; + word-break: inherit !important; +} +`; + +/** Measures natural code width in the styled, font-ready SVG measurement iframe. */ +export function getCodeBlockMarkdownImageWidth( + container: HTMLElement, + maximumWidth: number, + borderWidth: number, +): number { + const className = "excalidraw-code-image-measure"; + const style = deliberateCreateElement(container.ownerDocument, "style") as HTMLStyleElement; + setStyleText(style, ` +.${className}, .${className} pre, .${className} pre code { + width: max-content !important; + min-width: 0 !important; + max-width: none !important; + white-space: pre !important; +} +`); + container.ownerDocument.head.appendChild(style); + container.classList.add(className); + try { + const naturalWidth = Math.ceil(container.getBoundingClientRect().width + borderWidth); + return Math.min(maximumWidth, Math.max(180, naturalWidth)); + } finally { + container.classList.remove(className); + style.remove(); + } +} diff --git a/src/view/managers/codeBlockInsertion.ts b/src/view/managers/codeBlockInsertion.ts index 3677aa8f..ee18f890 100644 --- a/src/view/managers/codeBlockInsertion.ts +++ b/src/view/managers/codeBlockInsertion.ts @@ -1,6 +1,6 @@ import type ExcalidrawView from "../ExcalidrawView"; import { GenericInputPrompt, MultiOptionConfirmationPrompt } from "../../shared/Dialogs/Prompt"; -import { insertMarkdownImage } from "../../shared/MarkdownImage"; +import { insertCodeBlockMarkdownImage } from "../../shared/MarkdownImage"; import type { CodeBlockInsertionPreference } from "../../types/codeBlockTypes"; import { t } from "../../lang/helpers"; import { addBackOfTheNoteCard } from "../../utils/excalidrawViewUtils"; @@ -55,7 +55,7 @@ export async function insertCodeBlock(view: ExcalidrawView, data: string): Promi } } if (format === "markdown-image") { - await insertMarkdownImage(view, data, position); + await insertCodeBlockMarkdownImage(view, data, position); return; } const result = await input(t("PASTE_CODEBLOCK_TITLE"), t("PASTE_CODEBLOCK_TITLE_PLACEHOLDER")); diff --git a/tests/features.json b/tests/features.json index f4893615..0970ada3 100644 --- a/tests/features.json +++ b/tests/features.json @@ -483,7 +483,8 @@ "path": "scripts/testing/markdownImageInsertion.source.test.mjs", "cases": [ "node:scripts/testing/markdownImageInsertion.source.test.mjs::Markdown image insertion retains editable local text and commits once", - "node:scripts/testing/markdownImageInsertion.source.test.mjs::Markdown image render and decode cannot insert into a replaced file, API or migrating view" + "node:scripts/testing/markdownImageInsertion.source.test.mjs::Markdown image render and decode cannot insert into a replaced file, API or migrating view", + "node:scripts/testing/markdownImageInsertion.source.test.mjs::pasted code requests adaptive width once and persists the actual flow width without changing general defaults" ] }, { @@ -493,6 +494,21 @@ "native:code-block-format:main", "native:code-block-format:popout" ] + }, + { + "layer": "source", + "path": "scripts/testing/codeBlockMarkdownImageSizing.source.test.mjs", + "cases": [ + "node:scripts/testing/codeBlockMarkdownImageSizing.source.test.mjs::code width uses natural layout plus border, bounded to compact and maximum sizes" + ] + }, + { + "layer": "native", + "path": "scripts/testing/host/codeBlockImageLayout.mjs", + "cases": [ + "native:code-block-image-layout:main", + "native:code-block-image-layout:popout" + ] } ], "fixtures": [ diff --git a/tests/inventory.json b/tests/inventory.json index d6a252dc..7ccb9fff 100644 --- a/tests/inventory.json +++ b/tests/inventory.json @@ -2428,6 +2428,10 @@ "path": "scripts/testing/codeBlockInsertion.source.test.mjs", "mode": "direct-module-or-tooling" }, + { + "path": "scripts/testing/codeBlockMarkdownImageSizing.source.test.mjs", + "mode": "direct-module-or-tooling" + }, { "path": "scripts/testing/contracts.test.mjs", "mode": "direct-module-or-tooling"