Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(spreadsheet): render cell and floating images in share
Elian Doran7f84e52fb56c
diff --git a/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts b/packages/commons/src/lib/spreadsheet/render_to_html.spec.tsindex b435d336c9..f52809e42b 100644--- a/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts+++ b/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts@@ -1173,6 +1173,227 @@ describe("renderSpreadsheetToHtml", () => {expect(html).toContain("--spreadsheet-gridline-color:transparent");});+ // Builds a workbook whose single sheet carries floating drawings in the+ // SHEET_DRAWING_PLUGIN resource (Univer's z-ordered floating images).+ function workbookWithFloatingDrawings(+ drawings: Array<Record<string, unknown> & { drawingId: string }>,+ opts: { cellData?: unknown; rowData?: unknown; columnData?: unknown } = {}+ ): string {+ const sheetId = "s1";+ const data: Record<string, unknown> = {};+ for (const d of drawings) data[d.drawingId] = d;+ const order = drawings.map((d) => d.drawingId);+ return JSON.stringify({+ version: 1,+ workbook: {+ sheetOrder: [sheetId],+ styles: {},+ sheets: {+ [sheetId]: {+ id: sheetId,+ name: "Sheet1",+ hidden: 0,+ rowCount: 1000,+ columnCount: 20,+ defaultColumnWidth: 88,+ defaultRowHeight: 24,+ mergeData: [],+ cellData: opts.cellData ?? { "0": { "0": { v: "anchor" } } },+ rowData: opts.rowData ?? {},+ columnData: opts.columnData ?? {}+ }+ },+ resources: [+ { name: "SHEET_DRAWING_PLUGIN", data: JSON.stringify({ [sheetId]: { data, order } }) },+ { name: "SHEET_DATA_VALIDATION_PLUGIN", data: JSON.stringify({ [sheetId]: [] }) }+ ]+ }+ });+ }++ const urlDrawing = (id: string, source: string, transform: Record<string, number>) => ({+ drawingId: id,+ unitId: "u",+ subUnitId: "s1",+ drawingType: 0,+ imageSourceType: "URL",+ source,+ transform+ });++ // #region Cell images (cellData[r][c].p.drawings)++ it("renders a cell image embedded in a cell's rich-text document", () => {+ const html = renderSpreadsheetToHtml(+ singleCellWorkbook({+ p: {+ drawings: {+ d1: {+ drawingId: "d1",+ imageSourceType: "URL",+ source: "api/attachments/NyhtJbXR6Qxh/image/image.png",+ transform: { width: 113, height: 96.72268495835375 }+ }+ },+ drawingsOrder: ["d1"]+ }+ })+ );+ expect(html).toContain('<img class="spreadsheet-cell-image"');+ expect(html).toContain('src="api/attachments/NyhtJbXR6Qxh/image/image.png"');+ // The image lives inside a table cell, not a floating wrapper.+ expect(html).toContain("<td");+ expect(html).not.toContain("spreadsheet-sheet");+ // Dimensions come from the drawing transform, rounded to 2 decimals.+ expect(html).toContain("width:113px");+ expect(html).toContain("height:96.72px");+ });++ it("renders a base64 cell image", () => {+ const html = renderSpreadsheetToHtml(+ singleCellWorkbook({+ p: {+ drawings: {+ d1: {+ drawingId: "d1",+ imageSourceType: "BASE64",+ source: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUg==",+ transform: { width: 10, height: 10 }+ }+ },+ drawingsOrder: ["d1"]+ }+ })+ );+ expect(html).toContain('src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUg=="');+ });++ it("renders multiple cell images in drawingsOrder", () => {+ const html = renderSpreadsheetToHtml(+ singleCellWorkbook({+ p: {+ drawings: {+ first: { drawingId: "first", source: "api/attachments/AAAAAAAAAAAA/image/a.png", transform: { width: 5, height: 5 } },+ second: { drawingId: "second", source: "api/attachments/BBBBBBBBBBBB/image/b.png", transform: { width: 5, height: 5 } }+ },+ drawingsOrder: ["first", "second"]+ }+ })+ );+ expect(html.indexOf("AAAAAAAAAAAA")).toBeLessThan(html.indexOf("BBBBBBBBBBBB"));+ });++ it("skips a cell image with an unsafe source", () => {+ const html = renderSpreadsheetToHtml(+ singleCellWorkbook({+ p: {+ drawings: {+ d1: { drawingId: "d1", source: "javascript:alert(1)", transform: { width: 10, height: 10 } },+ d2: { drawingId: "d2", source: "http://evil.example/x.png", transform: { width: 10, height: 10 } }+ },+ drawingsOrder: ["d1", "d2"]+ }+ })+ );+ expect(html).not.toContain("<img");+ expect(html).not.toContain("javascript:");+ expect(html).not.toContain("evil.example");+ });++ // #endregion++ // #region Floating images (SHEET_DRAWING_PLUGIN resource)++ it("renders a floating image absolutely positioned in a per-sheet wrapper", () => {+ const html = renderSpreadsheetToHtml(+ workbookWithFloatingDrawings([+ urlDrawing("img1", "api/attachments/cgN4jEBCA1Kn/image/image.png", { left: 50, top: 60, width: 100, height: 80 })+ ])+ );+ expect(html).toContain('<div class="spreadsheet-sheet"');+ expect(html).toContain("position:relative");+ expect(html).toContain('<img class="spreadsheet-floating-image"');+ expect(html).toContain('src="api/attachments/cgN4jEBCA1Kn/image/image.png"');+ expect(html).toContain("position:absolute");+ // Anchor cell is at (0,0), so the origin offset is zero.+ expect(html).toContain("left:50px");+ expect(html).toContain("top:60px");+ expect(html).toContain("width:100px");+ expect(html).toContain("height:80px");+ });++ it("offsets a floating image by the trimmed table origin", () => {+ // Data only at row 2, col 1 -> the table is trimmed; origin is the px distance+ // from A1 to that corner: 2 default rows (48px) down, 1 default col (88px) right.+ const html = renderSpreadsheetToHtml(+ workbookWithFloatingDrawings(+ [urlDrawing("img1", "api/attachments/cgN4jEBCA1Kn/image/image.png", { left: 200, top: 100, width: 50, height: 40 })],+ { cellData: { "2": { "1": { v: "x" } } } }+ )+ );+ expect(html).toContain("left:112px"); // 200 - 88+ expect(html).toContain("top:52px"); // 100 - 48+ });++ it("preserves floating image z-order", () => {+ const html = renderSpreadsheetToHtml(+ workbookWithFloatingDrawings([+ urlDrawing("img1", "api/attachments/AAAAAAAAAAAA/image/a.png", { left: 0, top: 0, width: 10, height: 10 }),+ urlDrawing("img2", "api/attachments/BBBBBBBBBBBB/image/b.png", { left: 0, top: 0, width: 10, height: 10 })+ ])+ );+ expect(html.indexOf("AAAAAAAAAAAA")).toBeLessThan(html.indexOf("BBBBBBBBBBBB"));+ });++ it("renders a base64 floating image", () => {+ const html = renderSpreadsheetToHtml(+ workbookWithFloatingDrawings([+ { drawingId: "img1", imageSourceType: "BASE64", source: "data:image/jpeg;base64,/9j/4AAQSk==", transform: { left: 0, top: 0, width: 10, height: 10 } }+ ])+ );+ expect(html).toContain('src="data:image/jpeg;base64,/9j/4AAQSk=="');+ });++ it("rounds fractional floating-image coordinates to two decimals", () => {+ const html = renderSpreadsheetToHtml(+ workbookWithFloatingDrawings([+ urlDrawing("img1", "api/attachments/cgN4jEBCA1Kn/image/image.png", { left: 262.3, top: 458.1, width: 549.4, height: 148.555 })+ ])+ );+ expect(html).toContain("width:549.4px");+ expect(html).toContain("height:148.56px");+ });++ it("does not wrap the sheet when all floating drawings have unsafe sources", () => {+ const html = renderSpreadsheetToHtml(+ workbookWithFloatingDrawings([+ { drawingId: "img1", imageSourceType: "URL", source: "http://evil.example/x.png", transform: { left: 0, top: 0, width: 10, height: 10 } }+ ])+ );+ expect(html).not.toContain("spreadsheet-sheet");+ expect(html).not.toContain("<img");+ expect(html).not.toContain("evil.example");+ });++ it("does not add a floating wrapper to a sheet without drawings", () => {+ const html = renderSpreadsheetToHtml(singleCellWorkbook({ v: "x" }));+ expect(html).not.toContain("spreadsheet-sheet");+ expect(html).not.toContain("<img");+ });++ it("escapes a quote in an attachment-image source", () => {+ // A crafted source that passes the prefix check but carries an attribute-breaking quote.+ const html = renderSpreadsheetToHtml(+ workbookWithFloatingDrawings([+ urlDrawing("img1", 'api/attachments/AAAAAAAAAAAA/image/"onerror=alert(1).png', { left: 0, top: 0, width: 10, height: 10 })+ ])+ );+ expect(html).not.toContain('"onerror=alert(1)');+ expect(html).toContain(""onerror");+ });++ // #endregion+it("extends bounds to cover a merge range that exceeds the cell data", () => {const input = JSON.stringify({version: 1,diff --git a/packages/commons/src/lib/spreadsheet/render_to_html.ts b/packages/commons/src/lib/spreadsheet/render_to_html.tsindex 25fd465e4b..050edc73d8 100644--- a/packages/commons/src/lib/spreadsheet/render_to_html.ts+++ b/packages/commons/src/lib/spreadsheet/render_to_html.ts@@ -15,6 +15,7 @@ import { format as formatNumfmt, formatColor as formatNumfmtColor } from "numfmtimport {BorderStyle,computeBounds,+ getFloatingDrawings,getVisibleSheets,HorizontalAlign,type IBorderStyleData,@@ -22,6 +23,7 @@ import {isFiniteNumber,type IRange,type IStyleData,+ type IWorkbookData,type IWorksheetData,parseWorkbookData,resolveCellStyle,@@ -54,12 +56,126 @@ export function renderSpreadsheetToHtml(jsonContent: string): string {if (visibleSheets.length > 1) {parts.push(`<h3>${escapeHtml(sheet.name)}</h3>`);}- parts.push(renderSheet(sheet, workbook.styles ?? {}));+ const table = renderSheet(sheet, workbook.styles ?? {});+ parts.push(wrapWithFloatingImages(workbook, sheet, table));}return parts.join("\n");}+// #region Images++/**+ * Wraps a rendered sheet table in a positioned container carrying the sheet's floating images,+ * each placed absolutely. Univer stores a floating image's `transform.left`/`top` in px from the+ * sheet origin (A1), but the table is trimmed to populated cells, so positions are shifted by the+ * px distance from A1 to the trimmed top-left corner. The container's `min-height` is stretched to+ * contain images that float below the table so they don't overlap following content. Returns the+ * table unchanged when the sheet has no renderable floating images.+ */+function wrapWithFloatingImages(workbook: IWorkbookData, sheet: IWorksheetData, tableHtml: string): string {+ const drawings = getFloatingDrawings(workbook, sheet.id);+ if (drawings.length === 0) return tableHtml;++ const bounds = computeBounds(sheet.cellData, sheet.mergeData ?? []);+ const originX = bounds ? sumColumnWidths(sheet, 0, bounds.minCol) : 0;+ const originY = bounds ? sumRowHeights(sheet, 0, bounds.minRow) : 0;++ const images: string[] = [];+ let maxBottom = 0;+ for (const drawing of drawings) {+ const src = sanitizeImageSource(drawing.source);+ if (!src || !drawing.transform) continue;++ const left = toFinite(drawing.transform.left) - originX;+ const top = toFinite(drawing.transform.top) - originY;+ const width = toFinite(drawing.transform.width);+ const height = toFinite(drawing.transform.height);+ maxBottom = Math.max(maxBottom, top + height);++ images.push(+ `<img class="spreadsheet-floating-image" style="position:absolute;left:${px(left)}px;top:${px(top)}px;width:${px(width)}px;height:${px(height)}px" src="${escapeHtml(src)}" alt="">`+ );+ }++ if (images.length === 0) return tableHtml;++ return `<div class="spreadsheet-sheet" style="position:relative;min-height:${px(maxBottom)}px">\n${tableHtml}\n${images.join("\n")}\n</div>`;+}++/** Renders the images embedded in a cell's rich-text document (`cell.p.drawings`), in order. */+function renderCellImages(cell: ICellData): string {+ const doc = cell.p;+ const drawings = doc?.drawings;+ if (!drawings) return "";++ const order = Array.isArray(doc?.drawingsOrder) ? doc.drawingsOrder : Object.keys(drawings);+ const images: string[] = [];+ for (const id of order) {+ const drawing = drawings[id];+ const src = drawing ? sanitizeImageSource(drawing.source) : null;+ if (!drawing || !src) continue;++ const dims: string[] = [];+ if (isFiniteNumber(drawing.transform?.width)) dims.push(`width:${px(drawing.transform.width)}px`);+ if (isFiniteNumber(drawing.transform?.height)) dims.push(`height:${px(drawing.transform.height)}px`);+ const style = dims.length ? ` style="${dims.join(";")}"` : "";++ images.push(`<img class="spreadsheet-cell-image"${style} src="${escapeHtml(src)}" alt="">`);+ }+ return images.join("");+}++function sumRowHeights(sheet: IWorksheetData, fromRow: number, toRowExclusive: number): number {+ const rowData = sheet.rowData ?? {};+ const defaultHeight = sheet.defaultRowHeight ?? 24;+ let sum = 0;+ for (let row = fromRow; row < toRowExclusive; row++) {+ const meta = rowData[row];+ if (meta?.hd) continue;+ sum += isFiniteNumber(meta?.h) ? meta.h : defaultHeight;+ }+ return sum;+}++function sumColumnWidths(sheet: IWorksheetData, fromCol: number, toColExclusive: number): number {+ const columnData = sheet.columnData ?? {};+ const defaultWidth = sheet.defaultColumnWidth ?? 88;+ let sum = 0;+ for (let col = fromCol; col < toColExclusive; col++) {+ const meta = columnData[col];+ if (meta?.hd) continue;+ sum += isFiniteNumber(meta?.w) ? meta.w : defaultWidth;+ }+ return sum;+}++/**+ * Validates an image source for inclusion in shared/exported HTML. Accepts only the relative+ * attachment-image URL Trilium emits (`api/attachments/<id>/image/...`, served by both the app+ * and the share view) and inline `data:image/...` URLs. Anything else (`javascript:`, remote+ * `http(s)`, etc.) returns `null` so the image is dropped. The returned value is still escaped+ * before being placed in an attribute.+ */+function sanitizeImageSource(source: string | null | undefined): string | null {+ if (typeof source !== "string") return null;+ const trimmed = source.trim();+ if (/^api\/attachments\/[a-zA-Z0-9_]+\/image\//.test(trimmed)) return trimmed;+ if (/^data:image\/(?:png|jpe?g|gif|webp|bmp|svg\+xml)[;,]/i.test(trimmed)) return trimmed;+ return null;+}++/** Rounds a px measurement to 2 decimals and renders it without a trailing `.00`. */+function px(value: number): string {+ return String(Math.round(value * 100) / 100);+}++function toFinite(value: number | undefined): number {+ return isFiniteNumber(value) ? value : 0;+}++// #endregion+function renderSheet(sheet: IWorksheetData, styles: Record<string, IStyleData | null>): string {const { cellData, mergeData = [], columnData = {}, rowData = {} } = sheet;@@ -106,7 +222,7 @@ function renderSheet(sheet: IWorksheetData, styles: Record<string, IStyleData |const cell = cellData[row]?.[col];const cellStyle = resolveCellStyle(cell?.s, styles);const cssText = buildCssText(cellStyle, cell);- const value = formatCellValue(cell, cellStyle);+ const value = formatCellValue(cell, cellStyle) + (cell ? renderCellImages(cell) : "");const attrs: string[] = [];// Cells with a background fill carry `has-fill` so the stylesheet can suppressdiff --git a/packages/commons/src/lib/spreadsheet/workbook_model.ts b/packages/commons/src/lib/spreadsheet/workbook_model.tsindex c9523238eb..996c6e6d45 100644--- a/packages/commons/src/lib/spreadsheet/workbook_model.ts+++ b/packages/commons/src/lib/spreadsheet/workbook_model.ts@@ -24,6 +24,13 @@ export interface IWorkbookData {name?: string;styles?: Record<string, IStyleData | null>;sheets: Record<string, IWorksheetData>;+ /** Plugin payloads (e.g. floating drawings); each `data` is itself a JSON string. */+ resources?: IResource[];+}++export interface IResource {+ name: string;+ data: string;}export interface IWorksheetData {@@ -49,6 +56,28 @@ export interface ICellData {t?: number | null;s?: IStyleData | string | null;f?: string | null;+ /** Rich-text document payload; carries images anchored inside the cell. */+ p?: ICellDocumentData | null;+}++export interface ICellDocumentData {+ drawings?: Record<string, ISheetDrawing>;+ drawingsOrder?: string[];+}++export interface ISheetDrawing {+ drawingId?: string;+ imageSourceType?: string;+ source?: string;+ transform?: IDrawingTransform | null;+}++/** A drawing's absolute box. `left`/`top` are px from the sheet origin (A1); cell images omit them. */+export interface IDrawingTransform {+ left?: number;+ top?: number;+ width?: number;+ height?: number;}export interface IStyleData {@@ -250,3 +279,31 @@ export function computeBounds(cellData: CellMatrix, mergeData: IRange[] = []): Bexport function isFiniteNumber(v: unknown): v is number {return typeof v === "number" && Number.isFinite(v);}++/** Univer stores floating sheet images (drawings) under this workbook resource. */+export const SHEET_DRAWING_RESOURCE = "SHEET_DRAWING_PLUGIN";++/**+ * Extracts the floating drawings for one sheet from the `SHEET_DRAWING_PLUGIN` resource, in+ * their stored z-order. The resource `data` is itself a JSON string keyed by sheet id:+ * `{ [sheetId]: { data: { [drawingId]: drawing }, order: string[] } }`. Returns an empty array+ * when the resource is absent, unparseable, or carries no drawings for the sheet.+ */+export function getFloatingDrawings(workbook: IWorkbookData, sheetId: string): ISheetDrawing[] {+ const resource = workbook.resources?.find((r) => r.name === SHEET_DRAWING_RESOURCE);+ if (!resource?.data) return [];++ let parsed: unknown;+ try {+ parsed = JSON.parse(resource.data);+ } catch {+ return [];+ }++ const sheetEntry = (parsed as Record<string, { data?: Record<string, ISheetDrawing>; order?: string[] }> | null)?.[sheetId];+ const data = sheetEntry?.data;+ if (!data) return [];++ const order = Array.isArray(sheetEntry?.order) ? sheetEntry.order : Object.keys(data);+ return order.map((id) => data[id]).filter((d): d is ISheetDrawing => Boolean(d));+}diff --git a/packages/share-theme/src/styles/content.css b/packages/share-theme/src/styles/content.cssindex da7bd8c62a..afce14555a 100644--- a/packages/share-theme/src/styles/content.css+++ b/packages/share-theme/src/styles/content.css@@ -130,3 +130,21 @@ body.type-webView {.spreadsheet-table.show-gridlines td:not(.has-fill) {border: 1px solid var(--spreadsheet-gridline-color, var(--background-highlight));}++/* A sheet that has floating images is wrapped in a positioned container; the images are+ emitted as absolutely-positioned <img> with inline left/top/width/height (computed from the+ Univer drawing transform, relative to the trimmed table origin). */+.spreadsheet-sheet {+ position: relative;+}++.spreadsheet-floating-image {+ object-fit: contain;+}++/* Images embedded inside a cell flow with the cell content. */+.spreadsheet-cell-image {+ display: block;+ max-width: 100%;+ object-fit: contain;+}