@xlsx-editor.dev/react 0.0.0-stage → 0.1.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,180 @@
1
+ # Edit cells
2
+
3
+ This guide describes cell edits, typed values, the formula bar, the name box, and saves. For setup, see the [package README](../README.md).
4
+
5
+ ## Edit a cell
6
+
7
+ To edit a cell, select it and type, press F2, or double-click it. Press Enter to commit the edit. Text that starts with `=` is a formula in A1 notation. The editor stores a formula (`x:f`) without a cached result (`x:v`), and sets `x:calcPr/@fullCalcOnLoad` to ask the next consumer to recalculate the workbook. If the editor cannot store an edit, it keeps your text and shows the reason.
8
+
9
+ A typed formula can call only the predefined functions of ECMA-376 Part 1, 18.17.7, in any letter case. A call to another function, such as a future function or a name with a stored-name prefix, is refused with the reason `unsupported-function`. A defined name, a table reference, or a sheet name is not a call. A formula that the workbook holds keeps its stored text, and the formula bar, the cell editor, and the announcement show it as stored, prefixes included. A save writes it unchanged. A commit of an edit to such a formula is refused with `unsupported-function`, because the text calls a prefixed name; cancel the edit to keep the stored formula.
10
+
11
+ ## Typed values
12
+
13
+ Typed text in a number form stores a number: a percent (`12%`), a currency amount (`$5.50`), a grouped number (`1,234.5`), a negative in parentheses (`(100)`), a fraction with a whole part (`1 1/2`), a date (`2026-11-12`), a time (`13:45`), an elapsed time (`36:00`), or a date and a time (`2026-11-12 13:45`). A date or a time stores its serial number in the date system of the workbook (`x:workbookPr/@date1904`, ECMA-376 Part 1, 18.17.4.1). The `numberLocale` prop sets the separators and the day and month order of a date. A date with no year, such as `3/15`, takes the current year of the host clock. A cell with the General format also takes the number format of the form, in the same undo step. A cell with another number format keeps it. A cell with the Text format keeps your text, but a formula stays a formula.
14
+
15
+ On a sheet whose protection does not allow formatting cells, or in a workbook whose list of cell formats or number formats is full, or whose styles part the editor cannot read, the cell keeps its format and stores the number. So does a code of the number locale that the editor cannot read. To keep any entry as text, start it with an apostrophe (`'007`). In a date cell (`x:c/@t="d"`), ISO 8601 text such as `2024-03-01` stays a date.
16
+
17
+ When you edit the cell again, the cell editor shows a date as ISO 8601, a time on a 24-hour clock, an elapsed time in hours, and a percent with `%`. The formula bar shows the same text, also for such cells in a workbook that you open. A currency amount shows as a plain number. A plain number that you type in a percent cell is not scaled.
18
+
19
+ ## Formula bar
20
+
21
+ You can also edit the active cell in the formula bar. When you type in its content field, the edit opens over the cell, and the grid shows the same text as you type. Press Enter to commit and move down, Tab to commit and move right, Shift with either to move back, Alt+Enter to add a line break, or Escape to cancel. The grid then takes the keyboard. If the editor cannot store the edit, the text and the keyboard stay in the field, and the status strip shows the reason.
22
+
23
+ A text with more than one line shows a line count. A press on it, or on the gap beside the field, puts the caret at the end of the line that the field shows. With Shift, while the field has the keyboard, the press extends the text selection to the end of that line. While an input method composes, Enter commits nothing. In view mode, the field is read-only.
24
+
25
+ ## Name box
26
+
27
+ To go to a cell, type a reference in the name box and press Enter: a cell such as `B2`, a range such as `B2:C5`, whole columns such as `C:E`, whole rows such as `3:5`, or a reference with a sheet name such as `Sheet2!A1` or `'My sheet'!A1:B2`. Letters can be in any case. You can also type a defined name whose text is one reference with a sheet name, such as `Data!$A$1:$B$4`. A name that the shown sheet scopes comes before a workbook name. A sheet name before a defined name, such as `Data!Rates`, reads only the names of that sheet.
28
+
29
+ If the text names no cell or range, the name box keeps your text and the status strip shows the reason. This also happens for a defined name that names a formula, several ranges, or a range on a sheet that is not a visible worksheet, and for a sheet that is not a visible worksheet. Press Escape to drop the typed reference.
30
+
31
+ ## Edit from your own chrome
32
+
33
+ Your own chrome can do the same through the editor instance:
34
+
35
+ - `setEditText(text, { composing })` makes `text` the text of the open cell edit. With no open edit, it opens one over the active cell without taking the keyboard, and it returns the refusals of `beginEdit()`, such as `locked`, `view-mode`, and `cell-alternate-content`. Pass `composing: true` while an input method composes in your field, and call it again with `false` when the composition ends, also when the field loses the keyboard or unmounts. Until then, every commit is refused with `composing`. A cancel of the edit, or a key in the cell editor, also ends it. A `text` that is not a string throws a `TypeError`.
36
+ - `commitEdit(move)` commits the open edit and moves the active cell `down`, `up`, `right`, or `left`, as Enter and Tab do. With no open edit, it only moves the active cell. When an open edit commits, or the active cell moves with no open edit, the grid takes the keyboard. A `move` that is not one of these values throws a `TypeError`.
37
+ - `selectReference(reference)` selects the range that a reference names, or returns the refusal `go-to-reference`, `go-to-name`, or `go-to-sheet`. It reads at most `MAX_GO_TO_LENGTH` (255) characters: a longer text is refused with `go-to-reference`.
38
+
39
+ The functions `editMoveOf(keys)`, `composesKey(event, composing)`, and `fieldHistoryKey(keys, typing)` give the key rules of the formula bar, so your field acts as the bar does. Their `keys` argument is a `FieldKeys`, which a DOM or React key event satisfies. `refusesEditText(code)` tells whether a refusal refuses the text of the open edit, so the field that shows it can be marked invalid. `refusesReference(code)` tells whether a refusal of `selectReference` refuses the typed reference, not the open edit. Import them, and the types `EditMove` and `EditTextOptions`, from `@xlsx-editor.dev/react`. `contentFieldText(text)` gives the start of a cell text that a content field holds: at most `MAX_CONTENT_FIELD_CHARS` (65,536) UTF-16 code units, with no half of a surrogate pair at its end. If the result is shorter than the text, make the field read-only, as the formula bar does. The edit keeps the complete text.
40
+
41
+ Inside `XlsxEditor.Root`, this field is a small form of the content field of the formula bar. It edits the active cell, commits and moves, cancels, and passes the history keys:
42
+
43
+ <!-- sample: guide-cell-field -->
44
+
45
+ ```tsx
46
+ import {
47
+ composesKey,
48
+ editMoveOf,
49
+ fieldHistoryKey,
50
+ refusesEditText,
51
+ useEditorSnapshot,
52
+ useXlsxEditor,
53
+ } from '@xlsx-editor.dev/react';
54
+
55
+ function CellField() {
56
+ const editor = useXlsxEditor();
57
+ const snap = useEditorSnapshot();
58
+ const text = snap.editText ?? snap.activeCell?.content ?? '';
59
+ // Mark the field while the engine refuses the text of the open edit.
60
+ const refusal = snap.editing ? snap.refusal : null;
61
+ const invalid = refusal !== null && refusesEditText(refusal.code);
62
+ return (
63
+ <textarea
64
+ rows={1}
65
+ aria-label="Cell"
66
+ aria-invalid={invalid || undefined}
67
+ value={text}
68
+ onChange={(e) => editor?.setEditText(e.currentTarget.value)}
69
+ onKeyDown={(e) => {
70
+ if (!editor || composesKey(e.nativeEvent, false)) return;
71
+ const history = fieldHistoryKey(e, snap.editing);
72
+ const move = editMoveOf(e);
73
+ if (history) {
74
+ e.preventDefault();
75
+ if (history === 'undo') editor.undo();
76
+ else editor.redo();
77
+ } else if (move) {
78
+ e.preventDefault();
79
+ editor.commitEdit(move);
80
+ } else if (e.key === 'Escape') {
81
+ e.preventDefault();
82
+ editor.cancelEdit();
83
+ }
84
+ }}
85
+ />
86
+ );
87
+ }
88
+ ```
89
+
90
+ The sample is a text area, so it keeps the line breaks of a cell. An edit that opens clears an earlier refusal, so the mark shows only a refusal of this edit. The sample keeps the mark until the next commit or cancel; the formula bar removes it when the text changes. The sample does not report a composition or add a line break on Alt+Enter: the formula bar also calls `setEditText(text, { composing })` for each composition.
91
+
92
+ ## The ref
93
+
94
+ The ref is small: `load()`, `save()`, `saveInTasks()`, `getEditor()`, `focus()`, and `snapshot()`. Call the editing commands on the editor instance that `getEditor()` returns. The ref differs from the DOCX Editor ref in these ways:
95
+
96
+ - It has no `exec()`. Each command is a typed method of `XlsxEditorInstance`, and the engine has no command union to dispatch on. To run a toolbar slot, use `useEditorCommand`.
97
+ - It has no `getDocumentHandle()`. Read the state with `snapshot()`, and edit through `getEditor()`.
98
+ - `save()` is synchronous, as in PPTX Editor. DOCX Editor's `save()` returns a promise, so the save in short tasks has its own name here, and `save()` keeps its synchronous result. `saveInTasks()` writes the same bytes in short tasks, so the page stays responsive during the save of a large workbook. It resolves to a `SavedWorkbook`, or to `null` when the save is refused.
99
+ - `load()` returns a promise of the snapshot after the open, or `null` before the editor mounts. Opening a workbook loads fonts and parses the package asynchronously, so the caller can wait for the result. If the file passes a limit of the editor, the snapshot turns `failed` with the code `package`, and `failure.limit` names the limit, such as `xml.maxBytes`. If an XML part did not read, `failure.part` names it, such as `/xl/sharedStrings.xml`. The editor then shows that the file is too large to open, with the part and the limit, as DOCX Editor does for a file that is too large. `failure.detail` is for logs only. If a styles part, a theme part, a drawing, or another relationship part passes a limit, the workbook opens without that part, and a save keeps its bytes. `snapshot().partsPastLimit` lists each such part with its `kind` and its `limit`, as a `PartPastLimit` type, and the editor shows a notice that names the part. Each message shows a part name through `displayName` from `@xlsx-editor.dev/core/editor`: it drops control characters and bidirectional format controls, and cuts the name to 64 characters. If you show `failure.part` or a `PartPastLimit` part in your own message, pass it through `displayName` too. The [workbook limits](https://github.com/eigenpal/xlsx-editor/blob/main/docs/site/content/workbook-limits.mdx) page lists the limits and their values.
100
+
101
+ ## Save the workbook
102
+
103
+ To get the edited workbook, call `save()` on the ref. The [package README](../README.md#edit-and-save) has a sample.
104
+
105
+ The bytes keep the kind of the opened package: a workbook (`.xlsx`) stays a workbook, and a template (`.xltx`) stays a template. Name the file with the extension of `snapshot().workbookKind`. If the workbook already has a shared string table, text that an edit adds to it stays in the saved file after an undo of the edit, because the editor never removes items from a table that it opened. If the edit created the table, the undo removes the table, with its relationship and content type.
106
+
107
+ ## Rules for open edits and loads
108
+
109
+ These rules apply while a cell edit is open, while an input method composes, and while a workbook loads:
110
+
111
+ - `save()`, `select()`, `setActiveSheet()`, `setMode('view')`, and the format, clear, insert, and delete commands commit an open cell edit first. `enterValue()` without `at`, or with the cell of the open edit, also commits it first.
112
+ - If the editor cannot store that edit, these calls do nothing. `save()` returns `null`, `select()` and `setMode()` return `false`, and the commands return the refusal. The editor shows the reason.
113
+ - A refused save keeps its refusal in `snapshot().refusal` with `command` set to `save`, and the editor shows and announces "The workbook was not saved", with the reason. A host that tracks saves reads that field. A save that is refused during a load is shown and announced while the load runs, and clears when the load settles. A good save clears an older refusal.
114
+ - While an input method composes in the cell editor or the formula bar, `snapshot().composing` is true. Each of these calls is refused with the reason `composing`, as are `undo()`, `redo()`, `commitEdit()`, and `selectReference()`, because the composed text is not converted yet. `setMode('view')` returns `false` then, with no announcement.
115
+ - If the surface closes while an input method composes, through `detach()`, `destroy()`, or an unmount of `XlsxEditor.Content`, the editor drops the edit and stores nothing. It sets `snapshot().refusal` to the code `edit-dropped` and notifies the listeners while the surface is still attached, so `onChange` and the status strip see it. After `destroy()`, no listener is left to notify.
116
+ - `snapshot().refusal` holds the last refusal until one of these events clears it:
117
+ - An edit that the editor stores.
118
+ - A good save.
119
+ - A copy or a cut that succeeds.
120
+ - A change of the selection, the sheet, or the mode.
121
+ - A cancel of the open cell edit.
122
+ - A cell edit that opens, unless the refusal is `edit-dropped`.
123
+ - The start or the settle of a load.
124
+ - A new rename in the sheet tabs, when the refusal is the reason of an earlier refused rename.
125
+
126
+ A new refusal replaces it, and so does `edit-dropped` when the editor drops an open edit with changed text. While a load runs, each new refusal has the code `loading`. To clear the refusal from your own chrome, such as when the user closes the control that it explains, call `dismissRefusal()` on the editor instance. It changes no cell.
127
+
128
+ - An edit (a typed value or formula, or a paste), a clear, or the clear of `mergeCells({ dropValues: true })` is refused with the reason `shared-formula` in these cases. The editor keeps each formula range whole.
129
+ - The cell is the master of, or inside, an array or data table formula range. Its master can be inside `mc:AlternateContent`. An edit of that wrapped master itself is refused with `cell-alternate-content`.
130
+ - The cell is a shared formula master whose text cannot be read.
131
+ - The cell is a shared formula master, and a child has its `x:f` inside `mc:AlternateContent` in its cell. The editor cannot rewrite that child. A paste over the master is refused, also when it covers that child. A clear that also covers that child is refused with `cell-alternate-content`.
132
+ - The edit would move the formula of a shared child out of the grid.
133
+
134
+ Typing on such a cell opens no cell editor, except when the refusal comes from a shared child that would move out of the grid. That case is refused at the commit.
135
+
136
+ An edit to any other shared formula master writes each child's own formula first, so the children keep their formulas.
137
+
138
+ The refusal's `subject` names the cell or the formula range that blocks the edit, such as `Sheet1!A2:A3`. When a shared child blocks the edit of its master, the subject is the shared range that holds both cells, or the child cell when that range does not hold it. When one cell's formula blocks the edit of a shared formula master, the refusal's `causeCell` names that cell, such as `Sheet1!A3`, and `masterCell` names the master, such as `Sheet1!A2`. The message names both and tells you to leave the master out. That cell is a child inside `mc:AlternateContent`, a child whose formula would move out of the grid, or the master when its text cannot be read. In the last case, `causeUnreadable` is `true`, and the message says that the formula cannot be read.
139
+
140
+ A refused clear, paste, or merge has `command` set to `clear`, `clearAll`, `paste`, or `merge`, so its message names that command. A refused commit of an open cell edit has `command: 'commit'`. The cell editor stays open, and the message tells you to cancel the cell edit.
141
+
142
+ A cut and its paste follow these rules:
143
+
144
+ - A cut runs the checks of a copy first, so a cut and a copy of one range give the same copy reason. For example, a cell whose formula is inside `mc:AlternateContent` gives `copy-wrapped-formula`.
145
+ - A cut whose source the editor cannot clear is refused at the cut, with the code of that clear.
146
+ - Every refusal of a cut has `command: 'cut'`. `refusalText` shows its message from `editing.cutRefused.<code>`, or from `editing.cutRefusedUnnamed.<code>` when the refusal names no cell. A `shared-formula` cut with `causeCell` and `masterCell` shows `editing.formulaCellRefused.cut` or `editing.formulaUnreadableRefused.cut`. Each message says that the cells were not cut.
147
+
148
+ `CUT_REFUSAL_CODES` in `@xlsx-editor.dev/core/editor` lists the codes that have their own cut message. A `locked` cut has a protection message, and a cut with another store code, such as `style-limit`, shows `editing.cutRefused.other`. A refusal of the open cell edit that the cut commits first is not a refusal of the cut. It has `command: 'commit'` or no command.
149
+
150
+ - The paste of a cut clears the source cells that it does not write. So a paste over part of the source is refused with the code of that clear, such as `locked` or `shared-formula`, when that clear alone is refused.
151
+
152
+ - A cell can hold data in a form that the editor cannot update. That is other markup compatibility content, such as a formula in `mc:AlternateContent`. It is also an element in another namespace that holds `x:f`, `x:v`, or `x:is`. Typing on that cell opens no cell editor.
153
+
154
+ A value edit and a paste onto it are refused with the reason `cell-alternate-content`. So is a clear of it while it holds a value, and a cut of it, except a cut of a cell whose formula is inside `mc:AlternateContent`. That cut is refused with `copy-wrapped-formula`, as its copy is.
155
+
156
+ The refusal's `subject` names the sheet and the cell, such as `Data!B5`. Such a refusal of a clear, a cut, a paste, or the clear of `mergeCells({ dropValues: true })` has `command` set to `clear`, `clearAll`, `cut`, `paste`, or `merge`, so its message names that command. A refused commit of an open cell edit has `command: 'commit'`, and its message tells you to cancel the cell edit. The snapshot field `selectionContentBlocked` names the first such cell of the selection that holds a value, or is null.
157
+
158
+ - `redo()` commits no changed edit. If the open edit holds changed text, it returns the refusal `edit-pending`. An open edit with no change closes first.
159
+ - `undo()` commits no open edit. If the open edit holds changed text, `undo()` cancels the edit, the cell shows its content again, and the history does not change. If the open edit holds unchanged text, `undo()` closes it and undoes the last stored edit.
160
+ - When a new workbook starts to load, the editor drops an open edit at once with the refusal `edit-dropped`. While the load runs, the editor shows each refusal under the loading text and announces it. When the load settles, ready or failed, the other refusals clear. The refusal `edit-dropped`, and `snapshot().editDropped`, stay until the next command after the load, done or refused, an edit that the editor stores, or a selection change, or the next load, so the status message still shows that the typed text was not stored.
161
+
162
+ `close()` drops an edit in the same way, and the empty message shows it. Until the load settles, every command is refused with the reason `loading`: the edit commands, `undo()`, and `redo()` return it, `save()` returns `null` with a refused save, `select()` and `setActiveSheet()` return `false`, `setZoom()` does nothing, and the toolbar disables its controls with the reason `loading`.
163
+
164
+ ## Undo and redo
165
+
166
+ After an undo, the editor selects the selection that the edit started from, on its sheet, and scrolls its active cell into view. After a redo, it selects the selection that the edit ended with. An edit that `enterValue(text, at)` writes to another cell than the active one keeps no selection, so its undo and redo leave the selection as it is. When an undo or a redo changes a sheet that is not shown, such as a hidden sheet, or a sheet whose edit kept no selection, the editor stays on the shown sheet and announces the name of the changed sheet. A redo of a sheet rename selects on the new name, and a redo of a sheet add shows the added sheet. An undo or a redo of a sheet add or delete announces the change, the name of that sheet, and the sheet that shows.
167
+
168
+ ## Screen readers
169
+
170
+ The grid has a live region for screen readers. It says the active cell or the selection when the selection moves.
171
+
172
+ When the focus enters the grid from another control, such as with Tab or F6, the live region says the active cell, or the selection with its active cell. If the step that moved the focus already says something, such as a press on a sheet tab or Enter in the formula bar, the live region says only those words. If a toolbar menu applies a format and gives the grid the focus, the live region says the change after the grid updates, or the active cell when the change keeps its shown text. A press on the grid says the cell that it selects, also when it is the active cell.
173
+
174
+ An edit, such as a number format or a typed entry, can change the shown text of the active cell. The live region then says the active cell and its new text once, after the grid updates. A format or a clear on a selection of many cells also says its active cell. A paste says the pasted selection.
175
+
176
+ When Enter or Tab moves the active cell inside a selection of many cells, the live region says the selection with the new active cell. A paste that changes cells in such a selection does the same. An undo or a redo says its step, and the active cell when the step changed its text. An edit that keeps the shown text says nothing, except a decimal step or a number format change. That edit says that the decimal places increased or decreased, or that the number format changed. A select of the same selection again also says nothing while the live region still holds its words.
177
+
178
+ The grid's accessible description says how to leave the grid: press Escape and then Tab or Shift+Tab, or press F6. F6 moves to the next region of the editor, so it leaves the grid when your layout has a toolbar, a formula bar, or a footer. When Escape arms the exit, the live region says to press Tab or Shift+Tab, and a cue over the foot of the grid shows the same words until the exit is used or canceled.
179
+
180
+ Some screen readers take Escape in their own modes. If the hint does not come, press F6, or press Home and then Shift+Tab. If your page handles Escape before the grid, such as in a `keydown` listener in the capture phase, call `preventDefault()` when you use the key. Otherwise the same Escape also arms the exit.
@@ -0,0 +1,85 @@
1
+ # Format cells and change the structure
2
+
3
+ This guide describes cell formats, the format state of the snapshot, row and column inserts and deletes, and merged cells. For setup, see the [package README](../README.md).
4
+
5
+ ## Format cells
6
+
7
+ To format the selected cells, call `applyFormat()` on the editor with the properties to set. Each cell keeps the properties that you do not set. The editor stores the result as a cell format (`x:xf` in `x:cellXfs`, ECMA-376 Part 1, 18.8.45 and 18.8.10), and the cell names it by index in `x:c/@s`. One call is one undo step:
8
+
9
+ <!-- sample: guide-apply-format -->
10
+
11
+ ```tsx
12
+ ref.current?.getEditor()?.applyFormat({
13
+ bold: true,
14
+ fill: { type: 'solid', color: 'FFF2CC' },
15
+ borders: { edges: 'outline', style: 'thin' },
16
+ numberFormat: { code: '0.00' },
17
+ });
18
+ ```
19
+
20
+ Give one of `id` and `code` in `numberFormat`. A patch that gives both is refused with `bad-format`. The `id` is a number format id (`x:numFmt/@numFmtId`): a built-in id of ECMA-376 Part 1, 18.8.30, or a custom id of the workbook. The `code` is a format code (`x:numFmt/@formatCode`). A border `style` is an `ST_BorderStyle` value (ECMA-376 Part 1, 18.18.3), such as `thin`.
21
+
22
+ The editor also has `toggleFormat()` for bold, italic, and underline, `clearValues()`, `clearFormats()`, and `clearAll()`. A format command that would create more than 16,384 new cells (one whole row), such as a format on a whole column or on the whole sheet, is refused with the reason `range-too-large`. A clear of formats writes a plain cell in each empty position that shows a row or column format, with the same limit, and is refused past it with the reason `clear-too-large`. The snapshot holds these refusals in `formatRefusal` and `clearRefusal`.
23
+
24
+ ## Read the format state
25
+
26
+ The editor snapshot holds the format of the active cell in `activeFormat`. Its `numberFormat` holds the format id, the code of the id in the number locale, and `hasCode`. `hasCode` is `false` when the id has no code in the workbook or the number locale, so the cell shows General.
27
+
28
+ `decimalSteps` holds the state of the two decimal steps on the selection, in `increase` and `decrease`. Each is `null` when at least one selected cell can step. Otherwise it holds the refusal that the step gives, with the reason in `reason`, as [Decimal places](toolbar-and-keyboard.md#decimal-places) describes. `selectionSingle` is `true` when the selection is one cell or exactly one merged range.
29
+
30
+ The state reads the stored cells, and it is not the enabled state of the controls. View mode, input method composition, a protected sheet, and a cell edit with changed text also disable both controls. So read the enabled state only from `toolbarCommandState()` or `useEditorCommand()`, as for every other control.
31
+
32
+ If a true conditional formatting rule changes the state of a format control at the active cell, `conditionalFormat` holds the format state that the grid shows; otherwise it is `null`. A rule that changes only strike, superscript or subscript (`x:vertAlign`), or the underline style gives `null`, because no control shows them. A differential format does not apply alignment, so the alignment controls never get a hint. The format commands read and set the cell format in `activeFormat`.
33
+
34
+ If the sheet has conditional formatting that the grid can leave out, `conditionalHidden` is `true`, and the editor shows a notice. The causes are a rule that the engine does not evaluate, rules past the read limits, more shown rules or ranges than the caps of one cell or one row can take, rules in `x:extLst`, and a layout that ran out of its check budget. After a budget cut, the notice stays until the shown sheet changes or another workbook opens, and `conditionalFormat` is `null` until then.
35
+
36
+ ## Insert and delete rows and columns
37
+
38
+ To insert or delete rows and columns, select whole rows or columns by their headings, or select a cell, and call `insertRows()`, `deleteRows()`, `insertColumns()`, or `deleteColumns()` on the editor. Rows go in above the selection, and columns to the left of it. Every reference in the workbook moves with the cells: formulas on every sheet, defined names, merged ranges, hyperlinks, column widths, and drawings. A reference to a deleted cell becomes `#REF!`.
39
+
40
+ If the workbook holds content that refers to cells and that the editor cannot move, such as conditional formatting, data validation, a table, or a chart, the command is refused with the reason `structure-blocked`, and the message names that content in words, such as "conditional formatting on sheet Data" or "the defined name Rates". The part path stays in the refusal's `subject` and `detail`, for logs.
41
+
42
+ To show a refusal in your own chrome, call `refusalText(refusal, t, snapshot().numberLocale)` of `@xlsx-editor.dev/core/editor`. The number locale groups the digits of a number in the message, such as a cell limit. Inside `XlsxEditor.Root`, get `t` from `useTranslation()` of `@xlsx-editor.dev/react`. Outside it, call `translatorFor(locale)` of `@xlsx-editor.dev/react` with the same `locale` that you pass to the root. A refusal is a typed code with fields, not a catalog key, so a host can branch on the code and on `lock`, and `refusalText` picks the one whole message for it.
43
+
44
+ A refusal with the code `locked` has `lock` set to the protection rule that refused it. The sheet protection is `x:sheetProtection` (ECMA-376 Part 1, 18.3.1.85), and the workbook protection is `x:workbookProtection` (ECMA-376 Part 1, 18.2.29). For the rules, see [View mode and protection](view-mode-and-protection.md). The message names that rule:
45
+
46
+ - `cell`: a locked cell, or a new cell format that would change the protection of a cell.
47
+ - `format`: the sheet does not allow formatting cells.
48
+ - `structure`: the sheet does not allow the insert or the delete.
49
+ - `size`: the sheet does not allow a column width or a row height.
50
+ - `workbook`: the workbook protection does not allow a sheet add, rename, delete, or move.
51
+ - `merge`: the sheet is protected, so no merge or unmerge is allowed.
52
+
53
+ A `locked` refusal of a cut or a paste also has `command` set to `cut` or `paste`, so its message names that command. If the whole sheet is selected, the command is refused with the reason `whole-sheet`. Other edits stay available.
54
+
55
+ ## Merge cells
56
+
57
+ To merge the selection into one cell, call `mergeCells()` on the editor. A merged range is an `x:mergeCell` in the `x:mergeCells` of the worksheet (ECMA-376 Part 1, 18.3.1.54 and 18.3.1.55). To also center its text, call `mergeCells({ center: true })`. The merged cell keeps the value of its top-left cell only. If other cells in the selection hold values, the merge is refused with the reason `merge-drops-values`, and the refusal's `subject` names the first of those cells, such as `C1`.
58
+
59
+ To merge anyway, call `mergeCells({ dropValues: true })`: the merge then clears those cells in the same undo step. That clear can refuse with the reasons of a clear of values, such as `shared-formula` for a part of an array formula range. A `shared-formula` or `cell-alternate-content` refusal of that clear has `command` set to `merge`.
60
+
61
+ A merge of one cell is refused with `merge-one-cell`, and a selection that overlaps a merged range with `merge-overlap`, which names that range. With `center`, a range too large to format is refused with `range-too-large`. To unmerge, call `unmergeCells()`: it unmerges each merged range that the selection meets.
62
+
63
+ To enable your own merge controls, call `mergeCommandState(snapshot, command)` with `merge`, `mergeCenter`, or `unmerge`. It gives `enabled` and a `disabledReason` catalog key, as `toolbarCommandState` does. For an enabled merge, `dropsValuesAt` names the first cell that would lose its value, or is null. The state reads the snapshot fields `selectionMerged` and `selectionDropsValuesAt`. An open cell edit counts as it would be after its commit. If `dropsValuesAt` is set, ask the user before the merge:
64
+
65
+ <!-- sample: guide-merge-button -->
66
+
67
+ <!-- prettier-ignore -->
68
+ ```tsx
69
+ import { mergeCommandState, useEditorSnapshot, useXlsxEditor } from '@xlsx-editor.dev/react';
70
+
71
+ function MergeButton({ confirm }: { confirm: (cell: string) => boolean }) {
72
+ const editor = useXlsxEditor();
73
+ const state = mergeCommandState(useEditorSnapshot(), 'merge');
74
+ const merge = () => {
75
+ const cell = state.dropsValuesAt;
76
+ if (cell === null) editor?.mergeCells();
77
+ else if (confirm(cell)) editor?.mergeCells({ dropValues: true });
78
+ };
79
+ return (
80
+ <button type="button" disabled={!state.enabled} onClick={merge}>
81
+ Merge
82
+ </button>
83
+ );
84
+ }
85
+ ```
@@ -0,0 +1,141 @@
1
+ # Layout and props
2
+
3
+ This guide describes the parts of a custom layout, the props of `XlsxEditor.Root`, and the hooks of `@xlsx-editor.dev/react`. For setup, see the [package README](../README.md).
4
+
5
+ ## Viewport props
6
+
7
+ `XlsxEditor.Viewport` takes three optional props:
8
+
9
+ | Prop | Type | What it does |
10
+ | --- | --- | --- |
11
+ | `style` | `CSSProperties` | Inline style of the viewport. Without a height here or in `className`, the grid has a height of 0. |
12
+ | `className` | `string` | Added after the `xlsx-editor` and `xlsx-editor-viewport` classes. |
13
+ | `label` | `string \| false` | The name of the landmark region. The default is "Workbook editor". `false` renders no region. |
14
+
15
+ ## Status message
16
+
17
+ Keep `XlsxEditor.StatusMessage` in your layout. It is the only part that shows the text of the editor state: the empty and loading messages, the reason a workbook did not open, the reason an edit was refused, the notice that formula results can be out of date, and the notice for conditional formatting that the grid can leave out.
18
+
19
+ While a workbook is open, it is a strip above the grid. The strip is one line high when it is empty. A refusal shows in full on its own row, and the strip grows while the refusal shows. A notice that shows alone wraps when the strip is too narrow for it. The `xlsx-footer` class marks the footer region that F6 visits.
20
+
21
+ In development, `XlsxEditor.Root` logs one warning when the layout has `XlsxEditor.Content` and no `XlsxEditor.StatusMessage`.
22
+
23
+ ## Named exports
24
+
25
+ Each part is also a named export: `XlsxEditorRoot`, `XlsxEditorViewport`, `XlsxEditorContent`, `XlsxEditorToolbar`, `XlsxEditorToolbarSlot`, `XlsxEditorToolbarGroup`, `FormulaBar`, `SheetTabs`, `ZoomControl`, and `StatusMessage`. The `XlsxEditorNamespace` type describes `XlsxEditor` with its parts, and the `XlsxEditorToolbarNamespace` type describes `XlsxEditor.Toolbar` with its parts.
26
+
27
+ ## Root props
28
+
29
+ `XlsxEditor.Root` takes these props:
30
+
31
+ | Prop | Type | Default | What it does |
32
+ | --- | --- | --- | --- |
33
+ | `document` | `Uint8Array` or `ArrayBuffer` | none | The bytes of a workbook (`.xlsx`) or a template (`.xltx`). A new array or buffer opens the new workbook. A change to `undefined` closes the workbook, and the editor shows none. |
34
+ | `fonts` | `FontSource[]` or a function that resolves to them | the packaged substitute faces | The faces that measure and paint text. Different faces replace the current faces in place: the workbook, the selection, and the undo history stay. A list is compared by its faces, so an inline list with the same faces loads nothing. A function is compared by identity, so keep it stable, for example with `useCallback`. |
35
+ | `numberLocale` | `NumberLocale` | US English separators | The separators and built-in format codes of the shown values, and how typed values read. See [Number locale](#number-locale). |
36
+ | `mode` | `'edit'` or `'view'` | `'edit'` | Whether the editor takes edits. A change applies without a reload. For when a change applies and when it waits, see [View mode](view-mode-and-protection.md#view-mode). |
37
+ | `locale` | `Translations` | English | The UI strings. A missing or `null` entry falls back to English. |
38
+ | `colorMode` | `'light'`, `'dark'`, or `'system'` | `'light'` | The color theme of the chrome, as in DOCX Editor. See [Color mode](#color-mode). |
39
+ | `onReady` | `(editor: XlsxEditorInstance) => void` | none | Called once for each editor, after the grid attaches and the first open of `document` settles, as in DOCX Editor. Without `document`, it is called right after the grid attaches. A selection or a zoom set from it applies to the opened workbook. |
40
+ | `onChange` | `(snapshot: EditorSnapshot) => void` | none | Called after each change of the editor state: a content change or a view change. |
41
+ | `onFontError` | `(failure: EditorFailure) => void` | none | Called once when the fonts do not load. The editor also shows the failure, and the snapshot turns `failed` with the code `fonts`. When some packaged substitute faces do not load and the others do, the workbook opens, and the failure lists them in `substituteFailures`. A download of a packaged substitute face fails when it sends no byte for 10 seconds. After one download fails this way, the limit for the others is 2.5 seconds. All substitute face downloads of one open end after 30 seconds, so a slow network cannot hold the open. Without a handler, each failure prints one console warning. |
42
+ | `ref` | `XlsxEditorRef` | none | The imperative handle. |
43
+
44
+ `XlsxEditor` takes the same props, and also `className`, `style`, `onSave`, `onSaveStart`, and `opening`.
45
+
46
+ ### Number locale
47
+
48
+ `numberLocale` sets the separators and built-in format codes of the shown values. `currencySymbol` sets the symbol of the currency entries of the list. The number locale also sets how typed values read: the separators, and the day and month order of a typed date, from built-in format 14.
49
+
50
+ A typed date and time takes built-in format 22 when format 22 is a plain date in the order of format 14 and one clock. Typed seconds add `:ss`, and a typed AM or PM replaces the clock of format 22. Otherwise it takes the code of format 14 and the typed clock, such as `dd/mm/yyyy h:mm AM/PM`, or `yyyy-mm-dd` and the clock when format 14 has no date order. Format 14 has an order only when it is a day, a month, and a year with one separator. With no order, only an ISO 8601 date reads as a date, and it takes `yyyy-mm-dd`.
51
+
52
+ A different value applies in place. An open cell edit keeps the number locale it opened with; the next edit reads the new one. The value is compared by its separators, codes, and currency symbol, so an inline object with the same value changes nothing.
53
+
54
+ The `currencySymbol` of `numberLocale` is `$` when absent, also with `decimal: ','`. A symbol has 1 to 8 UTF-16 code units. It has no control code, no U+FFFE or U+FFFF, and no lone surrogate. If the symbol does not meet these rules, the list leaves out Currency and Accounting. The symbol always goes before the number.
55
+
56
+ ### Color mode
57
+
58
+ `colorMode` sets the color theme of the chrome, as in DOCX Editor. `'system'` follows the OS setting as it changes. `XlsxEditor.Viewport` carries the theme for the parts inside it. A part outside the viewport, such as a popup in `document.body`, gets the theme from the classes of `useScopeClassName()`: `'xlsx-editor '` or `'xlsx-editor dark '`. Inside the viewport, the hook returns `''`. See [Appearance](https://xlsx-editor.dev/docs/customization/appearance). The workbook canvas keeps the workbook's own colors. A change applies without a remount. To match parts that you build, read `useEditorColorMode()`, which returns `{ colorMode: 'light' | 'dark' }`.
59
+
60
+ ## High contrast themes
61
+
62
+ The stylesheet supports high contrast themes with no prop. With a forced-colors theme (`@media (forced-colors: active)`), the browser replaces the chrome colors with system colors and removes shadows. The stylesheet then draws each state with system colors:
63
+
64
+ - Pressed toolbar toggles, the selected sheet tab, the selected list option, the selected **No fill**, and the hovered or focused menu row use `Highlight` with `HighlightText`. A focused menu row also gets a `HighlightText` ring inside it, so it differs from a hovered row. A hovered or focused list option, and the **More number formats** item of the number format list, get a `CanvasText` ring inside them, so they differ from the selected option.
65
+ - Other focus rings use `Highlight`. The ring of a sheet tab is inside the tab, and on the selected tab it uses `HighlightText`. The grid draws its focus ring as an outline.
66
+ - The selection and the active cell draw a `Highlight` line with a `Canvas` line inside it, so they show on any cell fill. When the grid does not have the focus, the line of the active cell is `CanvasText`.
67
+ - The selected row and column headings and the guide line of a resize drag use `Highlight`.
68
+ - Disabled controls use `GrayText`. A disabled toolbar button, field, or color trigger also keeps its fade to 35% opacity, as in the light and dark themes. A disabled control that has the focus does not fade.
69
+ - The line between two toolbar groups uses `CanvasText`.
70
+ - Color swatches and the color bar of the font color and fill color buttons keep their own colors (`forced-color-adjust: none`). The selected swatch gets a `Highlight` outline and a `Highlight` line inside its edge. A focused swatch gets a `CanvasText` ring in place of the outline, so it differs from the selected swatch. The line inside stays while the selected swatch has the focus.
71
+
72
+ The workbook canvas keeps the workbook's own colors. If you override these states, use system colors in a `forced-colors` media query of your own.
73
+
74
+ Each color swatch in the color lists is 24 by 24 CSS pixels, the minimum target size of Web Content Accessibility Guidelines (WCAG) 2.5.8. In the light and dark themes, the selected **No fill** gets the outline of a selected swatch.
75
+
76
+ ## Unsaved edits
77
+
78
+ `onChange` receives the snapshot. DOCX Editor passes a document change, and PPTX Editor passes the editor instance. This editor passes the snapshot because it is the one immutable state object that chrome renders, and it carries the content revision. `snapshot.revision` is 0 after an open and grows by one with each edit, undo, or redo; a selection, zoom, or sheet change keeps it. To act on content changes only, or to track unsaved edits, compare it with the revision that you kept:
79
+
80
+ <!-- sample: react-unsaved -->
81
+
82
+ ```tsx
83
+ import { useRef, useState } from 'react';
84
+ import { XlsxEditor, type XlsxEditorRef } from '@xlsx-editor.dev/react';
85
+ import '@xlsx-editor.dev/react/styles.css';
86
+
87
+ export function TrackedEditor({ bytes }: { bytes: Uint8Array }) {
88
+ const editor = useRef<XlsxEditorRef>(null);
89
+ const savedRevision = useRef(0);
90
+ const [unsaved, setUnsaved] = useState(false);
91
+
92
+ function save() {
93
+ const output = editor.current?.save();
94
+ // `save()` returns null before the editor mounts, when no workbook is open,
95
+ // while a workbook loads, after a load fails, and when the editor cannot
96
+ // store an open cell edit.
97
+ if (!output || !editor.current) return;
98
+ // Store `output` here. A save calls `onChange` only when it commits
99
+ // an open cell edit, clears an earlier refusal, or is refused.
100
+ savedRevision.current = editor.current.snapshot().revision;
101
+ setUnsaved(false);
102
+ }
103
+
104
+ return (
105
+ <>
106
+ <button type="button" onClick={save}>
107
+ Save
108
+ </button>
109
+ <span role="status">{unsaved ? 'Unsaved edits' : 'No unsaved edits'}</span>
110
+ <XlsxEditor
111
+ ref={editor}
112
+ document={bytes}
113
+ style={{ height: 600 }}
114
+ onChange={(snapshot) => {
115
+ // A new open starts at revision 0 with nothing unsaved. An undo also
116
+ // increases the revision, so an undo back to the saved content still
117
+ // counts as unsaved. An open cell edit with changed text counts too:
118
+ // opening another workbook drops it.
119
+ if (snapshot.status !== 'ready') savedRevision.current = 0;
120
+ const draft = snapshot.editing && snapshot.editChanged;
121
+ setUnsaved(snapshot.revision !== savedRevision.current || draft);
122
+ }}
123
+ />
124
+ </>
125
+ );
126
+ }
127
+ ```
128
+
129
+ `onChange` runs after every change of the editor state, also a selection or a zoom. The sample sets state each time; `setUnsaved` with the same value does not render again. To skip more work, compare the value with the last one before you set state, or read it with `useEditorState` and a selector. A save with nothing to commit does not call `onChange`, so the `save` function of the sample keeps the saved revision and clears `unsaved` itself. If you store the bytes of `saveInTasks()` or `onSave`, first check that `SavedWorkbook.stillOpen` is `true`. Then set `savedRevision.current` to `SavedWorkbook.revision`, because an edit made during the save is not in the bytes. `save()` commits an open cell edit first. A new `document` does not: the editor drops an open cell edit when it opens other bytes, so ask before you open them while `editing` and `editChanged` are both true.
130
+
131
+ ## Font changes
132
+
133
+ When `fonts` changes, the editor loads the new faces first. If they do not load, the old faces stay and `onFontError` is called with the cause. These are the instance methods `setFonts()` and `setNumberLocale()`.
134
+
135
+ ## Differences from the DOCX Editor root
136
+
137
+ These props differ from the DOCX Editor root. There, `locale` is a BCP-47 tag for regional input, and the UI strings are the `i18n` prop. Here, `locale` holds the UI strings, as the PPTX Editor root does. The number locale is a separate prop, `numberLocale`, because the engine formats numbers from explicit separators and format codes, not from a BCP-47 tag: it ships no regional data to resolve a tag.
138
+
139
+ ## Hooks
140
+
141
+ Read a slice of the editor state with `useEditorState(selector)`, which re-renders only when the slice changes. Read the whole state with `useEditorSnapshot()`, and the editor with `useXlsxEditor()`. Get the translator of the root's `locale` with `useTranslation()`, which returns `{ t }`. Read whether a change of the `mode` prop waits for a cell edit with `useViewModeWaits()`. Get the scope classes for a part outside the viewport with `useScopeClassName()`, as [Color mode](#color-mode) describes. Run code on a content change, a selection change, a refused edit, or a failed open with `useEditorEvent(event, handler)`, as [Editor events](https://xlsx-editor.dev/docs/customization/events) describes. Its `change` event fires only for content changes, while `onChange` fires after every state change.
@@ -0,0 +1,94 @@
1
+ # Sheets, clipboard, and sizes
2
+
3
+ This guide describes sheet commands, copy and paste, and column widths and row heights. For setup, see the [package README](../README.md).
4
+
5
+ ## Sheets
6
+
7
+ Each sheet is an `x:sheet` in the `x:sheets` of the workbook part, and the order of those elements is the tab order. To add a sheet, click **Add a sheet** after the sheet tabs. The new sheet goes after the shown sheet. To rename a sheet, double-click its tab, or press F2 on the tab, then type the name and press Enter. Press Escape to keep the old name. If the editor refuses the name after Enter, the name stays in the field so you can fix it. If the field loses focus, a refused name ends the rename and keeps the old name.
8
+
9
+ To open the sheet actions, right-click a tab, or press Shift+F10 or the Menu key on it. The menu has **Rename**, **Delete**, **Move left**, and **Move right**. **Move left** and **Move right** move the sheet past the next tab that you can see. If the editor cannot make the change, such as a name that another sheet has, it shows the reason.
10
+
11
+ A sheet add, rename, delete, or move is one undo step. Ctrl+Z (Cmd+Z on macOS) on a focused tab undoes it. In an open sheet menu, the key closes the menu and undoes the last step.
12
+
13
+ A rename changes each formula, defined name (`x:definedName`), and hyperlink (`x:hyperlink/@location`) that names the sheet. A delete turns each reference to the sheet into `#REF!`, and removes the defined names that belong to the sheet. A rename and a delete are refused with the reason `structure-blocked` in these cases:
14
+
15
+ - The workbook holds a chart, a pivot table, or a sheet that is not a worksheet, such as a chartsheet.
16
+ - A table, conditional formatting, data validation, a drawing, or a control names the sheet.
17
+ - The workbook relates to a part that can refer to cells, such as data connections or revisions.
18
+ - For a delete: the sheet has a related part other than hyperlinks and printer settings, such as comments. A custom workbook view that shows the sheet also refuses a delete.
19
+
20
+ A `moveSheet()` or a `deleteSheet()` of a sheet that is not a worksheet, such as a chartsheet, is refused with the reason `structure-blocked`. The `about` kind of that refusal is `not-worksheet`, and its message says that the editor can move or delete only a worksheet. View mode, an open input method composition, and the workbook protection refuse such a command first, with their own reasons.
21
+
22
+ If a formula or a defined name refers to a range of sheets, such as `Sheet1:Sheet3!A1`, some sheet edits are refused with the reason `sheet-range-blocked`. A move is refused when it changes the sheets in that range, or which end comes first. A delete is refused for the first or last sheet of the range. A delete of a sheet between them keeps the reference. Charts never refuse a move. A right-click on a chartsheet tab opens no menu.
23
+
24
+ A file can give two sheets the same name in different case, such as `Data` and `DATA`. Then a delete or a row or column edit of either is refused with the reason `sheet-name-ambiguous`. So is a rename while a reference names one of them. The sheet titles in `docProps/app.xml` keep their old text.
25
+
26
+ A file can store a sheet name of more than 31 characters. Then a move or a delete of any sheet, and an insert or delete of rows or columns, is refused with `sheet-name-too-long`, which names that sheet. A rename can shorten the name.
27
+
28
+ ## Copy and paste
29
+
30
+ To copy cells, select them and press Ctrl+C (Cmd+C on macOS). To cut them, press Ctrl+X. To paste, select the first cell of the target and press Ctrl+V. A paste of cells from the same editor writes their values, formulas, and cell formats, as one undo step. A copied formula changes its relative references by the distance between the source and the target. A paste of cut cells clears the source, and the cut formulas keep the cells that they refer to, also on another sheet.
31
+
32
+ Formulas that refer to the cut cells keep the old address. Hyperlinks, comments, data validation, and conditional formatting stay with the source cells. The plain text of a copy shows the number format of a true conditional formatting rule, as the grid does. When a layout of the grid runs out of its conditional formatting check budget, the notice for conditional formatting that the grid can leave out shows, and the plain text shows the cell format. A copy or a cut of a range with more conditional formatting than one copy can check is refused with the reason `copy-conditional-limit`. Copy a smaller range.
33
+
34
+ Rich text pastes as plain text, and an error value such as `#N/A` pastes as text. Text from another program pastes as typed input, one cell for each tab-separated value and one row for each line. A tab or a line break inside a copied cell becomes a space in the text that other programs paste. A date whose shown text does not read back to the same day, such as `2-Jan` or a two-digit year outside 1930 to 2029, copies its ISO 8601 text, such as `2035-06-01`.
35
+
36
+ The editor refuses these copies and pastes:
37
+
38
+ - A paste of HTML only.
39
+ - A copy or a paste that meets a merged range.
40
+ - A copy of more than 16,384 cells, of an array formula, or of a data table. The master of the array formula or data table can be inside `mc:AlternateContent`.
41
+ - A copy or a cut of a range with more conditional formatting than one copy can check, with the reason `copy-conditional-limit`.
42
+ - A copy of a formula whose text the editor cannot get, and a paste of a formula that it cannot read.
43
+ - A copy or a cut of a cell whose formula is inside `mc:AlternateContent`, with the reason `copy-wrapped-formula`. The editor shows that formula but cannot copy it.
44
+ - A paste of a formula whose moved reference leaves the sheet.
45
+ - A cut of a cell whose only value is in an `mc:AlternateContent` child, with the reason `cut-wrapped-value`. The copy cannot carry that value. A clear of the cell removes it.
46
+ - A paste of cut cells after another edit, also an undo or a redo, with the reason `cut-expired`. Cut the cells again.
47
+ - A paste of copied formulas after an insert or a delete of rows or columns on any sheet, or after a rename, a move, or a delete of a sheet that a copied formula names, with the reason `copy-expired`. A formula with a reference across a span of sheets, such as `Jan:Mar!A1`, also expires at an add, a rename, a move, or a delete of any sheet. An undo or a redo of such an edit does not bring the copy back. Copy the cells again.
48
+ - A paste after a copied cell format changed, with the reason `copy-expired`. Copy the cells again.
49
+ - On another sheet, a paste of a copied or cut formula with a name with no sheet prefix, with the reason `paste-name-scope`. This applies when the target sheet scopes the name and the source sheet does not. It also applies to a function name that the source sheet scopes.
50
+
51
+ A dashed outline marks the source cells of a pending copy or cut. The outline is not part of the workbook, and it does not print. A paste of cut cells ends it. A copy stays pending after a paste, until the next edit or Escape. An undo or a redo also ends it. Press Escape on the grid of any sheet to end the outline of a pending copy: the live region says so, and a later paste still writes the copied cells. Press Escape on the grid of any sheet to forget a pending cut: the cells stay, the live region says so, and a later paste writes only the copied text. A paste of plain text also ends a pending cut in the same way. A paste of a copy that changes its own source ends the outline, also a paste at the source cells that changes a rich text cell, an error, or a cached formula value. Escape does not forget an expired cut, so a later paste still gives the reason `cut-expired`. A copy says what it copied in the live region. After the first paste of cut cells, a second paste writes a copy. Until you copy or cut again, each later paste of an expired copy is refused with the same reason.
52
+
53
+ A copied or cut formula pasted on another sheet gives a name that the source sheet scopes the source sheet prefix. For a paste on another sheet, the copy then depends on that sheet. So such a paste after a rename or delete of that sheet is refused with the reason `copy-expired`.
54
+
55
+ ## Column widths and row heights
56
+
57
+ To change a column width, drag the right edge of the column heading. To change a row height, drag the bottom edge of the row heading. A column is at most 255 characters wide, and a row at most 409 points tall. If whole columns or rows are selected and the dragged one is among them, all of them get the new size. Press Escape during the drag to cancel it. Each drag is one undo step.
58
+
59
+ A width edit writes `x:col/@width` and `@customWidth` (ECMA-376 Part 1, 18.3.1.13). A height edit writes `x:row/@ht` and `@customHeight` (ECMA-376 Part 1, 18.3.1.73).
60
+
61
+ An object that keeps its size or position, such as a picture or a control, can refuse a resize. The reason is then `resize-anchor`.
62
+
63
+ To fit a column or row to its content, double-click the same edge. A column takes the width of its widest shown text, after the number format and in the cell's font. That text must show at each zoom step from 50% and at the current zoom. So the column can be wider than the text needs at one zoom. The extra room is a few pixels for most text, and more for a long run of one repeated character, such as a line of dashes. If you fit at 50% or more and then zoom below 50%, text can be cut and a number can show `#` signs.
64
+
65
+ These cells do not count: text that wraps, rotated text, justified or distributed text, and text centered across cells. Text of a merged range over more than one column and text in a hidden row do not count either. A column with no text keeps its width. So does a column with more conditional formats than layout checks.
66
+
67
+ A row takes the height of its tallest font and of its wrapped lines. That height must hold the lines at each zoom step from 50% and at the current zoom. If you zoom below 50% after the fit, the last wrapped line can be cut. A fitted row fits again when you change its font or a value in it. A row with no cells takes the default row height of the sheet.
68
+
69
+ A row with rotated text keeps its height. Wrapped text in a merged range does not count, so a fit can cut it. A cell in a hidden column counts, as it does for the automatic height. On a sheet whose default row height is set by hand, a row also fits its content. There, a later font or value edit gives the row that default height again.
70
+
71
+ A double-click commits an open cell edit first, and the fit counts its text. If whole columns or rows are selected and the edge is among them, each one fits its own content. A hidden column or row keeps its size in every fit. Each fit is one undo step. In view mode, or on a protected sheet that does not allow the size change, a double-click fits nothing.
72
+
73
+ An object that keeps its size or position can refuse the whole fit. It refuses a fit that changes a row height, or that removes a height set by hand. For a column, only a width change counts.
74
+
75
+ ## Commands on the editor instance
76
+
77
+ The ref is small. Call the sheet, clipboard, and resize commands on the editor instance that `getEditor()` returns:
78
+
79
+ <!-- sample: guide-sheet-calls -->
80
+
81
+ ```tsx
82
+ const editor = ref.current?.getEditor();
83
+ editor?.addSheet('Notes');
84
+ // Column B is 1: indexes are 0-based. The width is 20 characters.
85
+ editor?.setColumnWidth(1, 1, 20);
86
+ const copied = editor?.copy();
87
+ if (copied?.ok) {
88
+ editor?.paste({ token: copied.content.token, text: copied.content.text });
89
+ }
90
+ ```
91
+
92
+ `copy()` and `cut()` return a `CopyResult`. When it is `ok`, its `content` is a `ClipboardContent`: the `text/plain` text and a token for the private type `CLIPBOARD_TYPE`. `paste()` takes a `PasteData`, which holds the untrusted data of a paste event.
93
+
94
+ `setColumnWidth()` takes at most `MAX_COLUMN_WIDTH` characters, and `setRowHeight()` at most `MAX_ROW_HEIGHT` points. One `setRowHeight()` creates at most `MAX_RESIZE_NEW_ROWS` new rows. `selectReference()` reads at most `MAX_GO_TO_LENGTH` characters. Each name is exported from `@xlsx-editor.dev/core/editor`.