Skip to content
Open
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
55 changes: 37 additions & 18 deletions src/core/xlsx/drawings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
* frame does not hold.
*/
import { isWebImage, type OpcPackage } from '../opc'
import { desc, descAll, kid, num, textOf, type XEl } from '../xml'
import { desc, descAll, kid, textOf, type XEl } from '../xml'
import { MAX_COL, MAX_ROWS, MAX_SHEET_WIDTH_PX, MAX_SHEET_HEIGHT_PX, ooxmlInt } from './limits'

/** A cell corner: 0-based column and row, and the offset into that cell in CSS pixels */
export interface DrawingCorner {
Expand Down Expand Up @@ -49,15 +50,39 @@ const attr = (el: XEl | undefined, local: string) => {
return undefined
}

const corner = (el: XEl | undefined): DrawingCorner | undefined =>
el
? {
c: num(textOf(kid(el, 'col')), 0)!,
r: num(textOf(kid(el, 'row')), 0)!,
dx: num(textOf(kid(el, 'colOff')), 0)! / EMU_PER_PX,
dy: num(textOf(kid(el, 'rowOff')), 0)! / EMU_PER_PX,
}
: undefined
function emu(value: string | undefined, maxPx: number, signed = false): number | undefined {
const n = ooxmlInt(value, signed ? -maxPx * EMU_PER_PX : 0, maxPx * EMU_PER_PX)
return n === undefined ? undefined : n / EMU_PER_PX
}

function corner(el: XEl | undefined): DrawingCorner | undefined {
if (!el) return undefined
const c = ooxmlInt(textOf(kid(el, 'col')), 0, MAX_COL - 1)
const r = ooxmlInt(textOf(kid(el, 'row')), 0, MAX_ROWS - 1)
const dx = emu(textOf(kid(el, 'colOff')), MAX_SHEET_WIDTH_PX, true)
const dy = emu(textOf(kid(el, 'rowOff')), MAX_SHEET_HEIGHT_PX, true)
if (c === undefined || r === undefined || dx === undefined || dy === undefined) return undefined
return { c, r, dx, dy }
}

/** Reject an invalid anchor as a whole; do not move corrupt drawings to the sheet's last cell. */
function placement(anchor: XEl): Pick<SheetDrawing, 'from' | 'to' | 'at' | 'size'> | undefined {
const from = corner(kid(anchor, 'from'))
if (anchor.n === 'twoCellAnchor') {
const to = corner(kid(anchor, 'to'))
return from && to ? { from, to } : undefined
}
const ext = kid(anchor, 'ext')
const w = emu(ext?.a.cx, MAX_SHEET_WIDTH_PX)
const h = emu(ext?.a.cy, MAX_SHEET_HEIGHT_PX)
if (w === undefined || h === undefined) return undefined
const size = { w, h }
if (anchor.n === 'oneCellAnchor') return from ? { from, size } : undefined
const pos = kid(anchor, 'pos')
const x = emu(pos?.a.x, MAX_SHEET_WIDTH_PX, true)
const y = emu(pos?.a.y, MAX_SHEET_HEIGHT_PX, true)
return x !== undefined && y !== undefined ? { at: { x, y }, size } : undefined
}

/** a chart's kind and title, from its chart part */
async function chartOf(pkg: OpcPackage, part: string): Promise<{ chart: string; title: string }> {
Expand All @@ -81,14 +106,8 @@ export async function readSheetDrawings(pkg: OpcPackage, sheetPath: string): Pro
const rels = await pkg.rels(rel.target)
for (const anchor of root?.c ?? []) {
if (anchor.n !== 'twoCellAnchor' && anchor.n !== 'oneCellAnchor' && anchor.n !== 'absoluteAnchor') continue
const ext = kid(anchor, 'ext')
const pos = kid(anchor, 'pos')
const place = {
from: corner(kid(anchor, 'from')),
to: corner(kid(anchor, 'to')),
at: pos ? { x: num(pos.a.x, 0)! / EMU_PER_PX, y: num(pos.a.y, 0)! / EMU_PER_PX } : undefined,
size: ext ? { w: num(ext.a.cx, 0)! / EMU_PER_PX, h: num(ext.a.cy, 0)! / EMU_PER_PX } : undefined,
}
const place = placement(anchor)
if (!place) continue
const chartRef = desc(anchor, 'chart')
const blip = desc(anchor, 'blip')
if (chartRef) {
Expand Down
20 changes: 20 additions & 0 deletions src/core/xlsx/limits.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/** OOXML worksheet limits. Imported CSV row counts and the generic view axes may exceed these. */
export const MAX_COL = 16_384
export const MAX_ROWS = 1_048_576
export const MAX_ROW_HEIGHT_PT = 409.5
export const MAX_COL_WIDTH = 255

/** Conservative drawing geometry budget: a whole worksheet at its largest cell sizes, in CSS px. */
export const MAX_SHEET_WIDTH_PX = MAX_COL * (MAX_COL_WIDTH * 7 + 8)
export const MAX_SHEET_HEIGHT_PX = MAX_ROWS * MAX_ROW_HEIGHT_PT * (4 / 3)

export function ooxmlNumber(value: string | undefined, min: number, max: number): number | undefined {
if (value === undefined || !value.trim()) return undefined
const n = Number(value)
return Number.isFinite(n) && n >= min && n <= max ? n : undefined
}

export function ooxmlInt(value: string | undefined, min: number, max: number): number | undefined {
const n = ooxmlNumber(value, min, max)
return Number.isSafeInteger(n) ? n : undefined
}
66 changes: 44 additions & 22 deletions src/core/xlsx/workbook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ import type { LoadReport, RowPages, SheetLoader } from './import'
import { toCsv } from '../convert'
import { parseTheme, type Theme } from '../theme'
import { Calc } from './calc'
import { kid, kids, num, parseXmlStream, type Attrs, type SaxHandler } from '../xml'
import { kid, kids, parseXmlStream, type Attrs, type SaxHandler } from '../xml'
import { formatValue, formatText } from './numfmt'
import { parseSheetStyles, type SheetStyles } from './styles'
import { MAX_COL, MAX_ROWS, MAX_COL_WIDTH, MAX_ROW_HEIGHT_PT, ooxmlInt, ooxmlNumber } from './limits'
import type { BlockOut, CellDetail, CellOut, ColInfo, FindMatch, FindOptions, Merge, RowOut, SheetInfo, SheetProgress, WorkbookMeta } from './types'

export const T_NUM = 0
Expand All @@ -17,9 +18,7 @@ export const T_ERR = 4
export const T_DATE = 5
export const T_EMPTY = 6

export const MAX_COL = 16384
/** rows a worksheet holds (Excel's limit): a sheet with more cannot be saved as a workbook */
export const MAX_ROWS = 1_048_576
export { MAX_COL, MAX_ROWS } from './limits'

const decodeX = (s: string) => (s.indexOf('_x') >= 0 ? s.replace(/_x([0-9A-Fa-f]{4})_/g, (_, h: string) => String.fromCharCode(parseInt(h, 16))) : s)

Expand Down Expand Up @@ -58,6 +57,13 @@ export function parseRange(ref: string): Merge | undefined {
return { r0, c0, r1, c1 }
}

/** Validate file coordinates here, without restricting parseRef/parseRange used by CSV and editing. */
function worksheetRef(ref: string): [number, number] | undefined {
if (!/^\$?[A-Z]{1,3}\$?[1-9][0-9]{0,6}$/.test(ref)) return undefined
const [r, c] = parseRef(ref.replace(/\$/g, ''))
return r < MAX_ROWS && c < MAX_COL ? [r, c] : undefined
}

export class SheetData {
/** shared formula groups: si → master cell key + formula text */
shared = new Map<number, { master: number; text: string }>()
Expand Down Expand Up @@ -121,8 +127,11 @@ class SheetHandler implements SaxHandler {
open(name: string, a: Attrs): boolean | void {
switch (name) {
case 'c': {
if (!this.rowCells) return true
const r = a.r
this.col = r ? parseRef(r)[1] : this.col + 1
const ref = r === undefined ? [this.row, this.col + 1] : worksheetRef(r)
if (!ref || ref[0] !== this.row || ref[1] >= MAX_COL) return true
this.col = ref[1]
this.cType = a.t ?? ''
this.cStyle = a.s ? Number(a.s) : 0
this.val = ''
Expand All @@ -149,40 +158,49 @@ class SheetHandler implements SaxHandler {
return true
case 'row': {
this.headerReady = true
this.row = a.r ? Number(a.r) - 1 : this.row + 1
const row = a.r === undefined ? this.row + 1 : (ooxmlInt(a.r, 1, MAX_ROWS) ?? 0) - 1
// Discard the whole record before sparse array lengths or progress counts can grow.
if (row < 0 || row >= MAX_ROWS) return true
this.row = row
this.col = -1
this.rowCells = []
const hidden = a.hidden === '1' || a.hidden === 'true'
if (hidden || a.ht) this.d.rowAttrs.set(this.row, { ht: a.ht ? Number(a.ht) : undefined, hidden: hidden || undefined })
this.rowHasHt = hidden || !!a.ht
const ht = ooxmlNumber(a.ht, 0, MAX_ROW_HEIGHT_PT)
if (hidden || ht !== undefined) this.d.rowAttrs.set(this.row, { ht, hidden: hidden || undefined })
this.rowHasHt = hidden || ht !== undefined
this.rowMaxPt = 0
if (hidden) this.newSizes.push([this.row, 0])
else if (a.ht) {
const px = Math.round((Number(a.ht) * 4) / 3)
else if (ht !== undefined) {
const px = Math.round((ht * 4) / 3)
if (px !== this.d.defaultRowH) this.newSizes.push([this.row, px])
}
return
}
case 'sheetFormatPr': {
const h = num(a.defaultRowHeight)
if (h) this.d.defaultRowH = Math.round((h * 4) / 3)
const w = num(a.defaultColWidth)
const base = num(a.baseColWidth)
if (w) this.d.defaultColW = Math.round(w * 7)
const h = ooxmlNumber(a.defaultRowHeight, 0, MAX_ROW_HEIGHT_PT)
if (h) this.d.defaultRowH = Math.max(1, Math.round((h * 4) / 3))
const w = ooxmlNumber(a.defaultColWidth, 0, MAX_COL_WIDTH)
const base = ooxmlInt(a.baseColWidth, 0, MAX_COL_WIDTH)
if (w) this.d.defaultColW = Math.max(1, Math.round(w * 7))
else if (base !== undefined) this.d.defaultColW = Math.round(base * 7 + 8)
return
}
case 'col': {
const min = Number(a.min) - 1
const max = Math.min(Number(a.max) - 1, MAX_COL - 1)
const first = ooxmlInt(a.min, 1, MAX_COL)
const last = ooxmlInt(a.max, 1, MAX_COL)
if (first === undefined || last === undefined || first > last) return
const min = first - 1
const max = last - 1
const hidden = a.hidden === '1' || a.hidden === 'true'
const w = hidden ? 0 : a.width ? Math.round(Number(a.width) * 7) : this.d.defaultColW
const width = ooxmlNumber(a.width, 0, MAX_COL_WIDTH)
if (a.width !== undefined && width === undefined) return
const w = hidden ? 0 : width !== undefined ? Math.round(width * 7) : this.d.defaultColW
this.d.colInfo.push({ min, max, w })
return
}
case 'pane':
if (a.state === 'frozen' || a.state === 'frozenSplit') {
this.d.frozen = { rows: Math.round(num(a.ySplit, 0)!), cols: Math.round(num(a.xSplit, 0)!) }
this.d.frozen = { rows: ooxmlInt(a.ySplit, 0, MAX_ROWS - 1) ?? 0, cols: ooxmlInt(a.xSplit, 0, MAX_COL - 1) ?? 0 }
}
return
case 'sheetView':
Expand All @@ -192,8 +210,12 @@ class SheetHandler implements SaxHandler {
this.headerReady = true
return
case 'mergeCell': {
const m = a.ref ? parseRange(a.ref) : undefined
if (m) this.d.merges.push(m)
const parts = a.ref?.split(':') ?? []
const start = worksheetRef(parts[0] ?? '')
const end = parts.length === 1 ? start : worksheetRef(parts[1] ?? '')
if (parts.length <= 2 && start && end && start[0] <= end[0] && start[1] <= end[1]) {
this.d.merges.push({ r0: start[0], c0: start[1], r1: end[0], c1: end[1] })
}
return
}
case 'extLst':
Expand Down Expand Up @@ -274,7 +296,7 @@ class SheetHandler implements SaxHandler {
}
case 'row':
if (!this.rowHasHt && this.rowMaxPt > this.basePt * 1.15) {
const px = Math.round(this.rowMaxPt * (4 / 3) * 1.3 + 3)
const px = Math.min(MAX_ROW_HEIGHT_PT * (4 / 3), Math.round(this.rowMaxPt * (4 / 3) * 1.3 + 3))
if (px > this.d.defaultRowH) {
this.newSizes.push([this.row, px])
this.d.autoRowH.set(this.row, px)
Expand Down
7 changes: 4 additions & 3 deletions src/react/xlsx/axis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export class Axis {
let hi = this.keys.length - 1
let k = -1
while (lo <= hi) {
const mid = (lo + hi) >> 1
const mid = lo + Math.floor((hi - lo) / 2)
if (this.keys[mid] < i) {
k = mid
lo = mid + 1
Expand All @@ -53,11 +53,12 @@ export class Axis {

/** Index containing offset px (clamped to [0, count-1]). */
index(px: number): number {
if (px <= 0) return 0
if (px <= 0 || Number.isNaN(px) || !Number.isSafeInteger(this.count)) return 0
let lo = 0
let hi = Math.max(0, this.count - 1)
while (lo < hi) {
const mid = (lo + hi + 1) >> 1
// Bitwise midpoints overflow at 2^31; large CSV axes intentionally exceed Excel's limits.
const mid = lo + Math.ceil((hi - lo) / 2)
if (this.pos(mid) <= px) lo = mid
else hi = mid - 1
}
Expand Down
9 changes: 6 additions & 3 deletions src/react/xlsx/drawings.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useEffect, useState, type CSSProperties, type ReactNode } from 'react'
import type { DocumentClient } from '../../core/worker/client'
import type { SheetDrawing } from '../../core/xlsx/drawings'
import { MAX_COL, MAX_ROWS } from '../../core/xlsx/limits'
import { Icon } from '../edit/Toolbar'
import type { Axis } from './axis'

Expand Down Expand Up @@ -54,9 +55,11 @@ export function drawingExtent(list: SheetDrawing[], cols: Axis, rows: Axis): { r
const end = d.to ?? (d.from && d.size ? { c: d.from.c + Math.ceil(d.size.w / cols.def), r: d.from.r + Math.ceil(d.size.h / rows.def) } : undefined)
const fromAt = !end && d.at && d.size ? { c: Math.ceil((d.at.x + d.size.w) / cols.def), r: Math.ceil((d.at.y + d.size.h) / rows.def) } : undefined
const e = end ?? fromAt
if (e) {
r = Math.max(r, e.r + 1)
c = Math.max(c, e.c + 1)
if (e && Number.isFinite(e.r) && Number.isFinite(e.c)) {
// Sizes/absolute positions are in pixels and can span many default-sized cells. Only this
// OOXML drawing contribution is bounded; the sheet's CSV row count and Axis stay unrestricted.
r = Math.max(r, Math.min(MAX_ROWS, e.r + 1))
c = Math.max(c, Math.min(MAX_COL, e.c + 1))
}
}
return { rows: r, cols: c }
Expand Down
53 changes: 53 additions & 0 deletions test/axis.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { expect, test } from 'bun:test'
import { Axis } from '../src/react/xlsx/axis'

/** Bound the old non-converging search as well, so a regression fails without hanging the test runner. */
class BoundedAxis extends Axis {
lookups = 0
override pos(i: number): number {
if (++this.lookups > 64) throw new Error('Axis.index did not converge within 64 lookups')
return super.pos(i)
}
lookup(px: number): number {
this.lookups = 0
return this.index(px)
}
}

test('axis lookup preserves large CSV counts without signed 32-bit overflow', () => {
const axis = new BoundedAxis(20)
for (const count of [500_000_000, 2 ** 31, 4_000_000_000, 2 ** 32 + 1, Number.MAX_SAFE_INTEGER]) {
axis.count = count
expect(axis.lookup(0)).toBe(0)
expect(axis.lookup(20)).toBe(1)
expect(axis.lookup((count - 2) * 20)).toBe(count - 2)
expect(axis.lookup(Infinity)).toBe(count - 1)
expect(axis.count).toBe(count)
}
})

test('large sparse axes find custom-sized and hidden rows at their exact boundaries', () => {
const axis = new BoundedAxis(20)
axis.count = 4_000_000_000
axis.set(0, 0)
axis.set(3_000_000_000, 40)
axis.set(3_000_000_001, 0)
expect(axis.lookup(1)).toBe(1)
const start = axis.pos(3_000_000_000)
expect(start).toBe(3_000_000_000 * 20 - 20)
expect(axis.lookup(start)).toBe(3_000_000_000)
expect(axis.lookup(start + 39)).toBe(3_000_000_000)
expect(axis.lookup(start + 40)).toBe(3_000_000_002)
expect(axis.total()).toBe(axis.count * 20 - 20)
})

test('empty axes and nonfinite inputs terminate', () => {
const axis = new BoundedAxis(20)
for (const count of [0, -1, NaN, Infinity, 1.5]) {
axis.count = count
expect(axis.lookup(20)).toBe(0)
}
axis.count = 4_000_000_000
expect(axis.lookup(NaN)).toBe(0)
expect(axis.lookup(-Infinity)).toBe(0)
})
Loading
Loading