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
5 changes: 5 additions & 0 deletions .changeset/render-row-heights.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"javascript-excel": minor
---

`javascript-excel/render`: `setRowHeights(sheet, heights)` sets measured heights for rows without a stored height (a viewer's auto-fit). It grows rows only, clamped to 409 pt, and rebuilds the offsets from the first changed row. `hasStoredRowHeight(sheet, row)` tells which rows the file sized.
7 changes: 7 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -1372,6 +1372,8 @@ export function rowAt(s: RenderSheet, y: number): number; // the visible
export function colAt(s: RenderSheet, x: number): number;
export function isRowHidden(s: RenderSheet, row: number): boolean;
export function isColHidden(s: RenderSheet, col: number): boolean;
export function hasStoredRowHeight(s: RenderSheet, row: number): boolean; // the file sets this row's height
export function setRowHeights(s: RenderSheet, heights: ReadonlyArray<readonly [row: number, px: number]>): boolean; // auto-fit

export interface CellRef { row: number; col: number }
export interface RangeRef { start: CellRef; end: CellRef } // inclusive, start <= end
Expand All @@ -1382,6 +1384,11 @@ export interface RangeRef { start: CellRef; end: CellRef } // inclusive, s
- **Column widths.** A width in characters becomes pixels with the file-width formula and `maxDigitWidth` (§3.3). Missing widths use `sheet.defaultColWidth`, else 8.43 characters (64 px at the default 7).
- **Hidden rows and columns.** Hidden, or width/height 0, means size 0. `rowAt`/`colAt` never return a hidden index.
- **Cost.** Offsets are prefix sums, built once in O(rows + columns) (`Float64Array`). `rowTop`/`colLeft` are O(1), and `rowAt`/`colAt` are O(log n).
- **Auto-fit** (react-xlsx-viewer decision Q11). Excel fits rows without a stored height to their content (wrapped, rotated or larger text) when it opens a file. The render model can't measure text, so the viewer measures and calls `setRowHeights` with CSS px at zoom 100 %.
- It only applies to rows without a stored height (`hasStoredRowHeight` is false) that aren't hidden.
- Heights are clamped to [the default row height, 409 pt], so auto-fit only grows rows.
- The offsets are rebuilt from the first changed row onwards, so a batch costs O(rows after it). `rowTop`, `rowHeight` and `rowAt` reflect the new heights at once.
- The model isn't changed, only the handle's geometry. Cells don't depend on row heights, so their cache is kept.
- **Settings.** They come from `sheet.view` and `sheet.tabColor`:
- zoom defaults to 100, the active cell to A1;
- grid lines and headers are shown unless the file turns them off;
Expand Down
4 changes: 3 additions & 1 deletion packages/javascript-excel/scripts/consumer.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ void bytes; void fromWorker; void asText; void exposeWorker;
`;

const RENDER_FIXTURE = `
import { createRenderSheet, edge, rangeAsTsv, renderCell, rowAt, sheetSettings, type RenderCell, type RenderFormatter, type RenderOptions, type RenderSheet } from ${JSON.stringify(`${pkg.name}/render`)};
import { createRenderSheet, edge, hasStoredRowHeight, rangeAsTsv, renderCell, rowAt, setRowHeights, sheetSettings, type RenderCell, type RenderFormatter, type RenderOptions, type RenderSheet } from ${JSON.stringify(`${pkg.name}/render`)};
import { resolveColor, type Cell as RCell, type Workbook as RWorkbook } from ${JSON.stringify(pkg.name)};
declare const book: RWorkbook<RCell>;
const renderFmt: RenderFormatter = (cell, o) => ({ text: String(cell.value ?? ""), align: o.locale ? "right" : undefined });
Expand All @@ -205,6 +205,8 @@ const bg: string | undefined = rc?.style.background.kind === "solid" ? rc.style.
const where: { row: number; col: number } = edge(rs, { row: 0, col: 0 }, "down");
const tsv: string = rangeAsTsv(rs, { start: where, end: where }, { values: "raw" });
const frozen: number = sheetSettings(rs).freeze.rows + rowAt(rs, 100);
const grew: boolean = setRowHeights(rs, [[0, 40]]) && !hasStoredRowHeight(rs, 0);
void grew;
const argb: string = resolveColor({ theme: 4, tint: 0.4 }, { theme: book.theme, indexedColors: book.indexedColors });
void bg; void tsv; void frozen; void argb;
`;
Expand Down
46 changes: 46 additions & 0 deletions packages/javascript-excel/src/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,8 @@ interface State {
usedRows: number;
usedCols: number;
rowTops: Float64Array;
/** Default row height in px at zoom 100 %, the floor for auto-fitted rows. */
defaultRowPx: number;
colLefts: Float64Array;
merges: Merge[];
buckets: Map<number, number[]>;
Expand Down Expand Up @@ -270,6 +272,7 @@ export function createRenderSheet(workbook: Workbook<CellInput>, sheet: number,
usedRows,
usedCols,
rowTops,
defaultRowPx,
colLefts,
merges,
buckets,
Expand Down Expand Up @@ -342,6 +345,49 @@ export function colWidth(s: RenderSheet, col: number): number {
export function isRowHidden(s: RenderSheet, row: number): boolean {
return rowHeight(s, row) === 0;
}
/** Excel's largest row height, 409 pt, in CSS px. */
const MAX_ROW_PX = (409 * 96) / 72;

/** True when the row's height comes from the file (`rowProps[row].height`); only other rows may be auto-fitted (§5.8.1). */
export function hasStoredRowHeight(s: RenderSheet, row: number): boolean {
return state(s).sh.rowProps?.[row]?.height !== undefined;
}

/**
* Sets measured heights, in CSS px at zoom 100 %, for rows without a stored height: the viewer's
* auto-fit (§5.8.1). Rows with a stored height, hidden rows and rows outside the extent are ignored.
* Heights are clamped to [default row height, 409 pt], so auto-fit only grows rows. The offset table
* is rebuilt from the first changed row onwards. Returns true when anything changed.
* (An array, not an Iterable, so the declaration works with ES5 lib typings; see Consumer TS.)
*/
export function setRowHeights(s: RenderSheet, heights: ReadonlyArray<readonly [row: number, px: number]>): boolean {
const st = state(s);
const tops = st.rowTops;
const updates = new Map<number, number>();
let first = Number.POSITIVE_INFINITY;
for (const [row, px] of heights) {
if (!(Number.isInteger(row) && row >= 0 && row < st.rows) || !Number.isFinite(px)) continue;
const props = st.sh.rowProps?.[row];
if (props?.hidden || props?.height !== undefined) continue;
const current = tops[row + 1]! - tops[row]!;
if (current === 0) continue;
const next = Math.min(MAX_ROW_PX, Math.max(st.defaultRowPx, px));
if (next !== current) {
updates.set(row, next);
if (row < first) first = row;
}
}
if (updates.size === 0) return false;
// Rebuild the prefix sums from the first changed row, reading each old height before it is overwritten.
let oldTop = tops[first]!;
for (let r = first; r < st.rows; r++) {
const oldNext = tops[r + 1]!;
tops[r + 1] = tops[r]! + (updates.get(r) ?? oldNext - oldTop);
oldTop = oldNext;
}
return true;
}

export function isColHidden(s: RenderSheet, col: number): boolean {
return colWidth(s, col) === 0;
}
Expand Down
4 changes: 2 additions & 2 deletions packages/javascript-excel/test/entries.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ describe("entries", () => {

it("/render exports the documented API", () => {
expect(Object.keys(render).sort()).toEqual([
"colAt", "colLeft", "colWidth", "createRenderSheet", "edge", "isColHidden", "isRowHidden", "lastUsedCell", "mergeAt",
"rangeAsHtml", "rangeAsTsv", "rangeStats", "renderCell", "rowAt", "rowHeight", "rowTop", "sheetExtent", "sheetSettings", "step",
"colAt", "colLeft", "colWidth", "createRenderSheet", "edge", "hasStoredRowHeight", "isColHidden", "isRowHidden", "lastUsedCell", "mergeAt",
"rangeAsHtml", "rangeAsTsv", "rangeStats", "renderCell", "rowAt", "rowHeight", "rowTop", "setRowHeights", "sheetExtent", "sheetSettings", "step",
]);
});

Expand Down
32 changes: 32 additions & 0 deletions packages/javascript-excel/test/render/render.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import {
rowAt,
rowHeight,
rowTop,
hasStoredRowHeight,
setRowHeights,
sheetExtent,
sheetSettings,
step,
Expand Down Expand Up @@ -83,6 +85,36 @@ describe("geometry", () => {
});
});

describe("row-height overrides (auto-fit)", () => {
const sheet = () =>
rs({ name: "S", rows: [[1], [2], [3], [4], [5]], rowProps: [undefined, { height: 30 }, { hidden: true }] }, {}, { margin: { rows: 0, cols: 0 } });

it("knows which rows have a stored height", () => {
const s = sheet();
expect(hasStoredRowHeight(s, 0)).toBe(false);
expect(hasStoredRowHeight(s, 1)).toBe(true);
});

it("grows rows without a stored height and rebuilds the offsets after them", () => {
const s = sheet();
expect(rowTop(s, 5)).toBe(20 + 40 + 0 + 20 + 20);
expect(setRowHeights(s, [[0, 50], [3, 35]])).toBe(true);
expect([0, 1, 2, 3, 4].map((r) => rowHeight(s, r))).toEqual([50, 40, 0, 35, 20]);
expect([0, 1, 2, 3, 4, 5].map((r) => rowTop(s, r))).toEqual([0, 50, 90, 90, 125, 145]);
expect(rowAt(s, 100)).toBe(3);
// Unchanged heights report no change.
expect(setRowHeights(s, [[0, 50]])).toBe(false);
});

it("ignores stored-height, hidden and out-of-range rows; clamps to [default, 409 pt]", () => {
const s = sheet();
expect(setRowHeights(s, [[1, 99], [2, 99], [9, 99], [-1, 99], [0, Number.NaN]])).toBe(false);
expect(setRowHeights(s, [[0, 5], [3, 10_000]])).toBe(true);
expect(rowHeight(s, 0)).toBe(20); // never below the default
expect(rowHeight(s, 3)).toBeCloseTo((409 * 96) / 72, 6);
});
});

describe("cells, styles and merges", () => {
it("returns null for nothing to draw, and for covered merge cells", () => {
const s = rs({ name: "S", rows: [[{ value: "Title" }, { value: "hidden by the merge" }]], merges: ["A1:C2"] });
Expand Down
Loading