@m3ui-vue/m3ui-vue 1.7.0 → 1.8.1

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.
Files changed (87) hide show
  1. package/dist/API.md +579 -4
  2. package/dist/{MButton-CN3wYwIG.js → MButton-B6eZTfFV.js} +2 -2
  3. package/dist/{MButton-CN3wYwIG.js.map → MButton-B6eZTfFV.js.map} +1 -1
  4. package/dist/{MColorPickerModal-BKM1CHxr.js → MColorPickerModal-Dajjf6tH.js} +4 -4
  5. package/dist/{MColorPickerModal-BKM1CHxr.js.map → MColorPickerModal-Dajjf6tH.js.map} +1 -1
  6. package/dist/{MDialog-1LAk9WAO.js → MDialog-DQvE_JBv.js} +2 -2
  7. package/dist/{MDialog-1LAk9WAO.js.map → MDialog-DQvE_JBv.js.map} +1 -1
  8. package/dist/{MListItem-BU5KDRCB.js → MListItem-DiOAxaN7.js} +102 -102
  9. package/dist/{MListItem-BU5KDRCB.js.map → MListItem-DiOAxaN7.js.map} +1 -1
  10. package/dist/{MLoadingIndicator-RykOo5tf.js → MLoadingIndicator-CuTZYFFj.js} +2 -2
  11. package/dist/{MLoadingIndicator-RykOo5tf.js.map → MLoadingIndicator-CuTZYFFj.js.map} +1 -1
  12. package/dist/MPdfViewer-C5ngKPRM.js +1866 -0
  13. package/dist/MPdfViewer-C5ngKPRM.js.map +1 -0
  14. package/dist/{MSeekBar-B_Y3MpVz.js → MSeekBar-BCDQTx2t.js} +2 -2
  15. package/dist/{MSeekBar-B_Y3MpVz.js.map → MSeekBar-BCDQTx2t.js.map} +1 -1
  16. package/dist/{MSegmentedButton-CiOOY1-N.js → MSegmentedButton-BXzRsg1S.js} +2 -2
  17. package/dist/{MSegmentedButton-CiOOY1-N.js.map → MSegmentedButton-BXzRsg1S.js.map} +1 -1
  18. package/dist/MSignaturePad-CxOtelzE.js +140 -0
  19. package/dist/MSignaturePad-CxOtelzE.js.map +1 -0
  20. package/dist/{MSlider-BCeVIxcq.js → MSlider-D_O8J9YH.js} +3 -3
  21. package/dist/{MSlider-BCeVIxcq.js.map → MSlider-D_O8J9YH.js.map} +1 -1
  22. package/dist/{MSpinner-Cs03qoqE.js → MSpinner-UCdtSOHP.js} +2 -2
  23. package/dist/{MSpinner-Cs03qoqE.js.map → MSpinner-UCdtSOHP.js.map} +1 -1
  24. package/dist/{MTextField-NaFbMkjv.js → MTextField-CYk9yFvi.js} +3 -3
  25. package/dist/{MTextField-NaFbMkjv.js.map → MTextField-CYk9yFvi.js.map} +1 -1
  26. package/dist/{_useFieldValidation-Bz34IAQY.js → _useFieldValidation-B0B44M_t.js} +2 -2
  27. package/dist/{_useFieldValidation-Bz34IAQY.js.map → _useFieldValidation-B0B44M_t.js.map} +1 -1
  28. package/dist/api.json +1 -1
  29. package/dist/code-editor.js +2 -2
  30. package/dist/components/MFormBuilder.vue.d.ts +22 -0
  31. package/dist/components/MFormRenderer.vue.d.ts +151 -0
  32. package/dist/components/MMapRoute.vue.d.ts +13 -5
  33. package/dist/components/MPdfSigner.vue.d.ts +499 -0
  34. package/dist/components/MPdfViewer.vue.d.ts +12 -0
  35. package/dist/components/MPosKeypad.vue.d.ts +1 -1
  36. package/dist/components/MSpreadsheet.vue.d.ts +137 -0
  37. package/dist/components/MStack.vue.d.ts +1 -1
  38. package/dist/composables/pdfSign.d.ts +52 -0
  39. package/dist/composables/spreadsheetFormula.d.ts +55 -0
  40. package/dist/composables/useLocale.d.ts +154 -0
  41. package/dist/draw.js +2 -2
  42. package/dist/flow.js +1 -1
  43. package/dist/gantt.js +2 -2
  44. package/dist/index.d.ts +7 -0
  45. package/dist/locales/index.js +539 -0
  46. package/dist/locales/index.js.map +1 -1
  47. package/dist/m3ui-vue.css +1 -1
  48. package/dist/m3ui.js +16968 -15042
  49. package/dist/m3ui.js.map +1 -1
  50. package/dist/map.js +601 -585
  51. package/dist/map.js.map +1 -1
  52. package/dist/media.js +4 -4
  53. package/dist/pdf-sign.d.ts +3 -0
  54. package/dist/pdf-sign.js +548 -0
  55. package/dist/pdf-sign.js.map +1 -0
  56. package/dist/pdf.js +1 -1859
  57. package/dist/rich-text-editor.js +5 -5
  58. package/dist/styles.css +1 -1
  59. package/dist/{useLocale-Dh1xZZ8i.js → useLocale-DL96OFgr.js} +78 -1
  60. package/dist/useLocale-DL96OFgr.js.map +1 -0
  61. package/package.json +9 -1
  62. package/src/__tests__/MFormRenderer.test.ts +157 -0
  63. package/src/__tests__/MMapRoute.test.ts +34 -0
  64. package/src/__tests__/MPdfSigner.test.ts +175 -0
  65. package/src/__tests__/MSpreadsheet.test.ts +223 -0
  66. package/src/__tests__/spreadsheetFormula.test.ts +77 -0
  67. package/src/__tests__/ssr.test.ts +3 -0
  68. package/src/components/MFormBuilder.vue +417 -0
  69. package/src/components/MFormRenderer.vue +324 -0
  70. package/src/components/MMapRoute.vue +64 -11
  71. package/src/components/MPdfSigner.vue +433 -0
  72. package/src/components/MPdfViewer.vue +12 -0
  73. package/src/components/MSpreadsheet.vue +992 -0
  74. package/src/composables/pdfSign.ts +141 -0
  75. package/src/composables/spreadsheetFormula.ts +459 -0
  76. package/src/composables/useLocale.ts +231 -0
  77. package/src/index.ts +7 -0
  78. package/src/locales/de.ts +77 -0
  79. package/src/locales/es.ts +77 -0
  80. package/src/locales/fr.ts +77 -0
  81. package/src/locales/ja.ts +77 -0
  82. package/src/locales/ko.ts +77 -0
  83. package/src/locales/pt.ts +77 -0
  84. package/src/locales/zh.ts +77 -0
  85. package/src/pdf-sign.ts +5 -0
  86. package/dist/pdf.js.map +0 -1
  87. package/dist/useLocale-Dh1xZZ8i.js.map +0 -1
