mirror of
https://github.com/excalidraw/excalidraw.git
synced 2026-11-20 21:23:22 +03:00
fix: measurement-free embed placeholders; no render environment in SVG export
The placeholder drawn for an embed that isn't rendered live was the last text `exportToSvg` measured, which kept a canvas (via the render environment) in the SVG path and made headless SVG export throw on any scene with an embed unless the process had been polyfilled. - show the placeholder as a single line capped at 30 characters (`getPlaceholderLinkText`: scheme and `www.` dropped, ellipsis) instead of wrapping the whole link: at or below that length the existing `width / length` font size fits the box by construction, so nothing is measured, wrapped or clipped, and output is identical on every host. The full link stays on the element's `<a href>` in SVG - `newTextElement` accepts pre-computed `metrics` to skip measuring - drop `renderEnvironment` from `SVGRenderConfig`, `exportToSvg` and the `@excalidraw/utils` signature: SVG export's only host dependency is its owner document - throw a guided error from the default canvas/image factories when there is no `document`/`Image`, instead of a bare ReferenceError - tests: placeholder text capping and layout; SVG export of an iframe and a long-link embed with a render environment whose `createCanvas` throws Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
1 parent
295e7d88b5
commit
886bea142e
11 files changed
+256
-45
No files matched your search
@@ -2,17 +2,16 @@ import {
|
||||
FONT_FAMILY,
|
||||
VERTICAL_ALIGN,
|
||||
escapeDoubleQuotes,
|
||||
getFontString,
|
||||
getLineHeight,
|
||||
} from "@excalidraw/common";
|
||||
|
||||
import type { ExcalidrawProps } from "@excalidraw/excalidraw/types";
|
||||
import type { MarkRequired } from "@excalidraw/common/utility-types";
|
||||
|
||||
import { newTextElement } from "./newElement";
|
||||
import { wrapText } from "./textWrapping";
|
||||
import { getTextHeight } from "./textMeasurements";
|
||||
import { isIframeElement } from "./typeChecks";
|
||||
|
||||
import type { RenderEnvironment } from "./renderEnvironment";
|
||||
import type {
|
||||
ExcalidrawIframeLikeElement,
|
||||
IframeData,
|
||||
@@ -400,28 +399,51 @@ export const getEmbedLink = (
|
||||
};
|
||||
};
|
||||
|
||||
/** gap between the embed's edge and its placeholder text, per side */
|
||||
const PLACEHOLDER_PADDING = 10;
|
||||
|
||||
/**
|
||||
* Longest placeholder text. Below this the font size is `width / length`
|
||||
* (see below), so a line is at most `advance * width` wide -- which, at the
|
||||
* ~0.5em average advance of Latin text, fits the padded box without ever
|
||||
* measuring it. Above it the font size stops shrinking and text would have
|
||||
* to wrap.
|
||||
*/
|
||||
const PLACEHOLDER_MAX_CHARS = 30;
|
||||
|
||||
/** The link as shown in a placeholder: scheme and `www.` dropped, capped. */
|
||||
export const getPlaceholderLinkText = (link: string) => {
|
||||
const text = link.replace(/^https?:\/\//i, "").replace(/^www\./i, "");
|
||||
return text.length > PLACEHOLDER_MAX_CHARS
|
||||
? `${text.slice(0, PLACEHOLDER_MAX_CHARS - 1)}…`
|
||||
: text;
|
||||
};
|
||||
|
||||
/**
|
||||
* The text drawn in place of an embed that isn't rendered live (on export,
|
||||
* or when the embed fails validation). A single line, capped at
|
||||
* `PLACEHOLDER_MAX_CHARS`, laid out WITHOUT measuring text -- so it needs no
|
||||
* canvas and comes out the same on every host. The full link is not lost:
|
||||
* the SVG renderer wraps a linked element in an `<a href>`.
|
||||
*/
|
||||
export const createPlaceholderEmbeddableLabel = (
|
||||
element: ExcalidrawIframeLikeElement,
|
||||
renderEnvironment?: RenderEnvironment,
|
||||
): NonDeletedExcalidrawElement => {
|
||||
let text: string;
|
||||
if (isIframeElement(element)) {
|
||||
text = "IFrame element";
|
||||
} else {
|
||||
text =
|
||||
!element.link || element?.link === "" ? "Empty Web-Embed" : element.link;
|
||||
text = element.link ? getPlaceholderLinkText(element.link) : "";
|
||||
text = text || "Empty Web-Embed";
|
||||
}
|
||||
|
||||
const fontSize = Math.max(
|
||||
Math.min(element.width / 2, element.width / text.length),
|
||||
element.width / 30,
|
||||
element.width / PLACEHOLDER_MAX_CHARS,
|
||||
);
|
||||
const fontFamily = FONT_FAMILY.Helvetica;
|
||||
|
||||
const fontString = getFontString({
|
||||
fontSize,
|
||||
fontFamily,
|
||||
});
|
||||
const lineHeight = getLineHeight(fontFamily);
|
||||
const width = element.width - PLACEHOLDER_PADDING * 2;
|
||||
|
||||
return newTextElement({
|
||||
x: element.x + element.width / 2,
|
||||
@@ -431,10 +453,12 @@ export const createPlaceholderEmbeddableLabel = (
|
||||
backgroundColor: "transparent",
|
||||
fontFamily,
|
||||
fontSize,
|
||||
text: wrapText(text, fontString, element.width - 20, renderEnvironment),
|
||||
lineHeight,
|
||||
text,
|
||||
textAlign: "center",
|
||||
verticalAlign: VERTICAL_ALIGN.MIDDLE,
|
||||
angle: element.angle ?? 0,
|
||||
metrics: { width, height: getTextHeight(text, fontSize, lineHeight) },
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -348,18 +348,26 @@ export const newTextElement = (
|
||||
labelPosition?: ExcalidrawTextElement["labelPosition"];
|
||||
baseFontSize?: ExcalidrawTextElement["baseFontSize"];
|
||||
renderEnvironment?: RenderEnvironment;
|
||||
/**
|
||||
* Pre-computed dimensions. Skips measuring, for callers that lay the
|
||||
* (pre-wrapped) text out themselves -- e.g. export-time placeholders,
|
||||
* which have to work without a canvas.
|
||||
*/
|
||||
metrics?: { width: number; height: number };
|
||||
} & ElementConstructorOpts,
|
||||
): NonDeleted<ExcalidrawTextElement> => {
|
||||
const fontFamily = opts.fontFamily || DEFAULT_FONT_FAMILY;
|
||||
const fontSize = opts.fontSize || DEFAULT_FONT_SIZE;
|
||||
const lineHeight = opts.lineHeight || getLineHeight(fontFamily);
|
||||
const text = normalizeText(opts.text);
|
||||
const metrics = measureText(
|
||||
text,
|
||||
getFontString({ fontFamily, fontSize }),
|
||||
lineHeight,
|
||||
opts.renderEnvironment,
|
||||
);
|
||||
const metrics =
|
||||
opts.metrics ??
|
||||
measureText(
|
||||
text,
|
||||
getFontString({ fontFamily, fontSize }),
|
||||
lineHeight,
|
||||
opts.renderEnvironment,
|
||||
);
|
||||
const textAlign = opts.textAlign || DEFAULT_TEXT_ALIGN;
|
||||
const verticalAlign = opts.verticalAlign || DEFAULT_VERTICAL_ALIGN;
|
||||
const offsets = getTextElementPositionOffsets(
|
||||
|
||||
@@ -38,8 +38,28 @@ export type RenderEnvironment = {
|
||||
createPath?: (svgPath: string) => Path2D;
|
||||
};
|
||||
|
||||
const defaultCreateCanvas = () => document.createElement("canvas");
|
||||
const defaultCreateImage = () => new Image();
|
||||
const defaultCreateCanvas = () => {
|
||||
if (typeof document === "undefined") {
|
||||
throw new Error(
|
||||
"Excalidraw: creating a canvas needs a `document`, and this " +
|
||||
"environment has none. Install a host environment with " +
|
||||
"`setRenderEnvironment({ createCanvas, createImage })` (e.g. backed " +
|
||||
"by `@napi-rs/canvas`), or, if the canvas was only needed to measure " +
|
||||
"text, a provider via `setCustomTextMetricsProvider`.",
|
||||
);
|
||||
}
|
||||
return document.createElement("canvas");
|
||||
};
|
||||
const defaultCreateImage = () => {
|
||||
if (typeof Image === "undefined") {
|
||||
throw new Error(
|
||||
"Excalidraw: decoding an image needs a global `Image`, and this " +
|
||||
"environment has none. Pass `createImage` in " +
|
||||
"`setRenderEnvironment` (e.g. `@napi-rs/canvas`'s `Image`).",
|
||||
);
|
||||
}
|
||||
return new Image();
|
||||
};
|
||||
const defaultCreatePath = (svgPath: string) => {
|
||||
if (typeof Path2D === "undefined") {
|
||||
throw new Error(
|
||||
|
||||
@@ -1,4 +1,16 @@
|
||||
import { embeddableURLValidator, getEmbedLink } from "../src/embeddable";
|
||||
import {
|
||||
createPlaceholderEmbeddableLabel,
|
||||
embeddableURLValidator,
|
||||
getEmbedLink,
|
||||
getPlaceholderLinkText,
|
||||
} from "../src/embeddable";
|
||||
import { newEmbeddableElement, newIframeElement } from "../src/newElement";
|
||||
import {
|
||||
resetRenderEnvironment,
|
||||
setRenderEnvironment,
|
||||
} from "../src/renderEnvironment";
|
||||
import { getLineHeightInPx } from "../src/textMeasurements";
|
||||
import { isTextElement } from "../src/typeChecks";
|
||||
|
||||
describe("YouTube timestamp parsing", () => {
|
||||
it("should parse YouTube URLs with timestamp in seconds", () => {
|
||||
@@ -231,3 +243,101 @@ describe("Google Drive video embedding", () => {
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getPlaceholderLinkText", () => {
|
||||
it("drops the scheme and www., and keeps short links intact", () => {
|
||||
expect(getPlaceholderLinkText("https://www.example.com/a")).toBe(
|
||||
"example.com/a",
|
||||
);
|
||||
expect(getPlaceholderLinkText("http://example.com")).toBe("example.com");
|
||||
});
|
||||
|
||||
it("caps long links with an ellipsis", () => {
|
||||
const capped = getPlaceholderLinkText(
|
||||
"https://www.youtube.com/watch?v=dQw4w9WgXcQ&list=PL0123456789abcdefghijklmnopqrstuv",
|
||||
);
|
||||
expect(capped).toBe("youtube.com/watch?v=dQw4w9WgX…");
|
||||
expect(capped.length).toBe(30);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createPlaceholderEmbeddableLabel", () => {
|
||||
const spyOnCreateElement = () => vi.spyOn(document, "createElement");
|
||||
let createElementSpy: ReturnType<typeof spyOnCreateElement>;
|
||||
|
||||
beforeEach(() => {
|
||||
createElementSpy = spyOnCreateElement();
|
||||
// any text measurement would build a metrics canvas through the
|
||||
// environment; the placeholder must be laid out without one
|
||||
setRenderEnvironment({
|
||||
createCanvas: () => {
|
||||
throw new Error("placeholder layout must not create a canvas");
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
resetRenderEnvironment();
|
||||
createElementSpy.mockRestore();
|
||||
});
|
||||
|
||||
const expectNoCanvas = () => {
|
||||
expect(
|
||||
createElementSpy.mock.calls.filter(([tag]) => tag === "canvas"),
|
||||
).toHaveLength(0);
|
||||
};
|
||||
|
||||
it("centers a short label in the embed on a single line", () => {
|
||||
const iframe = newIframeElement({
|
||||
type: "iframe",
|
||||
x: 40,
|
||||
y: 60,
|
||||
width: 300,
|
||||
height: 200,
|
||||
});
|
||||
|
||||
const label = createPlaceholderEmbeddableLabel(iframe);
|
||||
expectNoCanvas();
|
||||
expect(isTextElement(label)).toBe(true);
|
||||
if (!isTextElement(label)) {
|
||||
return;
|
||||
}
|
||||
|
||||
expect(label.text).toBe("IFrame element");
|
||||
expect(label.width).toBe(iframe.width - 20);
|
||||
expect(label.height).toBe(
|
||||
getLineHeightInPx(label.fontSize, label.lineHeight),
|
||||
);
|
||||
// centered on the embed
|
||||
expect(label.x + label.width / 2).toBe(iframe.x + iframe.width / 2);
|
||||
expect(label.y + label.height / 2).toBe(iframe.y + iframe.height / 2);
|
||||
});
|
||||
|
||||
it("shows a long link capped to a single line, centered in the embed", () => {
|
||||
const link =
|
||||
"https://www.youtube.com/watch?v=dQw4w9WgXcQ&list=PL0123456789abcdefghijklmnopqrstuv";
|
||||
const embed = newEmbeddableElement({
|
||||
type: "embeddable",
|
||||
x: 100,
|
||||
y: 50,
|
||||
width: 560,
|
||||
height: 315,
|
||||
link,
|
||||
});
|
||||
|
||||
const label = createPlaceholderEmbeddableLabel(embed);
|
||||
expectNoCanvas();
|
||||
if (!isTextElement(label)) {
|
||||
throw new Error("expected a text element");
|
||||
}
|
||||
|
||||
expect(label.text).toBe(getPlaceholderLinkText(link));
|
||||
expect(label.text).not.toContain("\n");
|
||||
expect(label.width).toBe(embed.width - 20);
|
||||
expect(label.height).toBe(
|
||||
getLineHeightInPx(label.fontSize, label.lineHeight),
|
||||
);
|
||||
expect(label.x + label.width / 2).toBe(embed.x + embed.width / 2);
|
||||
expect(label.y + label.height / 2).toBe(embed.y + embed.height / 2);
|
||||
});
|
||||
});
|
||||
@@ -509,10 +509,7 @@ const _renderStaticScene = ({
|
||||
element.width &&
|
||||
element.height
|
||||
) {
|
||||
const label = createPlaceholderEmbeddableLabel(
|
||||
element,
|
||||
renderConfig.renderEnvironment,
|
||||
);
|
||||
const label = createPlaceholderEmbeddableLabel(element);
|
||||
renderElement(
|
||||
label,
|
||||
elementsMap,
|
||||
|
||||
@@ -435,10 +435,7 @@ const renderElementToSvg = (
|
||||
);
|
||||
addToRoot(node, element);
|
||||
|
||||
const label = createPlaceholderEmbeddableLabel(
|
||||
element,
|
||||
renderConfig.renderEnvironment,
|
||||
);
|
||||
const label = createPlaceholderEmbeddableLabel(element);
|
||||
renderElementToSvg(
|
||||
label,
|
||||
elementsMap,
|
||||
|
||||
@@ -314,7 +314,6 @@ export const exportToSvg = async (
|
||||
skipInliningFonts?: true;
|
||||
reuseImages?: boolean;
|
||||
ownerDocument?: Document;
|
||||
renderEnvironment?: RenderEnvironment;
|
||||
},
|
||||
): Promise<SVGSVGElement> => {
|
||||
const ownerDocument =
|
||||
@@ -513,7 +512,6 @@ export const exportToSvg = async (
|
||||
offsetX,
|
||||
offsetY,
|
||||
isExporting: true,
|
||||
renderEnvironment: opts?.renderEnvironment,
|
||||
exportWithDarkMode,
|
||||
renderEmbeddables,
|
||||
frameRendering,
|
||||
|
||||
@@ -56,15 +56,12 @@ export type StaticCanvasRenderConfig = {
|
||||
theme: AppState["theme"];
|
||||
};
|
||||
|
||||
/**
|
||||
* NOTE: deliberately carries no `RenderEnvironment`: SVG rendering measures
|
||||
* no text and creates no canvas -- its only host dependency is the document
|
||||
* `exportToSvg` builds into.
|
||||
*/
|
||||
export type SVGRenderConfig = {
|
||||
/**
|
||||
* Host environment for the one thing this render still measures text for:
|
||||
* embeddable placeholder labels (`createPlaceholderEmbeddableLabel`). The
|
||||
* SVG itself is built through `exportToSvg`'s owner document, and frame
|
||||
* labels are drawn without measuring. Defaults to the process-wide
|
||||
* environment.
|
||||
*/
|
||||
renderEnvironment?: RenderEnvironment;
|
||||
offsetX: number;
|
||||
offsetY: number;
|
||||
isExporting: boolean;
|
||||
|
||||
@@ -415,7 +415,8 @@ describe("headless (server-side) export", () => {
|
||||
expect(createPath.mock.calls[0][0]).toMatch(/^M/);
|
||||
|
||||
// `exportToSvg` builds real DOM nodes, so a server-side caller supplies
|
||||
// the document (a DOM shim) alongside the render environment
|
||||
// the document (a DOM shim). It takes no render environment: SVG
|
||||
// export measures no text and creates no canvas
|
||||
const svg = await exportToSvg(
|
||||
elements,
|
||||
{
|
||||
@@ -423,7 +424,7 @@ describe("headless (server-side) export", () => {
|
||||
viewBackgroundColor: "#ffffff",
|
||||
},
|
||||
files,
|
||||
{ ownerDocument: hostDocument, renderEnvironment },
|
||||
{ ownerDocument: hostDocument },
|
||||
);
|
||||
|
||||
expect(svg.tagName.toLowerCase()).toBe("svg");
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
} from "@excalidraw/common";
|
||||
|
||||
import {
|
||||
getPlaceholderLinkText,
|
||||
newElementWith,
|
||||
resetRenderEnvironment,
|
||||
setRenderEnvironment,
|
||||
@@ -763,3 +764,63 @@ describe("exporting frames", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("embed placeholders", () => {
|
||||
it("renders them in SVG without measuring text (no canvas needed)", async () => {
|
||||
const createElementSpy = vi.spyOn(document, "createElement");
|
||||
setRenderEnvironment({
|
||||
createCanvas: () => {
|
||||
throw new Error("exportToSvg must not create a canvas");
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const iframe = API.createElement({
|
||||
type: "iframe",
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: 300,
|
||||
height: 200,
|
||||
});
|
||||
const link =
|
||||
"https://www.youtube.com/watch?v=dQw4w9WgXcQ&list=PL0123456789abcdefghijklmnopqrstuv";
|
||||
const embed = newElementWith(
|
||||
API.createElement({
|
||||
type: "embeddable",
|
||||
x: 400,
|
||||
y: 0,
|
||||
width: 560,
|
||||
height: 315,
|
||||
}),
|
||||
{ link },
|
||||
);
|
||||
|
||||
const svg = await exportToSvg({
|
||||
elements: [iframe, embed],
|
||||
files: null,
|
||||
exportPadding: 0,
|
||||
});
|
||||
|
||||
expect(
|
||||
createElementSpy.mock.calls.filter(([tag]) => tag === "canvas"),
|
||||
).toHaveLength(0);
|
||||
|
||||
const texts = Array.from(svg.querySelectorAll("text")).map(
|
||||
(node) => node.textContent,
|
||||
);
|
||||
expect(texts).toContain("IFrame element");
|
||||
|
||||
// the link is shown capped to a single line; the full link lives on
|
||||
// the element's anchor
|
||||
expect(texts).toContain(getPlaceholderLinkText(link));
|
||||
expect(
|
||||
Array.from(svg.querySelectorAll("a[href]")).some((anchor) =>
|
||||
anchor.getAttribute("href")?.includes("youtube.com/watch?v="),
|
||||
),
|
||||
).toBe(true);
|
||||
} finally {
|
||||
resetRenderEnvironment();
|
||||
createElementSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -189,8 +189,7 @@ export const exportToSvg = async ({
|
||||
skipInliningFonts,
|
||||
reuseImages,
|
||||
ownerDocument,
|
||||
renderEnvironment,
|
||||
}: Omit<ExportOpts, "getDimensions"> & {
|
||||
}: Omit<ExportOpts, "getDimensions" | "renderEnvironment"> & {
|
||||
exportPadding?: number;
|
||||
renderEmbeddables?: boolean;
|
||||
skipInliningFonts?: true;
|
||||
@@ -215,7 +214,6 @@ export const exportToSvg = async ({
|
||||
skipInliningFonts,
|
||||
reuseImages,
|
||||
ownerDocument,
|
||||
renderEnvironment,
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
Reference in new issue
Block a user