Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,8 @@ it("preserves merged text across tile clears", async () => {
context,
{
viewport: { x: 0, y: 0, width: 400, height: 80 },
behind: { x: 0, y: 0 },
panes: { width: 0, height: 0 },
list: { width: 400, height: 80, commands: [] },
tiles: [
{
Expand Down
181 changes: 116 additions & 65 deletions apps/web/src/components/files/office/sheet-frame.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.
import {
paintDisplayList,
type DisplayList,
type GridMeta,
type WorkbookHandle,
} from "@betteroffice/xlsx";
import { paintDisplayList, type DisplayList, type WorkbookHandle } from "@betteroffice/xlsx";
import { attempt } from "./sheet-cells";
import { frozenSize } from "./sheet-paint";
import type { SheetViewport } from "./sheet-protocol";
Expand All @@ -21,6 +16,12 @@ const maxSplit = 8;
*/
const seamOverlap = 8;

/**
* How far before a frame its cells are drawn from, in CSS pixels. The engine draws only the cells from a viewport's
* first track on, so the text of a cell before it, overflowing or merged into the frame, would vanish with that cell.
*/
const reach = { x: 1024, y: 512 };

/** Part of a frame: its display list, where its origin sits in the frame, and where it starts to show. */
type Tile = {
readonly list: DisplayList;
Expand All @@ -32,12 +33,14 @@ type Tile = {

/**
* A frame of cells: the tiles that draw it, one display list for its grid and links, without draw commands, and the
* viewport it shows.
* viewport it shows. The tiles' cells past the frozen panes start `behind` the viewport's.
*/
export type Frame = {
readonly list: DisplayList;
readonly tiles: readonly Tile[];
readonly viewport: SheetViewport;
readonly behind: { readonly x: number; readonly y: number };
readonly panes: { readonly width: number; readonly height: number };
};

/**
Expand All @@ -50,22 +53,20 @@ export function drawFrame(
frozen: { readonly rows: number; readonly cols: number },
wider?: SheetViewport,
): Frame | undefined {
const around = wider && untruncated(workbook, wider);

if (wider && around)
return {
list: around,
tiles: [{ list: around, x: 0, y: 0, clipX: 0, clipY: 0 }],
viewport: wider,
};

const whole = untruncated(workbook, viewport);

if (whole)
return { list: whole, tiles: [{ list: whole, x: 0, y: 0, clipX: 0, clipY: 0 }], viewport };
return (
(wider && reaching(workbook, wider, frozen, false)) ||
reaching(workbook, viewport, frozen, true)
);
}

// The engine refuses a viewport with too many cells, as a wide pane of narrow columns has. One row and one column of
// the frame give its tracks, and so where its frozen panes end.
/** A frame of `viewport` drawn from up to `reach` before it, split into tiles when `split` and the engine needs it. */
function reaching(
workbook: WorkbookHandle,
viewport: SheetViewport,
frozen: { readonly rows: number; readonly cols: number },
split: boolean,
): Frame | undefined {
// One row and one column of the viewport give its tracks, and so where its frozen panes end.
const columns = untruncated(workbook, { ...viewport, height: 1 })?.grid;
const rows = untruncated(workbook, { ...viewport, width: 1 })?.grid;

Expand All @@ -79,8 +80,33 @@ export function drawFrame(
...(columns.colIndices ? { colIndices: columns.colIndices } : {}),
colOffsets: columns.colOffsets,
};
const panes = frozenSize(grid, frozen);
const behind = { x: Math.min(reach.x, viewport.x), y: Math.min(reach.y, viewport.y) };
const area = {
x: viewport.x - behind.x,
y: viewport.y - behind.y,
width: viewport.width + behind.x,
height: viewport.height + behind.y,
};
const whole = untruncated(workbook, area);
// The engine refuses a viewport with too many cells, as a wide pane of narrow columns has.
const tiles = whole
? [{ list: whole, x: 0, y: 0, clipX: 0, clipY: 0 }]
: split
? tiled(workbook, area, panes, 2)
: undefined;

return tiled(workbook, viewport, frozenSize(grid, frozen), grid, 2);
if (!tiles) return undefined;

const hyperlinks = tiles.flatMap((tile) => tile.list.hyperlinks ?? []);

return {
list: { width: viewport.width, height: viewport.height, commands: [], grid, hyperlinks },
tiles,
viewport,
behind,
panes,
};
}

/** The engine's screen gridlines: one-pixel solid lines in its gridline grey, unlike any border it draws. */
Expand Down Expand Up @@ -133,7 +159,7 @@ export function chartFonts(

/**
* Draws a frame's tiles with the cells' top-left corner at `origin`, in device pixels, each tile from its seam on, so a
* tile covers the panes it repeats.
* tile covers the panes it repeats. The cells past the frozen panes move back by `behind`; the panes stay put.
*/
export function paintFrame(
context: OffscreenCanvasRenderingContext2D,
Expand All @@ -148,58 +174,92 @@ export function paintFrame(
const tiled = frame.tiles.length > 1;
const text = tiled ? new OffscreenCanvas(context.canvas.width, context.canvas.height) : undefined;
const textContext = text?.getContext("2d");

frame.tiles.forEach((tile) => {
const at = { x: origin.x + tile.x * ratio, y: origin.y + tile.y * ratio };
const list = tiled
? { ...tile.list, commands: tile.list.commands.filter((command) => command.op !== "text") }
: tile.list;

if (tile.clipX === 0 && tile.clipY === 0) return paintDisplayList(painter, list, ratio, at);
const columns = bands(frame.panes.width, frame.behind.x);
const rows = bands(frame.panes.height, frame.behind.y);
const parts = frame.tiles.flatMap((tile) =>
rows.flatMap((row) =>
columns.flatMap((column) => {
const left = Math.max(column.start, tile.clipX - column.shift);
const top = Math.max(row.start, tile.clipY - row.shift);

if (left >= column.end || top >= row.end) return [];

const clip = {
left: Math.round(origin.x + left * ratio),
top: Math.round(origin.y + top * ratio),
right: Math.round(origin.x + column.end * ratio),
bottom: Math.round(origin.y + row.end * ratio),
};

return [
{
tile,
at: {
x: origin.x + (tile.x - column.shift) * ratio,
y: origin.y + (tile.y - row.shift) * ratio,
},
clip:
left === 0 && top === 0 && column.end === Infinity && row.end === Infinity
? undefined
: clip,
},
];
}),
),
);
const clipped = (clip: (typeof parts)[number]["clip"], paint: () => void) => {
if (!clip) return paint();

context.save();
context.setTransform(1, 0, 0, 1, 0, 0);
context.beginPath();
context.rect(
Math.round(origin.x + tile.clipX * ratio),
Math.round(origin.y + tile.clipY * ratio),
context.canvas.width,
context.canvas.height,
clip.left,
clip.top,
Math.min(clip.right, context.canvas.width) - clip.left,
Math.min(clip.bottom, context.canvas.height) - clip.top,
);
context.clip();
paintDisplayList(painter, list, ratio, at);
paint();
context.restore();
};

parts.forEach(({ tile, at, clip }) => {
const list = tiled
? { ...tile.list, commands: tile.list.commands.filter((command) => command.op !== "text") }
: tile.list;

clipped(clip, () => paintDisplayList(painter, list, ratio, at));
});
// Text clips can span a merged range beyond its tile. Composite it after all tile clears and backgrounds.
if (text && textContext)
frame.tiles.forEach((tile) => {
parts.forEach(({ tile, at, clip }) => {
textContext.reset();
paintDisplayList(
textContext as unknown as CanvasRenderingContext2D,
{
...tile.list,
width: frame.viewport.width - tile.x,
height: frame.viewport.height - tile.y,
width: frame.viewport.width + frame.behind.x - tile.x,
height: frame.viewport.height + frame.behind.y - tile.y,
commands: tile.list.commands.filter((command) => command.op === "text"),
},
ratio,
{ x: origin.x + tile.x * ratio, y: origin.y + tile.y * ratio },
);
context.save();
context.setTransform(1, 0, 0, 1, 0, 0);
context.beginPath();
context.rect(
Math.round(origin.x + tile.clipX * ratio),
Math.round(origin.y + tile.clipY * ratio),
context.canvas.width,
context.canvas.height,
at,
);
context.clip();
context.drawImage(text, 0, 0);
context.restore();
clipped(clip, () => context.drawImage(text, 0, 0));
});
}

/** A side's frozen pane, drawn where it is, and the cells past it, drawn `behind` further on. */
function bands(panes: number, behind: number) {
return panes > 0 && behind > 0
? [
{ start: 0, end: panes, shift: 0 },
{ start: panes, end: Infinity, shift: behind },
]
: [{ start: 0, end: Infinity, shift: behind }];
}

/**
* A frame split into `split` tiles a side, each under the engine's cap. A tile past the first along an axis asks for
* the frozen panes too, as every viewport has them, so the cells past them start just before its seam.
Expand All @@ -208,9 +268,8 @@ function tiled(
workbook: WorkbookHandle,
viewport: SheetViewport,
panes: { readonly width: number; readonly height: number },
grid: GridMeta,
split: number,
): Frame | undefined {
): Tile[] | undefined {
const columns = segments(viewport.width, panes.width, split);
const rows = segments(viewport.height, panes.height, split);
const tiles: Tile[] = [];
Expand All @@ -236,19 +295,11 @@ function tiled(
}),
);

if (complete) {
const hyperlinks = tiles.flatMap((tile) => tile.list.hyperlinks ?? []);

return {
list: { width: viewport.width, height: viewport.height, commands: [], grid, hyperlinks },
tiles,
viewport,
};
}
if (complete) return tiles;

if (split >= maxSplit) return undefined;

return tiled(workbook, viewport, panes, grid, split + 1);
return tiled(workbook, viewport, panes, split + 1);
}

/** A viewport's display list, or undefined where the engine refuses it or cuts it short at its cell limit. */
Expand Down
63 changes: 63 additions & 0 deletions apps/web/src/components/files/office/sheet-resize.browser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,69 @@ it.each([false, true])(
},
);

it.each([false, true])(
"draws text from cells scrolled out before the frame, frozen: %s",
async (frozen) => {
const archive = new JSZip();
archive.file(
"xl/workbook.xml",
'<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Sample" sheetId="1" r:id="sheet"/></sheets></workbook>',
);
archive.file(
"xl/_rels/workbook.xml.rels",
'<Relationships><Relationship Id="sheet" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>',
);
archive.file(
"xl/styles.xml",
'<styleSheet><fonts count="1"><font><sz val="11"/><name val="Calibri"/></font></fonts><fills count="1"><fill><patternFill patternType="none"/></fill></fills><borders count="1"><border/></borders><cellXfs count="2"><xf/><xf applyAlignment="1"><alignment vertical="center"/></xf></cellXfs></styleSheet>',
);
archive.file(
"xl/worksheets/sheet1.xml",
`<worksheet>${frozen ? '<sheetViews><sheetView workbookViewId="0"><pane xSplit="1" ySplit="1" state="frozen" topLeftCell="B2"/></sheetView></sheetViews>' : ""}<sheetData><row r="2"><c r="B2" t="inlineStr"><is><t>${"M".repeat(60)}</t></is></c></row><row r="4"><c r="C4" t="inlineStr" s="1"><is><t>MMMM</t></is></c></row></sheetData><mergeCells><mergeCell ref="C4:C40"/></mergeCells></worksheet>`,
);
const bytes = await archive.generateAsync({ type: "arraybuffer" });
const client = createWorkerClient<SheetMethods>(
new Worker(new URL("./spreadsheet.worker.ts", import.meta.url), { type: "module" }),
);
const inked = async (
at: { x: number; y: number },
area: { x: number; y: number; width: number; height: number },
) => {
const frame = await client.call("frame", {
sheet: 0,
...at,
width: 400,
height: 300,
ratio: 1,
offset: { x: 0, y: 0 },
wider: undefined,
});
const canvas = new OffscreenCanvas(frame!.bitmap.width, frame!.bitmap.height);
const context = canvas.getContext("2d")!;
context.drawImage(frame!.bitmap, 0, 0);
frame!.bitmap.close();
const pixels = context.getImageData(area.x, area.y, area.width, area.height).data;
return pixels.some(
(value, index) => index % 4 === 0 && value < 128 && pixels[index + 3]! > 0,
);
};
try {
await client.call("open", {
bytes,
view: { hiddenGridlines: [], themeFonts: { major: "Calibri Light", minor: "Calibri" } },
});
// B2's text overflows to the right well past B, and the merge centres C4's text far below row 4.
const panes = frozen ? { x: 64, y: 20 } : { x: 0, y: 0 };
expect(
await inked({ x: 160, y: 0 }, { x: panes.x + 40, y: 20, width: 200, height: 20 }),
).toBe(true);
expect(await inked({ x: 0, y: 200 }, { x: 128, y: 200, width: 64, height: 80 })).toBe(true);
} finally {
client.close();
}
},
);

it("requests current dimensions after resizing and scrolling away and back before a frame arrives", async () => {
const archive = new JSZip();
archive.file(
Expand Down
Loading