@@ -0,0 +1,992 @@
1
+ <script lang="ts">
2
+ import type { SpreadsheetCell } from '../composables/spreadsheetFormula'
3
+
4
+ /** A cell's position, 0-based */
5
+ export interface SpreadsheetPosition {
6
+ row: number
7
+ col: number
8
+ }
9
+
10
+ /** A block of cells, corners included */
11
+ export interface SpreadsheetRange {
12
+ start: SpreadsheetPosition
13
+ end: SpreadsheetPosition
14
+ }
15
+
16
+ /** One cell written by an edit, a paste, a fill or a clear */
17
+ export interface SpreadsheetChange {
18
+ row: number
19
+ col: number
20
+ value: SpreadsheetCell
21
+ oldValue: SpreadsheetCell
22
+ }
23
+ </script>
24
+
25
+ <script setup lang="ts">
26
+ /**
27
+ * An editable grid of cells, like a small Excel or Google Sheets: type into cells, select ranges with the mouse or
28
+ * Shift+arrows, copy and paste to and from Excel/Sheets (tab-separated text), drag the fill handle to copy cells or
29
+ * continue a series, formulas (`=SUM(A1:A10)`, `=IF(B2>0,"yes","no")`, relative and `$`-locked references), undo and
30
+ * redo, frozen rows and columns, resizable columns. Only the rows in view are rendered, so thousands of rows stay
31
+ * smooth. `v-model` is the cells as typed (a formula is a string starting with `=`); the values formulas work out to
32
+ * are shown, not stored. Not an M3 spec component.
33
+ *
34
+ * @event change Cells were written (typing, paste, fill, clear, undo): `{ row, col, value, oldValue }[]`
35
+ * @event selection-change The selection moved: `{ start, end }`
36
+ */
37
+ import { computed, nextTick, onBeforeUnmount, onMounted, ref, useId, watch } from 'vue'
38
+ import {
39
+ FormulaError, cellName, columnName, createSheetEvaluator, formatNumber, shiftFormula,
40
+ type SpreadsheetFunction, type SpreadsheetValue,
41
+ } from '../composables/spreadsheetFormula'
42
+ import { useLocale } from '../composables/useLocale'
43
+
44
+ const props = withDefaults(
45
+ defineProps<{
46
+ /** The cells, row by row, as typed: numbers, text, booleans, `null` for empty, formulas as `'=…'` strings */
47
+ modelValue?: SpreadsheetCell[][]
48
+ /** Rows the grid shows at least (more when the data has more) */
49
+ rows?: number
50
+ /** Columns the grid shows at least (more when the data has more) */
51
+ cols?: number
52
+ /** Each column's width in px (`v-model:columnWidths`, updated when the user resizes one) */
53
+ columnWidths?: number[]
54
+ /** Width of columns without one in `columnWidths`, in px */
55
+ defaultColumnWidth?: number
56
+ /** Row height in px */
57
+ rowHeight?: number
58
+ /** Rows kept at the top while scrolling */
59
+ frozenRows?: number
60
+ /** Columns kept at the left while scrolling */
61
+ frozenColumns?: number
62
+ /** Cells can be selected and copied, not changed */
63
+ readonly?: boolean
64
+ /** Show the column letters and row numbers */
65
+ headers?: boolean
66
+ /** Column header text instead of A, B, C… (missing ones keep the letter) */
67
+ columnLabels?: string[]
68
+ /** Show the formula bar (the selected cell's name and its contents, editable) */
69
+ formulaBar?: boolean
70
+ /** Work formulas out. Off: `=…` is shown as typed */
71
+ formulas?: boolean
72
+ /** More functions for formulas, by upper-case name: `{ TAX: ([amount]) => amount * 0.21 }` */
73
+ functions?: Record<string, SpreadsheetFunction>
74
+ /** How a cell shows its value (currencies, dates…). Gets the worked-out value and where it is */
75
+ format?: (value: SpreadsheetValue, cell: { row: number; col: number; raw: SpreadsheetCell }) => string
76
+ /** Extra rows rendered above and below the ones in view */
77
+ overscan?: number
78
+ /** The grid's accessible name */
79
+ label?: string
80
+ }>(),
81
+ {
82
+ modelValue: () => [], rows: 100, cols: 26, defaultColumnWidth: 100, rowHeight: 32, frozenRows: 0, frozenColumns: 0,
83
+ headers: true, formulaBar: true, formulas: true, overscan: 6,
84
+ },
85
+ )
86
+
87
+ const emit = defineEmits<{
88
+ 'update:modelValue': [cells: SpreadsheetCell[][]]
89
+ 'update:columnWidths': [widths: number[]]
90
+ change: [changes: SpreadsheetChange[]]
91
+ 'selection-change': [range: SpreadsheetRange]
92
+ }>()
93
+
94
+ const locale = useLocale()
95
+ const uid = useId()
96
+
97
+ // ── size ──
98
+ const rowCount = computed(() => Math.max(props.rows, props.modelValue.length))
99
+ const colCount = computed(() => Math.max(props.cols, ...props.modelValue.map((r) => r?.length ?? 0)))
100
+ const rowHeaderWidth = computed(() => (props.headers ? Math.max(44, String(rowCount.value).length * 9 + 20) : 0))
101
+ const headerHeight = computed(() => (props.headers ? props.rowHeight : 0))
102
+
103
+ const localWidths = ref<number[]>([])
104
+ watch(() => props.columnWidths, (w) => { localWidths.value = w ? [...w] : [] }, { immediate: true })
105
+ const widthOf = (c: number) => localWidths.value[c] ?? props.defaultColumnWidth
106
+ const colLeft = computed(() => {
107
+ const out = [0]
108
+ for (let c = 0; c < colCount.value; c++) out.push(out[c]! + widthOf(c))
109
+ return out
110
+ })
111
+ const totalWidth = computed(() => colLeft.value[colCount.value]!)
112
+ const frozenCols = computed(() => Math.min(props.frozenColumns, colCount.value))
113
+ const frozenRowCount = computed(() => Math.min(props.frozenRows, rowCount.value))
114
+
115
+ // ── values ──
116
+ const raw = (r: number, c: number): SpreadsheetCell => props.modelValue[r]?.[c] ?? null
117
+ const evaluator = computed(() =>
118
+ createSheetEvaluator(props.modelValue, { functions: props.functions, rows: rowCount.value, cols: colCount.value }),
119
+ )
120
+ function valueAt(r: number, c: number): SpreadsheetValue {
121
+ const v = raw(r, c)
122
+ if (!props.formulas && typeof v === 'string') return v
123
+ return evaluator.value.value(r, c)
124
+ }
125
+ function display(r: number, c: number): string {
126
+ const v = valueAt(r, c)
127
+ if (props.format) return props.format(v, { row: r, col: c, raw: raw(r, c) })
128
+ if (v == null) return ''
129
+ if (v instanceof FormulaError) return v.code
130
+ if (typeof v === 'number') return formatNumber(v)
131
+ if (typeof v === 'boolean') return v ? 'TRUE' : 'FALSE'
132
+ return v
133
+ }
134
+ function align(r: number, c: number): string {
135
+ const v = valueAt(r, c)
136
+ return typeof v === 'number' ? 'text-right' : typeof v === 'boolean' || v instanceof FormulaError ? 'text-center' : 'text-left'
137
+ }
138
+
139
+ /** What a typed text is stored as: a number, a boolean, text, or null for nothing */
140
+ function parseInput(text: string): SpreadsheetCell {
141
+ if (text === '') return null
142
+ if (text[0] === '=') return text
143
+ const t = text.trim()
144
+ if (t !== '' && /^[-+]?(\d+\.?\d*|\.\d+)(e[-+]?\d+)?$/i.test(t)) return Number(t)
145
+ const u = t.toUpperCase()
146
+ if (u === 'TRUE' || u === 'FALSE') return u === 'TRUE'
147
+ return text
148
+ }
149
+ const rawText = (v: SpreadsheetCell) => (v == null ? '' : typeof v === 'boolean' ? (v ? 'TRUE' : 'FALSE') : String(v))
150
+
151
+ // ── writing, undo ──
152
+ interface Snapshot { cells: SpreadsheetCell[][]; range: SpreadsheetRange }
153
+ const undoStack: Snapshot[] = []
154
+ const redoStack: Snapshot[] = []
155
+
156
+ function write(changes: { row: number; col: number; value: SpreadsheetCell }[]) {
157
+ if (props.readonly) return
158
+ const real: SpreadsheetChange[] = []
159
+ const next = [...props.modelValue]
160
+ for (const ch of changes) {
161
+ const old = raw(ch.row, ch.col)
162
+ if (old === ch.value || (old == null && ch.value == null)) continue
163
+ while (next.length <= ch.row) next.push([])
164
+ const row = next[ch.row] === props.modelValue[ch.row] ? [...(next[ch.row] ?? [])] : next[ch.row]!
165
+ while (row.length <= ch.col) row.push(null)
166
+ row[ch.col] = ch.value
167
+ next[ch.row] = row
168
+ real.push({ ...ch, oldValue: old })
169
+ }
170
+ if (!real.length) return
171
+ undoStack.push({ cells: props.modelValue, range: currentRange() })
172
+ if (undoStack.length > 100) undoStack.shift()
173
+ redoStack.length = 0
174
+ emit('update:modelValue', next)
175
+ emit('change', real)
176
+ }
177
+
178
+ function diff(from: SpreadsheetCell[][], to: SpreadsheetCell[][]): SpreadsheetChange[] {
179
+ const out: SpreadsheetChange[] = []
180
+ const rows = Math.max(from.length, to.length)
181
+ for (let r = 0; r < rows; r++) {
182
+ if (from[r] === to[r]) continue
183
+ const cols = Math.max(from[r]?.length ?? 0, to[r]?.length ?? 0)
184
+ for (let c = 0; c < cols; c++) {
185
+ const a = from[r]?.[c] ?? null
186
+ const b = to[r]?.[c] ?? null
187
+ if (a !== b) out.push({ row: r, col: c, value: b, oldValue: a })
188
+ }
189
+ }
190
+ return out
191
+ }
192
+ function restore(from: Snapshot[], to: Snapshot[]) {
193
+ const snap = from.pop()
194
+ if (!snap || props.readonly) return
195
+ to.push({ cells: props.modelValue, range: currentRange() })
196
+ const changes = diff(props.modelValue, snap.cells)
197
+ emit('update:modelValue', snap.cells)
198
+ if (changes.length) emit('change', changes)
199
+ anchor.value = { ...snap.range.start }
200
+ head.value = { ...snap.range.end }
201
+ }
202
+ const undo = () => restore(undoStack, redoStack)
203
+ const redo = () => restore(redoStack, undoStack)
204
+
205
+ // ── selection ──
206
+ const anchor = ref<SpreadsheetPosition>({ row: 0, col: 0 })
207
+ const head = ref<SpreadsheetPosition>({ row: 0, col: 0 })
208
+ const range = computed(() => ({
209
+ r1: Math.min(anchor.value.row, head.value.row), r2: Math.max(anchor.value.row, head.value.row),
210
+ c1: Math.min(anchor.value.col, head.value.col), c2: Math.max(anchor.value.col, head.value.col),
211
+ }))
212
+ function currentRange(): SpreadsheetRange {
213
+ const { r1, r2, c1, c2 } = range.value
214
+ return { start: { row: r1, col: c1 }, end: { row: r2, col: c2 } }
215
+ }
216
+ const inRange = (r: number, c: number) => r >= range.value.r1 && r <= range.value.r2 && c >= range.value.c1 && c <= range.value.c2
217
+ const isActive = (r: number, c: number) => anchor.value.row === r && anchor.value.col === c
218
+ const clampPos = (p: SpreadsheetPosition) => ({
219
+ row: Math.min(Math.max(p.row, 0), rowCount.value - 1),
220
+ col: Math.min(Math.max(p.col, 0), colCount.value - 1),
221
+ })
222
+ watch(() => [range.value.r1, range.value.r2, range.value.c1, range.value.c2].join(), () => emit('selection-change', currentRange()))
223
+
224
+ function select(start: SpreadsheetPosition, end: SpreadsheetPosition = start) {
225
+ commitEdit()
226
+ anchor.value = clampPos(start)
227
+ head.value = clampPos(end)
228
+ nextTick(() => scrollIntoView(head.value))
229
+ }
230
+
231
+ const rangeName = computed(() => {
232
+ const { r1, r2, c1, c2 } = range.value
233
+ return r1 === r2 && c1 === c2 ? cellName(r1, c1) : `${cellName(r1, c1)}:${cellName(r2, c2)}`
234
+ })
235
+
236
+ // ── virtual rows ──
237
+ const scroller = ref<HTMLElement>()
238
+ const scrollTop = ref(0)
239
+ const viewHeight = ref(400)
240
+ const bodyRows = computed(() => rowCount.value - frozenRowCount.value)
241
+ const firstRow = computed(() => Math.max(0, Math.floor(scrollTop.value / props.rowHeight) - props.overscan))
242
+ const lastRow = computed(() => Math.min(bodyRows.value, Math.ceil((scrollTop.value + viewHeight.value) / props.rowHeight) + props.overscan))
243
+ const visibleRows = computed(() => {
244
+ const out: number[] = []
245
+ for (let i = firstRow.value; i < lastRow.value; i++) out.push(frozenRowCount.value + i)
246
+ return out
247
+ })
248
+ const frozenRowList = computed(() => Array.from({ length: frozenRowCount.value }, (_, i) => i))
249
+ const colList = computed(() => Array.from({ length: colCount.value }, (_, i) => i))
250
+
251
+ function onScroll() {
252
+ if (scroller.value) scrollTop.value = scroller.value.scrollTop
253
+ }
254
+ let resize: ResizeObserver | undefined
255
+ onMounted(() => {
256
+ if (!scroller.value) return
257
+ viewHeight.value = scroller.value.clientHeight || 400
258
+ if (typeof ResizeObserver !== 'undefined') {
259
+ resize = new ResizeObserver(() => { if (scroller.value) viewHeight.value = scroller.value.clientHeight || viewHeight.value })
260
+ resize.observe(scroller.value)
261
+ }
262
+ })
263
+
264
+ function scrollIntoView(p: SpreadsheetPosition) {
265
+ const el = scroller.value
266
+ if (!el) return
267
+ const frozenH = frozenRowCount.value * props.rowHeight
268
+ if (p.row >= frozenRowCount.value) {
269
+ const top = (p.row - frozenRowCount.value) * props.rowHeight
270
+ const room = el.clientHeight - headerHeight.value - frozenH
271
+ if (top < el.scrollTop) el.scrollTop = top
272
+ else if (top + props.rowHeight > el.scrollTop + room) el.scrollTop = top + props.rowHeight - room
273
+ }
274
+ if (p.col >= frozenCols.value) {
275
+ const frozenW = colLeft.value[frozenCols.value]!
276
+ const left = colLeft.value[p.col]! - frozenW
277
+ const room = el.clientWidth - rowHeaderWidth.value - frozenW
278
+ const w = widthOf(p.col)
279
+ if (left < el.scrollLeft) el.scrollLeft = left
280
+ else if (left + w > el.scrollLeft + room) el.scrollLeft = left + w - room
281
+ }
282
+ onScroll()
283
+ }
284
+
285
+ // ── editing ──
286
+ const editing = ref(false)
287
+ /** `enter`: started by typing, arrows leave the cell. `edit`: F2/double-click/formula bar, arrows move the caret */
288
+ const editMode = ref<'enter' | 'edit'>('enter')
289
+ const editValue = ref('')
290
+ const cellInput = ref<HTMLInputElement>()
291
+ // The editor sits inside the v-for'd cells, so its ref comes through a function (a plain ref there is an array)
292
+ const setCellInput = (el: unknown) => { cellInput.value = (el as HTMLInputElement | null) ?? undefined }
293
+ const barInput = ref<HTMLInputElement>()
294
+ const editingIn = ref<'cell' | 'bar'>('cell')
295
+
296
+ function startEdit(initial?: string, mode: 'enter' | 'edit' = 'edit', where: 'cell' | 'bar' = 'cell') {
297
+ if (props.readonly) return
298
+ editing.value = true
299
+ editMode.value = mode
300
+ editingIn.value = where
301
+ editValue.value = initial ?? rawText(raw(anchor.value.row, anchor.value.col))
302
+ nextTick(() => {
303
+ const input = where === 'bar' ? barInput.value : cellInput.value
304
+ input?.focus()
305
+ if (input && where === 'cell') input.setSelectionRange(input.value.length, input.value.length)
306
+ })
307
+ }
308
+ function commitEdit() {
309
+ if (!editing.value) return
310
+ editing.value = false
311
+ write([{ row: anchor.value.row, col: anchor.value.col, value: parseInput(editValue.value) }])
312
+ }
313
+ function cancelEdit() {
314
+ editing.value = false
315
+ scroller.value?.focus()
316
+ }
317
+ function move(dr: number, dc: number, extend = false) {
318
+ const from = extend ? head.value : anchor.value
319
+ const to = clampPos({ row: from.row + dr, col: from.col + dc })
320
+ if (extend) head.value = to
321
+ else {
322
+ anchor.value = to
323
+ head.value = to
324
+ }
325
+ nextTick(() => scrollIntoView(to))
326
+ }
327
+
328
+ function onEditorKeydown(e: KeyboardEvent) {
329
+ const arrows: Record<string, [number, number]> = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1] }
330
+ if (e.key === 'Enter' || e.key === 'Tab') {
331
+ e.preventDefault()
332
+ commitEdit()
333
+ if (e.key === 'Enter') move(e.shiftKey ? -1 : 1, 0)
334
+ else move(0, e.shiftKey ? -1 : 1)
335
+ scroller.value?.focus()
336
+ } else if (e.key === 'Escape') {
337
+ e.preventDefault()
338
+ cancelEdit()
339
+ } else if (arrows[e.key] && editMode.value === 'enter' && editingIn.value === 'cell') {
340
+ e.preventDefault()
341
+ commitEdit()
342
+ move(...arrows[e.key]!)
343
+ scroller.value?.focus()
344
+ } else if (e.key === 'F2') {
345
+ editMode.value = editMode.value === 'enter' ? 'edit' : 'enter'
346
+ }
347
+ }
348
+ function onEditorBlur(e: FocusEvent) {
349
+ // Moving between the cell's editor and the formula bar keeps editing
350
+ const to = e.relatedTarget as Node | null
351
+ if (to && (to === cellInput.value || to === barInput.value)) return
352
+ commitEdit()
353
+ }
354
+
355
+ // ── keyboard on the grid ──
356
+ function onKeydown(e: KeyboardEvent) {
357
+ if (editing.value) return
358
+ const mod = e.ctrlKey || e.metaKey
359
+ const k = e.key
360
+ const page = Math.max(1, Math.floor((viewHeight.value - headerHeight.value) / props.rowHeight) - 1)
361
+ const lastR = rowCount.value - 1
362
+ const lastC = colCount.value - 1
363
+ const go = (row: number, col: number) => {
364
+ e.preventDefault()
365
+ const to = clampPos({ row, col })
366
+ if (e.shiftKey) head.value = to
367
+ else { anchor.value = to; head.value = to }
368
+ nextTick(() => scrollIntoView(to))
369
+ }
370
+ const from = e.shiftKey ? head.value : anchor.value
371
+ if (k === 'ArrowUp') return go(mod ? 0 : from.row - 1, from.col)
372
+ if (k === 'ArrowDown') return go(mod ? lastDataRow(from.col) : from.row + 1, from.col)
373
+ if (k === 'ArrowLeft') return go(from.row, mod ? 0 : from.col - 1)
374
+ if (k === 'ArrowRight') return go(from.row, mod ? lastDataCol(from.row) : from.col + 1)
375
+ if (k === 'Home') return go(mod ? 0 : from.row, 0)
376
+ if (k === 'End') return go(mod ? lastR : from.row, lastC)
377
+ if (k === 'PageDown') return go(from.row + page, from.col)
378
+ if (k === 'PageUp') return go(from.row - page, from.col)
379
+ if (k === 'Tab') {
380
+ e.preventDefault()
381
+ return move(0, e.shiftKey ? -1 : 1)
382
+ }
383
+ if (k === 'Enter' || k === 'F2') {
384
+ e.preventDefault()
385
+ return startEdit(undefined, 'edit')
386
+ }
387
+ if (k === 'Escape') {
388
+ head.value = { ...anchor.value }
389
+ return
390
+ }
391
+ if (k === 'Delete' || k === 'Backspace') {
392
+ e.preventDefault()
393
+ return clearRange()
394
+ }
395
+ if (mod && (k === 'z' || k === 'Z')) {
396
+ e.preventDefault()
397
+ return e.shiftKey ? redo() : undo()
398
+ }
399
+ if (mod && (k === 'y' || k === 'Y')) {
400
+ e.preventDefault()
401
+ return redo()
402
+ }
403
+ if (mod && (k === 'a' || k === 'A')) {
404
+ e.preventDefault()
405
+ anchor.value = { row: 0, col: 0 }
406
+ head.value = { row: lastR, col: lastC }
407
+ return
408
+ }
409
+ // A character starts typing into the cell, replacing it
410
+ if (k.length === 1 && !mod && !e.altKey) {
411
+ e.preventDefault()
412
+ startEdit(k, 'enter')
413
+ }
414
+ }
415
+ /** Ctrl+↓: the last filled row of the column (or the sheet's last one) */
416
+ function lastDataRow(col: number) {
417
+ for (let r = props.modelValue.length - 1; r >= 0; r--) if (raw(r, col) != null && raw(r, col) !== '') return r
418
+ return rowCount.value - 1
419
+ }
420
+ function lastDataCol(row: number) {
421
+ const cells = props.modelValue[row] ?? []
422
+ for (let c = cells.length - 1; c >= 0; c--) if (cells[c] != null && cells[c] !== '') return c
423
+ return colCount.value - 1
424
+ }
425
+
426
+ function clearRange() {
427
+ const { r1, r2, c1, c2 } = range.value
428
+ const changes = []
429
+ for (let r = r1; r <= r2; r++) for (let c = c1; c <= c2; c++) if (raw(r, c) != null) changes.push({ row: r, col: c, value: null })
430
+ write(changes)
431
+ }
432
+
433
+ // ── clipboard: tab-separated text, what Excel and Sheets put on it ──
434
+ /** The last copy from this grid: pasting it back moves its formulas' references like Excel does */
435
+ let lastCopy: { text: string; cells: SpreadsheetCell[][]; origin: SpreadsheetPosition } | null = null
436
+
437
+ function toTsv(rows: string[][]): string {
438
+ const quote = (s: string) => (/[\t\n"]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s)
439
+ return rows.map((r) => r.map(quote).join('\t')).join('\n')
440
+ }
441
+ /** Tab-separated text into rows, quoted cells (with tabs, line breaks, `""`) included */
442
+ function parseTsv(text: string): string[][] {
443
+ const rows: string[][] = [[]]
444
+ let cell = ''
445
+ let i = 0
446
+ let quoted = false
447
+ const t = text.replace(/\r\n?/g, '\n').replace(/\n$/, '')
448
+ while (i < t.length) {
449
+ const ch = t[i]!
450
+ if (quoted) {
451
+ if (ch === '"' && t[i + 1] === '"') { cell += '"'; i += 2; continue }
452
+ if (ch === '"') { quoted = false; i++; continue }
453
+ cell += ch
454
+ i++
455
+ continue
456
+ }
457
+ if (ch === '"' && cell === '') { quoted = true; i++; continue }
458
+ if (ch === '\t') { rows.at(-1)!.push(cell); cell = ''; i++; continue }
459
+ if (ch === '\n') { rows.at(-1)!.push(cell); rows.push([]); cell = ''; i++; continue }
460
+ cell += ch
461
+ i++
462
+ }
463
+ rows.at(-1)!.push(cell)
464
+ return rows
465
+ }
466
+
467
+ function copySelection(): string {
468
+ const { r1, r2, c1, c2 } = range.value
469
+ const shown: string[][] = []
470
+ const cells: SpreadsheetCell[][] = []
471
+ for (let r = r1; r <= r2; r++) {
472
+ const s: string[] = []
473
+ const v: SpreadsheetCell[] = []
474
+ for (let c = c1; c <= c2; c++) {
475
+ s.push(display(r, c))
476
+ v.push(raw(r, c))
477
+ }
478
+ shown.push(s)
479
+ cells.push(v)
480
+ }
481
+ const text = toTsv(shown)
482
+ lastCopy = { text, cells, origin: { row: r1, col: c1 } }
483
+ return text
484
+ }
485
+
486
+ function paste(text: string) {
487
+ const { r1, r2, c1, c2 } = range.value
488
+ const internal = lastCopy && lastCopy.text === text ? lastCopy : null
489
+ const cells = internal ? internal.cells : parseTsv(text).map((row) => row.map(parseInput))
490
+ const h = cells.length
491
+ const w = Math.max(...cells.map((r) => r.length))
492
+ // One copied block repeated over a bigger selection, as Excel does when it fits a whole number of times
493
+ const rowsOut = r2 > r1 && (r2 - r1 + 1) % h === 0 ? r2 - r1 + 1 : h
494
+ const colsOut = c2 > c1 && (c2 - c1 + 1) % w === 0 ? c2 - c1 + 1 : w
495
+ const changes = []
496
+ for (let i = 0; i < rowsOut; i++) {
497
+ for (let j = 0; j < colsOut; j++) {
498
+ const r = r1 + i
499
+ const c = c1 + j
500
+ if (r >= rowCount.value || c >= colCount.value) continue
501
+ let v = cells[i % h]?.[j % w] ?? null
502
+ // Copied from this grid: a formula's references move by how far it travelled, as in Excel
503
+ if (internal && typeof v === 'string' && v[0] === '=') v = shiftFormula(v, r - (internal.origin.row + (i % h)), c - (internal.origin.col + (j % w)))
504
+ changes.push({ row: r, col: c, value: v })
505
+ }
506
+ }
507
+ write(changes)
508
+ anchor.value = { row: r1, col: c1 }
509
+ head.value = clampPos({ row: r1 + rowsOut - 1, col: c1 + colsOut - 1 })
510
+ nextTick(() => scrollIntoView(head.value))
511
+ }
512
+
513
+ const owns = () => !!scroller.value && document.activeElement === scroller.value && !editing.value
514
+ function onCopy(e: ClipboardEvent) {
515
+ if (!owns()) return
516
+ e.preventDefault()
517
+ e.clipboardData?.setData('text/plain', copySelection())
518
+ }
519
+ function onCut(e: ClipboardEvent) {
520
+ if (!owns()) return
521
+ onCopy(e)
522
+ clearRange()
523
+ }
524
+ function onPaste(e: ClipboardEvent) {
525
+ if (!owns() || props.readonly) return
526
+ const text = e.clipboardData?.getData('text/plain')
527
+ if (text == null || text === '') return
528
+ e.preventDefault()
529
+ paste(text)
530
+ }
531
+ onMounted(() => {
532
+ document.addEventListener('copy', onCopy)
533
+ document.addEventListener('cut', onCut)
534
+ document.addEventListener('paste', onPaste)
535
+ })
536
+
537
+ // ── pointer: select ranges, the fill handle, column widths ──
538
+ function cellFromPoint(x: number, y: number): SpreadsheetPosition | null {
539
+ const el = scroller.value
540
+ if (!el) return null
541
+ const box = el.getBoundingClientRect()
542
+ // From the grid's own geometry, so it works over headers, outside the grid (clamped) and under the finger
543
+ const frozenW = colLeft.value[frozenCols.value]!
544
+ const frozenH = frozenRowCount.value * props.rowHeight
545
+ let cx = x - box.left - rowHeaderWidth.value
546
+ let cy = y - box.top - headerHeight.value
547
+ cx = cx < frozenW ? cx : cx + el.scrollLeft
548
+ cy = cy < frozenH ? cy : cy + el.scrollTop
549
+ const row = Math.floor(cy / props.rowHeight)
550
+ let col = 0
551
+ while (col < colCount.value - 1 && colLeft.value[col + 1]! <= cx) col++
552
+ return clampPos({ row, col: cx < 0 ? 0 : col })
553
+ }
554
+
555
+ let dragging: 'select' | 'fill' | null = null
556
+ const fillTarget = ref<SpreadsheetPosition | null>(null)
557
+ let autoScroll = 0
558
+ let lastPointer = { x: 0, y: 0 }
559
+
560
+ function onCellPointerdown(e: PointerEvent, r: number, c: number) {
561
+ if (e.button !== 0) return
562
+ if (editing.value && isActive(r, c)) return
563
+ // A formula being typed: a click inserts the cell's reference instead of moving away
564
+ if (editing.value && editValue.value.startsWith('=') && /[=+\-*/^&(,;:<>]$/.test(editValue.value)) {
565
+ e.preventDefault()
566
+ editValue.value += cellName(r, c)
567
+ ;(editingIn.value === 'bar' ? barInput.value : cellInput.value)?.focus()
568
+ return
569
+ }
570
+ commitEdit()
571
+ if (e.shiftKey) head.value = { row: r, col: c }
572
+ else {
573
+ anchor.value = { row: r, col: c }
574
+ head.value = { row: r, col: c }
575
+ }
576
+ scroller.value?.focus({ preventScroll: true })
577
+ // Touch scrolls the grid; mouse and pen drag out a range
578
+ if (e.pointerType !== 'touch') startDrag('select', e)
579
+ }
580
+ function onFillPointerdown(e: PointerEvent) {
581
+ if (props.readonly) return
582
+ e.preventDefault()
583
+ e.stopPropagation()
584
+ commitEdit()
585
+ fillTarget.value = null
586
+ startDrag('fill', e)
587
+ }
588
+ function startDrag(kind: 'select' | 'fill', e: PointerEvent) {
589
+ dragging = kind
590
+ lastPointer = { x: e.clientX, y: e.clientY }
591
+ window.addEventListener('pointermove', onDragMove)
592
+ window.addEventListener('pointerup', onDragEnd)
593
+ window.addEventListener('pointercancel', onDragEnd)
594
+ cancelAnimationFrame(autoScroll)
595
+ autoScroll = requestAnimationFrame(scrollTick)
596
+ }
597
+ function onDragMove(e: PointerEvent) {
598
+ lastPointer = { x: e.clientX, y: e.clientY }
599
+ track()
600
+ }
601
+ function track() {
602
+ const p = cellFromPoint(lastPointer.x, lastPointer.y)
603
+ if (!p) return
604
+ if (dragging === 'select') head.value = p
605
+ else if (dragging === 'fill') {
606
+ const { r1, r2, c1, c2 } = range.value
607
+ // Along the axis the pointer has gone further out of the selection
608
+ const down = p.row > r2 ? p.row - r2 : p.row < r1 ? p.row - r1 : 0
609
+ const right = p.col > c2 ? p.col - c2 : p.col < c1 ? p.col - c1 : 0
610
+ fillTarget.value = !down && !right ? null
611
+ : Math.abs(down) >= Math.abs(right) ? { row: p.row, col: c2 } : { row: r2, col: p.col }
612
+ }
613
+ }
614
+ /** Near the grid's edge while dragging, it scrolls that way */
615
+ function scrollTick() {
616
+ const el = scroller.value
617
+ if (!el || !dragging) return
618
+ const box = el.getBoundingClientRect()
619
+ const edge = 28
620
+ const { x, y } = lastPointer
621
+ const dy = y > box.bottom - edge ? 12 : y < box.top + headerHeight.value + edge ? -12 : 0
622
+ const dx = x > box.right - edge ? 12 : x < box.left + rowHeaderWidth.value + edge ? -12 : 0
623
+ if (dx || dy) {
624
+ el.scrollTop += dy
625
+ el.scrollLeft += dx
626
+ onScroll()
627
+ track()
628
+ }
629
+ autoScroll = requestAnimationFrame(scrollTick)
630
+ }
631
+ function onDragEnd() {
632
+ window.removeEventListener('pointermove', onDragMove)
633
+ window.removeEventListener('pointerup', onDragEnd)
634
+ window.removeEventListener('pointercancel', onDragEnd)
635
+ cancelAnimationFrame(autoScroll)
636
+ if (dragging === 'fill' && fillTarget.value) fill(fillTarget.value)
637
+ fillTarget.value = null
638
+ dragging = null
639
+ }
640
+
641
+ const fillRange = computed(() => {
642
+ const t = fillTarget.value
643
+ if (!t) return null
644
+ const { r1, r2, c1, c2 } = range.value
645
+ return { r1: Math.min(r1, t.row), r2: Math.max(r2, t.row), c1: Math.min(c1, t.col), c2: Math.max(c2, t.col) }
646
+ })
647
+ const inFill = (r: number, c: number) => {
648
+ const f = fillRange.value
649
+ return !!f && r >= f.r1 && r <= f.r2 && c >= f.c1 && c <= f.c2 && !inRange(r, c)
650
+ }
651
+
652
+ /**
653
+ * Fills from the selection out to `target`: numbers that make a series (2 or more) go on with its step; anything
654
+ * else repeats, a formula's references moving with it, a lone "Item 1" counting on
655
+ */
656
+ function fill(target: SpreadsheetPosition) {
657
+ const { r1, r2, c1, c2 } = range.value
658
+ const vertical = target.row > r2 || target.row < r1
659
+ const changes: { row: number; col: number; value: SpreadsheetCell }[] = []
660
+ const lines = vertical ? [c1, c2] : [r1, r2]
661
+ for (let line = lines[0]!; line <= lines[1]!; line++) {
662
+ const src: SpreadsheetCell[] = []
663
+ const from = vertical ? r1 : c1
664
+ const to = vertical ? r2 : c2
665
+ for (let i = from; i <= to; i++) src.push(vertical ? raw(i, line) : raw(line, i))
666
+ const n = src.length
667
+ const numeric = n >= 2 && src.every((v) => typeof v === 'number')
668
+ const step = numeric ? ((src[n - 1] as number) - (src[0] as number)) / (n - 1) : 0
669
+ const forward = vertical ? target.row > r2 : target.col > c2
670
+ const count = vertical ? (forward ? target.row - r2 : r1 - target.row) : (forward ? target.col - c2 : c1 - target.col)
671
+ for (let k = 1; k <= count; k++) {
672
+ // Index into the source, cycling; and how far that copy moved
673
+ const idx = forward ? (k - 1) % n : n - 1 - ((k - 1) % n)
674
+ const offset = forward ? n - 1 - idx + k : -(idx + k)
675
+ const at = forward ? to + k : from - k
676
+ const v = src[idx]!
677
+ let value: SpreadsheetCell = v
678
+ if (numeric) value = forward ? (src[n - 1] as number) + step * k : (src[0] as number) - step * k
679
+ else if (typeof v === 'string' && v[0] === '=') value = vertical ? shiftFormula(v, offset, 0) : shiftFormula(v, 0, offset)
680
+ else if (n === 1 && typeof v === 'string') {
681
+ const m = /^(.*?)(\d+)$/.exec(v)
682
+ if (m) value = m[1]! + String(Number(m[2]) + (forward ? k : -k))
683
+ }
684
+ if (typeof value === 'number') value = Number(formatNumber(value))
685
+ changes.push(vertical ? { row: at, col: line, value } : { row: line, col: at, value })
686
+ }
687
+ }
688
+ write(changes.filter((ch) => ch.row >= 0 && ch.col >= 0 && ch.row < rowCount.value && ch.col < colCount.value))
689
+ anchor.value = { row: Math.min(r1, target.row), col: Math.min(c1, target.col) }
690
+ head.value = { row: Math.max(r2, target.row), col: Math.max(c2, target.col) }
691
+ }
692
+
693
+ // Headers: a click selects the column or row (Shift extends), the corner everything
694
+ function selectColumn(e: PointerEvent, c: number) {
695
+ if (e.button !== 0) return
696
+ commitEdit()
697
+ if (!e.shiftKey) anchor.value = { row: 0, col: c }
698
+ head.value = { row: rowCount.value - 1, col: c }
699
+ scroller.value?.focus({ preventScroll: true })
700
+ }
701
+ function selectRow(e: PointerEvent, r: number) {
702
+ if (e.button !== 0) return
703
+ commitEdit()
704
+ if (!e.shiftKey) anchor.value = { row: r, col: 0 }
705
+ head.value = { row: r, col: colCount.value - 1 }
706
+ scroller.value?.focus({ preventScroll: true })
707
+ }
708
+ function selectAll() {
709
+ commitEdit()
710
+ anchor.value = { row: 0, col: 0 }
711
+ head.value = { row: rowCount.value - 1, col: colCount.value - 1 }
712
+ scroller.value?.focus({ preventScroll: true })
713
+ }
714
+ const colSelected = (c: number) => c >= range.value.c1 && c <= range.value.c2
715
+ const rowSelected = (r: number) => r >= range.value.r1 && r <= range.value.r2
716
+
717
+ let resizing: { col: number; x: number; w: number } | null = null
718
+ function onResizeDown(e: PointerEvent, c: number) {
719
+ e.preventDefault()
720
+ e.stopPropagation()
721
+ resizing = { col: c, x: e.clientX, w: widthOf(c) }
722
+ ;(e.target as HTMLElement).setPointerCapture?.(e.pointerId)
723
+ }
724
+ function onResizeMove(e: PointerEvent) {
725
+ if (!resizing) return
726
+ const next = [...localWidths.value]
727
+ for (let i = 0; i <= resizing.col; i++) next[i] ??= props.defaultColumnWidth
728
+ next[resizing.col] = Math.max(32, Math.round(resizing.w + e.clientX - resizing.x))
729
+ localWidths.value = next
730
+ }
731
+ function onResizeUp() {
732
+ if (!resizing) return
733
+ resizing = null
734
+ emit('update:columnWidths', [...localWidths.value])
735
+ }
736
+
737
+ onBeforeUnmount(() => {
738
+ resize?.disconnect()
739
+ document.removeEventListener('copy', onCopy)
740
+ document.removeEventListener('cut', onCut)
741
+ document.removeEventListener('paste', onPaste)
742
+ onDragEnd()
743
+ })
744
+
745
+ // ── cell look ──
746
+ const frozenLeft = (c: number) => (c < frozenCols.value ? rowHeaderWidth.value + colLeft.value[c]! : undefined)
747
+ function cellStyle(r: number, c: number) {
748
+ const s: Record<string, string> = { width: `${widthOf(c)}px`, height: `${props.rowHeight}px`, lineHeight: `${props.rowHeight - 1}px` }
749
+ const left = frozenLeft(c)
750
+ if (left != null) {
751
+ s.position = 'sticky'
752
+ s.left = `${left}px`
753
+ s.zIndex = '1'
754
+ }
755
+ // The selection's outline: each edge cell draws its part
756
+ const shadows: string[] = []
757
+ const P = 'var(--color-primary)'
758
+ if (inRange(r, c)) {
759
+ const { r1, r2, c1, c2 } = range.value
760
+ if (r === r1) shadows.push(`inset 0 2px 0 ${P}`)
761
+ if (r === r2) shadows.push(`inset 0 -2px 0 ${P}`)
762
+ if (c === c1) shadows.push(`inset 2px 0 0 ${P}`)
763
+ if (c === c2) shadows.push(`inset -2px 0 0 ${P}`)
764
+ }
765
+ if (isActive(r, c) && (range.value.r1 !== range.value.r2 || range.value.c1 !== range.value.c2)) shadows.push(`inset 0 0 0 1px ${P}`)
766
+ if (inFill(r, c)) shadows.push('inset 0 0 0 1px var(--color-outline)')
767
+ if (shadows.length) s.boxShadow = shadows.join(', ')
768
+ return s
769
+ }
770
+ const isFillCorner = (r: number, c: number) => !props.readonly && r === range.value.r2 && c === range.value.c2
771
+ const cellId = (r: number, c: number) => `${uid}-c${r}-${c}`
772
+ const activeId = computed(() => cellId(anchor.value.row, anchor.value.col))
773
+
774
+ function onBarFocus() {
775
+ if (!editing.value) startEdit(undefined, 'edit', 'bar')
776
+ else editingIn.value = 'bar'
777
+ }
778
+ const barValue = computed(() => (editing.value ? editValue.value : rawText(raw(anchor.value.row, anchor.value.col))))
779
+
780
+ defineExpose({
781
+ /** Focuses the grid (keyboard, paste) */
782
+ focus: () => scroller.value?.focus(),
783
+ /** Selects a cell, or a range from `start` to `end`, and scrolls it into view */
784
+ select,
785
+ /** The selection now */
786
+ selection: computed(currentRange),
787
+ /** A cell's value, its formula worked out */
788
+ value: valueAt,
789
+ /** Undoes the last change made in the grid */
790
+ undo,
791
+ /** Redoes what undo undid */
792
+ redo,
793
+ /** Clears the selected cells */
794
+ clear: clearRange,
795
+ })
796
+ </script>
797
+
798
+ <template>
799
+ <div class="m3-spreadsheet rounded-md border border-outline-variant bg-surface text-on-surface">
800
+ <div v-if="formulaBar" class="flex h-10 shrink-0 items-stretch border-b border-outline-variant bg-surface-container-low text-body-medium">
801
+ <div
802
+ class="flex w-24 shrink-0 items-center border-r border-outline-variant px-3 font-medium text-on-surface-variant"
803
+ role="status"
804
+ :aria-label="locale.spreadsheetName"
805
+ >
806
+ {{ rangeName }}
807
+ </div>
808
+ <span class="flex w-9 shrink-0 items-center justify-center font-mono text-label-large italic text-on-surface-variant" aria-hidden="true">fx</span>
809
+ <input
810
+ ref="barInput"
811
+ class="min-w-0 flex-1 bg-transparent px-2 font-mono text-body-medium text-on-surface outline-none focus:bg-surface"
812
+ :value="barValue"
813
+ :readonly="readonly"
814
+ :aria-label="locale.spreadsheetFormula"
815
+ spellcheck="false"
816
+ @focus="onBarFocus"
817
+ @input="editValue = ($event.target as HTMLInputElement).value"
818
+ @keydown="onEditorKeydown"
819
+ @blur="onEditorBlur"
820
+ >
821
+ </div>
822
+
823
+ <div
824
+ ref="scroller"
825
+ class="m3-spreadsheet-scroller relative min-h-0 flex-1 select-none overflow-auto overscroll-contain outline-none focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-primary"
826
+ tabindex="0"
827
+ role="grid"
828
+ :aria-label="label ?? locale.spreadsheet"
829
+ :aria-rowcount="rowCount + (headers ? 1 : 0)"
830
+ :aria-colcount="colCount + (headers ? 1 : 0)"
831
+ aria-multiselectable="true"
832
+ :aria-readonly="readonly || undefined"
833
+ :aria-activedescendant="activeId"
834
+ @scroll="onScroll"
835
+ @keydown="onKeydown"
836
+ >
837
+ <div class="relative" :style="{ width: `${rowHeaderWidth + totalWidth}px`, height: `${headerHeight + rowCount * rowHeight}px` }">
838
+ <!-- Column headers -->
839
+ <div
840
+ v-if="headers"
841
+ class="sticky top-0 z-[3] flex"
842
+ role="row"
843
+ aria-rowindex="1"
844
+ :style="{ height: `${headerHeight}px`, width: `${rowHeaderWidth + totalWidth}px` }"
845
+ >
846
+ <div
847
+ class="sticky left-0 z-[4] flex-none border-r border-b border-outline-variant bg-surface-container"
848
+ :style="{ width: `${rowHeaderWidth}px` }"
849
+ role="columnheader"
850
+ @pointerdown="selectAll"
851
+ />
852
+ <div
853
+ v-for="c in colList"
854
+ :key="c"
855
+ role="columnheader"
856
+ :aria-colindex="c + 2"
857
+ class="relative flex-none select-none truncate border-r border-b border-outline-variant px-2 text-center text-label-medium"
858
+ :class="colSelected(c) ? 'bg-secondary-container text-on-secondary-container' : 'bg-surface-container text-on-surface-variant'"
859
+ :style="{ width: `${widthOf(c)}px`, lineHeight: `${headerHeight - 1}px`, ...(frozenLeft(c) != null ? { position: 'sticky', left: `${frozenLeft(c)}px`, zIndex: 1 } : {}) }"
860
+ @pointerdown="selectColumn($event, c)"
861
+ >
862
+ {{ columnLabels?.[c] ?? columnName(c) }}
863
+ <span
864
+ class="absolute inset-y-0 -right-1 z-[1] w-2 cursor-col-resize touch-none"
865
+ aria-hidden="true"
866
+ @pointerdown="onResizeDown($event, c)"
867
+ @pointermove="onResizeMove"
868
+ @pointerup="onResizeUp"
869
+ @pointercancel="onResizeUp"
870
+ />
871
+ </div>
872
+ </div>
873
+
874
+ <!-- Frozen rows, then the rows in view (a spacer stands in for the ones above) -->
875
+ <div
876
+ v-if="frozenRowList.length"
877
+ class="sticky z-[2]"
878
+ :style="{ top: `${headerHeight}px`, width: `${rowHeaderWidth + totalWidth}px` }"
879
+ >
880
+ <template v-for="r in frozenRowList" :key="r">
881
+ <div class="flex" role="row" :aria-rowindex="r + (headers ? 2 : 1)" :class="r === frozenRowList.length - 1 ? 'shadow-[0_1px_0_var(--color-outline)]' : ''">
882
+ <div
883
+ v-if="headers"
884
+ role="rowheader"
885
+ class="sticky left-0 z-[1] flex-none select-none border-r border-b border-outline-variant text-center text-label-medium"
886
+ :class="rowSelected(r) ? 'bg-secondary-container text-on-secondary-container' : 'bg-surface-container text-on-surface-variant'"
887
+ :style="{ width: `${rowHeaderWidth}px`, height: `${rowHeight}px`, lineHeight: `${rowHeight - 1}px` }"
888
+ @pointerdown="selectRow($event, r)"
889
+ >{{ r + 1 }}</div>
890
+ <div
891
+ v-for="c in colList"
892
+ :id="cellId(r, c)"
893
+ :key="c"
894
+ role="gridcell"
895
+ :aria-colindex="c + (headers ? 2 : 1)"
896
+ :aria-selected="inRange(r, c)"
897
+ :data-row="r"
898
+ :data-col="c"
899
+ class="m3-spreadsheet-cell relative flex-none border-r border-b border-outline-variant px-2 text-body-medium"
900
+ :class="[align(r, c), inRange(r, c) && !isActive(r, c) ? 'm3-spreadsheet-selected' : 'bg-surface', valueAt(r, c) instanceof FormulaError ? 'text-error' : '']"
901
+ :style="cellStyle(r, c)"
902
+ @pointerdown="onCellPointerdown($event, r, c)"
903
+ @dblclick="startEdit(undefined, 'edit')"
904
+ >
905
+ <span class="block truncate">{{ display(r, c) }}</span>
906
+ <input
907
+ v-if="editing && editingIn === 'cell' && isActive(r, c)"
908
+ :ref="setCellInput"
909
+ v-model="editValue"
910
+ class="absolute inset-0 z-[2] w-full select-text bg-surface px-2 text-body-medium text-on-surface shadow-[inset_0_0_0_2px_var(--color-primary)] outline-none"
911
+ spellcheck="false"
912
+ @keydown="onEditorKeydown"
913
+ @blur="onEditorBlur"
914
+ >
915
+ <span v-if="isFillCorner(r, c)" class="m3-spreadsheet-fill" aria-hidden="true" @pointerdown="onFillPointerdown" />
916
+ </div>
917
+ </div>
918
+ </template>
919
+ </div>
920
+
921
+ <div :style="{ height: `${firstRow * rowHeight}px` }" />
922
+ <div v-for="r in visibleRows" :key="r" class="flex" role="row" :aria-rowindex="r + (headers ? 2 : 1)" :style="{ height: `${rowHeight}px` }">
923
+ <div
924
+ v-if="headers"
925
+ role="rowheader"
926
+ class="sticky left-0 z-[1] flex-none select-none border-r border-b border-outline-variant text-center text-label-medium"
927
+ :class="rowSelected(r) ? 'bg-secondary-container text-on-secondary-container' : 'bg-surface-container text-on-surface-variant'"
928
+ :style="{ width: `${rowHeaderWidth}px`, height: `${rowHeight}px`, lineHeight: `${rowHeight - 1}px` }"
929
+ @pointerdown="selectRow($event, r)"
930
+ >{{ r + 1 }}</div>
931
+ <div
932
+ v-for="c in colList"
933
+ :id="cellId(r, c)"
934
+ :key="c"
935
+ role="gridcell"
936
+ :aria-colindex="c + (headers ? 2 : 1)"
937
+ :aria-selected="inRange(r, c)"
938
+ :data-row="r"
939
+ :data-col="c"
940
+ class="m3-spreadsheet-cell relative flex-none border-r border-b border-outline-variant px-2 text-body-medium"
941
+ :class="[align(r, c), inRange(r, c) && !isActive(r, c) ? 'm3-spreadsheet-selected' : 'bg-surface', valueAt(r, c) instanceof FormulaError ? 'text-error' : '']"
942
+ :style="cellStyle(r, c)"
943
+ @pointerdown="onCellPointerdown($event, r, c)"
944
+ @dblclick="startEdit(undefined, 'edit')"
945
+ >
946
+ <span class="block truncate">{{ display(r, c) }}</span>
947
+ <input
948
+ v-if="editing && editingIn === 'cell' && isActive(r, c)"
949
+ :ref="setCellInput"
950
+ v-model="editValue"
951
+ class="absolute inset-0 z-[2] w-full select-text bg-surface px-2 text-body-medium text-on-surface shadow-[inset_0_0_0_2px_var(--color-primary)] outline-none"
952
+ spellcheck="false"
953
+ @keydown="onEditorKeydown"
954
+ @blur="onEditorBlur"
955
+ >
956
+ <span v-if="isFillCorner(r, c)" class="m3-spreadsheet-fill" aria-hidden="true" @pointerdown="onFillPointerdown" />
957
+ </div>
958
+ </div>
959
+ <span class="sr-only" aria-live="polite">{{ rangeName }} {{ display(anchor.row, anchor.col) }}</span>
960
+ </div>
961
+ </div>
962
+ </div>
963
+ </template>
964
+
965
+ <style>
966
+ @layer base {
967
+ .m3-spreadsheet {
968
+ display: flex;
969
+ flex-direction: column;
970
+ height: 24rem;
971
+ overflow: hidden;
972
+ }
973
+ }
974
+ .m3-spreadsheet-selected {
975
+ background: color-mix(in srgb, var(--color-primary) 10%, var(--color-surface));
976
+ }
977
+ .m3-spreadsheet-fill {
978
+ position: absolute;
979
+ right: -4px;
980
+ bottom: -4px;
981
+ z-index: 3;
982
+ width: 8px;
983
+ height: 8px;
984
+ border: 1px solid var(--color-surface);
985
+ background: var(--color-primary);
986
+ cursor: crosshair;
987
+ touch-action: none;
988
+ }
989
+ .m3-spreadsheet-cell:has(.m3-spreadsheet-fill) {
990
+ z-index: 2;
991
+ }
992
+ </style>