diff --git a/docs/api.md b/docs/api.md index a42fb0c..f3cd4c2 100644 --- a/docs/api.md +++ b/docs/api.md @@ -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 diff --git a/docs/features.md b/docs/features.md index ace13ed..84e9bab 100644 --- a/docs/features.md +++ b/docs/features.md @@ -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 (``, ``): 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 @@ -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 diff --git a/e2e/xlsx-validation.spec.ts b/e2e/xlsx-validation.spec.ts new file mode 100644 index 0000000..5ec5974 --- /dev/null +++ b/e2e/xlsx-validation.spec.ts @@ -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 = + `` + + `"Red,Green,Blue"` + + `$E$1:$E$3` + + `` + +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( + '"Small,Large,Huge"', + ) + // 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() + }) +}) diff --git a/src/collab/xlsx-ops.ts b/src/collab/xlsx-ops.ts index 92220a4..9373fdb 100644 --- a/src/collab/xlsx-ops.ts +++ b/src/collab/xlsx-ops.ts @@ -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 } @@ -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 } @@ -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 } diff --git a/src/collab/xlsx-worker.ts b/src/collab/xlsx-worker.ts index 2a20764..0d16d1d 100644 --- a/src/collab/xlsx-worker.ts +++ b/src/collab/xlsx-worker.ts @@ -75,6 +75,8 @@ export class XlsxCollabWorker { this.dropSheet(null) return { res, rec: null } } + // nothing changed: nothing to revert + if (!ch && !grew) return { res, rec: null } const id = ++this.seq this.recs.set(id, { ch, styles: grew ? styles : undefined, op: op.id }) this.byOp.set(op.id, id) diff --git a/src/collab/xlsx.ts b/src/collab/xlsx.ts index 6a1537c..69ca8ef 100644 --- a/src/collab/xlsx.ts +++ b/src/collab/xlsx.ts @@ -41,6 +41,8 @@ export class XlsxCollab implements Adapter { onPresence?: (p: XlsxPresence) => void private undoStack: UndoEntry[] = [] private redoStack: UndoEntry[] = [] + /** operations made here that changed nothing */ + private idle = new WeakSet() private offLocal: () => void constructor(private client: DocumentClient) { @@ -86,7 +88,7 @@ export class XlsxCollab implements Adapter { case 'xlsx.set': { // (the locale goes with the op: each replica, and a server replaying the log, reads the numbers as typed) const locale = inputLocale((a[2] as SetOptions | undefined)?.locale) - return this.local({ t: 'set', id: this.id(), sheet: this.path(a[0]), cells: a[1], ...(locale ? { locale } : {}) }) + return this.local({ t: 'set', id: this.id(), sheet: this.path(a[0]), cells: a[1], ...(locale ? { locale } : {}), ...((a[2] as SetOptions | undefined)?.validate ? { validate: true } : {}) }) } case 'xlsx.format': return this.local({ t: 'fmt', id: this.id(), sheet: this.path(a[0]), range: a[1], patch: a[2] }) @@ -124,14 +126,33 @@ export class XlsxCollab implements Adapter { } private local(op: XOp): Promise { + let entry: UndoEntry | undefined if (op.t === 'sheet' && (op.op.op === 'insertRows' || op.op.op === 'insertCols')) { const del: SheetOp = { op: op.op.op === 'insertRows' ? 'deleteRows' : 'deleteCols', at: op.op.at, n: op.op.n } - this.undoStack.push({ kind: 'inverse', sheet: op.sheet, undo: del, redo: op.op }) - } else if (!isStructural(op)) this.undoStack.push({ kind: 'op', id: op.id }) + entry = { kind: 'inverse', sheet: op.sheet, undo: del, redo: op.op } + } else if (!isStructural(op)) entry = { kind: 'op', id: op.id } + if (entry) this.undoStack.push(entry) if (this.undoStack.length > 200) this.undoStack.shift() - this.redoStack = [] + const redo = this.redoStack + const cleared: UndoEntry[] = (this.redoStack = []) this.publishHistory() - return this.submit!(op) + // refused here (a value its cell's list does not take, a sort over merged cells), or without effect (a list taken + // away where there is none): nothing to undo, and what could be redone still can + const nothing = () => { + if (entry && this.undoStack.includes(entry)) this.undoStack.splice(this.undoStack.indexOf(entry), 1) + if (this.redoStack === cleared && !cleared.length) this.redoStack = redo + this.publishHistory() + } + return this.submit!(op).then( + (r) => { + if (this.idle.delete(op)) nothing() + return r + }, + (e) => { + nothing() + throw e + }, + ) } private history(from: UndoEntry[], to: UndoEntry[], which: 'prev' | 'next'): Promise { @@ -159,7 +180,16 @@ export class XlsxCollab implements Adapter { async apply(op: XOp, kind: 'local' | 'replay' | 'remote'): Promise { if (op.t === 'comment') return applyComment(this.client, op) + if (kind === 'local' && op.t === 'set' && op.validate) { + delete op.validate + // what is typed here where a list says which values a cell takes: refused before it is shared (what the room + // sends was let through where it was typed) + const sheet = this.meta.sheets.findIndex((s) => s.path === op.sheet) + const no = sheet < 0 ? null : await this.client.direct('xlsx.refused', sheet, op.cells, op.locale ? { locale: op.locale } : undefined) + if (no) throw new Error(no.title ? `${no.title}: ${no.message}` : no.message) + } const { res, rec } = await this.client.direct('collab.xlsx.apply', op) + if (kind === 'local' && rec === null && !isStructural(op)) this.idle.add(op) // a sort goes to the room with the order it made here: the same rows move for everyone (see `transformX`) if (kind === 'local' && op.t === 'sheet' && op.op.op === 'sort' && !op.op.order && res?.sorted) op.op = { ...op.op, order: res.sorted } // the view follows a collaborator's rows / columns with its selection and the cell being typed in diff --git a/src/core/worker/engine.ts b/src/core/worker/engine.ts index 81c2132..7ebef39 100644 --- a/src/core/worker/engine.ts +++ b/src/core/worker/engine.ts @@ -208,8 +208,16 @@ export class Engine { ) return } - case 'xlsx.set': + case 'xlsx.set': { + // what a person types where a list says which values a cell takes: refused before anything changes + const no = (args[2] as SetOptions | undefined)?.validate && (await this.xed().refused(args[0] as number, args[1] as CellInput[], args[2] as SetOptions | undefined)) + if (no) throw new Error(no.title ? `${no.title}: ${no.message}` : no.message) return this.withHistory(this.xed().setCells(args[0] as number, args[1] as CellInput[], args[2] as SetOptions | undefined)) + } + case 'xlsx.refused': + return this.xed().refused(args[0] as number, args[1] as CellInput[], args[2] as SetOptions | undefined) + case 'xlsx.listValues': + return this.xed().listValues(args[0] as number, args[1] as number, args[2] as number) case 'xlsx.copy': return this.xed().copy(args[0] as number, args[1] as Range) case 'xlsx.region': diff --git a/src/core/worker/protocol.ts b/src/core/worker/protocol.ts index cd0feac..5d08d26 100644 --- a/src/core/worker/protocol.ts +++ b/src/core/worker/protocol.ts @@ -6,7 +6,7 @@ import type { XOp } from '../../collab/xlsx-ops' import type { POp } from '../../collab/pptx-ops' import type { PptxCollabResult } from '../../collab/pptx-worker' import type { CanonStyle, DocxMeta, Block, EditOp, EditResult, HFSet, HFSetResult, PageSet, PageSetResult, ParaSpec, StyleInfo, StyleLook, StyleSetResult, TableOp } from '../docx/types' -import type { BlockOut, BookOp, CellDetail, CellInput, FindMatch, FindOptions, FmtPatch, Range, SetOptions, SheetOp, SheetProgress, WorkbookMeta, XlsxClip, XlsxEditResult } from '../xlsx/types' +import type { BlockOut, BookOp, CellDetail, CellInput, FindMatch, FindOptions, FmtPatch, ListValues, Range, Refused, SetOptions, SheetOp, SheetProgress, WorkbookMeta, XlsxClip, XlsxEditResult } from '../xlsx/types' import type { SheetDrawing } from '../xlsx/drawings' import type { PParaSpec, PresentationMeta, ShapeOp, SlideModel, SlideOp } from '../pptx/types' import type { FontSource } from '../fonts' @@ -117,8 +117,21 @@ export interface Methods { 'xlsx.text'(sheet: number, sep: string, limit?: number): Blob /** replaces text in matching cells (or only `at`); null when nothing changed */ 'xlsx.replace'(sheet: number, query: string, by: string, opts?: FindOptions, at?: { r: number; c: number }): XlsxEditResult | null - /** what was typed into cells; `opts.locale`: the BCP 47 tag numbers were typed in (`1,5` in `de-DE`), a decimal point without one */ + /** + * what was typed into cells; `opts.locale`: the BCP 47 tag numbers were typed in (`1,5` in `de-DE`), a decimal point + * without one; `opts.validate`: fails, changing nothing, when a cell's list refuses its input (what a person types) + */ 'xlsx.set'(sheet: number, cells: CellInput[], opts?: SetOptions): XlsxEditResult + /** + * the values of the list cell (r, c) takes (its data validation), for a dropdown: typed in the rule, or what the + * cells it names show (2,000 at most: `capped` past it); none when the cell has no list + */ + 'xlsx.listValues'(sheet: number, r: number, c: number): ListValues + /** + * what the lists of the sheet refuse of what would be typed (`xlsx.set` with `validate` asks by itself): the first input that is + * not a value of its cell's list, where the list stops the others; null when none is refused + */ + 'xlsx.refused'(sheet: number, cells: CellInput[], opts?: SetOptions): Refused | null /** the block of filled cells a range is part of (the table around it), and whether its first row reads as a header */ 'xlsx.region'(sheet: number, range: Range): { range: Range; header: boolean } /** the cells of a range as they are (values, formulas, formats) for the `paste` sheet operation, and as text for the clipboard; rows not shown yet included */ diff --git a/src/core/xlsx/calc.ts b/src/core/xlsx/calc.ts index 705c464..ed63f4a 100644 --- a/src/core/xlsx/calc.ts +++ b/src/core/xlsx/calc.ts @@ -7,6 +7,7 @@ import { evaluate, evaluateArray, evaluateDynamic, + evaluateRange, FormulaError, isVolatile, namesIn, @@ -416,6 +417,24 @@ export class Calc { return undefined } + /** + * The cells a formula names when read at cell (r, c) of `sheet`: the source of a list (a range, a defined name, + * OFFSET, INDIRECT). Undefined when it gives no cells, or does not read. + */ + cellsOf(sheet: number, text: string, r: number, c: number): { sheet: number; r0: number; c0: number; r1: number; c1: number } | undefined { + const prev = this.cur + this.cur = sheet + try { + const rg = evaluateRange(parseFormula(text), { provider: this.provider(new Set(), new Set()), sheet: this.wb.sheets[sheet]?.name, r, c }) + const s = rg ? this.sheetIndex(rg.sheet, sheet) : -1 + return rg && s >= 0 ? { sheet: s, r0: rg.r0, c0: rg.c0, r1: rg.r1, c1: rg.c1 } : undefined + } catch { + return undefined + } finally { + this.cur = prev + } + } + /** whether a cell holds a value a dynamic array formula spilled there (not the formula's own cell) */ spilledAt(sheet: number, key: number): boolean { return this.spillOwner(sheet, key) !== undefined diff --git a/src/core/xlsx/editor.ts b/src/core/xlsx/editor.ts index 9b96202..b72ec8c 100644 --- a/src/core/xlsx/editor.ts +++ b/src/core/xlsx/editor.ts @@ -14,17 +14,18 @@ import { decodeEntities, parseXml } from '../xml' import { BUILTIN_FORMATS, isDateFormat } from './numfmt' import { readTyped, type TypedNumber } from '../number-input' import { parseSheetStyles } from './styles' -import type { BookOp, BorderKind, CellInput, ClipCell, ColInfo, FindOptions, FmtPatch, Merge, Range, RowAttrs, SetOptions, SheetOp, SheetProgress, XlsxClip, XlsxEditResult } from './types' +import type { BookOp, BorderKind, CellInput, ClipCell, ColInfo, FindOptions, FmtPatch, ListRule, ListValues, Merge, Range, Refused, RowAttrs, SetOptions, SheetOp, SheetProgress, XlsxClip, XlsxEditResult } from './types' +import { LIST_REFUSED, listFormula, mapValidations, stops, validationAt, validationsXml, withinRange, withoutRange, type DataValidation } from './validation' import { expandShared, overflows, restore, setColStyle, setColWidth, setFormula, setMerge, setRowHeight, shiftSheet, snapshot, type Snapshot } from './structure' -import { dropSheetInFormula, FormulaSyntaxError, moveRefsInFormula, parseFormula, renameSheetInFormula, translateFormula, withFunctionPrefixes, type Ast, type MoveOp, type RefAddr } from './formula' +import { dropSheetInFormula, FormulaSyntaxError, moveRefsInFormula, parseFormula, renameSheetInFormula, shiftFormula, translateFormula, withFunctionPrefixes, type Ast, type MoveOp, type RefAddr } from './formula' import { loadDelimited, type DelimitedImport } from './import' import { tsvCell } from './clip' import { compare } from './formula/values' import type { Value } from './formula' -import { followParts, followSheetTail, renameInCharts, sheetTail, type PartEdit } from './follow' +import { followNodes, followParts, followSheetTail, renameInCharts, sheetTail, type PartEdit } from './follow' import { colAt, colName, DEFAULT_STYLES_PART, ownRow, MAX_COL, MAX_ROWS, parseRef, rowSizesOf, SheetData, stylesPartOf, T_BOOL, T_DATE, T_EMPTY, T_ERR, T_NUM, T_SST, - T_STR, XlsxWorkbook, + T_STR, XlsxWorkbook, type ListItem, } from './workbook' export const XLSX_MIME = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' @@ -81,6 +82,11 @@ export interface Change { * move), by cell. */ sort?: { order: number[]; before: [number, string][]; after: [number, string][] } + /** + * the data validations of sheets before and after. `range`: the cells they were set on (without it they followed + * rows / columns); a validation is never changed in place, the list is + */ + rules?: { sheet: number; range?: Range; before: DataValidation[]; after: DataValidation[] }[] /** the format (style index) of cells before and after, by cell key; -1: no cell (the change made one to hold a format) */ restyle?: { keys: Float64Array; before: Int32Array; after: Int32Array } } @@ -640,6 +646,9 @@ export class XlsxEditor { case 'sort': this.denySheet(d, 'sort', 'sorting') return this.denyLocked(d, op.range) + // (a protected sheet has no flag that allows it: Excel takes Data Validation away on one) + case 'validate': + return this.denySheet(d, 'dataValidation', 'changing the data validation') } } @@ -728,6 +737,61 @@ export class XlsxEditor { return [...this.wb.calc.recalc([], all)] } + /** + * The values of the list cell (r, c) takes, for its dropdown (none: it has no list). What to type for a number is + * what it shows where that reads as the number (a date, a percentage: the cell then shows it so too). + */ + async listValues(sheet: number, r: number, c: number): Promise { + // (the cells that hold the values may be computed, and found by formulas reading any sheet) + await this.ready() + const l = await this.wb.listItems(sheet, r, c, LIST_VALUES_MAX) + if (!l) return { values: [], inputs: [] } + const st = this.lockStyleAt(this.sheet(sheet), r, c) + const ctx = { fmt: this.wb.styles.xfs[st]?.numFmt ?? '', date1904: this.wb.date1904 } + const input = (it: ListItem) => { + if (it.num === undefined) return it.input + const iso = it.date && it.num > 0 && it.num < 2958466 ? new Date((it.num - 25569 + (ctx.date1904 ? 1462 : 0)) * 86400000).toISOString().slice(0, 10) : '' + return [it.text, iso, it.input].find((t) => { + const { e, f } = parseInput(t, st, ctx) + return f === undefined && e?.[0] === T_NUM && e[1] === it.num + }) ?? it.input + } + return { values: l.items.map((i) => i.text), inputs: l.items.map(input), ...(l.capped ? { capped: true } : {}) } + } + + /** + * What the lists of a sheet refuse of `inputs` (null: nothing): the first input that is not a value of the list its + * cell takes, when that list says to stop the others (its error alert is on, of the kind that stops), with the + * message the file has for it. Read as `setCells` reads them. An empty input and a formula are let through (what a + * formula gives is not checked); so is every input where the list cannot be read, or is longer than is compared. + * The validations of the other kinds refuse nothing. `setCells` does not ask: what a person types is asked about + * before (`SetOptions.validate`); a paste, a fill, a replace and what collaborators send are not checked. + */ + async refused(sheet: number, inputs: CellInput[], opts: SetOptions = {}): Promise { + // (most sheets have no such list: nothing to wait for) + const read = this.wb.sheetsData.get(sheet) + if (read?.done && !read.validations.some(stops)) return null + await this.ready() + const d = this.sheet(sheet) + const xfs = this.wb.styles.xfs + for (const { r, c, input } of inputs) { + const v = validationAt(d.validations, r, c) + if (!v || !stops(v) || input === '') continue + const l = await this.wb.listItems(sheet, r, c, LIST_CHECK_MAX) + if (!l || l.capped || (!l.typed && !l.items.length)) continue + const st = getEntry(d, r, c)?.[2] ?? this.lockStyleAt(d, r, c) + const { e, f } = parseInput(input, st, { fmt: xfs[st]?.numFmt ?? '', date1904: this.wb.date1904, locale: opts.locale }) + if (f !== undefined || !e) continue + // values typed in the rule are told apart by case, those held by cells are not (as Excel compares them) + const same = (a: string, b: string) => (l.typed ? a === b : a.toLowerCase() === b.toLowerCase()) + const text = input.trim() + const num = (s: string) => (s.trim() !== '' && Number.isFinite(Number(s)) ? Number(s) : undefined) + const ok = l.items.some((it) => same(it.text, text) || same(it.input, text) || (e[0] === T_NUM && (it.num ?? num(it.input)) === e[1]) || (e[0] === T_BOOL && it.input.toUpperCase() === (e[1] ? 'TRUE' : 'FALSE'))) + if (!ok) return { r, c, ...(v.a.errorTitle ? { title: v.a.errorTitle } : {}), message: v.a.error || LIST_REFUSED } + } + return null + } + /** `opts.locale`: the BCP 47 tag the numbers among `inputs` were typed in (undefined: a decimal point; formulas are never read in it) */ async setCells(sheet: number, inputs: CellInput[], opts: SetOptions = {}): Promise { await this.ready() @@ -1010,6 +1074,10 @@ export class XlsxEditor { const od = this.wb.sheetsData.get(o.sheet) if (od) setFormula(od, o.key, which === 'prev' ? o.prev : o.next) } + for (const v of ch.rules ?? []) { + const vd = this.wb.sheetsData.get(v.sheet) + if (vd) setValidations(vd, which === 'prev' ? v.before : v.after) + } for (const p of ch.parts ?? []) this.wb.pkg.setPart(p.path, which === 'prev' ? p.prev : p.next) if (ch.book) { const b = which === 'prev' ? ch.book.before : ch.book.after @@ -1082,6 +1150,12 @@ export class XlsxEditor { range: ch.range, lay: ch.lay ? { before: layoutState(d), after: which === 'prev' ? ch.lay.before : ch.lay.after } : undefined, full: ch.full ? { before: snapshot(d), after: which === 'prev' ? ch.full.before : ch.full.after } : undefined, + // (the cells of the change as they were; what others set on other cells since is theirs) + rules: ch.rules?.map((v) => { + const now = this.wb.sheetsData.get(v.sheet)?.validations ?? [] + const [left, to] = which === 'prev' ? [v.after, v.before] : [v.before, v.after] + return { ...v, before: now, after: now === left || !v.range ? to : [...withoutRange(now, v.range), ...withinRange(to, v.range)] } + }), others: ch.others?.map((o) => ({ ...o, prev: this.wb.sheetsData.get(o.sheet)?.formulas.get(o.key) ?? '', next: which === 'prev' ? o.prev : o.next })), // (the cells as they are formatted now, given the format of then) restyle: ch.restyle && { @@ -1184,6 +1258,14 @@ export class XlsxEditor { this.formulaTouched = true const recalc = this.recalcAll() const ch: Change = { sheet, cells: [], range: all, full: { before, after: snapshot(d) }, cm } + // the lists of the other sheets that name cells of this one + for (const o of others) { + if (o.d === d || !o.d.validations.length) continue + const moved = mapValidations(o.d.validations, (f) => shiftFormula(f, { sheet: name, formulaSheet: o.name, axis, at: op.at, delta })) + if (moved.every((v, i) => v === o.d.validations[i])) continue + ;(ch.rules ??= []).push({ sheet: this.indexOf(o.d), before: o.d.validations, after: moved }) + setValidations(o.d, moved) + } if (edits.length) ch.others = edits.map((e) => ({ sheet: this.indexOf(e.d), key: e.key, prev: e.prev, next: e.next })) if (followed.parts.length) { ch.parts = followed.parts @@ -1259,6 +1341,25 @@ export class XlsxEditor { case 'sort': await this.wb.ensure(d, op.range.r0, op.range.r1) return this.sort(sheet, d, op.range, op.col, !!op.desc, op.order) + case 'validate': { + const R: Range = { r0: Math.max(0, op.range.r0), c0: Math.max(0, op.range.c0), r1: Math.min(op.range.r1, MAX_ROWS - 1), c1: Math.min(op.range.c1, MAX_COL - 1) } + if (R.r1 < R.r0 || R.c1 < R.c0) throw new Error('No cells to validate') + // (a whole column may be given a list: the view is told of the cells there are) + const there = this.used(d, R) + const range: Range = { ...R, r1: Math.max(R.r0, there.r1), c1: Math.max(R.c0, there.c1) } + const next = withoutRange(d.validations, R) + if (op.rule) { + // the list these cells all had, edited: its messages are the file's own, and stay + const had = validationAt(d.validations, R.r0, R.c0) + next.push(listValidation(R, op.rule, had?.ranges.some((g) => g.r0 <= R.r0 && g.r1 >= R.r1 && g.c0 <= R.c0 && g.c1 >= R.c1) ? had : undefined)) + } + // nothing to take away: nothing to undo either + else if (next.length === d.validations.length && next.every((v, i) => v === d.validations[i])) return { sheet, range } + this.undoStack.push({ sheet, cells: [], range, rules: [{ sheet, range: R, before: d.validations, after: next }] }) + this.redoStack = [] + setValidations(d, next) + return { sheet, range } + } } } @@ -1755,6 +1856,7 @@ export class XlsxEditor { const d = this.wb.sheetsData.get(s.index) if (!d) continue d.renames.push([old.name, name]) + d.validations = mapValidations(d.validations, (f) => renameSheetInFormula(f, old.name, name)) if (!this.newSheets.has(s.path) && !needsWrite(d) && (await sheetTail(pkg, s.path).catch(() => '')).toLowerCase().includes(old.name.toLowerCase())) d.formulaChanged = true } old.name = name @@ -1781,6 +1883,10 @@ export class XlsxEditor { remap(sheets.map((_, i) => i).filter((i) => i !== op.index)) // what read the sheet reads #REF! from now on, as Excel has it: a reference to a sheet the workbook does not have is not a formula it opens eachFormula((f) => dropSheetInFormula(f, s.name)) + for (const d of this.wb.sheetsData.values()) { + const left = mapValidations(d.validations, (f) => dropSheetInFormula(f, s.name)) + if (left.some((v, i) => v !== d.validations[i])) setValidations(d, left) + } // the calculation chain lists its cells: it goes at the next save this.formulaTouched = true this.wb.calc.invalidate() @@ -2125,7 +2231,42 @@ function cellXml(d: SheetData, r: number, c: number, P: string, wb: XlsxWorkbook } function needsWrite(d: SheetData): boolean { - return d.edited.size > 0 || d.structural || d.dirtyCols || d.dirtyMerges || d.dirtyView || d.dirtyRows.size > 0 || d.formulaChanged || d.revalued.size > 0 || d.rewrite.size > 0 + return d.edited.size > 0 || d.structural || d.dirtyCols || d.dirtyMerges || d.dirtyView || d.dirtyRows.size > 0 || d.formulaChanged || d.revalued.size > 0 || d.rewrite.size > 0 || d.dirtyValidations +} + +function setValidations(d: SheetData, list: DataValidation[]) { + d.validations = list + d.dirtyValidations = true +} + +/** values the dropdown of a list holds at most */ +const LIST_VALUES_MAX = 2000 +/** values of a list past which what is typed in its cells is not compared with them (it is let through) */ +const LIST_CHECK_MAX = 100_000 + +/** + * The validation that gives the cells of `range` a list. `had`: the list they had, whose messages and alert stay + * (they are the file's own) where the rule does not say otherwise. + */ +function listValidation(range: Range, rule: ListRule, had: DataValidation | undefined): DataValidation { + let f1: string + if (rule.source !== undefined) { + f1 = rule.source.trim().replace(/^=/, '') + try { + if (!f1) throw new Error('empty') + parseFormula(f1) + } catch { + throw new Error('The cells of the list are not given as a range that reads: write them like $A$1:$A$9 or Sheet2!$A$1:$A$9, or as a defined name.') + } + f1 = withFunctionPrefixes(f1) + } else f1 = listFormula(rule.values ?? []) + const a: Record = had?.a.type === 'list' ? { ...had.a } : { type: 'list', allowBlank: '1', showInputMessage: '1', showErrorMessage: '1' } + const strict = rule.strict ?? true + if (strict !== (had?.a.type === 'list' ? stops(had) : undefined)) { + a.showErrorMessage = strict ? '1' : '0' + if (strict) delete a.errorStyle + } + return { ranges: [range], a, f1 } } /** the order that puts back what `order` moved */ @@ -2189,6 +2330,27 @@ function applyLayout(d: SheetData, l: LayoutState) { d.dirtyCols = d.dirtyMerges = d.dirtyView = true } +/** + * Where, in what follows the rows of a sheet, the elements named (`a|b|c`, in the order of the schema) end: each is + * skipped whole, with what it holds (a filter holds its sort state). What comes after them in the schema goes there. + */ +function tailAfter(tail: string, names: string): number { + let at = 0 + const open = new RegExp(`\\s*<([\\w.-]+:)?(${names})\\b(?:[^>"']|"[^"]*"|'[^']*')*>`, 'y') + for (;;) { + open.lastIndex = at + const m = open.exec(tail) + if (!m) break + at = m.index + m[0].length + if (m[0].endsWith('/>')) continue + const close = `` + const end = tail.indexOf(close, at) + if (end < 0) break + at = end + close.length + } + return at +} + /** hides / shows columns a..b (the width before hiding is kept for unhiding) */ function hideCols(d: SheetData, a: number, b: number, hidden: boolean) { const out: ColInfo[] = [] @@ -2362,30 +2524,36 @@ class RowPatcher { private tailFix(tail: string): string { const d = this.d // filters, links, validations, conditional formats: with the rows / columns that moved, the sheets that were renamed + const source = tail tail = followSheetTail(tail, d.shifts, d.renames, this.sheetName) + if (d.dirtyValidations) tail = this.validationsFix(tail, source) if (!d.dirtyMerges && !d.structural) return tail const P = this.P const ms = d.merges const xml = ms.length ? `<${P}mergeCells count="${ms.length}">${ms.map((m) => `<${P}mergeCell ref="${colName(m.c0)}${m.r0 + 1}:${colName(m.c1)}${m.r1 + 1}"/>`).join('')}` : '' const re = new RegExp(`<${P}mergeCells\\b[\\s\\S]*?<\\/${P}mergeCells>|<${P}mergeCells\\b[^>]*\\/>`) if (re.test(tail)) return tail.replace(re, xml) - // after the elements that precede mergeCells in the schema: each skipped whole, with what it holds (a filter holds its sort state) - let at = 0 - const open = /\s*<([\w.-]+:)?(sheetCalcPr|sheetProtection|protectedRanges|scenarios|autoFilter|sortState|dataConsolidate|customSheetViews)\b(?:[^>"']|"[^"]*"|'[^']*')*>/y - for (;;) { - open.lastIndex = at - const m = open.exec(tail) - if (!m) break - at = m.index + m[0].length - if (m[0].endsWith('/>')) continue - const close = `` - const end = tail.indexOf(close, at) - if (end < 0) break - at = end + close.length - } + // after the elements that precede mergeCells in the schema + const at = tailAfter(tail, 'sheetCalcPr|sheetProtection|protectedRanges|scenarios|autoFilter|sortState|dataConsolidate|customSheetViews') return tail.slice(0, at) + xml + tail.slice(at) } + /** + * The sheet's as the model has them, in the place of those of `tail`. `source`: the tail as the file + * has it, whose elements the rules that were read keep. (The ones a newer Excel keeps in the extension list are not + * read: they stay as they are.) + */ + private validationsFix(tail: string, source: string): string { + const find = (xml: string) => { + const at = tailAfter(xml, 'sheetCalcPr|sheetProtection|protectedRanges|scenarios|autoFilter|sortState|dataConsolidate|customSheetViews|mergeCells|phoneticPr|conditionalFormatting') + return { at, text: /^\s*<([\w.-]+:)?dataValidations\b(?:[^>"']|"[^"]*"|'[^']*')*?(?:\/>|>[\s\S]*?<\/\1dataValidations>)/.exec(xml.slice(at))?.[0] ?? '' } + } + const was = find(source).text + const now = find(tail) + const xml = validationsXml(this.d.validations, this.P, was ? rootEl(parseRaw(was)) : undefined, (n) => followNodes(n, this.d.shifts, this.d.renames, this.sheetName)) + return tail.slice(0, now.at) + xml + tail.slice(now.at + now.text.length) + } + /** feeds decoded text; returns what can be written so far */ async push(text: string, final: boolean): Promise { const s = this.buf + text diff --git a/src/core/xlsx/follow.ts b/src/core/xlsx/follow.ts index ba4343b..1eda827 100644 --- a/src/core/xlsx/follow.ts +++ b/src/core/xlsx/follow.ts @@ -92,6 +92,11 @@ export function followSheetTail(xml: string, shifts: Shift[], renames: [string, } catch { return xml } + return serialize(followNodes(nodes, shifts, renames, sheetName)) + xml.slice(end) +} + +/** Elements of a sheet's tail, with the rows / columns that moved and the sheets that were renamed: see `followSheetTail`. */ +export function followNodes(nodes: RChild[], shifts: Shift[], renames: [string, string][], sheetName: string): RChild[] { const formula = (text: string) => { for (const [from, to] of renames) text = renameSheetInFormula(text, from, to) for (const s of shifts) text = shiftFormula(text, { sheet: sheetName, formulaSheet: sheetName, ...s }) @@ -147,7 +152,7 @@ export function followSheetTail(xml: string, shifts: Shift[], renames: [string, } return out } - return serialize(walk(nodes)) + xml.slice(end) + return walk(nodes) } /** rewrites the text of every `` (the cells a chart draws) of a chart part */ diff --git a/src/core/xlsx/formula/evaluate.ts b/src/core/xlsx/formula/evaluate.ts index 3fac93b..253a359 100644 --- a/src/core/xlsx/formula/evaluate.ts +++ b/src/core/xlsx/formula/evaluate.ts @@ -533,6 +533,24 @@ export function evaluateDynamic(ast: Ast, ctx: EvalContext): Value[][] { } } +/** + * The cells a formula gives, when it gives a range (a reference, a defined name, OFFSET, INDIRECT…): what the source + * of a list names. `sheet` as the formula says it (undefined: its own). Undefined when it gives values, or an error. + */ +export function evaluateRange(ast: Ast, ctx: EvalContext): { sheet: string | undefined; r0: number; c0: number; r1: number; c1: number } | undefined { + const prev = getDate1904() + setDate1904(!!ctx.provider.date1904) + try { + const v = new Evaluator(ctx, ast).eval(ast, false) + return v instanceof RangeV ? { sheet: v.sheet, r0: v.r0, c0: v.c0, r1: v.r1, c1: v.c1 } : undefined + } catch (e) { + if (e instanceof EvalSignal) throw e + return undefined + } finally { + setDate1904(prev) + } +} + /** Parse + evaluate. Syntax errors evaluate to #NAME?. */ export function evaluateFormula(text: string, ctx: EvalContext): Value { let ast: Ast diff --git a/src/core/xlsx/formula/index.ts b/src/core/xlsx/formula/index.ts index 96c329e..3d2598a 100644 --- a/src/core/xlsx/formula/index.ts +++ b/src/core/xlsx/formula/index.ts @@ -6,7 +6,7 @@ export { parseFormula } from './parser' export type { Ast, BinOp } from './parser' export type { RefAddr } from './refs' export { colIndex, colName, quoteSheet } from './refs' -export { evaluate, evaluateArray, evaluateDynamic, evaluateFormula } from './evaluate' +export { evaluate, evaluateArray, evaluateDynamic, evaluateFormula, evaluateRange } from './evaluate' export { dropSheetInFormula, isVolatile, moveRefsInFormula, namesIn, references, renameSheetInFormula, shiftFormula, stripFunctionPrefixes, translateFormula, translator, withFunctionPrefixes } from './transform' export type { MoveOp, ShiftOp } from './transform' export { supportedFunctions } from './functions' diff --git a/src/core/xlsx/structure.ts b/src/core/xlsx/structure.ts index ba3f16d..72167a7 100644 --- a/src/core/xlsx/structure.ts +++ b/src/core/xlsx/structure.ts @@ -6,6 +6,7 @@ import { shiftFormula, translateFormula, translator } from './formula' import type { ColInfo, Merge, Range, RowAttrs } from './types' import type { Shift } from './follow' import { MAX_COL, MAX_ROWS, T_EMPTY, type SheetData } from './workbook' +import { shiftValidations, type DataValidation } from './validation' export interface Snapshot { rows: (unknown[] | undefined)[] @@ -20,6 +21,7 @@ export interface Snapshot { maxRow: number maxCol: number frozen: { rows: number; cols: number } + validations: DataValidation[] } /** @@ -43,6 +45,8 @@ export function snapshot(d: SheetData): Snapshot { maxRow: d.maxRow, maxCol: d.maxCol, frozen: { ...d.frozen }, + // (a validation is never changed in place: the list is) + validations: d.validations, } } @@ -60,6 +64,8 @@ export function restore(d: SheetData, s: Snapshot) { d.maxRow = s.maxRow d.maxCol = s.maxCol d.frozen = { ...s.frozen } + if (d.validations !== s.validations) d.dirtyValidations = true + d.validations = s.validations d.structural = true d.dirtyCols = d.dirtyMerges = d.dirtyView = true } @@ -275,6 +281,10 @@ export function shiftSheet(d: SheetData, sheetName: string, axis: 'row' | 'col', d.merges = shiftMerges(d.merges, axis, at, delta).filter((m) => m.r0 < MAX_ROWS && m.c0 < MAX_COL).map((m) => ({ ...m, r1: Math.min(m.r1, MAX_ROWS - 1), c1: Math.min(m.c1, MAX_COL - 1) })).filter((m) => m.r0 !== m.r1 || m.c0 !== m.c1) if (axis === 'row' && d.frozen.rows > at) d.frozen = { ...d.frozen, rows: Math.max(0, d.frozen.rows + (delta > 0 ? delta : Math.max(delta, at - d.frozen.rows))) } if (axis === 'col' && d.frozen.cols > at) d.frozen = { ...d.frozen, cols: Math.max(0, d.frozen.cols + (delta > 0 ? delta : Math.max(delta, at - d.frozen.cols))) } + if (d.validations.length) { + d.validations = shiftValidations(d.validations, sheetName, { axis, at, delta }) + d.dirtyValidations = true + } d.structural = true d.dirtyMerges = true d.dirtyView = true diff --git a/src/core/xlsx/types.ts b/src/core/xlsx/types.ts index 88ab9e9..ff9e9e1 100644 --- a/src/core/xlsx/types.ts +++ b/src/core/xlsx/types.ts @@ -106,6 +106,49 @@ export interface CellDetail { type: string /** where the cell links to, when it does (see `CellLink`) */ links?: CellLink[] + /** the rule the file gives the cell for what may be typed in it, when it has one */ + validation?: CellValidation +} + +/** the data validation of a cell. Only a list is understood: the other kinds are kept in the file, and not enforced. */ +export interface CellValidation { + /** its kind, as the file says it: 'list', 'whole', 'decimal', 'date', 'time', 'textLength', 'custom' */ + type: string + /** a list: the cell shows a button that opens it (a file can say not to); `xlsx.listValues` reads its values */ + dropdown?: boolean + /** a list: its values, when they are typed in the rule */ + values?: string[] + /** a list: the formula naming the cells that hold its values (no "="), when that is how it is given */ + source?: string + /** a list: a value outside it is refused when typed (its error alert is on, of the kind that stops) */ + strict?: boolean +} + +/** the list of values cells take: typed (`values`) or held by cells (`source`); see the `validate` operation */ +export interface ListRule { + values?: string[] + /** a formula naming cells: `$A$1:$A$9`, `Lists!$A$2:$A$40`, a defined name (no "=") */ + source?: string + /** a value outside the list is refused when typed (default: true) */ + strict?: boolean +} + +/** the values of a cell's list, for its dropdown: see `xlsx.listValues` */ +export interface ListValues { + /** the values as shown, in the order of the list, each once */ + values: string[] + /** what to give `xlsx.set` for each, without a locale */ + inputs: string[] + /** the list has more values than these */ + capped?: boolean +} + +/** an input a validation refuses: the cell, and the message for it (the file's own when it has one) */ +export interface Refused { + r: number + c: number + title?: string + message: string } /** @@ -139,6 +182,12 @@ export interface SetOptions { * Undefined: a decimal point and commas grouping by thousands. Formulas are read the same in every locale. */ locale?: string + /** + * Refuse the inputs a person could not type: when the list of a cell (its data validation) takes no other values + * than its own and one of `cells` is another, nothing changes and the call fails with the message for it. Left out, + * every input goes in, as with a paste. + */ + validate?: boolean } export type BorderKind = 'all' | 'outer' | 'inner' | 'none' | 'top' | 'bottom' | 'left' | 'right' @@ -234,6 +283,11 @@ export type SheetOp = * typed in one of them at the same moment. An order that does not fit the range is left out. */ | { op: 'sort'; range: Range; col: number; desc?: boolean; order?: number[] } + /** + * The list of values the cells of `range` take (a data validation of the list kind), in place of whatever + * validation they had; `rule: null` only takes that away. The cells already filled are not checked. + */ + | { op: 'validate'; range: Range; rule: ListRule | null } export type BookOp = | { op: 'add'; name?: string; after?: number } diff --git a/src/core/xlsx/validation.ts b/src/core/xlsx/validation.ts new file mode 100644 index 0000000..46fa62d --- /dev/null +++ b/src/core/xlsx/validation.ts @@ -0,0 +1,224 @@ +/** + * The data validations of a sheet (``): the rules a file gives its cells for what may be typed in + * them. All are kept as read, follow their cells and are written back. A list (`type="list"`) is understood: its + * values are offered at the cell and, when its error alert says to stop, a value outside it is refused when typed. + * The other kinds (whole numbers, dates, text lengths, custom formulas) are not enforced. + */ +import { el, escAttr, escText, getAttr, kidOf, kidsOf, prefixOf, serialize, setAttr, textContent, type RChild, type RNode } from '../raw' +import { shiftSqref, type Shift } from './follow' +import { shiftFormula, stripFunctionPrefixes, translateFormula } from './formula' +import type { CellValidation, Range } from './types' +import { colName, MAX_COL, MAX_ROWS, parseRef } from './workbook' + +/** a `` of a sheet */ +export interface DataValidation { + /** the cells it is on, where they are now */ + ranges: Range[] + /** its attributes as read (`sqref` apart): the kind, the operator, the messages, what its alert does */ + a: Record + /** its formulas (no "="), as they read for the first cell of its first range: the others read them moved by as much */ + f1?: string + f2?: string + /** its place among the `` of the file (none: it was made here) */ + n?: number +} + +/** validations of a sheet past which the rest are not read (Excel keeps 65,534 at most) */ +export const MAX_VALIDATIONS = 100_000 +/** what is said of a value a list refuses when the file has no message of its own (the view says it in its language) */ +export const LIST_REFUSED = 'This cell takes a value of its list only.' +/** characters the typed values of a list take at most, commas included (Excel's limit for the formula of a validation) */ +export const LIST_TEXT_MAX = 255 + +const CELLS = /^\$?([A-Za-z]{1,3})\$?(\d{1,7})(?::\$?([A-Za-z]{1,3})\$?(\d{1,7}))?$/ +const on = (v: string | undefined) => v === '1' || v === 'true' + +/** the ranges of a `sqref` (`A1 B2:C9`) that are cells of a sheet */ +export function parseSqref(text: string): Range[] { + const out: Range[] = [] + for (const part of text.trim().split(/\s+/)) { + const m = CELLS.exec(part) + if (!m) continue + const [r0, c0] = parseRef(`${m[1].toUpperCase()}${m[2]}`) + const [r1, c1] = m[3] ? parseRef(`${m[3].toUpperCase()}${m[4]}`) : [r0, c0] + if (r0 < 0 || c0 < 0 || r1 < r0 || c1 < c0 || r1 >= MAX_ROWS || c1 >= MAX_COL) continue + out.push({ r0, c0, r1, c1 }) + } + return out +} + +export function sqrefOf(ranges: Range[]): string { + return ranges + .map((g) => { + const a = `${colName(g.c0)}${g.r0 + 1}` + const b = `${colName(g.c1)}${g.r1 + 1}` + return a === b ? a : `${a}:${b}` + }) + .join(' ') +} + +/** the validation cell (r, c) is under */ +export function validationAt(list: DataValidation[], r: number, c: number): DataValidation | undefined { + for (const v of list) for (const g of v.ranges) if (r >= g.r0 && r <= g.r1 && c >= g.c0 && c <= g.c1) return v + return undefined +} + +/** a list (`type="list"`) refuses the values outside it: its error alert is on, and of the kind that stops */ +export const stops = (v: DataValidation) => v.a.type === 'list' && on(v.a.showErrorMessage) && (v.a.errorStyle ?? 'stop') === 'stop' + +/** the values a list has typed in its rule (`"a,b,c"`); undefined when its formula names the cells that hold them */ +export function literalList(f: string | undefined): string[] | undefined { + if (!f || f.length < 2 || f[0] !== '"' || f[f.length - 1] !== '"') return undefined + const inner = f.slice(1, -1) + // (a quote that is not doubled ends the text: this is a formula of several, not a list) + if (inner.replace(/""/g, '').includes('"')) return undefined + return inner + .replace(/""/g, '"') + .split(',') + .map((s) => s.trim()) + .filter((s) => s !== '') +} + +/** the formula of a list of typed values; throws when they cannot be one */ +export function listFormula(values: string[]): string { + const vals = values.map((v) => v.trim()).filter((v) => v !== '') + if (!vals.length) throw new Error('A list needs at least one value.') + if (vals.some((v) => v.includes(','))) throw new Error('A value of a list cannot hold a comma. Put the values in cells and give the list their range.') + const text = vals.join(',') + if (text.length > LIST_TEXT_MAX) throw new Error(`The values of a list take ${LIST_TEXT_MAX} characters at most, commas included. Put the values in cells and give the list their range.`) + return `"${text.replace(/"/g, '""')}"` +} + +/** the formula of a validation as cell (r, c) reads it: moved from the first cell of the first range by as much as the cell is */ +export function formulaFor(v: DataValidation, f: string, r: number, c: number): string { + const g = v.ranges[0] + return g && (r !== g.r0 || c !== g.c0) ? translateFormula(f, r - g.r0, c - g.c0) : f +} + +/** what the view is told of the validation of a cell */ +export function cellValidation(v: DataValidation, r: number, c: number): CellValidation { + const type = v.a.type ?? 'none' + if (type !== 'list') return { type } + const values = literalList(v.f1) + return { type, dropdown: !on(v.a.showDropDown), ...(values ? { values } : v.f1 ? { source: stripFunctionPrefixes(formulaFor(v, v.f1, r, c)) } : {}), strict: stops(v) } +} + +/** the validations with their formulas rewritten by `fn`; one it leaves as it was is the same object */ +export function mapValidations(list: DataValidation[], fn: (f: string) => string): DataValidation[] { + return list.map((v) => { + const f1 = v.f1 === undefined ? undefined : fn(v.f1) + const f2 = v.f2 === undefined ? undefined : fn(v.f2) + return f1 === v.f1 && f2 === v.f2 ? v : { ...v, ...(f1 !== undefined && { f1 }), ...(f2 !== undefined && { f2 }) } + }) +} + +/** a validation on other cells than it was: its formulas read for its first cell, with another one they are written for that one */ +function placed(v: DataValidation, ranges: Range[]): DataValidation { + const dr = ranges[0].r0 - v.ranges[0].r0 + const dc = ranges[0].c0 - v.ranges[0].c0 + const next = { ...v, ranges } + return dr || dc ? mapValidations([next], (f) => translateFormula(f, dr, dc))[0] : next +} + +const meet = (g: Range, range: Range) => g.r1 >= range.r0 && g.r0 <= range.r1 && g.c1 >= range.c0 && g.c0 <= range.c1 + +/** the validations after rows / columns moved: each on the cells it has left (none: it is gone), its formulas reading the cells where they are */ +export function shiftValidations(list: DataValidation[], sheetName: string, s: Shift): DataValidation[] { + const gone: Range | undefined = + s.delta >= 0 ? undefined : s.axis === 'row' ? { r0: s.at, c0: 0, r1: s.at - s.delta - 1, c1: MAX_COL - 1 } : { r0: 0, c0: s.at, r1: MAX_ROWS - 1, c1: s.at - s.delta - 1 } + const out: DataValidation[] = [] + for (const v of list) { + const sqref = shiftSqref(sqrefOf(v.ranges), [s]) + const ranges = sqref ? parseSqref(sqref) : [] + if (!ranges.length) continue + // (its first cell deleted, its formulas are those of the first one left) + const from = gone ? (withoutRange([v], gone)[0] ?? v) : v + out.push({ ...mapValidations([from], (f) => shiftFormula(f, { sheet: sheetName, formulaSheet: sheetName, ...s }))[0], ranges }) + } + return out +} + +/** the validations without the cells of `range`: one left without cells is gone */ +export function withoutRange(list: DataValidation[], range: Range): DataValidation[] { + return list.flatMap((v) => { + if (!v.ranges.some((g) => meet(g, range))) return [v] + const ranges: Range[] = [] + for (const g of v.ranges) { + if (!meet(g, range)) { + ranges.push(g) + continue + } + // what is above, left, right, under + const r0 = Math.max(g.r0, range.r0) + const r1 = Math.min(g.r1, range.r1) + if (g.r0 < range.r0) ranges.push({ r0: g.r0, c0: g.c0, r1: range.r0 - 1, c1: g.c1 }) + if (g.c0 < range.c0) ranges.push({ r0, c0: g.c0, r1, c1: range.c0 - 1 }) + if (g.c1 > range.c1) ranges.push({ r0, c0: range.c1 + 1, r1, c1: g.c1 }) + if (g.r1 > range.r1) ranges.push({ r0: range.r1 + 1, c0: g.c0, r1: g.r1, c1: g.c1 }) + } + return ranges.length ? [placed(v, ranges)] : [] + }) +} + +/** the validations on the cells of `range` only */ +export function withinRange(list: DataValidation[], range: Range): DataValidation[] { + return list.flatMap((v) => { + const ranges = v.ranges + .filter((g) => meet(g, range)) + .map((g) => ({ r0: Math.max(g.r0, range.r0), c0: Math.max(g.c0, range.c0), r1: Math.min(g.r1, range.r1), c1: Math.min(g.c1, range.c1) })) + return ranges.length ? [placed(v, ranges)] : [] + }) +} + +/** (a line break in an attribute is kept only as a character reference: Excel writes the lines of a message so) */ +const attr = (s: string) => escAttr(s).replace(/\t/g, ' ').replace(/\n/g, ' ').replace(/\r/g, ' ') + +/** the attributes a `` has in the schema (`sqref` apart): what else the file gave it stays on its own element only */ +const KNOWN = new Set(['type', 'errorStyle', 'imeMode', 'operator', 'allowBlank', 'showDropDown', 'showInputMessage', 'showErrorMessage', 'errorTitle', 'error', 'promptTitle', 'prompt']) + +/** a `` as the model has it */ +function ruleXml(v: DataValidation, P: string): string { + const a = Object.entries(v.a) + .map(([k, x]) => (KNOWN.has(k) ? ` ${k}="${attr(x)}"` : '')) + .join('') + const f = (v.f1 !== undefined ? `<${P}formula1>${escText(v.f1)}` : '') + (v.f2 !== undefined ? `<${P}formula2>${escText(v.f2)}` : '') + return `<${P}dataValidation${a} sqref="${sqrefOf(v.ranges)}"${f ? `>${f}` : '/>'}` +} + +/** + * `` as the model has them ('' without any). `had`: the element of the file. A rule read from it is + * written as its own element, on the cells and with the formulas it has now: what else the file says in it stays. + * One that was not read stays too, moved by `follow`. + */ +export function validationsXml(list: DataValidation[], P: string, had?: RNode, follow: (nodes: RChild[]) => RChild[] = (n) => n): string { + if (had) P = prefixOf(had.q) + const own = kidsOf(had, 'dataValidation') + // (the reader left those without cells it knows, and those past its limit: they are not the model's to take away) + let read = 0 + const left = own.filter((n) => !parseSqref(getAttr(n, 'sqref') ?? '').length || ++read > MAX_VALIDATIONS) + const items: string[] = [] + // (one parted in two by an edit: the second has no identity of its own in the file) + const taken = new Set() + for (const v of list) { + const node = v.n === undefined || taken.has(v.n) ? undefined : own[v.n] + if (!node) { + items.push(ruleXml(v, P)) + continue + } + taken.add(v.n!) + const sqref = sqrefOf(v.ranges) + if (sqrefOf(parseSqref(getAttr(node, 'sqref') ?? '')) !== sqref) setAttr(node, 'sqref', sqref) + for (const [name, f] of [['formula1', v.f1], ['formula2', v.f2]] as const) { + const at = kidOf(node, name) + if (at && f !== undefined && textContent(at) !== f) at.c = [escText(f)] + } + items.push(serialize([node])) + } + for (const n of follow(left)) items.push(serialize([n])) + if (!items.length) return '' + const open = had ? had : el(P + 'dataValidations', {}) + setAttr(open, 'count', String(items.length)) + open.c = items + open.self = false + return serialize([open]) +} diff --git a/src/core/xlsx/workbook.ts b/src/core/xlsx/workbook.ts index 1d805b9..ddb63ec 100644 --- a/src/core/xlsx/workbook.ts +++ b/src/core/xlsx/workbook.ts @@ -6,12 +6,13 @@ import { parseTheme, type Theme } from '../theme' import { Calc } from './calc' import { desc, kid, kids, parseXml, parseXmlStream, type Attrs, type SaxHandler, type XEl } from '../xml' import { sheetColor } from '../color' -import { formatValue, formatText } from './numfmt' +import { formatText, formatValue, isDateFormat } from './numfmt' import { parseSheetStyles, type SheetStyles } from './styles' import { expandShared, formulaAt } from './structure' import { stripFunctionPrefixes, type PivotInfo, type TableInfo } from './formula' import { readPivots } from './pivot' import { linksAt } from './links' +import { cellValidation, formulaFor, literalList, MAX_VALIDATIONS, parseSqref, validationAt, type DataValidation } from './validation' import { isoToSerial } from './formula/dates' import type { Shift } from './follow' import { MAX_COL, MAX_ROWS, MAX_COL_WIDTH, MAX_ROW_HEIGHT_PT, ooxmlCapped, ooxmlInt, ooxmlNumber } from './limits' @@ -160,6 +161,10 @@ export class SheetData { * as the sheet's XML is when it is saved (see `linksAt`). */ links: FileLink[] = [] + /** the data validations of the sheet (the rules for what may be typed in its cells), on the cells they are on now */ + validations: DataValidation[] = [] + /** a validation was set or taken away: their element is written from the model */ + dirtyValidations = false colInfo: ColInfo[] = [] defaultColW = 64 defaultRowH = 20 @@ -178,6 +183,14 @@ export interface FileLink { tooltip?: string } +/** a value of a list: as shown, as typed to enter it (the number behind a formatted one), that number, and whether it shows as a date */ +export interface ListItem { + text: string + input: string + num?: number + date?: boolean +} + /** links of a sheet past which the rest are not read (Excel keeps 65,530 at most) */ const MAX_LINKS = 100_000 @@ -199,7 +212,11 @@ class SheetHandler implements SaxHandler { private val = '' private formula = '' private hasVal = false - private capture = 0 // 1 v, 2 f, 3 inline t + private capture = 0 // 1 v, 2 f, 3 inline t, 4 / 5 the formulas of a validation + /** the being read */ + private dv?: DataValidation + /** the validations seen so far, those left out too */ + private dvs = 0 private fShared = -1 private fArray = '' private cm = 0 @@ -340,9 +357,21 @@ class SheetHandler implements SaxHandler { case 'hyperlink': if (a.ref && this.d.links.length < MAX_LINKS) this.d.links.push({ ref: a.ref, rid: a['r:id'] || undefined, location: a.location || undefined, tooltip: a.tooltip || undefined }) return true + case 'dataValidation': { + const n = this.dvs++ + const { sqref, ...rest } = a + const ranges = sqref ? parseSqref(sqref) : [] + if (!ranges.length || this.d.validations.length >= MAX_VALIDATIONS) return true + this.dv = { ranges, a: rest, n } + return + } + case 'formula1': + case 'formula2': + if (!this.dv) return true + this.capture = name === 'formula1' ? 4 : 5 + return case 'extLst': case 'conditionalFormatting': - case 'dataValidations': case 'headerFooter': return true } @@ -358,6 +387,14 @@ class SheetHandler implements SaxHandler { case 'is': this.inIs = false return + case 'formula1': + case 'formula2': + this.capture = 0 + return + case 'dataValidation': + if (this.dv) this.d.validations.push(this.dv) + this.dv = undefined + return case 'c': { const cells = this.rowCells if (!cells) return @@ -454,6 +491,8 @@ class SheetHandler implements SaxHandler { if (this.capture === 1) this.val += t else if (this.capture === 2) this.formula += t else if (this.capture === 3) this.val += t + else if (this.capture === 4 && this.dv) this.dv.f1 = (this.dv.f1 ?? '') + t + else if (this.capture === 5 && this.dv) this.dv.f2 = (this.dv.f2 ?? '') + t } } @@ -1087,12 +1126,63 @@ export class XlsxWorkbook { out = { value, formula: formula ? '=' + formula : undefined, type } break } - if (!d || !withLinks) return out + if (!d) return out + const rule = d.validations.length ? validationAt(d.validations, r, c) : undefined + if (rule) out = { ...(out ?? { value: '', type: 'empty' }), validation: cellValidation(rule, r, c) } + if (!withLinks) return out const links = await linksAt(this, sheet, d, r, c, formula || undefined, t === T_SST || t === T_STR ? out?.value : undefined) if (!links.length) return out return { ...(out ?? { value: '', type: 'empty' }), links } } + /** + * The values of the list cell (r, c) takes, when its validation is one: those typed in the rule (`typed`), or what + * the cells its formula names show, the empty ones left out, each value once. `max` values at most (`capped` past + * it). Undefined when the cell has no list. + */ + async listItems(sheet: number, r: number, c: number, max: number): Promise<{ items: ListItem[]; typed: boolean; capped: boolean } | undefined> { + const d = this.sheetsData.get(sheet) + const v = d && validationAt(d.validations, r, c) + if (!v || v.a.type !== 'list' || !v.f1) return undefined + const typed = literalList(v.f1) + if (typed) return { items: typed.slice(0, max).map((text) => ({ text, input: text })), typed: true, capped: typed.length > max } + const items: ListItem[] = [] + const at = this.calc.cellsOf(sheet, formulaFor(v, v.f1, r, c), r, c) + if (!at) return { items, typed: false, capped: false } + await this.loadSheet(at.sheet, () => {}) + const src = this.sheetsData.get(at.sheet) + if (!src) return { items, typed: false, capped: false } + const r1 = Math.min(at.r1, Math.max(src.maxRow, src.rows.length - 1)) + await this.ensure(src, at.r0, r1) + const xfs = this.styles.xfs + const seen = new Set() + for (let rr = at.r0; rr <= r1; rr++) { + const row = src.rows[rr] + if (!row) continue + for (let k = colAt(row, at.c0); k < row.length && (row[k] as number) <= at.c1; k += 4) { + const t = row[k + 1] as number + const val = row[k + 2] + const fmt = (xfs[row[k + 3] as number] ?? xfs[0])?.numFmt + let item: ListItem + if (t === T_NUM) item = { text: formatValue(val as number, fmt, this.date1904).text, input: String(val), num: val as number, date: isDateFormat(fmt ?? '') } + else if (t === T_SST || t === T_STR) { + const str = t === T_SST ? (this.sst[val as number] ?? '') : (val as string) + item = { text: formatText(str, fmt), input: str } + } else if (t === T_BOOL) item = { text: val ? 'TRUE' : 'FALSE', input: val ? 'TRUE' : 'FALSE' } + else if (t === T_DATE) { + const serial = isoToSerial(val as string, this.date1904) + const text = serial !== null && fmt && fmt !== 'General' ? formatValue(serial, fmt, this.date1904).text : (val as string).replace('T00:00:00', '').replace('T', ' ').replace(/Z$/, '') + item = serial === null ? { text, input: text } : { text, input: String(serial), num: serial, date: true } + } else continue + if (item.text === '' || seen.has(item.text)) continue + if (items.length >= max) return { items, typed: false, capped: true } + seen.add(item.text) + items.push(item) + } + } + return { items, typed: false, capped: false } + } + unload(sheet: number) { const d = this.sheetsData.get(sheet) if (d?.done) this.sheetsData.delete(sheet) diff --git a/src/react/edit/Toolbar.tsx b/src/react/edit/Toolbar.tsx index 8c663d6..4939568 100644 --- a/src/react/edit/Toolbar.tsx +++ b/src/react/edit/Toolbar.tsx @@ -162,6 +162,7 @@ const P = { present: , sheetAdd: , replace: , + validation: , } satisfies Record /** the name of one of the viewer's icons */ diff --git a/src/react/strings/de.ts b/src/react/strings/de.ts index e04d7d0..4901f09 100644 --- a/src/react/strings/de.ts +++ b/src/react/strings/de.ts @@ -402,6 +402,20 @@ export const de: Strings = { matchCase: 'Groß-/Kleinschreibung', entireCell: 'Ganzer Zellinhalt', inFormulas: 'In Formeln', + validation: 'Datenüberprüfung…', + validationTitle: 'Datenüberprüfung', + validationCells: (ref: string) => `Werteliste für ${ref}`, + validationValues: 'Hier eingegebene Werte', + validationRange: 'Werte aus Zellen', + validationValuesHint: 'Ein Wert pro Zeile oder durch Kommas getrennt', + validationRangeHint: '$A$1:$A$9, Tabelle2!$A$1:$A$9 oder ein Name', + validationStrict: 'Andere Werte ablehnen', + validationRemove: 'Überprüfung entfernen', + validationOther: 'Diese Zellen haben eine Überprüfung anderer Art (in Excel gesetzt). OK ersetzt sie durch die Liste.', + listOpen: 'Aus der Liste wählen', + listEmpty: 'Die Liste hat keine Werte', + listRefused: 'Diese Zelle nimmt nur einen Wert aus ihrer Liste an.', + listCapped: (n: number, locale: string | undefined = undefined) => `Nur die ersten ${n.toLocaleString(locale)} Werte sind aufgelistet`, paint: 'Format übertragen (klicken, dann Zellen auswählen)', currency: 'Als Währung formatieren', percent: 'Als Prozent formatieren', diff --git a/src/react/strings/en.ts b/src/react/strings/en.ts index 56748d1..2ba0af1 100644 --- a/src/react/strings/en.ts +++ b/src/react/strings/en.ts @@ -416,6 +416,22 @@ export const en = { matchCase: 'Match case', entireCell: 'Entire cell', inFormulas: 'In formulas', + /** data validation: the list of values cells take, its dialog, the dropdown of a cell */ + validation: 'Data validation…', + validationTitle: 'Data validation', + validationCells: (ref: string) => `List of values for ${ref}`, + validationValues: 'Values typed here', + validationRange: 'Values held by cells', + validationValuesHint: 'One value per line, or separated by commas', + validationRangeHint: '$A$1:$A$9, Sheet2!$A$1:$A$9 or a name', + validationStrict: 'Reject other values', + validationRemove: 'Remove validation', + validationOther: 'These cells have a validation of another kind (set in Excel). OK replaces it with the list.', + listOpen: 'Choose from the list', + listEmpty: 'The list has no values', + /** a value typed that the list does not take, where the file has no message for it */ + listRefused: 'This cell takes a value of its list only.', + listCapped: (n: number, locale: string | undefined = undefined) => `Only the first ${n.toLocaleString(locale)} values are listed`, paint: 'Paint format (click, then select cells)', currency: 'Format as currency', percent: 'Format as percent', diff --git a/src/react/styles.css b/src/react/styles.css index c774f62..b1fcae1 100644 --- a/src/react/styles.css +++ b/src/react/styles.css @@ -1138,6 +1138,24 @@ .de-linkcard-goto:hover { text-decoration: underline; } .de-linkcard-goto { padding: 0; border: 0; background: none; font: inherit; font-weight: 500; cursor: pointer; text-align: left; } .de-linkcard-hint { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--de-muted); font-size: 12px; } +/* XLSX: the list of values a cell takes (its data validation): a button at the cell, the values under it; its dialog */ +.de-list-btn { + position: absolute; z-index: 4; display: inline-flex; align-items: center; justify-content: center; box-sizing: border-box; padding: 0; + border: 1px solid var(--de-border); border-radius: 3px; background: var(--de-pop); color: var(--de-muted); cursor: pointer; +} +.de-list-btn:hover, .de-list-btn.open { border-color: var(--de-accent); color: var(--de-accent); } +.de-listcard { + position: absolute; z-index: 30; box-sizing: border-box; padding: 4px 0; overflow: auto; + background: var(--de-pop); border: 1px solid var(--de-border); border-radius: 8px; box-shadow: var(--de-pop-shadow); + color: var(--de-text); font: 13px/1.4 var(--de-font); text-align: left; cursor: default; user-select: none; +} +.de-listcard-item { padding: 4px 10px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; cursor: pointer; } +.de-listcard-item:hover { background: var(--de-hover-soft); } +.de-listcard-item.on { background: var(--de-hover-solid); } +.de-listcard-note { padding: 4px 10px; color: var(--de-muted); font-size: 12px; } +.de-dv-row { display: flex; flex-wrap: wrap; gap: 6px 16px; } +.de-dv-opt { display: inline-flex; align-items: center; gap: 6px; font-size: 13px; cursor: pointer; } +.de-dialog .de-dv-opt input, .de-dv-opt input { width: auto; padding: 0; margin: 0; accent-color: var(--de-accent); } /* docx: picture selection, outline, dialogs */ .de-img-sel { position: absolute; z-index: 4; border: 1.5px solid var(--de-accent); pointer-events: none; } diff --git a/src/react/xlsx/Validation.tsx b/src/react/xlsx/Validation.tsx new file mode 100644 index 0000000..15cbca3 --- /dev/null +++ b/src/react/xlsx/Validation.tsx @@ -0,0 +1,111 @@ +/** + * Data validation in the sheet view: the list of values a cell takes, under the cell (its button, Alt+Down), and the + * dialog that gives a list to the selected cells. + */ +import { useEffect, useRef, useState, type CSSProperties } from 'react' +import type { CellValidation, ListRule, ListValues } from '../../core/xlsx/types' +import { useStrings } from '../strings' +import { DefaultDialog, useHostUI, type DialogAction } from '../ui' + +/** + * The values of a cell's list. The keyboard stays with the grid (which moves `index` with the arrows and picks with + * Enter): the card only shows where it is, and takes clicks. + */ +export function ListCard(props: { style: CSSProperties; data?: ListValues; index: number; onPick: (i: number) => void }) { + const str = useStrings() + const hi = useRef(null) + useEffect(() => { + // (the value the keys are on is in view) + hi.current?.scrollIntoView({ block: 'nearest' }) + }, [props.index, props.data]) + const { data } = props + return ( +
{ + e.stopPropagation() + e.preventDefault() + }} + onDoubleClick={(e) => e.stopPropagation()} + onContextMenu={(e) => e.stopPropagation()} + > + {data?.values.map((v, i) => ( +
props.onPick(i)}> + {v} +
+ ))} + {data && !data.values.length &&
{str.xlsx.listEmpty}
} + {data?.capped &&
{str.xlsx.listCapped(data.values.length, str.locale)}
} +
+ ) +} + +/** + * The list the selected cells take: its values typed here, or the cells that hold them; whether another value is + * refused. `had`: the validation of the first of the cells, to start from (one of another kind is replaced). + */ +export function ValidationDialog(props: { cells: string; had?: CellValidation; onApply: (rule: ListRule | null) => void; onClose: () => void }) { + const str = useStrings() + const Dialog = useHostUI().Dialog ?? DefaultDialog + const list = props.had?.type === 'list' ? props.had : undefined + const [kind, setKind] = useState<'values' | 'range'>(list?.source !== undefined ? 'range' : 'values') + const [values, setValues] = useState((list?.values ?? []).join('\n')) + const [source, setSource] = useState(list?.source ?? '') + const [strict, setStrict] = useState(list ? !!list.strict : true) + const field = useRef(null) + useEffect(() => { + field.current?.focus() + }, [kind]) + const rule = (): ListRule => (kind === 'range' ? { source: source.trim().replace(/^=/, ''), strict } : { values: values.split(/[\n,]/).map((v) => v.trim()).filter((v) => v !== ''), strict }) + const empty = kind === 'range' ? !source.trim() : !values.trim() + const done = () => { + if (empty) return + props.onClose() + props.onApply(rule()) + } + const actions: DialogAction[] = [ + ...(props.had + ? [ + { + label: str.xlsx.validationRemove, + extra: true, + onClick: () => { + props.onClose() + props.onApply(null) + }, + }, + ] + : []), + { label: str.common.cancel, onClick: props.onClose }, + { label: str.common.ok, primary: true, submit: true, onClick: done }, + ] + return ( + +
{str.xlsx.validationCells(props.cells)}
+
+ + +
+ {kind === 'values' ? ( +