Skip to content

Build your personal knowledge base with Trilium Notes

feat(spreadsheet): extract cell-embedded images as attachments

Elian Doranb78845f14658
diff --git a/apps/client/src/widgets/type_widgets/spreadsheet/persistence.spec.ts b/apps/client/src/widgets/type_widgets/spreadsheet/persistence.spec.ts
index 0575cde1ba..e75e9584a0 100644
--- a/apps/client/src/widgets/type_widgets/spreadsheet/persistence.spec.ts
+++ b/apps/client/src/widgets/type_widgets/spreadsheet/persistence.spec.ts
@@ -19,6 +19,27 @@ function readDrawing(workbook: IWorkbookData) {
return JSON.parse(workbook.resources?.[0]?.data ?? "{}")["sheet-1"].data;
}
+/**
+ * Builds a workbook holding the given drawing nodes inside a single cell's rich-text document
+ * (`sheets["sheet-1"].cellData[2][1].p.drawings`), as Univer stores cell-embedded (in-cell) images.
+ */
+function cellDrawingWorkbook(drawings: Record<string, { imageSourceType: string; source: string }>) {
+ return makeWorkbook({
+ sheets: {
+ "sheet-1": {
+ cellData: {
+ 2: { 1: { p: { drawings } } }
+ }
+ }
+ } as unknown as IWorkbookData["sheets"]
+ });
+}
+
+function readCellDrawings(workbook: IWorkbookData) {
+ const sheet = workbook.sheets?.["sheet-1"] as { cellData?: Record<string, Record<string, { p?: { drawings?: Record<string, { imageSourceType: string; source: string }> } }>> } | undefined;
+ return sheet?.cellData?.["2"]?.["1"]?.p?.drawings ?? {};
+}
+
describe("slimWorkbookData", () => {
it("drops the top-level workbook id and locale (both reassigned on load)", () => {
const result = slimWorkbookData(makeWorkbook({ id: "abc123", locale: LocaleType.ZH_CN, name: "Sheet" }));
@@ -143,6 +164,46 @@ describe("uploadNewDrawingImages", () => {
await uploadNewDrawingImages(workbook, new Set(), new Map(), upload("api/attachments/x/image/x.png"));
expect(workbook.resources).toBeUndefined();
});
+
+ it("uploads a base64 image embedded in a cell and rewrites it in place", async () => {
+ const workbook = cellDrawingWorkbook({
+ d1: { imageSourceType: "BASE64", source: "data:image/png;base64,EEEE" },
+ // An already-URL cell image must be left alone.
+ d2: { imageSourceType: "URL", source: "api/attachments/existing/image/existing.png" }
+ });
+
+ const uploaded: string[] = [];
+ await uploadNewDrawingImages(workbook, new Set(), new Map(), async (source) => {
+ uploaded.push(source);
+ return "api/attachments/cell1/image/image.png";
+ });
+
+ expect(uploaded).toEqual([ "data:image/png;base64,EEEE" ]);
+ const drawings = readCellDrawings(workbook);
+ expect(drawings.d1).toEqual({ imageSourceType: "URL", source: "api/attachments/cell1/image/image.png" });
+ expect(drawings.d2.source).toBe("api/attachments/existing/image/existing.png");
+ });
+
+ it("uploads cell images even when there is no floating-image drawing resource", async () => {
+ // Cell drawings live directly in the workbook (not in a SHEET_DRAWING_PLUGIN resource), so a
+ // workbook with only cell images and no resource must still trigger uploads.
+ const workbook = cellDrawingWorkbook({ d1: { imageSourceType: "BASE64", source: "data:image/png;base64,FFFF" } });
+
+ await uploadNewDrawingImages(workbook, new Set(), new Map(), upload("api/attachments/cell2/image/image.png"));
+
+ expect(readCellDrawings(workbook).d1).toEqual({ imageSourceType: "URL", source: "api/attachments/cell2/image/image.png" });
+ });
+
+ it("leaves a preexisting cell image as base64, uploading nothing", async () => {
+ const source = "data:image/png;base64,GGGG";
+ const workbook = cellDrawingWorkbook({ d1: { imageSourceType: "BASE64", source } });
+
+ await uploadNewDrawingImages(workbook, new Set([ source ]), new Map(), async () => {
+ throw new Error("should not upload a preexisting image");
+ });
+
+ expect(readCellDrawings(workbook).d1).toEqual({ imageSourceType: "BASE64", source });
+ });
});
describe("collectBase64DrawingSources", () => {
@@ -157,4 +218,13 @@ describe("collectBase64DrawingSources", () => {
expect(collectBase64DrawingSources(workbook)).toEqual(new Set([ "data:image/png;base64,DDDD" ]));
expect(collectBase64DrawingSources(makeWorkbook({}))).toEqual(new Set());
});
+
+ it("includes base64 sources from cell-embedded drawings", () => {
+ const workbook = cellDrawingWorkbook({
+ x: { imageSourceType: "BASE64", source: "data:image/png;base64,HHHH" },
+ y: { imageSourceType: "URL", source: "api/attachments/z/image/z.png" }
+ });
+
+ expect(collectBase64DrawingSources(workbook)).toEqual(new Set([ "data:image/png;base64,HHHH" ]));
+ });
});
diff --git a/apps/client/src/widgets/type_widgets/spreadsheet/persistence.tsx b/apps/client/src/widgets/type_widgets/spreadsheet/persistence.tsx
index a4940724f1..ba74c24141 100644
--- a/apps/client/src/widgets/type_widgets/spreadsheet/persistence.tsx
+++ b/apps/client/src/widgets/type_widgets/spreadsheet/persistence.tsx
@@ -332,7 +332,9 @@ export async function uploadNewDrawingImages(
targets.push({ node, source });
}
});
- if (!walked || targets.length === 0) return;
+ // `walked` may be null when there are only cell-embedded images (no drawing resource); those are
+ // mutated in place and need no re-serialization, so only `targets` gates whether there's work.
+ if (targets.length === 0) return;
let mutated = false;
for (const { node, source } of targets) {
@@ -348,7 +350,9 @@ export async function uploadNewDrawingImages(
mutated = true;
}
- if (mutated) {
+ // Re-serialize the drawing resource if it carried any mutated node. Cell-embedded images live in
+ // the workbook object and are already mutated in place, so they need no re-serialization.
+ if (mutated && walked) {
walked.resource.data = JSON.stringify(walked.drawingData);
}
}
@@ -366,25 +370,22 @@ interface DrawingResource {
}
/**
- * Walks the drawing resource of a saved workbook, invoking `callback` for every base64 image node
- * (an object with `imageSourceType === "BASE64"` and a `data:` `source`). The callback may mutate
- * the node in place. Returns the parsed drawing data and its resource so callers can re-serialize
- * after mutating, or `null` when there is no drawing resource / it fails to parse.
+ * Walks every base64 image node of a saved workbook, invoking `callback` for each (an object with
+ * `imageSourceType === "BASE64"` and a `data:` `source`). The callback may mutate the node in place.
+ *
+ * Two locations carry images:
+ * - **Floating images** are serialized in the `SHEET_DRAWING_PLUGIN` resource (a JSON string); the
+ * returned `{ resource, drawingData }` lets callers re-serialize after mutating.
+ * - **Cell-embedded images** live directly in the workbook object under
+ * `sheets[*].cellData[row][col].p.drawings`; mutating those nodes in place is enough — they need
+ * no re-serialization, which is why this returns `null` when only cell images are present.
+ *
+ * Returns `null` when there is no (parsable) drawing resource, regardless of cell images.
*/
function forEachBase64DrawingImage(
workbookData: Partial<IWorkbookData>,
callback: (node: Record<string, unknown>, source: string) => void
): DrawingResource | null {
- const resource = workbookData.resources?.find((r) => r.name === DRAWING_RESOURCE_NAME);
- if (!resource?.data) return null;
-
- let drawingData: unknown;
- try {
- drawingData = JSON.parse(resource.data);
- } catch {
- return null;
- }
-
const visit = (value: unknown) => {
if (Array.isArray(value)) {
value.forEach(visit);
@@ -401,6 +402,28 @@ function forEachBase64DrawingImage(
visit(node[key]);
}
};
+
+ // Cell-embedded images: sheets[*].cellData[row][col].p.drawings (live objects, mutated in place).
+ for (const sheet of Object.values(workbookData.sheets ?? {})) {
+ for (const row of Object.values(sheet?.cellData ?? {})) {
+ if (!row || typeof row !== "object") continue;
+ for (const cell of Object.values(row)) {
+ const drawings = (cell as { p?: { drawings?: unknown } } | undefined)?.p?.drawings;
+ if (drawings) visit(drawings);
+ }
+ }
+ }
+
+ // Floating images: serialized in the SHEET_DRAWING_PLUGIN resource.
+ const resource = workbookData.resources?.find((r) => r.name === DRAWING_RESOURCE_NAME);
+ if (!resource?.data) return null;
+
+ let drawingData: unknown;
+ try {
+ drawingData = JSON.parse(resource.data);
+ } catch {
+ return null;
+ }
visit(drawingData);
return { resource, drawingData };