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
3 changes: 3 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -539,6 +539,9 @@ await doc.call('xlsx.set', 0, [{ r: 5, c: 1, input: '1.234,5' }], { locale: 'de-
const clip = await doc.call('xlsx.copy', 0, { r0: 0, c0: 0, r1: 9, c1: 2 }) // cells as they are (values, formats, formulas) + `text` for the clipboard
await doc.call('xlsx.sheetOp', 0, { op: 'paste', range: { r0: 20, c0: 0, r1: 29, c1: 2 }, cells: clip.cells, from: { sheet: clip.sheet, r0: 0, c0: 0 } })
await doc.call('xlsx.sheetOp', 0, { op: 'clear', range: { r0: 0, c0: 3, r1: 1048575, c1: 3 } }) // a whole column, every row of it
await doc.call('xlsx.sheetOp', 0, { op: 'validate', range: { r0: 1, c0: 1, r1: 99, c1: 1 }, rule: { values: ['Red', 'Green'] } }) // B2:B100 take a value of a list (`rule: { source: 'Lists!$A$1:$A$9' }`: held by cells; `strict: false`: others too; `rule: null` takes the validation off)
await doc.call('xlsx.listValues', 0, 1, 1) // { values, inputs, capped? }: the list of B2 as shown, and what `xlsx.set` takes for each
await doc.call('xlsx.set', 0, [{ r: 1, c: 1, input: 'Pink' }], { validate: true }) // as typed by a person: fails with the message of the list that does not take it (without `validate` every value goes in)
await doc.call('xlsx.import', 0, csvFile, { name: 'cities' }) // a new sheet after sheet 0 with the rows of a CSV / TSV, streamed in when loaded
await doc.call('xlsx.text', 0, ',') // the sheet as CSV (a Blob; '\t' for TSV), the values as shown
// open(src, { residentCells: 12_000_000 }): cells of a CSV / TSV kept in memory; the other rows are read from the file as they are shown
Expand Down
3 changes: 2 additions & 1 deletion docs/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,7 @@ Diagram sources open as a document holding the drawing (an SVG picture, editable
- **Typing formulas**: function name & argument hints while typing, click/drag cells (incl. other sheets, arrow keys) to insert references, colored references, auto-close parentheses, functions menu (SUM/AVERAGE/COUNT/MAX/MIN)
- **Formatting**: paint format, currency/percent/decimal buttons + 20 number formats and a format code typed by hand (*Custom format…*: `#,##0 "đ"`, `ddd dd/mm`), font, size, B/I/U/S, text/fill color, borders (8 kinds, color, line style), merge all/horizontally/vertically, horizontal & vertical alignment, wrap, text rotation, clear formatting. A column or a row selected by its header (or `Ctrl+Space` / `Shift+Space`), or the whole sheet, takes the format as its own (`<col style>`, `<row s>`): its empty cells show it and what is typed there later has it, without a cell per place; a plain range of more cells than can be formatted one by one is refused with a message
- **Rows & columns**: insert/delete/hide/unhide (defined names, print areas, filters, hyperlinks, data validation, conditional formats, page breaks, tables, the anchors of pictures and charts and the cells charts draw follow), drag to resize column width/row height, freeze, gridlines
- **Data validation**: a cell that takes a value of a list (typed in the rule, or held by cells: a range, also of another sheet, a defined name, a formula giving one) has a button that opens it (`Alt+Down` too: arrows, `Enter`, `Escape`). A value outside the list is refused when typed, with the message of the file, where the rule says to stop; a warning or an information lets it through. Only what is typed is checked (in the cell, in the formula bar, `Ctrl+Enter` over a selection): a paste, a fill, a replace and what a formula gives are not. *Data validation…* (toolbar, context menu) gives the selected cells a list, edits it or takes it away: one Undo, one operation in a room. The other kinds (whole numbers, decimals, dates, times, text lengths, custom formulas) are kept as they are and written back, not enforced; so are the lists a newer Excel keeps in the extension list, which show no button. The rules follow the rows and columns inserted and deleted, also those of the sheet that holds the values
- **Sheets**: add/rename/delete/reorder, duplicate (cells, formats, widths and merges; formulas naming the sheet itself name the copy; drawings, comments and tables of the original are not copied). A name that is empty or taken is refused with a message; one that is cut to 31 characters or has `\ / ? * [ ] :` replaced says so
- **Protection**: a protected sheet refuses the edits of its locked cells and the format / structure edits its protection does not allow, a workbook with a locked structure the changes of its sheet list, each with a message; locked cells are not cut either (the password is not asked for: protection is not removed here)
- **Other**: context menu, undo/redo
Expand Down Expand Up @@ -362,7 +363,7 @@ selected by dragging, nor shapes moved.

- Formulas: no names or tables can be defined or edited (those of the file are read); a formula pointing at another workbook keeps its value; pivot tables are not computed (`GETPIVOTDATA` reads what the file shows); the limits of single functions are in [formula-coverage.md](formula-coverage.md)
- DOCX: text boxes and nested tables are read-only; paragraphs with fields spanning multiple paragraphs (TOC) are read-only; headers / footers are edited as text lines (pictures, tables and shapes in them are replaced when edited, with a warning); a header taller than the top margin overlaps the text; tracked changes don't cover formatting changes, paragraph marks or pictures; page setup applies to the whole document (not per section); tab stops cannot be set or moved in the editor (those of the file are kept and followed), and a bar tab is not drawn
- XLSX: no chart/pivot/conditional format/data validation/filter editing; a table whose cells are all deleted stays in the file; cells cut and pasted do not take their merges, comments or conditional formats along; a sheet read by pages (a CSV past 12 million cells) takes no row / column insert or delete, and its formulas only the rows that fit in memory
- XLSX: no chart/pivot/conditional format/filter editing; data validation is for lists only (the other kinds are kept, not enforced), and is not copied with the cells pasted or filled; `INDIRECT` of a defined name gives a list no values; a table whose cells are all deleted stays in the file; cells cut and pasted do not take their merges, comments or conditional formats along; a sheet read by pages (a CSV past 12 million cells) takes no row / column insert or delete, and its formulas only the rows that fit in memory
- PPTX: can't rotate shapes with the mouse yet, no table insert / row or column edit (Tab in the last cell adds no row), no animations/transitions, speaker notes are not editable; undo of slide list changes (add/delete/move) is not available in a shared (collaborative) session
- Comments: plain text only; DOCX comments can't cover text in more than one table cell or across a table; comments in headers, footers and footnotes are kept but not shown; PPTX comments anchored to a shape are shown at the shape's position when the file is opened and keep that anchor until moved
- Files from someone else: nothing a file says is used as an address to load when it is opened (a color that is not a color, a link that is not a web / mail / phone link and a name the format does not know are ignored; pictures linked from outside the file are not fetched). A package is refused, with a message, when it names a part twice (also by case), holds more than 200,000 files, has a part that unpacks to more than 1 GB (16 GB for sheet data and the document body, which are streamed) or nests XML deeper than 1,024 elements
212 changes: 212 additions & 0 deletions e2e/xlsx-validation.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
import { describe, expect, test } from 'bun:test'
import { book, rows } from '../test/xlsx-builder'
import { ZipArchive } from '../src/core/zip'
import { BlobSource } from '../src/core/source'
import { useBrowser, viewer, type Viewer } from './harness'

useBrowser()

const GRID = [
['Item', 'Color', 'Size', null, 'S'],
['Shirt', null, null, null, 'M'],
['Hat', null, null, null, 'L'],
['Sock', null, null, null, null],
]

/** colors typed in the rule, with a message of the file's own; sizes held by cells */
const RULES =
`<dataValidations count="2">` +
`<dataValidation type="list" allowBlank="1" showErrorMessage="1" errorTitle="Color" error="Pick Red, Green or Blue." sqref="B2:B4"><formula1>"Red,Green,Blue"</formula1></dataValidation>` +
`<dataValidation type="list" allowBlank="1" showErrorMessage="1" sqref="C2:C4"><formula1>$E$1:$E$3</formula1></dataValidation>` +
`</dataValidations>`

async function open(opts: { tail?: string; editable?: boolean; texts?: string } = {}) {
const blob = await book({ sheets: [{ name: 'Data', rows: rows(GRID), tail: opts.tail ?? RULES }] })
const b64 = Buffer.from(await blob.arrayBuffer()).toString('base64')
return viewer({
src: `data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,${b64}`,
name: 'stock.xlsx',
editable: opts.editable ?? true,
onSave: true,
...(opts.texts ? { texts: opts.texts } : {}),
})
}

const button = (v: Viewer) => v.page.locator('.de-list-btn')
const card = (v: Viewer) => v.page.locator('.de-listcard')
const items = (v: Viewer) => card(v).locator('.de-listcard-item').allInnerTexts()
const dialog = (v: Viewer) => v.page.locator('.de-dialog')
/** the cell is selected and what the worker says of it is in: its button shows, or not */
const select = async (v: Viewer, ref: string) => {
await v.clickCell(ref)
await v.page.waitForFunction((r) => document.querySelector('.de-fx-ref')?.textContent === r, ref)
await v.page.waitForTimeout(300)
}

describe('xlsx: data validation', () => {
test('a cell that takes a value of a list has a button: its values open under it, the one picked goes into the cell', async () => {
const v = await open()
await select(v, 'A2')
expect(await button(v).count()).toBe(0)
await select(v, 'B2')
await button(v).waitFor()
expect(await button(v).getAttribute('aria-expanded')).toBe('false')
await button(v).click()
await card(v).locator('.de-listcard-item').first().waitFor()
expect(await items(v)).toEqual(['Red', 'Green', 'Blue'])
await card(v).getByText('Green').click()
await card(v).waitFor({ state: 'detached' })
await v.page.waitForFunction(() => [...document.querySelectorAll('.de-cell')].some((x) => x.textContent === 'Green'))
expect(await v.shown('B2')).toBe('Green')
// the values of cells: as they show, the empty one left out
await select(v, 'C3')
await button(v).click()
await card(v).locator('.de-listcard-item').first().waitFor()
expect(await items(v)).toEqual(['S', 'M', 'L'])
// a click on the sheet puts the list away
await v.clickCell('A4')
await card(v).waitFor({ state: 'detached' })
// one step of Undo takes the value back
await v.page.keyboard.press('ControlOrMeta+z')
await v.page.waitForFunction(() => ![...document.querySelectorAll('.de-cell')].some((x) => x.textContent === 'Green'))
expect(v.errors.filter((e) => !e.includes('[office-engine]'))).toEqual([])
})

test('by the keyboard: Alt+Down opens the list, the arrows walk it, Enter takes the value; a value outside the list is refused with the message of the file', async () => {
const v = await open()
await select(v, 'B3')
await v.page.keyboard.press('Alt+ArrowDown')
await card(v).locator('.de-listcard-item').first().waitFor()
await v.page.keyboard.press('ArrowDown')
await v.page.keyboard.press('ArrowDown')
expect(await card(v).locator('.de-listcard-item.on').innerText()).toBe('Green')
await v.page.keyboard.press('Escape')
await card(v).waitFor({ state: 'detached' })
expect(await v.shown('B3')).toBe('')
await v.page.keyboard.press('Alt+ArrowDown')
await card(v).locator('.de-listcard-item').first().waitFor()
await v.page.keyboard.press('ArrowDown')
await v.page.keyboard.press('ArrowDown')
await v.page.keyboard.press('ArrowDown')
await v.page.keyboard.press('Enter')
await card(v).waitFor({ state: 'detached' })
await v.page.waitForFunction(() => [...document.querySelectorAll('.de-cell')].some((x) => x.textContent === 'Blue'))
// opened again, the keys start on the value the cell holds
await v.page.keyboard.press('Alt+ArrowDown')
await card(v).locator('.de-listcard-item.on').waitFor()
expect(await card(v).locator('.de-listcard-item.on').innerText()).toBe('Blue')
await v.page.keyboard.press('Escape')
// typed: a value of the list is taken, another is refused and the cell stays as it was
await v.typeCell('B4', 'Red')
expect(await v.shown('B4')).toBe('Red')
await v.typeCell('B4', 'Purple')
expect(await v.toast()).toBe('Color: Pick Red, Green or Blue.')
// what was typed is back in its cell, to be put right; Escape lets it go
await v.page.waitForFunction(() => (document.activeElement as HTMLTextAreaElement | null)?.value === 'Purple')
await v.page.keyboard.press('ControlOrMeta+a')
await v.page.keyboard.type('Blue')
await v.page.keyboard.press('Enter')
await v.page.waitForTimeout(150)
expect(await v.shown('B4')).toBe('Blue')
await v.typeCell('B4', 'Purple')
await v.page.waitForFunction(() => (document.activeElement as HTMLTextAreaElement | null)?.value === 'Purple')
await v.page.keyboard.press('Escape')
await v.page.waitForTimeout(100)
expect(await v.shown('B4')).toBe('Blue')
await v.typeCell('C4', 'xl')
expect(await v.toast()).toBe('This cell takes a value of its list only.')
// a click elsewhere is not called back a second time
await v.page.waitForFunction(() => (document.activeElement as HTMLTextAreaElement | null)?.value === 'xl')
await select(v, 'A1')
await v.page.waitForTimeout(150)
expect(await v.page.locator('.de-fx-ref').innerText()).toBe('A1')
expect(await v.shown('C4')).toBe('')
})

test('the Data validation dialog gives the selected cells a list, edits it and takes it away; the file is saved with it', async () => {
const v = await open({ tail: '' })
await v.selectRange('B2', 'B4')
const p = await v.cellPoint('B3')
await v.page.mouse.click(p.x, p.y, { button: 'right' })
await v.page.locator('.de-ctx').getByText('Data validation…').click()
await dialog(v).waitFor()
expect(await dialog(v).locator('.de-dialog-label').innerText()).toBe('List of values for B2:B4')
// nothing to remove yet, nothing to apply without a value
expect(await dialog(v).getByText('Remove validation').count()).toBe(0)
await dialog(v).locator('textarea').fill('Small\nLarge, Huge')
await dialog(v).locator('.de-btn-primary').click()
await dialog(v).waitFor({ state: 'detached' })
await button(v).waitFor()
await button(v).click()
await card(v).locator('.de-listcard-item').first().waitFor()
expect(await items(v)).toEqual(['Small', 'Large', 'Huge'])
await v.page.keyboard.press('Escape')
await v.typeCell('B2', 'Tiny')
expect(await v.toast()).toBe('This cell takes a value of its list only.')
const saved = await v.save()
const zip = await ZipArchive.open(new BlobSource(new Blob([new Uint8Array(saved.bytes)])))
expect(await zip.text('xl/worksheets/sheet1.xml')).toContain(
'<dataValidations count="1"><dataValidation type="list" allowBlank="1" showInputMessage="1" showErrorMessage="1" sqref="B2:B4"><formula1>"Small,Large,Huge"</formula1></dataValidation></dataValidations>',
)
// the toolbar opens it on the list the cell has: made a list of cells that lets other values in
await select(v, 'B3')
await v.btn('Data validation').click()
await dialog(v).waitFor()
expect(await dialog(v).locator('textarea').inputValue()).toBe('Small\nLarge\nHuge')
await dialog(v).getByText('Values held by cells').click()
await dialog(v).locator('input:not([type])').fill('$E$1:$E$3')
await dialog(v).getByText('Reject other values').click()
await dialog(v).locator('.de-btn-primary').click()
await dialog(v).waitFor({ state: 'detached' })
await v.page.waitForTimeout(300)
await v.page.keyboard.press('Alt+ArrowDown')
await card(v).locator('.de-listcard-item').first().waitFor()
expect(await items(v)).toEqual(['S', 'M', 'L'])
await v.page.keyboard.press('Escape')
await v.typeCell('B3', 'Tiny')
expect(await v.shown('B3')).toBe('Tiny')
// taken away: no button
await select(v, 'B4')
await button(v).waitFor()
await v.btn('Data validation').click()
await dialog(v).getByText('Remove validation').click()
await dialog(v).waitFor({ state: 'detached' })
await button(v).waitFor({ state: 'detached' })
// B3 still has its list: the validation was taken from the cell selected only
await select(v, 'B3')
await button(v).waitFor()
expect(v.errors.filter((e) => !e.includes('[office-engine]'))).toEqual([])
})

test('a view that cannot edit has no list button', async () => {
const v = await open({ editable: false })
await select(v, 'B2')
expect(await button(v).count()).toBe(0)
await v.page.keyboard.press('Alt+ArrowDown')
await v.page.waitForTimeout(200)
expect(await card(v).count()).toBe(0)
expect(v.errors).toEqual([])
})

test('in German', async () => {
const v = await open({ texts: 'de' })
await select(v, 'B2')
await button(v).waitFor()
expect(await button(v).getAttribute('aria-label')).toBe('Aus der Liste wählen')
await v.btn('Datenüberprüfung').click()
await dialog(v).waitFor()
expect(await dialog(v).locator('.de-dialog-title').innerText()).toBe('Datenüberprüfung')
expect(await dialog(v).locator('.de-dialog-label').innerText()).toBe('Werteliste für B2')
expect(await dialog(v).locator('textarea').inputValue()).toBe('Red\nGreen\nBlue')
expect(await dialog(v).getByText('Andere Werte ablehnen').count()).toBe(1)
expect(await dialog(v).getByText('Überprüfung entfernen').count()).toBe(1)
await v.page.keyboard.press('Escape')
await dialog(v).waitFor({ state: 'detached' })
expect(v.errors).toEqual([])
// a refusal: in the language of the view, but for a message of the file
await v.typeCell('C4', 'xl')
expect(await v.toast()).toBe('Diese Zelle nimmt nur einen Wert aus ihrer Liste an.')
await v.typeCell('B4', 'Purple')
await v.page.getByText('Color: Pick Red, Green or Blue.').waitFor()
})
})
12 changes: 9 additions & 3 deletions src/collab/xlsx-ops.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ export type PBookOp =
| { op: 'duplicate'; path: string }

export type XOp =
/** `locale`: the tag numbers were typed in, for every replica to read them alike (left out: a decimal point) */
| { t: 'set'; id: string; sheet: string; cells: CellInput[]; locale?: string }
/** `locale`: the tag numbers were typed in, for every replica to read them alike (left out: a decimal point); `validate`: to be checked here before it is shared, never sent */
| { t: 'set'; id: string; sheet: string; cells: CellInput[]; locale?: string; validate?: boolean }
| { t: 'fmt'; id: string; sheet: string; range: Range; patch: FmtPatch }
/** `name`: the sheet's name where the operation was made, for rows / columns inserted or deleted (formulas typed meanwhile elsewhere read it by that name) */
| { t: 'sheet'; id: string; sheet: string; op: SheetOp; name?: string }
Expand Down Expand Up @@ -75,7 +75,8 @@ function shiftSheetOp(op: SheetOp, axis: 'row' | 'col', at: number, n: number):
case 'merge':
case 'unmerge':
case 'clear':
case 'fill': {
case 'fill':
case 'validate': {
const range = shiftRange(op.range, axis, at, n)
return range ? { ...op, range } : null
}
Expand Down Expand Up @@ -143,6 +144,11 @@ function mapFormulas(op: XOp, fn: (f: string) => string): XOp {
)
return changed ? { ...op, op: { ...op.op, cells } } : op
}
// the cells a list names
if (op.t === 'sheet' && op.op.op === 'validate' && op.op.rule?.source !== undefined) {
const source = fn(op.op.rule.source.replace(/^\s*=/, ''))
return source === op.op.rule.source ? op : { ...op, op: { ...op.op, rule: { ...op.op.rule, source } } }
}
return op
}

Expand Down
Loading