foldkit-data-grid 0.8.0 → 0.10.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.
- package/README.md +85 -15
- package/dist/clipboard.d.ts +7 -0
- package/dist/clipboard.d.ts.map +1 -1
- package/dist/clipboard.js +14 -0
- package/dist/clipboard.js.map +1 -1
- package/dist/columns.d.ts +17 -1
- package/dist/columns.d.ts.map +1 -1
- package/dist/columns.js.map +1 -1
- package/dist/fill.d.ts +14 -4
- package/dist/fill.d.ts.map +1 -1
- package/dist/fill.js +91 -11
- package/dist/fill.js.map +1 -1
- package/dist/grid.d.ts +879 -34
- package/dist/grid.d.ts.map +1 -1
- package/dist/grid.js +82 -3
- package/dist/grid.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/package.json +8 -8
package/README.md
CHANGED
|
@@ -38,15 +38,10 @@ simple path.
|
|
|
38
38
|
|
|
39
39
|
## Mental model
|
|
40
40
|
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
↓
|
|
46
|
-
GridProjection: visible cells in display order
|
|
47
|
-
↓
|
|
48
|
-
moves, ranges, positions: every answer an Option
|
|
49
|
-
```
|
|
41
|
+
A `RowModel` (rows by index, each with a stable key) is crossed with typed
|
|
42
|
+
`Columns` (by stable id) and a `ColumnLayout` (start, center or end, and hidden).
|
|
43
|
+
That gives a `GridProjection`: the visible cells in display order. Moves, ranges and
|
|
44
|
+
positions are computed over it, and every answer is an `Option`.
|
|
50
45
|
|
|
51
46
|
A cell is named by identity, `{ row: key, column: id }`, never by position. A
|
|
52
47
|
re-sort moves a row to another index, and the address still names the same
|
|
@@ -199,6 +194,15 @@ const shown = VirtualGrid.window({
|
|
|
199
194
|
- **`VirtualGrid.reveal(options)`** is the least scroll that shows a cell,
|
|
200
195
|
as `{ top, left }`, or none when it is already in view. A pinned column
|
|
201
196
|
never scrolls, so only its row is brought in.
|
|
197
|
+
- **The grid's `reveal` helper** asks for that scroll from outside the view,
|
|
198
|
+
as a "go to row" control does: `Placed.helpers.reveal(rows, { row, column,
|
|
199
|
+
rowHeight, headerHeight })` is a Step of the application, folded in its own
|
|
200
|
+
`update` like any helper (`Bundle.helpersOf(Grid.bundle).reveal(model.grid,
|
|
201
|
+
rows, target)` on the grid's Model alone). `row` counts from zero in `rows`
|
|
202
|
+
as they are now; `column` is optional, and without it the sideways scroll
|
|
203
|
+
stays where it is. It moves no focus, and does nothing for a row in view
|
|
204
|
+
or one that `rows` does not have. `rowHeight` and `headerHeight` are the
|
|
205
|
+
ones the view is given.
|
|
202
206
|
- **`GridViewport.bundle`** holds `{ top, left, width, height }`.
|
|
203
207
|
`GridViewport.Measure` is a Mount for the scroll container: it reports the
|
|
204
208
|
geometry when it mounts and on every scroll and resize. Readings that are
|
|
@@ -293,6 +297,9 @@ GridSelection.isSelected(picked.selection.rows)('p1') // true
|
|
|
293
297
|
`GridSelection.boxOf(projection, range)` is what it covers now. A plain
|
|
294
298
|
click or key (`Focused`, `Moved`) lets it go: one focused cell is the
|
|
295
299
|
default selection. `GridSelection.extend` is the range a Shift key makes.
|
|
300
|
+
`Grid.rangeSize(rows, model.grid)` is `Some({ rows, columns, cells })` for
|
|
301
|
+
the range the Model holds now (hidden columns left out), or none with no
|
|
302
|
+
range or a corner no longer shown: what a status line counts.
|
|
296
303
|
- **`GridSelection.isSelected(selection)`** indexes a selection once; call it
|
|
297
304
|
once per render, not per row.
|
|
298
305
|
|
|
@@ -330,8 +337,8 @@ const priced = Columns.define<Product>()({
|
|
|
330
337
|
},
|
|
331
338
|
})
|
|
332
339
|
const Prices = DataGrid.make({ id: 'prices', columns: priced })
|
|
333
|
-
// Edited({ row, column, text }) | Pasted({ accepted, refused }) |
|
|
334
|
-
// | UndoRequested | RedoRequested | RowsRequested({ from, to })
|
|
340
|
+
// Edited({ row, column, text }) | Pasted({ accepted, refused }) | Copied({ rows, columns })
|
|
341
|
+
// | Filled({ source, to }) | UndoRequested | RedoRequested | RowsRequested({ from, to })
|
|
335
342
|
type Out = typeof Prices.Out.Type
|
|
336
343
|
|
|
337
344
|
// In `onOut`: the committed text read back as its column's value, a number here.
|
|
@@ -424,15 +431,22 @@ const checked = (cell: Extract<typeof Tasks.Out.Type, { _tag: 'Edited' }>) =>
|
|
|
424
431
|
|
|
425
432
|
Copy and paste speak the tab-separated text spreadsheets do. `Clipboard` is
|
|
426
433
|
pure: it writes and reads that text and lays a paste onto the grid; the view
|
|
427
|
-
wires it to the browser's copy, cut and paste events.
|
|
434
|
+
wires it to the browser's copy, cut and paste events. A copy also carries the
|
|
435
|
+
same cells as an HTML table, for a target that reads `text/html`.
|
|
428
436
|
|
|
429
437
|
```ts
|
|
430
438
|
import { Clipboard } from 'foldkit-data-grid'
|
|
431
439
|
|
|
432
440
|
Clipboard.toTsv([['SKU', 'Price'], ['A-1', '9']]) // 'SKU\tPrice\nA-1\t9'
|
|
433
441
|
Clipboard.parseTsv('a\t"b\tc"\r\n') // [['a', 'b\tc']]
|
|
442
|
+
Clipboard.toHtml([['a<b', 'x\ny']]) // '<table><tbody><tr><td>a<b</td><td>x<br>y</td></tr></tbody></table>'
|
|
434
443
|
```
|
|
435
444
|
|
|
445
|
+
- **`Clipboard.toHtml(rows)`** is the same matrix as a `<table>`. Every cell
|
|
446
|
+
is escaped (`&`, `<`, `>`, `"`) and a line break becomes `<br>`, so nothing
|
|
447
|
+
a cell holds is markup. The view derives it from the TSV it wrote, so the
|
|
448
|
+
two cannot disagree. Paste still reads `text/plain` only: HTML pasted from
|
|
449
|
+
elsewhere is not parsed.
|
|
436
450
|
- **`Clipboard.copy(projection, box, textOf)`** is a box's cells as TSV,
|
|
437
451
|
rows in the projection's order and columns in display order.
|
|
438
452
|
- **`Clipboard.pasteAt(projection, anchor, matrix, { editable, from })`** is
|
|
@@ -445,8 +459,14 @@ Clipboard.parseTsv('a\t"b\tc"\r\n') // [['a', 'b\tc']]
|
|
|
445
459
|
rows win a diagonal). `Fill.cells(projection, plan, { editable, from })`
|
|
446
460
|
is the cells it writes, each lane of the source carried on by
|
|
447
461
|
`Fill.series(texts, count, backward)`: two or more numbers a constant step
|
|
448
|
-
apart continue their step, keeping the finest decimals
|
|
449
|
-
|
|
462
|
+
apart continue their step, keeping the finest decimals; two or more
|
|
463
|
+
`YYYY-MM-DD` days continue by months when they share a day of the month a
|
|
464
|
+
constant number of months apart (a 31st clamps to a shorter month and comes
|
|
465
|
+
back: Jan 31, Feb 28, Mar 31), else by days when a constant number of days
|
|
466
|
+
apart, and when both fit months win; anything else repeats in order. The
|
|
467
|
+
inference reads text, not the column, so a text column that happens to hold
|
|
468
|
+
ISO days steps where it once repeated. A column's own series is
|
|
469
|
+
`edit: { fill }`, below. Like a paste, it drops columns that do not edit and rows
|
|
450
470
|
not loaded, and keeps each cell's `from`.
|
|
451
471
|
- **`Pasted({ cells })`** hands those cells to the grid, which drops each one
|
|
452
472
|
its text leaves unchanged (as an edit judges it), checks the rest against
|
|
@@ -454,6 +474,12 @@ Clipboard.parseTsv('a\t"b\tc"\r\n') // [['a', 'b\tc']]
|
|
|
454
474
|
})`: one change for the application to apply, and say what it refused. A
|
|
455
475
|
paste or cut that changes no cell reports nothing. A paste while a cell is
|
|
456
476
|
edited is the field's.
|
|
477
|
+
- **`Copied({ rows, columns })`** is what the view's copy reports once it
|
|
478
|
+
has put the text on the clipboard: the size of the box copied, so a status
|
|
479
|
+
line can say "Copied 12 cells". It carries no text and changes nothing. A
|
|
480
|
+
cut reports the cells it clears as a `Pasted` and no `Copied`; a copy while
|
|
481
|
+
a cell is edited or a filter form is open is the field's and reports
|
|
482
|
+
nothing.
|
|
457
483
|
- **`UndoRequested` and `RedoRequested`** (Ctrl or Meta with Z, with Shift or
|
|
458
484
|
Ctrl+Y to redo) report `Out.UndoRequested` and `Out.RedoRequested`. They
|
|
459
485
|
carry nothing: the grid keeps no history, since what an edit meant and how
|
|
@@ -468,6 +494,47 @@ Clipboard.parseTsv('a\t"b\tc"\r\n') // [['a', 'b\tc']]
|
|
|
468
494
|
rows it draws: `{ accepted, refused }`, judged as a paste's cells are
|
|
469
495
|
(`Fill.plan` and `Fill.cells`, above). A fill from a lone cell, or by key
|
|
470
496
|
from a range one row tall, carries on the cell above (or before) it.
|
|
497
|
+
- **A column's own series**, `edit: { fill: lane => Option<ReadonlyArray<string>> }`,
|
|
498
|
+
replaces `Fill.series` for a fill down or up in that column. It is called
|
|
499
|
+
once per lane with `{ source, count, toward }`: the source's drafts top to
|
|
500
|
+
bottom, how many cells to write, and the direction. Return the texts, the
|
|
501
|
+
first next to the source, or `Option.none()` for the default. Of a longer
|
|
502
|
+
answer the first `count` are taken; for each cell past a shorter one the
|
|
503
|
+
fill reports a refusal in `refused` (empty `text`, the error "The column’s
|
|
504
|
+
series gave no text here") rather than padding or repeating. A fill right
|
|
505
|
+
or left crosses columns and keeps `Fill.series`. The texts are judged by
|
|
506
|
+
the column's `schema` like any fill.
|
|
507
|
+
|
|
508
|
+
```ts
|
|
509
|
+
import { Option } from 'effect'
|
|
510
|
+
import { Columns } from 'foldkit-data-grid'
|
|
511
|
+
|
|
512
|
+
const weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
|
|
513
|
+
|
|
514
|
+
interface Shift {
|
|
515
|
+
readonly day: string
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
Columns.define<Shift>()({
|
|
519
|
+
day: {
|
|
520
|
+
header: 'Day',
|
|
521
|
+
value: shift => shift.day,
|
|
522
|
+
edit: {
|
|
523
|
+
fill: ({ source, count, toward }) => {
|
|
524
|
+
const last = weekdays.indexOf(toward === 'down' ? source[source.length - 1]! : source[0]!)
|
|
525
|
+
return last === -1
|
|
526
|
+
? Option.none()
|
|
527
|
+
: Option.some(
|
|
528
|
+
Array.from({ length: count }, (_, index) => {
|
|
529
|
+
const step = toward === 'down' ? index + 1 : -(index + 1)
|
|
530
|
+
return weekdays[(((last + step) % 5) + 5) % 5]!
|
|
531
|
+
}),
|
|
532
|
+
)
|
|
533
|
+
},
|
|
534
|
+
},
|
|
535
|
+
},
|
|
536
|
+
})
|
|
537
|
+
```
|
|
471
538
|
|
|
472
539
|
## Over a `foldkit-crud` list
|
|
473
540
|
|
|
@@ -639,6 +706,7 @@ const filtered = (filters: JobFilters, out: typeof JobGrid.Out.Type) =>
|
|
|
639
706
|
Filtered: ({ change }) => JobGrid.setFilter(filters, change),
|
|
640
707
|
Edited: () => filters,
|
|
641
708
|
Pasted: () => filters,
|
|
709
|
+
Copied: () => filters,
|
|
642
710
|
UndoRequested: () => filters,
|
|
643
711
|
RedoRequested: () => filters,
|
|
644
712
|
Filled: () => filters,
|
|
@@ -667,7 +735,9 @@ const shown = (all: ReadonlyArray<Job>, filters: JobFilters) =>
|
|
|
667
735
|
variant. Each column's is typed by its spec (`FilterOf`), so
|
|
668
736
|
`JobGrid.Filters.Type['status']` is `Option<OneOf<'Open' | 'Done'>>`.
|
|
669
737
|
- **`Out.Filtered({ change })`** carries one column's new filter or none;
|
|
670
|
-
`setFilter` writes it in.
|
|
738
|
+
`setFilter` writes it in. `hasFilters(filters)` and `filterCount(filters)`
|
|
739
|
+
say whether any column is filtered and how many, since `Filters` is a record
|
|
740
|
+
of differently typed Options that no one `Option.isSome` reads. Only a grid with a filtering column has this arm,
|
|
671
741
|
so a grid that filters nothing matches no `Filtered`.
|
|
672
742
|
- **`keeps(filters, read)`** is a predicate over held rows. `read` names
|
|
673
743
|
each filtering column's own field, typed by its variant, never the text a
|
package/dist/clipboard.d.ts
CHANGED
|
@@ -11,6 +11,12 @@ export interface PastedCell<Id extends string> extends CellText<Id> {
|
|
|
11
11
|
}
|
|
12
12
|
/** Rows of cells as tab-separated text, the form spreadsheets copy and paste. */
|
|
13
13
|
declare const toTsv: (rows: ReadonlyArray<ReadonlyArray<string>>) => string;
|
|
14
|
+
/**
|
|
15
|
+
* Rows of cells as an HTML `<table>`, for a target that reads `text/html`.
|
|
16
|
+
* Every cell is escaped and a line break becomes `<br>`, so nothing a cell
|
|
17
|
+
* holds is markup.
|
|
18
|
+
*/
|
|
19
|
+
declare const toHtml: (rows: ReadonlyArray<ReadonlyArray<string>>) => string;
|
|
14
20
|
/**
|
|
15
21
|
* Tab-separated text as rows of cells. Quoted cells may hold tabs, line
|
|
16
22
|
* breaks and doubled quotes; `\r\n` and `\r` end a row as `\n` does; the line
|
|
@@ -36,6 +42,7 @@ declare const pasteAt: <Row, Id extends string>(projection: GridProjection<Row,
|
|
|
36
42
|
}) => ReadonlyArray<PastedCell<Id>>;
|
|
37
43
|
export declare const Clipboard: {
|
|
38
44
|
toTsv: typeof toTsv;
|
|
45
|
+
toHtml: typeof toHtml;
|
|
39
46
|
parseTsv: typeof parseTsv;
|
|
40
47
|
copy: typeof copy;
|
|
41
48
|
pasteAt: typeof pasteAt;
|
package/dist/clipboard.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clipboard.d.ts","names":[],"sources":["../src/clipboard.ts"],"mappings":";;iBAIiB,SAAS;WACf;WACA,QAAQ;WACR;;;iBAIM,WAAW,2BAA2B,SAAS;WACrD;;;cAWL,QAAK,MAAU,cAAc;;;;;;
|
|
1
|
+
{"version":3,"file":"clipboard.d.ts","names":[],"sources":["../src/clipboard.ts"],"mappings":";;iBAIiB,SAAS;WACf;WACA,QAAQ;WACR;;;iBAIM,WAAW,2BAA2B,SAAS;WACrD;;;cAWL,QAAK,MAAU,cAAc;;;;;;cAkB7B,SAAM,MAAU,cAAc;;;;;;cAU9B,WAAQ,iBAAmB,cAAc;;;;;;cA8CzC,OAAQ,KAAK,mBAAiB,YACtB,eAAe,KAAK,KAAG,KAC9B,QAAQ,KAAG,SACP,SAAS,YAAY;;;;;;;;cAqB1B,UAAW,KAAK,mBAAiB,YACzB,eAAe,KAAK,KAAG,QAC3B,YAAY,KAAG,QACf,cAAc,wBAAsB;WAEjC,WAAW,QAAQ;WACnB,OAAO,SAAS,YAAY;MAEtC,cAAc,WAAW;qBAoBf"}
|
package/dist/clipboard.js
CHANGED
|
@@ -4,6 +4,19 @@ const needsQuotes = /[\t\n\r"]/;
|
|
|
4
4
|
const quote = (cell) => needsQuotes.test(cell) ? `"${cell.replaceAll("\"", "\"\"")}"` : cell;
|
|
5
5
|
/** Rows of cells as tab-separated text, the form spreadsheets copy and paste. */
|
|
6
6
|
const toTsv = (rows) => rows.map((row) => row.map(quote).join(" ")).join("\n");
|
|
7
|
+
const escapes = {
|
|
8
|
+
"&": "&",
|
|
9
|
+
"<": "<",
|
|
10
|
+
">": ">",
|
|
11
|
+
"\"": """
|
|
12
|
+
};
|
|
13
|
+
const htmlCell = (cell) => cell.replace(/[&<>"]/g, (char) => escapes[char]).replace(/\r\n|\r|\n/g, "<br>");
|
|
14
|
+
/**
|
|
15
|
+
* Rows of cells as an HTML `<table>`, for a target that reads `text/html`.
|
|
16
|
+
* Every cell is escaped and a line break becomes `<br>`, so nothing a cell
|
|
17
|
+
* holds is markup.
|
|
18
|
+
*/
|
|
19
|
+
const toHtml = (rows) => `<table><tbody>${rows.map((row) => `<tr>${row.map((cell) => `<td>${htmlCell(cell)}</td>`).join("")}</tr>`).join("")}</tbody></table>`;
|
|
7
20
|
/**
|
|
8
21
|
* Tab-separated text as rows of cells. Quoted cells may hold tabs, line
|
|
9
22
|
* breaks and doubled quotes; `\r\n` and `\r` end a row as `\n` does; the line
|
|
@@ -100,6 +113,7 @@ const pasteAt = (projection, anchor, matrix, cells) => Option.match(projection.p
|
|
|
100
113
|
});
|
|
101
114
|
const Clipboard = {
|
|
102
115
|
toTsv,
|
|
116
|
+
toHtml,
|
|
103
117
|
parseTsv,
|
|
104
118
|
copy,
|
|
105
119
|
pasteAt
|
package/dist/clipboard.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clipboard.js","names":[],"sources":["../src/clipboard.ts"],"sourcesContent":["import { Option } from 'effect'\nimport type { CellAddress, CellBox, GridProjection } from './projection.js'\n\n/** One cell's text in a paste, by identity: what the grid hands the application. */\nexport interface CellText<Id extends string> {\n readonly row: string\n readonly column: Id\n readonly text: string\n}\n\n/** A pasted cell, with the text it showed before, so an unchanged one is no edit. */\nexport interface PastedCell<Id extends string> extends CellText<Id> {\n readonly from: string\n}\n\n// A cell holding a tab, a line break or a quote is quoted, its quotes doubled,\n// as spreadsheets write and read tab-separated text.\nconst needsQuotes = /[\\t\\n\\r\"]/\n\nconst quote = (cell: string): string =>\n needsQuotes.test(cell) ? `\"${cell.replaceAll('\"', '\"\"')}\"` : cell\n\n/** Rows of cells as tab-separated text, the form spreadsheets copy and paste. */\nconst toTsv = (rows: ReadonlyArray<ReadonlyArray<string>>): string =>\n rows.map(row => row.map(quote).join('\\t')).join('\\n')\n\n/**\n * Tab-separated text as rows of cells. Quoted cells may hold tabs, line\n * breaks and doubled quotes; `\\r\\n` and `\\r` end a row as `\\n` does; the line\n * break a spreadsheet adds after the last row makes no empty row.\n */\nconst parseTsv = (text: string): ReadonlyArray<ReadonlyArray<string>> => {\n const rows: Array<Array<string>> = []\n let row: Array<string> = []\n let cell = ''\n let quoted = false\n let index = 0\n const endCell = () => {\n row.push(cell)\n cell = ''\n }\n const endRow = () => {\n endCell()\n rows.push(row)\n row = []\n }\n while (index < text.length) {\n const char = text[index]!\n if (quoted) {\n if (char === '\"' && text[index + 1] === '\"') {\n cell += '\"'\n index += 2\n continue\n }\n if (char === '\"') quoted = false\n else cell += char\n index += 1\n continue\n }\n if (char === '\"' && cell === '') quoted = true\n else if (char === '\\t') endCell()\n else if (char === '\\r' || char === '\\n') {\n endRow()\n if (char === '\\r' && text[index + 1] === '\\n') index += 1\n } else cell += char\n index += 1\n }\n // Text that ends in a line break has said all its rows.\n if (cell !== '' || row.length > 0) endRow()\n return rows\n}\n\n/**\n * The text of the cells a box covers, row by row in the projection's order\n * and column by column in display order. A row counted but not loaded copies\n * as empty cells, so the shape is the box's.\n */\nconst copy = <Row, Id extends string>(\n projection: GridProjection<Row, Id>,\n box: CellBox<Id>,\n textOf: (address: CellAddress<Id>) => string,\n): string => {\n const rows: Array<ReadonlyArray<string>> = []\n for (let index = box.rows.start; index < box.rows.end; index++) {\n const key = projection.rows.keyAt(index)\n rows.push(\n box.columns.map(column =>\n Option.match(key, { onNone: () => '', onSome: row => textOf({ row, column }) }),\n ),\n )\n }\n return toTsv(rows)\n}\n\n/**\n * Where pasted cells land: the matrix laid from `anchor` across rows in the\n * projection's order and columns in display order. Cells past the grid's\n * edges are dropped, as are those landing on a column that does not edit or\n * a row not loaded; the rest keep their place, each with `from`, the text\n * the cell showed (the text an edit of it would begin from).\n */\nconst pasteAt = <Row, Id extends string>(\n projection: GridProjection<Row, Id>,\n anchor: CellAddress<Id>,\n matrix: ReadonlyArray<ReadonlyArray<string>>,\n cells: {\n readonly editable: (column: Id) => boolean\n readonly from: (address: CellAddress<Id>) => string\n },\n): ReadonlyArray<PastedCell<Id>> =>\n Option.match(projection.positionOf(anchor), {\n onNone: () => [],\n onSome: start => {\n const landed: Array<PastedCell<Id>> = []\n matrix.forEach((texts, down) => {\n const key = projection.rows.keyAt(start.row + down)\n if (Option.isNone(key)) return\n const row = key.value\n texts.forEach((text, across) => {\n const column = projection.columns[start.column + across]\n if (column !== undefined && cells.editable(column)) {\n landed.push({ row, column, text, from: cells.from({ row, column }) })\n }\n })\n })\n return landed\n },\n })\n\nexport const Clipboard = { toTsv, parseTsv, copy, pasteAt }\n"],"mappings":";;AAiBA,MAAM,cAAc;AAEpB,MAAM,SAAS,SACb,YAAY,KAAK,IAAI,IAAI,IAAI,KAAK,WAAW,MAAK,MAAI,EAAE,KAAK;;AAG/D,MAAM,SAAS,SACb,KAAK,KAAI,QAAO,IAAI,IAAI,KAAK,CAAC,CAAC,KAAK,GAAI,CAAC,CAAC,CAAC,KAAK,IAAI;;;;;;
|
|
1
|
+
{"version":3,"file":"clipboard.js","names":[],"sources":["../src/clipboard.ts"],"sourcesContent":["import { Option } from 'effect'\nimport type { CellAddress, CellBox, GridProjection } from './projection.js'\n\n/** One cell's text in a paste, by identity: what the grid hands the application. */\nexport interface CellText<Id extends string> {\n readonly row: string\n readonly column: Id\n readonly text: string\n}\n\n/** A pasted cell, with the text it showed before, so an unchanged one is no edit. */\nexport interface PastedCell<Id extends string> extends CellText<Id> {\n readonly from: string\n}\n\n// A cell holding a tab, a line break or a quote is quoted, its quotes doubled,\n// as spreadsheets write and read tab-separated text.\nconst needsQuotes = /[\\t\\n\\r\"]/\n\nconst quote = (cell: string): string =>\n needsQuotes.test(cell) ? `\"${cell.replaceAll('\"', '\"\"')}\"` : cell\n\n/** Rows of cells as tab-separated text, the form spreadsheets copy and paste. */\nconst toTsv = (rows: ReadonlyArray<ReadonlyArray<string>>): string =>\n rows.map(row => row.map(quote).join('\\t')).join('\\n')\n\nconst escapes: Readonly<Record<string, string>> = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n}\n\nconst htmlCell = (cell: string): string =>\n cell.replace(/[&<>\"]/g, char => escapes[char]!).replace(/\\r\\n|\\r|\\n/g, '<br>')\n\n/**\n * Rows of cells as an HTML `<table>`, for a target that reads `text/html`.\n * Every cell is escaped and a line break becomes `<br>`, so nothing a cell\n * holds is markup.\n */\nconst toHtml = (rows: ReadonlyArray<ReadonlyArray<string>>): string =>\n `<table><tbody>${rows\n .map(row => `<tr>${row.map(cell => `<td>${htmlCell(cell)}</td>`).join('')}</tr>`)\n .join('')}</tbody></table>`\n\n/**\n * Tab-separated text as rows of cells. Quoted cells may hold tabs, line\n * breaks and doubled quotes; `\\r\\n` and `\\r` end a row as `\\n` does; the line\n * break a spreadsheet adds after the last row makes no empty row.\n */\nconst parseTsv = (text: string): ReadonlyArray<ReadonlyArray<string>> => {\n const rows: Array<Array<string>> = []\n let row: Array<string> = []\n let cell = ''\n let quoted = false\n let index = 0\n const endCell = () => {\n row.push(cell)\n cell = ''\n }\n const endRow = () => {\n endCell()\n rows.push(row)\n row = []\n }\n while (index < text.length) {\n const char = text[index]!\n if (quoted) {\n if (char === '\"' && text[index + 1] === '\"') {\n cell += '\"'\n index += 2\n continue\n }\n if (char === '\"') quoted = false\n else cell += char\n index += 1\n continue\n }\n if (char === '\"' && cell === '') quoted = true\n else if (char === '\\t') endCell()\n else if (char === '\\r' || char === '\\n') {\n endRow()\n if (char === '\\r' && text[index + 1] === '\\n') index += 1\n } else cell += char\n index += 1\n }\n // Text that ends in a line break has said all its rows.\n if (cell !== '' || row.length > 0) endRow()\n return rows\n}\n\n/**\n * The text of the cells a box covers, row by row in the projection's order\n * and column by column in display order. A row counted but not loaded copies\n * as empty cells, so the shape is the box's.\n */\nconst copy = <Row, Id extends string>(\n projection: GridProjection<Row, Id>,\n box: CellBox<Id>,\n textOf: (address: CellAddress<Id>) => string,\n): string => {\n const rows: Array<ReadonlyArray<string>> = []\n for (let index = box.rows.start; index < box.rows.end; index++) {\n const key = projection.rows.keyAt(index)\n rows.push(\n box.columns.map(column =>\n Option.match(key, { onNone: () => '', onSome: row => textOf({ row, column }) }),\n ),\n )\n }\n return toTsv(rows)\n}\n\n/**\n * Where pasted cells land: the matrix laid from `anchor` across rows in the\n * projection's order and columns in display order. Cells past the grid's\n * edges are dropped, as are those landing on a column that does not edit or\n * a row not loaded; the rest keep their place, each with `from`, the text\n * the cell showed (the text an edit of it would begin from).\n */\nconst pasteAt = <Row, Id extends string>(\n projection: GridProjection<Row, Id>,\n anchor: CellAddress<Id>,\n matrix: ReadonlyArray<ReadonlyArray<string>>,\n cells: {\n readonly editable: (column: Id) => boolean\n readonly from: (address: CellAddress<Id>) => string\n },\n): ReadonlyArray<PastedCell<Id>> =>\n Option.match(projection.positionOf(anchor), {\n onNone: () => [],\n onSome: start => {\n const landed: Array<PastedCell<Id>> = []\n matrix.forEach((texts, down) => {\n const key = projection.rows.keyAt(start.row + down)\n if (Option.isNone(key)) return\n const row = key.value\n texts.forEach((text, across) => {\n const column = projection.columns[start.column + across]\n if (column !== undefined && cells.editable(column)) {\n landed.push({ row, column, text, from: cells.from({ row, column }) })\n }\n })\n })\n return landed\n },\n })\n\nexport const Clipboard = { toTs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|
2
2
|
/** What a column shows and where it starts out. Its id is its key in `Columns.define`. */
|
|
3
3
|
export interface ColumnSpec<Row, Value> {
|
|
4
4
|
readonly header: string;
|
|
@@ -35,6 +35,14 @@ export interface ColumnSpec<Row, Value> {
|
|
|
35
35
|
*/
|
|
36
36
|
readonly filter?: true | CellEditor;
|
|
37
37
|
}
|
|
38
|
+
/** What a fill down or up asks of a column's own series: one lane, one column. */
|
|
39
|
+
export interface FillLane {
|
|
40
|
+
/** The source's drafts in this column, top to bottom. */
|
|
41
|
+
readonly source: ReadonlyArray<string>;
|
|
42
|
+
/** How many cells the fill writes beyond the source. */
|
|
43
|
+
readonly count: number;
|
|
44
|
+
readonly toward: 'down' | 'up';
|
|
45
|
+
}
|
|
38
46
|
export interface ColumnEdit<Row, Value = string> {
|
|
39
47
|
/** The text an edit of a row's cell begins with. Default the value as a string. */
|
|
40
48
|
readonly draft?: (row: Row) => string;
|
|
@@ -45,6 +53,14 @@ export interface ColumnEdit<Row, Value = string> {
|
|
|
45
53
|
* any text, as itself.
|
|
46
54
|
*/
|
|
47
55
|
readonly schema?: Schema.Codec<Value, string>;
|
|
56
|
+
/**
|
|
57
|
+
* The texts a fill down or up writes in this column, the first next to the
|
|
58
|
+
* source; `Option.none()` uses `Fill.series`. Called once per lane. Of a
|
|
59
|
+
* longer answer the first `count` are taken; for a cell past a shorter
|
|
60
|
+
* one the fill reports a refusal, never a repeat. A fill right or left
|
|
61
|
+
* crosses columns and keeps `Fill.series`.
|
|
62
|
+
*/
|
|
63
|
+
readonly fill?: (lane: FillLane) => Option.Option<ReadonlyArray<string>>;
|
|
48
64
|
}
|
|
49
65
|
/**
|
|
50
66
|
* How a cell's edit is drawn, read from its column's schema: a checkbox, a
|
package/dist/columns.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"columns.d.ts","names":[],"sources":["../src/columns.ts"],"mappings":";;iBAGiB,WAAW,KAAK;WACtB;WACA,QAAQ,KAAK,QAAQ;;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AAM;;;;;;EAMN,SACG,WACA,cAAc,eAAe,WAAW,gBAAc,OAC9C,QAAQ,eAAe,KAAK,WAClC,QAAQ,QAAQ,KAAK"}
|
package/dist/columns.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"columns.js","names":[],"sources":["../src/columns.ts"],"sourcesContent":["import { Option, Schema, SchemaAST, SchemaGetter } from 'effect'\nimport { defineTaggedUnion } from 'foldkit/schema'\n/** What a column shows and where it starts out. Its id is its key in `Columns.define`. */\nexport interface ColumnSpec<Row, Value> {\n readonly header: string\n readonly value: (row: Row) => Value\n /** The region the column starts in; `ColumnLayout.initial` reads it. */\n readonly pinned?: 'start' | 'end'\n /** Whether the column starts hidden; `ColumnLayout.initial` reads it. */\n readonly hidden?: boolean\n /** Its width in pixels until resized. Default `Columns.defaultWidth`. */\n readonly width?: number\n /** The narrowest a resize makes it. Default `Columns.minWidth`. */\n readonly minWidth?: number\n /** The widest a resize makes it. Default no limit. */\n readonly maxWidth?: number\n /** Whether it can be resized. Default `true`. */\n readonly resizable?: boolean\n /** Whether it can be hidden. Default `true`. */\n readonly hideable?: boolean\n /**\n * Makes the column's cells editable. The grid holds the draft, commits it\n * only when the column's schema decodes it, and reports the committed text\n * as an `Edited` OutMessage; `matchEdit` reads its value back, and writing\n * it is the application's. A schema that decodes to a boolean\n * (`Columns.checkbox`) makes the cells checkboxes, toggled in place.\n */\n readonly edit?: ColumnEdit<Row, unknown>\n /**\n * Draws a filter control on the column's header (`foldkit-mixins-data-grid`).\n * `true` reads its kind from `edit.schema`'s decoded side (`filterKindOf`):\n * a boolean is a checkbox, a `Date` a range of days, a number a range, text\n * literals a choice of them, anything else text. A `CellEditor` names the\n * kind for a column that does not edit. The value filtered by is the\n * application's: the grid reports it as `Out.Filtered`.\n */\n readonly filter?: true | CellEditor\n}\n\nexport interface ColumnEdit<Row, Value = string> {\n /** The text an edit of a row's cell begins with. Default the value as a string. */\n readonly draft?: (row: Row) => string\n /**\n * What the text means: from the text typed to the column's value. A draft\n * is committed only when it decodes, and the failure's message is the\n * cell's error, so a check's own `message` is what a person reads. Default\n * any text, as itself.\n */\n readonly schema?: Schema.Codec<Value, string>\n}\n\n/**\n * How a cell's edit is drawn, read from its column's schema: a checkbox, a\n * choice of the literals its text may be, a number typed, or text.\n */\nexport const CellEditor = defineTaggedUnion({\n Text: {},\n /** The schema decodes to a number: typed with a decimal keypad on touch. */\n Number: {},\n /** The schema's text is one of these, offered in order. */\n Choice: { options: Schema.Array(Schema.String) },\n /** The schema decodes to a date: a native date field over the draft text. */\n Date: {},\n /**\n * The schema decodes to a boolean: a checkbox drawn from the column's\n * value, toggled in place (`EditToggled`); it opens no draft.\n */\n Checkbox: {},\n})\nexport type CellEditor = typeof CellEditor.Type\n\n/**\n * Whether a schema decodes to a date, found as Effect's own tools find it:\n * by the declaration's representation id. Only Date-ness is read here, never\n * the text format: committing decodes the draft through the schema, and a\n * refusal is the cell's error.\n */\nconst DATE_ID = 'effect/schema/Date'\n\nconst isDate = (ast: SchemaAST.AST): boolean => {\n if (!SchemaAST.isDeclaration(ast)) return false\n const representation: unknown = ast.annotations?.['representation']\n return (\n typeof representation === 'object' &&\n representation !== null &&\n 'id' in representation &&\n representation.id === DATE_ID\n )\n}\n\nconst isBooleanLike = (ast: SchemaAST.AST): boolean =>\n SchemaAST.isBoolean(ast) ||\n (SchemaAST.isLiteral(ast) && typeof ast.literal === 'boolean') ||\n (SchemaAST.isUnion(ast) && ast.types.length > 0 && ast.types.every(isBooleanLike))\n// A TypeScript enum: its members' values, numbers or text or both.\nconst enumValues = (ast: SchemaAST.AST): ReadonlyArray<string | number> =>\n SchemaAST.isEnum(ast) ? ast.enums.map(([, value]) => value) : []\nconst isNumberLike = (ast: SchemaAST.AST): boolean =>\n SchemaAST.isNumber(ast) ||\n (SchemaAST.isLiteral(ast) && typeof ast.literal === 'number') ||\n (SchemaAST.isEnum(ast) &&\n ast.enums.length > 0 &&\n enumValues(ast).every(value => typeof value === 'number')) ||\n (SchemaAST.isUnion(ast) && ast.types.length > 0 && ast.types.every(isNumberLike))\n/** The text literals an AST is one of, when it is nothing else. */\nconst textLiterals = (ast: SchemaAST.AST): Option.Option<ReadonlyArray<string>> => {\n if (SchemaAST.isEnum(ast)) {\n const values = enumValues(ast)\n const texts = values.flatMap(value => (typeof value === 'string' ? [value] : []))\n return texts.length > 0 && texts.length === values.length ? Option.some(texts) : Option.none()\n }\n if (SchemaAST.isLiteral(ast)) {\n return typeof ast.literal === 'string' ? Option.some([ast.literal]) : Option.none()\n }\n if (!SchemaAST.isUnion(ast) || ast.types.length === 0) return Option.none()\n const options = ast.types.flatMap(member =>\n SchemaAST.isLiteral(member) && typeof member.literal === 'string' ? [member.literal] : [],\n )\n return options.length === ast.types.length ? Option.some(options) : Option.none()\n}\n\n/**\n * The one classifier behind `editorOf` and `filterKindOf`: a checkbox when\n * the value is a boolean (first: `Columns.checkbox`'s text is the literals\n * `true` and `false`), a choice when `choice` is text literals, then a date,\n * a number, or text. `FilterKind` says the same at the type level, and a\n * table test holds the two together.\n */\nconst classify = (type: SchemaAST.AST, choice: SchemaAST.AST): CellEditor => {\n if (isBooleanLike(type)) return CellEditor.Checkbox()\n const options = textLiterals(choice)\n if (Option.isSome(options)) return CellEditor.Choice({ options: options.value })\n if (isDate(type)) return CellEditor.Date()\n return isNumberLike(type) ? CellEditor.Number() : CellEditor.Text()\n}\n\n/**\n * A column's editor, from its schema; a column with none edits text. A choice\n * is read from the text side, since its literals are what is typed.\n */\nexport const editorOf = (schema: Schema.Top | undefined): CellEditor =>\n schema === undefined\n ? CellEditor.Text()\n : classify(SchemaAST.toType(schema.ast), SchemaAST.toEncoded(schema.ast))\n\n/**\n * A column's filter kind, from its schema; a column with none filters text.\n * Everything is read from the decoded side, the values a filter compares.\n */\nexport const filterKindOf = (schema: Schema.Top | undefined): CellEditor => {\n if (schema === undefined) return CellEditor.Text()\n const type = SchemaAST.toType(schema.ast)\n return classify(type, type)\n}\n\n/** The ids of the columns that edit. */\nexport type EditableId<Specs> = {\n [K in keyof Specs]: Specs[K] extends { readonly edit: object } ? K : never\n}[keyof Specs] &\n string\n\n/** What an editable column's text decodes to: its schema's value, or the text. */\nexport type EditValue<Spec> = Spec extends {\n readonly edit: { readonly schema: Schema.Codec<infer Value, string> }\n}\n ? Value\n : string\n\n/**\n * A checkbox column's cells are drawn from its value, so a spec whose edit\n * decodes to a boolean must read a boolean from its row.\n */\nexport type CheckboxValues<Row, Specs> = {\n readonly [K in keyof Specs]: Specs[K] extends {\n readonly edit: { readonly schema: Schema.Codec<boolean, string> }\n }\n ? { readonly value: (row: Row) => boolean }\n : unknown\n}\n\nexport interface Column<Row, Id extends string, Value> extends ColumnSpec<Row, Value> {\n readonly id: Id\n}\n\ntype ValueOf<Spec> = Spec extends ColumnSpec<never, infer Value> ? Value : never\n\nexport type ColumnId<C> = C extends Columns<never, infer Specs> ? keyof Specs & string : never\n\n/**\n * A grid's columns, keyed by stable id. Order, visibility and pinning live in\n * a `ColumnLayout`, so every reference to a column (focus, a selected range,\n * a saved width) names its id and survives a reorder.\n */\nexport interface Columns<Row, Specs extends Record<string, ColumnSpec<Row, unknown>>> {\n /** In definition order: the order `ColumnLayout.initial` starts from. */\n readonly ids: ReadonlyArray<keyof Specs & string>\n readonly byId: {\n readonly [Id in keyof Specs & string]: Column<Row, Id, ValueOf<Specs[Id]>>\n }\n /**\n * Type-only: the specs as written, so a grid made from these columns infers\n * each one exactly, its edit's schema included. Never set.\n */\n readonly Specs?: Specs\n}\n\n// Integer-like keys are enumerated before every other key, whatever the order\n// they were written in, so `{ name, 2024 }` would put 2024 first.\nconst arrayIndex = /^(0|[1-9][0-9]*)$/\n\nexport const Columns = {\n /** The width of a column that names none. */\n defaultWidth: 120,\n /** The narrowest a column with no `minWidth` resizes to. */\n minWidth: 40,\n /**\n * A boolean as a cell's text, `true` or `false`: give it as a column's\n * `edit.schema` and the cells are checkboxes. Any schema from text to a\n * boolean does the same; this one reads what `textOf` writes.\n */\n checkbox: Schema.Literals(['true', 'false']).pipe(\n Schema.decodeTo(Schema.Boolean, {\n decode: SchemaGetter.transform(text => text === 'true'),\n encode: SchemaGetter.transform(value => (value ? 'true' : 'false')),\n }),\n ),\n /** A value as a cell shows it: nothing for `null` or `undefined`. */\n textOf: (value: unknown): string => (value === null || value === undefined ? '' : String(value)),\n /**\n * Declares a grid's columns over `Row`. Call it twice, once with the row\n * type and once with the specs, so the ids and values are inferred:\n * `Columns.define<Product>()({ sku: { header: 'SKU', value: p => p.sku } })`.\n */\n define:\n <Row>() =>\n <Specs extends Record<string, ColumnSpec<Row, unknown>>>(\n specs: Specs & CheckboxValues<Row, Specs>,\n ): NoInfer<Columns<Row, Specs>> => {\n // A literal `__proto__:` key sets the prototype instead of naming a\n // column, so the column would vanish from `Object.keys`.\n if (Object.getPrototypeOf(specs) !== Object.prototype || Object.hasOwn(specs, '__proto__')) {\n throw new Error('Columns.define: \"__proto__\" cannot name a column.')\n }\n const given: Record<string, ColumnSpec<Row, unknown>> = specs\n const ids = Object.keys(given)\n const byId: Record<string, Column<Row, string, unknown>> = {}\n for (const id of ids) {\n if (arrayIndex.test(id)) {\n throw new Error(\n `Columns.define: the column id \"${id}\" is an array index, which JavaScript orders before every other key. Give it a name that is not a number.`,\n )\n }\n byId[id] = Object.freeze({ ...given[id]!, id })\n }\n return Object.freeze({\n ids: Object.freeze(ids),\n byId: Object.freeze(byId),\n }) as Columns<Row, Specs>\n },\n}\n"],"mappings":";;;;;;;AAuDA,MAAa,aAAa,kBAAkB;CAC1C,MAAM,CAAC;;CAEP,QAAQ,CAAC;;CAET,QAAQ,EAAE,SAAS,OAAO,MAAM,OAAO,MAAM,EAAE;;CAE/C,MAAM,CAAC;;;;;CAKP,UAAU,CAAC;AACb,CAAC;;;;;;;AASD,MAAM,UAAU;AAEhB,MAAM,UAAU,QAAgC;CAC9C,IAAI,CAAC,UAAU,cAAc,GAAG,GAAG,OAAO;CAC1C,MAAM,iBAA0B,IAAI,cAAc;C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KAAK,KAAK;EAC7B,MAAM,OAAqD,CAAC;EAC5D,KAAK,MAAM,MAAM,KAAK;GACpB,IAAI,WAAW,KAAK,EAAE,GACpB,MAAM,IAAI,MACR,kCAAkC,GAAG,0GACvC;GAEF,KAAK,MAAM,OAAO,OAAO;IAAE,GAAG,MAAM;IAAM;GAAG,CAAC;EAChD;EACA,OAAO,OAAO,OAAO;GACnB,KAAK,OAAO,OAAO,GAAG;GACtB,MAAM,OAAO,OAAO,IAAI;EAC1B,CAAC;CACH;AACJ"}
|
|
1
|
+
{"version":3,"file":"columns.js","names":[],"sources":["../src/columns.ts"],"sourcesContent":["import { Option, Schema, SchemaAST, SchemaGetter } from 'effect'\nimport { defineTaggedUnion } from 'foldkit/schema'\n/** What a column shows and where it starts out. Its id is its key in `Columns.define`. */\nexport interface ColumnSpec<Row, Value> {\n readonly header: string\n readonly value: (row: Row) => Value\n /** The region the column starts in; `ColumnLayout.initial` reads it. */\n readonly pinned?: 'start' | 'end'\n /** Whether the column starts hidden; `ColumnLayout.initial` reads it. */\n readonly hidden?: boolean\n /** Its width in pixels until resized. Default `Columns.defaultWidth`. */\n readonly width?: number\n /** The narrowest a resize makes it. Default `Columns.minWidth`. */\n readonly minWidth?: number\n /** The widest a resize makes it. Default no limit. */\n readonly maxWidth?: number\n /** Whether it can be resized. Default `true`. */\n readonly resizable?: boolean\n /** Whether it can be hidden. Default `true`. */\n readonly hideable?: boolean\n /**\n * Makes the column's cells editable. The grid holds the draft, commits it\n * only when the column's schema decodes it, and reports the committed text\n * as an `Edited` OutMessage; `matchEdit` reads its value back, and writing\n * it is the application's. A schema that decodes to a boolean\n * (`Columns.checkbox`) makes the cells checkboxes, toggled in place.\n */\n readonly edit?: ColumnEdit<Row, unknown>\n /**\n * Draws a filter control on the column's header (`foldkit-mixins-data-grid`).\n * `true` reads its kind from `edit.schema`'s decoded side (`filterKindOf`):\n * a boolean is a checkbox, a `Date` a range of days, a number a range, text\n * literals a choice of them, anything else text. A `CellEditor` names the\n * kind for a column that does not edit. The value filtered by is the\n * application's: the grid reports it as `Out.Filtered`.\n */\n readonly filter?: true | CellEditor\n}\n\n/** What a fill down or up asks of a column's own series: one lane, one column. */\nexport interface FillLane {\n /** The source's drafts in this column, top to bottom. */\n readonly source: ReadonlyArray<string>\n /** How many cells the fill writes beyond the source. */\n readonly count: number\n readonly toward: 'down' | 'up'\n}\n\nexport interface ColumnEdit<Row, Value = string> {\n /** The text an edit of a row's cell begins with. Default the value as a string. */\n readonly draft?: (row: Row) => string\n /**\n * What the text means: from the text typed to the column's value. A draft\n * is committed only when it decodes, and the failure's message is the\n * cell's error, so a check's own `message` is what a person reads. Default\n * any text, as itself.\n */\n readonly schema?: Schema.Codec<Value, string>\n /**\n * The texts a fill down or up writes in this column, the first next to the\n * source; `Option.none()` uses `Fill.series`. Called once per lane. Of a\n * longer answer the first `count` are taken; for a cell past a shorter\n * one the fill reports a refusal, never a repeat. A fill right or left\n * crosses columns and keeps `Fill.series`.\n */\n readonly fill?: (lane: FillLane) => Option.Option<ReadonlyArray<string>>\n}\n\n/**\n * How a cell's edit is drawn, read from its column's schema: a checkbox, a\n * choice of the literals its text may be, a number typed, or text.\n */\nexport const CellEditor = defineTaggedUnion({\n Text: {},\n /** The schema decodes to a number: typed with a decimal keypad on touch. */\n Number: {},\n /** The schema's text is one of these, offered in order. */\n Choice: { options: Schema.Array(Schema.String) },\n /** The schema decodes to a date: a native date field over the draft text. */\n Date: {},\n /**\n * The schema decodes to a boolean: a checkbox drawn from the column's\n * value, toggled in place (`EditToggled`); it opens no draft.\n */\n Checkbox: {},\n})\nexport type CellEditor = typeof CellEditor.Type\n\n/**\n * Whether a schema decodes to a date, found as Effect's own tools find it:\n * by the declaration's representation id. Only Date-ness is read here, never\n * the text format: committing decodes the draft through the schema, and a\n * refusal is the cell's error.\n */\nconst DATE_ID = 'effect/schema/Date'\n\nconst isDate = (ast: SchemaAST.AST): boolean => {\n if (!SchemaAST.isDeclaration(ast)) return false\n const representation: unknown = ast.annotations?.['representation']\n return (\n typeof representation === 'object' &&\n representation !== null &&\n 'id' in representation &&\n representation.id === DATE_ID\n )\n}\n\nconst isBooleanLike = (ast: SchemaAST.AST): boolean =>\n SchemaAST.isBoolean(ast) ||\n (SchemaAST.isLiteral(ast) && typeof ast.literal === 'boolean') ||\n (SchemaAST.isUnion(ast) && ast.types.length > 0 && ast.types.every(isBooleanLike))\n// A TypeScript enum: its members' values, numbers or text or both.\nconst enumValues = (ast: SchemaAST.AST): ReadonlyArray<string | number> =>\n SchemaAST.isEnum(ast) ? ast.enums.map(([, value]) => value) : []\nconst isNumberLike = (ast: SchemaAST.AST): boolean =>\n SchemaAST.isNumber(ast) ||\n (SchemaAST.isLiteral(ast) && typeof ast.literal === 'number') ||\n (SchemaAST.isEnum(ast) &&\n ast.enums.length > 0 &&\n enumValues(ast).every(value => typeof value === 'number')) ||\n (SchemaAST.isUnion(ast) && ast.types.length > 0 && ast.types.every(isNumberLike))\n/** The text literals an AST is one of, when it is nothing else. */\nconst textLiterals = (ast: SchemaAST.AST): Option.Option<ReadonlyArray<string>> => {\n if (SchemaAST.isEnum(ast)) {\n const values = enumValues(ast)\n const texts = values.flatMap(value => (typeof value === 'string' ? [value] : []))\n return texts.length > 0 && texts.length === values.length ? Option.some(texts) : Option.none()\n }\n if (SchemaAST.isLiteral(ast)) {\n return typeof ast.literal === 'string' ? Option.some([ast.literal]) : Option.none()\n }\n if (!SchemaAST.isUnion(ast) || ast.types.length === 0) return Option.none()\n const options = ast.types.flatMap(member =>\n SchemaAST.isLiteral(member) && typeof member.literal === 'string' ? [member.literal] : [],\n )\n return options.length === ast.types.length ? Option.some(options) : Option.none()\n}\n\n/**\n * The one classifier behind `editorOf` and `filterKindOf`: a checkbox when\n * the value is a boolean (first: `Columns.checkbox`'s text is the literals\n * `true` and `false`), a choice when `choice` is text literals, then a date,\n * a number, or text. `FilterKind` says the same at the type level, and a\n * table test holds the two together.\n */\nconst classify = (type: SchemaAST.AST, choice: SchemaAST.AST): CellEditor => {\n if (isBooleanLike(type)) return CellEditor.Checkbox()\n const options = textLiterals(choice)\n if (Option.isSome(options)) return CellEditor.Choice({ options: options.value })\n if (isDate(type)) return CellEditor.Date()\n return isNumberLike(type) ? CellEditor.Number() : CellEditor.Text()\n}\n\n/**\n * A column's editor, from its schema; a column with none edits text. A choice\n * is read from the text side, since its literals are what is typed.\n */\nexport const editorOf = (schema: Schema.Top | undefined): CellEditor =>\n schema === undefined\n ? CellEditor.Text()\n : classify(SchemaAST.toType(schema.ast), SchemaAST.toEncoded(schema.ast))\n\n/**\n * A column's filter kind, from its schema; a column with none filters text.\n * Everything is read from the decoded side, the values a filter compares.\n */\nexport const filterKindOf = (schema: Schema.Top | undefined): CellEditor => {\n if (schema === undefined) return CellEditor.Text()\n const type = SchemaAST.toType(schema.ast)\n return classify(type, type)\n}\n\n/** The ids of the columns that edit. */\nexport type EditableId<Specs> = {\n [K in keyof Specs]: Specs[K] extends { readonly edit: object } ? K : never\n}[keyof Specs] &\n string\n\n/** What an editable column's text decodes to: its schema's value, or the text. */\nexport type EditValue<Spec> = Spec extends {\n readonly edit: { readonly schema: Schema.Codec<infer Value, string> }\n}\n ? Value\n : string\n\n/**\n * A checkbox column's cells are drawn from its value, so a spec whose edit\n * decodes to a boolean must read a boolean from its row.\n */\nexport type CheckboxValues<Row, Specs> = {\n readonly [K in keyof Specs]: Specs[K] extends {\n readonly edit: { readonly schema: Schema.Codec<boolean, string> }\n }\n ? { readonly value: (row: Row) => boolean }\n : unknown\n}\n\nexport interface Column<Row, Id extends string, Value> extends ColumnSpec<Row, Value> {\n readonly id: Id\n}\n\ntype ValueOf<Spec> = Spec extends ColumnSpec<never, infer Value> ? Value : never\n\nexport type ColumnId<C> = C extends Columns<never, infer Specs> ? keyof Specs & string : never\n\n/**\n * A grid's columns, keyed by stable id. Order, visibility and pinning live in\n * a `ColumnLayout`, so every reference to a column (focus, a selected range,\n * a saved width) names its id and survives a reorder.\n */\nexport interface Columns<Row, Specs extends Record<string, ColumnSpec<Row, unknown>>> {\n /** In definition order: the order `ColumnLayout.initial` starts from. */\n readonly ids: ReadonlyArray<keyof Specs & string>\n readonly byId: {\n readonly [Id in keyof Specs & string]: Column<Row, Id, ValueOf<Specs[Id]>>\n }\n /**\n * Type-only: the specs as written, so a grid made from these columns infers\n * each one exactly, its edit's schema included. Never set.\n */\n readonly Specs?: Specs\n}\n\n// Integer-like keys are enumerated before every other key, whatever the order\n// they were written in, so `{ name, 2024 }` would put 2024 first.\nconst arrayIndex = /^(0|[1-9][0-9]*)$/\n\nexport const Columns = {\n /** The width of a column that names none. */\n defaultWidth: 120,\n /** The narrowest a column with no `minWidth` resizes to. */\n minWidth: 40,\n /**\n * A boolean as a cell's text, `true` or `false`: give it as a column's\n * `edit.schema` and the cells are checkboxes. Any schema from text to a\n * boolean does the same; this one reads what `textOf` writes.\n */\n checkbox: Schema.Literals(['true', 'false']).pipe(\n Schema.decodeTo(Schema.Boolean, {\n decode: SchemaGetter.transform(text => text === 'true'),\n encode: SchemaGetter.transform(value => (value ? 'true' : 'false')),\n }),\n ),\n /** A value as a cell shows it: nothing for `null` or `undefined`. */\n textOf: (value: unknown): string => (value === null || value === undefined ? '' : String(value)),\n /**\n * Declares a grid's columns over `Row`. Call it twice, once with the row\n * type and once with the specs, so the ids and values are inferred:\n * `Columns.define<Product>()({ sku: { header: 'SKU', value: p => p.sku } })`.\n */\n define:\n <Row>() =>\n <Specs extends Record<string, ColumnSpec<Row, unknown>>>(\n specs: Specs & CheckboxValues<Row, Specs>,\n ): NoInfer<Columns<Row, Specs>> => {\n // A literal `__proto__:` key sets the prototype instead of naming a\n // column, so the column would vanish from `Object.keys`.\n if (Object.getPrototypeOf(specs) !== Object.prototype || Object.hasOwn(specs, '__proto__')) {\n throw new Error('Columns.define: \"__proto__\" cannot name a column.')\n }\n const given: Record<string, ColumnSpec<Row, unknown>> = specs\n const ids = Object.keys(given)\n const byId: Record<string, Column<Row, string, unknown>> = {}\n for (const id of ids) {\n if (arrayIndex.test(id)) {\n throw new Error(\n `Columns.define: the column id \"${id}\" is an array index, which JavaScript orders before every other key. Give it a name that is not a number.`,\n )\n }\n byId[id] = Object.freeze({ ...given[id]!, id })\n }\n return Object.freeze({\n ids: Object.freeze(ids),\n byId: Object.freeze(byId),\n }) as Columns<Row, Specs>\n },\n}\n"],"mappings":";;;;;;;AAwEA,MAAa,aAAa,kBAAkB;CAC1C,MAAM,CAAC;;CAEP,QAAQ,CAAC;;CAET,QAAQ,EAAE,SAAS,OAAO,MAAM,OAAO,MAAM,EAAE;;CAE/C,MAAM,CAAC;;;;;CAKP,UAAU,CAAC;AACb,CAAC;;;;;;;AASD,MAAM,UAAU;AAEhB,MAAM,UAAU,QAAgC;CAC9C,IAAI,CAAC,UAAU,cAAc,GAAG,GAAG,OAAO;CAC1C,MAAM,iBAA0B,IAAI,cAAc;CAClD,OACE,OAAO,mBAAmB,YAC1B,mBAAmB,QACnB,QAAQ,kBACR,eAAe,OAAO;AAE1B;AAEA,MAAM,iBAAiB,QACrB,UAAU,UAAU,GAAG,KACtB,UAAU,UAAU,GAAG,KAAK,OAAO,IAAI,YAAY,aACnD,UAAU,QAAQ,GAAG,KAAK,IAAI,MAAM,SAAS,KAAK,IAAI,MAAM,MAAM,aAAa;AAElF,MAAM,cAAc,QAClB,UAAU,OAAO,GAAG,IAAI,IAAI,MAAM,KAAK,GAAG,WAAW,KAAK,IAAI,CAAC;AACjE,MAAM,gBAAgB,QACpB,UAAU,SAAS,GAAG,KACrB,UAAU,UAAU,GAAG,KAAK,OAAO,IAAI,YAAY,YACnD,UAAU,OAAO,GAAG,KACnB,IAAI,MAAM,SAAS,KACnB,WAAW,GAAG,CAAC,CAAC,OAAM,UAAS,OAAO,UAAU,QAAQ,KACzD,UAAU,QAAQ,GAAG,KAAK,IAAI,MAAM,SAAS,KAAK,IAAI,MAAM,MAAM,YAAY;;AAEjF,MAAM,gBAAgB,QAA6D;CACjF,IAAI,UAAU,OAAO,GAAG,GAAG;EACz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AAI;AAC5B;AAuDA,MAAM,aAAa;AAEnB,MAAa,UAAU;;CAErB,cAAc;;CAEd,UAAU;;;;;;CAMV,UAAU,OAAO,SAAS,CAAC,QAAQ,OAAO,CAAC,CAAC,CAAC,KAC3C,OAAO,SAAS,OAAO,SAAS;EAC9B,QAAQ,aAAa,WAAU,SAAQ,SAAS,MAAM;EACtD,QAAQ,aAAa,WAAU,UAAU,QAAQ,SAAS,OAAQ;CACpE,CAAC,CACH;;CAEA,SAAS,UAA4B,UAAU,QAAQ,UAAU,KAAA,IAAY,KAAK,OAAO,KAAK;;;;;;CAM9F,eAGI,UACiC;EAGjC,IAAI,OAAO,eAAe,KAAK,MAAM,OAAO,aAAa,OAAO,OAAO,OAAO,WAAW,GACvF,MAAM,IAAI,MAAM,qDAAmD;EAErE,MAAM,QAAkD;EACxD,MAAM,MAAM,OAAO,KAAK,KAAK;EAC7B,MAAM,OAAqD,CAAC;EAC5D,KAAK,MAAM,MAAM,KAAK;GACpB,IAAI,WAAW,KAAK,EAAE,GACpB,MAAM,IAAI,MACR,kCAAkC,GAAG,0GACvC;GAEF,KAAK,MAAM,OAAO,OAAO;IAAE,GAAG,MAAM;IAAM;GAAG,CAAC;EAChD;EACA,OAAO,OAAO,OAAO;GACnB,KAAK,OAAO,OAAO,GAAG;GACtB,MAAM,OAAO,OAAO,IAAI;EAC1B,CAAC;CACH;AACJ"}
|
package/dist/fill.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Option } from "effect";
|
|
2
|
+
import { FillLane } from "./columns.js";
|
|
2
3
|
import { CellAddress, CellBox, GridProjection } from "./projection.js";
|
|
3
4
|
import { PastedCell } from "./clipboard.js";
|
|
4
5
|
/** A fill: the range whose cells are carried on, and the cell it was carried to. */
|
|
@@ -23,23 +24,32 @@ export interface FillPlan<Id extends string> {
|
|
|
23
24
|
/**
|
|
24
25
|
* The texts that carry `source` on for `count` cells, the first of them next
|
|
25
26
|
* to it. Two or more numbers a constant step apart continue their step, with
|
|
26
|
-
* as many decimals as the most precise of them
|
|
27
|
-
*
|
|
27
|
+
* as many decimals as the most precise of them. Two or more `YYYY-MM-DD`
|
|
28
|
+
* days continue by months when they share a day of the month a constant number
|
|
29
|
+
* of months apart (a 31st clamps to a shorter month and comes back), else by
|
|
30
|
+
* a constant number of days. Anything else repeats, in order. `backward` carries the source on before its first text, as filling
|
|
28
31
|
* up or left does.
|
|
29
32
|
*/
|
|
30
33
|
declare const series: (source: ReadonlyArray<string>, count: number, backward: boolean) => ReadonlyArray<string>;
|
|
31
34
|
/** The source's box and the box beyond it toward `to`; none when `to` is inside it. */
|
|
32
35
|
declare const plan: <Row, Id extends string>(projection: GridProjection<Row, Id>, request: FillRequest<Id>) => Option.Option<FillPlan<Id>>;
|
|
36
|
+
/** A cell a fill writes, or one it could not: `refusal` is why no text was given. */
|
|
37
|
+
export interface FilledCell<Id extends string> extends PastedCell<Id> {
|
|
38
|
+
readonly refusal?: string;
|
|
39
|
+
}
|
|
33
40
|
/**
|
|
34
41
|
* The cells a fill writes: each lane of the source (a column for a fill down
|
|
35
42
|
* or up, a row for one right or left) carried on through the target by
|
|
36
|
-
* `series
|
|
43
|
+
* `series`, or by the column's `custom` series when it answers (fills down
|
|
44
|
+
* and up only). A custom answer shorter than the target leaves the cells past
|
|
45
|
+
* it with a `refusal`. Cells on a column that does not edit, or on a row not loaded, are
|
|
37
46
|
* dropped; each kept cell has `from`, the text it showed.
|
|
38
47
|
*/
|
|
39
48
|
declare const cells: <Row, Id extends string>(projection: GridProjection<Row, Id>, fill: FillPlan<Id>, options: {
|
|
40
49
|
readonly editable: (column: Id) => boolean;
|
|
41
50
|
readonly from: (address: CellAddress<Id>) => string;
|
|
42
|
-
|
|
51
|
+
readonly custom?: (column: Id, lane: FillLane) => Option.Option<ReadonlyArray<string>>;
|
|
52
|
+
}) => ReadonlyArray<FilledCell<Id>>;
|
|
43
53
|
export declare const Fill: {
|
|
44
54
|
series: typeof series;
|
|
45
55
|
plan: typeof plan;
|
package/dist/fill.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fill.d.ts","names":[],"sources":["../src/fill.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"fill.d.ts","names":[],"sources":["../src/fill.ts"],"mappings":";;;;;iBAMiB,YAAY;WAClB;aAAmB,QAAQ,YAAY;aAAc,OAAO,YAAY;;WACxE,IAAI,YAAY;;;;;;;iBAQV,SAAS;WACf,QAAQ,QAAQ;WAChB,QAAQ,QAAQ;;WAEhB;;;;;;;;;;;cAyFL,SAAM,QACF,uBAAqB,eAChB,sBAEZ;;cAuBG,OAAQ,KAAK,mBAAiB,YACtB,eAAe,KAAK,KAAG,SAC1B,YAAY,QACpB,OAAO,OAAO,SAAS;;iBAoCT,WAAW,2BAA2B,WAAW;WACvD;;;;;;;;;;cAaL,QAAS,KAAK,mBAAiB,YACvB,eAAe,KAAK,KAAG,MAC7B,SAAS,KAAG;WAEP,WAAW,QAAQ;WACnB,OAAO,SAAS,YAAY;WAC5B,UAAU,QAAQ,IAAI,MAAM,aAAa,OAAO,OAAO;MAEjE,cAAc,WAAW;qBAmDf"}
|
package/dist/fill.js
CHANGED
|
@@ -1,17 +1,79 @@
|
|
|
1
1
|
import { Option } from "effect";
|
|
2
2
|
// src/fill.ts
|
|
3
3
|
const number = /^-?\d+(?:\.(\d+))?$/;
|
|
4
|
+
const day = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
5
|
+
const msPerDay = 864e5;
|
|
6
|
+
const utcDate = (year, month, date) => {
|
|
7
|
+
const made = /* @__PURE__ */ new Date(0);
|
|
8
|
+
made.setUTCFullYear(year, month, date);
|
|
9
|
+
return made;
|
|
10
|
+
};
|
|
11
|
+
const daysInMonth = (year, month) => utcDate(year, month + 1, 0).getUTCDate();
|
|
12
|
+
const calendarDay = (text) => {
|
|
13
|
+
const match = day.exec(text.trim());
|
|
14
|
+
if (match === null) return void 0;
|
|
15
|
+
const [year, month, date] = [
|
|
16
|
+
Number(match[1]),
|
|
17
|
+
Number(match[2]) - 1,
|
|
18
|
+
Number(match[3])
|
|
19
|
+
];
|
|
20
|
+
const made = utcDate(year, month, date);
|
|
21
|
+
if (made.getUTCMonth() !== month || made.getUTCDate() !== date) return void 0;
|
|
22
|
+
return {
|
|
23
|
+
year,
|
|
24
|
+
month,
|
|
25
|
+
date,
|
|
26
|
+
epoch: made.getTime() / msPerDay
|
|
27
|
+
};
|
|
28
|
+
};
|
|
29
|
+
const dayText = (made) => `${String(made.getUTCFullYear()).padStart(4, "0")}-${String(made.getUTCMonth() + 1).padStart(2, "0")}-${String(made.getUTCDate()).padStart(2, "0")}`;
|
|
30
|
+
/**
|
|
31
|
+
* Calendar days continued by months when they share a day of the month and
|
|
32
|
+
* are a constant number of months apart, else by days when a constant
|
|
33
|
+
* number of days apart. Each month's day is the source's, clamped to the
|
|
34
|
+
* month's length. None when the source is not such a series.
|
|
35
|
+
*/
|
|
36
|
+
const daySeries = (source, count, backward) => {
|
|
37
|
+
const days = source.map(calendarDay);
|
|
38
|
+
if (days.some((found) => found === void 0)) return void 0;
|
|
39
|
+
const known = days;
|
|
40
|
+
const steps = (read) => known.slice(1).map((found, index) => read(found) - read(known[index]));
|
|
41
|
+
const constant = (diffs) => diffs[0] !== 0 && diffs.every((diff) => diff === diffs[0]);
|
|
42
|
+
const first = known[0];
|
|
43
|
+
const last = known[known.length - 1];
|
|
44
|
+
const months = steps((found) => found.year * 12 + found.month);
|
|
45
|
+
if (known.every((found) => found.date === first.date) && constant(months)) {
|
|
46
|
+
const step = months[0];
|
|
47
|
+
const from = backward ? first : last;
|
|
48
|
+
const origin = from.year * 12 + from.month;
|
|
49
|
+
return Array.from({ length: count }, (_, index) => {
|
|
50
|
+
const at = origin + (backward ? -step : step) * (index + 1);
|
|
51
|
+
const year = Math.floor(at / 12);
|
|
52
|
+
const month = at - year * 12;
|
|
53
|
+
return dayText(utcDate(year, month, Math.min(first.date, daysInMonth(year, month))));
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
const dayDiffs = steps((found) => found.epoch);
|
|
57
|
+
if (!constant(dayDiffs)) return void 0;
|
|
58
|
+
const step = dayDiffs[0];
|
|
59
|
+
const from = backward ? first : last;
|
|
60
|
+
return Array.from({ length: count }, (_, index) => dayText(/* @__PURE__ */ new Date((from.epoch + (backward ? -step : step) * (index + 1)) * msPerDay)));
|
|
61
|
+
};
|
|
4
62
|
/**
|
|
5
63
|
* The texts that carry `source` on for `count` cells, the first of them next
|
|
6
64
|
* to it. Two or more numbers a constant step apart continue their step, with
|
|
7
|
-
* as many decimals as the most precise of them
|
|
8
|
-
*
|
|
65
|
+
* as many decimals as the most precise of them. Two or more `YYYY-MM-DD`
|
|
66
|
+
* days continue by months when they share a day of the month a constant number
|
|
67
|
+
* of months apart (a 31st clamps to a shorter month and comes back), else by
|
|
68
|
+
* a constant number of days. Anything else repeats, in order. `backward` carries the source on before its first text, as filling
|
|
9
69
|
* up or left does.
|
|
10
70
|
*/
|
|
11
71
|
const series = (source, count, backward) => {
|
|
12
72
|
const at = (index) => source[(index % source.length + source.length) % source.length];
|
|
13
73
|
const repeated = Array.from({ length: count }, (_, index) => backward ? at(-1 - index) : at(source.length + index));
|
|
14
74
|
if (source.length < 2) return repeated;
|
|
75
|
+
const days = daySeries(source, count, backward);
|
|
76
|
+
if (days !== void 0) return days;
|
|
15
77
|
const parsed = source.map((text) => number.exec(text.trim()));
|
|
16
78
|
if (parsed.some((match) => match === null)) return repeated;
|
|
17
79
|
const decimals = Math.max(...parsed.map((match) => match[1]?.length ?? 0));
|
|
@@ -60,10 +122,13 @@ const plan = (projection, request) => Option.flatMap(projection.box(request.sour
|
|
|
60
122
|
toward: right > 0 ? "right" : "left"
|
|
61
123
|
});
|
|
62
124
|
}));
|
|
125
|
+
const noSeriesText = "The column’s series gave no text here";
|
|
63
126
|
/**
|
|
64
127
|
* The cells a fill writes: each lane of the source (a column for a fill down
|
|
65
128
|
* or up, a row for one right or left) carried on through the target by
|
|
66
|
-
* `series
|
|
129
|
+
* `series`, or by the column's `custom` series when it answers (fills down
|
|
130
|
+
* and up only). A custom answer shorter than the target leaves the cells past
|
|
131
|
+
* it with a `refusal`. Cells on a column that does not edit, or on a row not loaded, are
|
|
67
132
|
* dropped; each kept cell has `from`, the text it showed.
|
|
68
133
|
*/
|
|
69
134
|
const cells = (projection, fill, options) => {
|
|
@@ -78,22 +143,37 @@ const cells = (projection, fill, options) => {
|
|
|
78
143
|
});
|
|
79
144
|
const cell = (index, column, text) => options.editable(column) ? Option.match(keyAt(index), {
|
|
80
145
|
onNone: () => [],
|
|
81
|
-
onSome: (row) =>
|
|
82
|
-
|
|
83
|
-
column,
|
|
84
|
-
text,
|
|
85
|
-
from: options.from({
|
|
146
|
+
onSome: (row) => {
|
|
147
|
+
const from = options.from({
|
|
86
148
|
row,
|
|
87
149
|
column
|
|
88
|
-
})
|
|
89
|
-
|
|
150
|
+
});
|
|
151
|
+
return [text === void 0 ? {
|
|
152
|
+
row,
|
|
153
|
+
column,
|
|
154
|
+
text: "",
|
|
155
|
+
from,
|
|
156
|
+
refusal: noSeriesText
|
|
157
|
+
} : {
|
|
158
|
+
row,
|
|
159
|
+
column,
|
|
160
|
+
text,
|
|
161
|
+
from
|
|
162
|
+
}];
|
|
163
|
+
}
|
|
90
164
|
}) : [];
|
|
91
165
|
const backward = fill.toward === "up" || fill.toward === "left";
|
|
92
166
|
const away = (items) => backward ? [...items].reverse() : items;
|
|
93
167
|
if (fill.toward === "down" || fill.toward === "up") {
|
|
94
168
|
const targetRows = away(rowsOf(fill.target.rows));
|
|
95
169
|
return fill.source.columns.flatMap((column) => {
|
|
96
|
-
const
|
|
170
|
+
const source = rowsOf(fill.source.rows).map((index) => textAt(index, column));
|
|
171
|
+
const count = targetRows.length;
|
|
172
|
+
const texts = Option.getOrElse(options.custom?.(column, {
|
|
173
|
+
source,
|
|
174
|
+
count,
|
|
175
|
+
toward: backward ? "up" : "down"
|
|
176
|
+
}) ?? Option.none(), () => series(source, count, backward));
|
|
97
177
|
return targetRows.flatMap((index, at) => cell(index, column, texts[at]));
|
|
98
178
|
});
|
|
99
179
|
}
|