@iyulab/flex-table 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 iyulab
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,424 @@
1
+ # flex-table
2
+
3
+ A lightweight, schema-agnostic data grid web component built with [Lit](https://lit.dev/).
4
+
5
+ Designed for effortless data input and crystal-clear visibility. Bridges the gap between spreadsheet freedom and database structural integrity.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install @iyulab/flex-table
11
+ ```
12
+
13
+ ## Quick Start
14
+
15
+ ```html
16
+ <flex-table id="table" row-height="32" show-row-numbers></flex-table>
17
+
18
+ <script type="module">
19
+ import '@iyulab/flex-table';
20
+
21
+ const table = document.getElementById('table');
22
+
23
+ table.columns = [
24
+ { key: 'name', header: 'Name', type: 'text', width: 200 },
25
+ { key: 'age', header: 'Age', type: 'number', width: 100 },
26
+ { key: 'active', header: 'Active', type: 'boolean', width: 80 },
27
+ ];
28
+
29
+ table.data = [
30
+ { name: 'Alice', age: 30, active: true },
31
+ { name: 'Bob', age: 25, active: false },
32
+ ];
33
+ </script>
34
+ ```
35
+
36
+ ## Features
37
+
38
+ - **Virtual Scroll** — Smooth scrolling through 100,000+ rows (horizontal + vertical)
39
+ - **Keyboard Navigation** — Arrow, Tab, Home, End, Ctrl+Home/End
40
+ - **Inline Editing** — Enter/F2 to edit, Escape to cancel, type-aware editors
41
+ - **Custom Editor** — `editor` callback for fully custom cell editing UI
42
+ - **Validation** — `validator` callback with visual feedback (red border + `aria-invalid`)
43
+ - **Range Selection** — Shift+Arrow, Shift+Click for multi-cell selection
44
+ - **Column Selection** — Ctrl+Click header or `selectColumn()` API
45
+ - **Row Selection** — Checkbox-based row selection (`selectable`, single/multi mode)
46
+ - **Clipboard** — Ctrl+C/X/V with TSV format (Excel/Google Sheets compatible, RFC 4180)
47
+ - **Sorting** — Click header to sort (asc/desc/none), Shift+click for multi-sort
48
+ - **Column Resize** — Drag header border, double-click to auto-fit, Alt+Arrow keyboard resize
49
+ - **Column Operations** — `addColumn()`, `deleteColumn()`, `moveColumn()` with undo
50
+ - **Pinned Columns** — Freeze columns to left or right (`pinned: 'left' | 'right'`)
51
+ - **Filtering** — Programmatic API + built-in header filter UI (`show-filters`)
52
+ - **Filter Types** — Text search, number range, boolean toggle, date/datetime range picker
53
+ - **Row Operations** — `addRow()`, `deleteRows()`, `updateRows()` with undo
54
+ - **Undo/Redo** — Ctrl+Z / Ctrl+Y for all operations; configurable stack size
55
+ - **Export** — CSV, TSV, JSON; full data or selection-only
56
+ - **Dark Theme** — Auto via `prefers-color-scheme`, or manual `theme="dark"`
57
+ - **Row Numbers** — Optional `show-row-numbers` attribute with sticky positioning
58
+ - **Footer Row** — Summary/aggregate row via `footer-data` property
59
+ - **Data Mode** — Client-side or server-side sorting/filtering (`dataMode`)
60
+ - **Context Menu** — `context-menu` event for custom right-click menus
61
+ - **React Wrapper** — `@iyulab/flex-table/react` subpath for idiomatic React usage
62
+ - **ARIA** — `role="grid"`, `aria-sort`, `aria-selected`, `aria-readonly`, `aria-invalid`, `aria-rowcount`, `aria-colcount`
63
+
64
+ ## Properties
65
+
66
+ | Property | Attribute | Type | Default | Description |
67
+ |----------|-----------|------|---------|-------------|
68
+ | `columns` | — | `ColumnDefinition[]` | `[]` | Column definitions |
69
+ | `data` | — | `DataRow[]` | `[]` | Data rows (`Record<string, unknown>[]`) |
70
+ | `rowHeight` | `row-height` | `number` | `32` | Row height in pixels |
71
+ | `showRowNumbers` | `show-row-numbers` | `boolean` | `false` | Show row number column |
72
+ | `theme` | `theme` | `'light' \| 'dark'` | auto | Force theme; auto-detects `prefers-color-scheme` |
73
+ | `editable` | `editable` | `boolean` | `true` | Global read-only mode when `false` |
74
+ | `showFilters` | `show-filters` | `boolean` | `false` | Show built-in header filter dropdowns |
75
+ | `maxRows` | `max-rows` | `number` | `0` | Max row count (0 = unlimited); blocks `addRow()` and paste expansion |
76
+ | `maxUndoSize` | `max-undo-size` | `number` | `100` | Max undo history stack size |
77
+ | `selectable` | `selectable` | `boolean` | `false` | Enable row-level checkbox selection |
78
+ | `selectionMode` | `selection-mode` | `'single' \| 'multi'` | `'multi'` | Row selection mode |
79
+ | `dataMode` | `data-mode` | `'client' \| 'server'` | `'client'` | Client-side or server-side data processing |
80
+ | `footerData` | `footer-data` | `Record<string, string>` | `null` | Footer/summary row data (keys match column keys) |
81
+
82
+ ### Read-only Properties
83
+
84
+ | Property | Type | Description |
85
+ |----------|------|-------------|
86
+ | `visibleColumns` | `ColumnDefinition[]` | Columns where `hidden !== true` |
87
+ | `filteredRowCount` | `number` | Number of rows after filtering |
88
+ | `canUndo` | `boolean` | Whether undo is available |
89
+ | `canRedo` | `boolean` | Whether redo is available |
90
+ | `activeCell` | `CellPosition \| null` | Currently focused cell `{ row, col }` |
91
+ | `editingCell` | `CellPosition \| null` | Currently editing cell `{ row, col }` |
92
+ | `sortCriteria` | `SortCriteria[]` | Active sort criteria `[{ key, direction }]` |
93
+ | `filterKeys` | `string[]` | Column keys with active filters |
94
+
95
+ ## Column Definition
96
+
97
+ ```typescript
98
+ interface ColumnDefinition {
99
+ key: string; // Unique key matching data property names
100
+ header: string; // Display header text
101
+ type?: ColumnType; // 'text' | 'number' | 'boolean' | 'date' | 'datetime'
102
+ width?: number; // Column width in pixels (default: 120)
103
+ minWidth?: number; // Minimum width in pixels (default: 40, enforced in rendering)
104
+ hidden?: boolean; // Hide column from view
105
+ sortable?: boolean; // Enable sorting (default: true)
106
+ editable?: boolean; // Per-column edit control (follows global editable)
107
+ pinned?: 'left' | 'right'; // Freeze column during horizontal scroll
108
+ renderer?: CellRenderer; // Custom cell render: (value, row, col) => TemplateResult | string
109
+ editor?: CellEditor; // Custom cell editor: (value, row, col) => TemplateResult
110
+ validator?: CellValidator; // Validate before commit: (value, row, col) => string | null
111
+ }
112
+ ```
113
+
114
+ The `editor` callback must return a Lit `TemplateResult` containing an input element with class `"ft-editor"`. The component reads `.value` from that element on commit. See [Custom Editor](#custom-editor) for details.
115
+
116
+ The `validator` callback returns `null` if valid, or an error message string. On failure, the cell shows a red border for 3 seconds and a `validation-error` event is dispatched.
117
+
118
+ ## Methods
119
+
120
+ ### Row Operations
121
+
122
+ | Method | Returns | Description |
123
+ |--------|---------|-------------|
124
+ | `addRow(row?, index?)` | `DataRow \| null` | Add a row. Returns `null` if `maxRows` reached |
125
+ | `deleteRows(indices?)` | `void` | Delete rows by data index (default: selected rows) |
126
+ | `updateRows(changes)` | `void` | Batch update cells as single undo action. `changes: Array<{ row, key, value }>` |
127
+ | `refreshData()` | `void` | Force re-render after in-place data mutation |
128
+
129
+ ### Column Operations
130
+
131
+ | Method | Returns | Description |
132
+ |--------|---------|-------------|
133
+ | `addColumn(def, index?)` | `ColumnDefinition` | Add column at position (default: end) |
134
+ | `deleteColumn(key)` | `void` | Remove column + cleanup filters/sort/widths |
135
+ | `moveColumn(key, newIndex)` | `void` | Reorder column to target index (clamped) |
136
+ | `getColumnWidth(key)` | `number \| undefined` | Get internal resize width for column |
137
+ | `selectColumn(colIndex)` | `void` | Select entire column (range selection) |
138
+
139
+ ### Row Selection
140
+
141
+ | Method | Returns | Description |
142
+ |--------|---------|-------------|
143
+ | `selectAll()` | `void` | Select all visible rows (multi mode only) |
144
+ | `deselectAll()` | `void` | Deselect all rows |
145
+ | `getSelectedRows()` | `{ selectedIndices, selectedRows }` | Get selected row data |
146
+
147
+ ### Filtering
148
+
149
+ | Method | Returns | Description |
150
+ |--------|---------|-------------|
151
+ | `setFilter(key, predicate)` | `void` | Set column filter. `predicate: (value, row) => boolean` |
152
+ | `removeFilter(key)` | `void` | Remove filter for a column |
153
+ | `clearFilters()` | `void` | Remove all filters |
154
+
155
+ ### Export
156
+
157
+ | Method | Returns | Description |
158
+ |--------|---------|-------------|
159
+ | `exportToString(format, options?)` | `string` | Export to `'csv'` / `'tsv'` / `'json'`. Pass `{ selectionOnly: true }` for selection range |
160
+ | `exportToFile(format, filename?)` | `void` | Export and trigger browser file download |
161
+
162
+ ## Events
163
+
164
+ All events use `CustomEvent` with `bubbles: true, composed: true`.
165
+
166
+ ### Cell Events
167
+
168
+ | Event | Detail | Description |
169
+ |-------|--------|-------------|
170
+ | `cell-select` | `{ row, col }` | Cell focus changed |
171
+ | `cell-edit-start` | `{ row, col, key, value }` | Cell editing started |
172
+ | `cell-edit-commit` | `{ row, col, key, oldValue, newValue }` | Cell value committed |
173
+ | `cell-edit-cancel` | `{ row, col }` | Cell edit cancelled (Escape) |
174
+ | `validation-error` | `{ row, col, key, value, error }` | Cell validator rejected value |
175
+
176
+ ### Data Events
177
+
178
+ | Event | Detail | Description |
179
+ |-------|--------|-------------|
180
+ | `row-add` | `{ row, index }` | Row added |
181
+ | `row-delete` | `{ indices, rows }` | Rows deleted |
182
+ | `batch-update` | `{ changes: [{ row, key, oldValue, newValue }] }` | Batch update applied |
183
+
184
+ ### Column Events
185
+
186
+ | Event | Detail | Description |
187
+ |-------|--------|-------------|
188
+ | `column-add` | `{ column, index }` | Column added |
189
+ | `column-delete` | `{ column, key, index }` | Column removed |
190
+ | `column-reorder` | `{ key, oldIndex, newIndex }` | Column moved |
191
+ | `column-resize` | `{ key, width, colIndex }` | Column resized (drag, auto-fit, or keyboard) |
192
+ | `column-select` | `{ colIndex, key, rowCount }` | Entire column selected |
193
+
194
+ ### Sort & Filter Events
195
+
196
+ | Event | Detail | Description |
197
+ |-------|--------|-------------|
198
+ | `sort-change` | `{ criteria: [{ key, direction }] }` | Sort criteria changed |
199
+ | `filter-change` | `{ keys, filteredCount }` | Filter added/removed |
200
+ | `filter-error` | `{ error, row, filterKey }` | Filter predicate threw an error |
201
+
202
+ ### Selection Events
203
+
204
+ | Event | Detail | Description |
205
+ |-------|--------|-------------|
206
+ | `selection-change` | `{ selectedIndices, selectedRows }` | Row checkbox selection changed |
207
+
208
+ ### Clipboard Events
209
+
210
+ | Event | Detail | Description |
211
+ |-------|--------|-------------|
212
+ | `clipboard-copy` | `{ range, text }` | Range copied as TSV |
213
+ | `clipboard-cut` | `{ range, text }` | Range cut as TSV |
214
+ | `clipboard-paste` | `{ changes, addedRows }` | Data pasted from clipboard |
215
+ | `clipboard-error` | `{ action, error }` | Clipboard API failed (`action`: `'copy'` or `'paste'`) |
216
+
217
+ ### State Events
218
+
219
+ | Event | Detail | Description |
220
+ |-------|--------|-------------|
221
+ | `undo-state-change` | `{ canUndo, canRedo }` | Undo/redo availability changed |
222
+ | `context-menu` | `{ x, y, row, col, dataRow, column }` | Right-click on cell |
223
+
224
+ ## CSS Custom Properties
225
+
226
+ All colors and styles are customizable via CSS custom properties:
227
+
228
+ ```css
229
+ flex-table {
230
+ --ft-font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
231
+ --ft-font-size: 14px;
232
+ --ft-border-color: #e0e0e0;
233
+ --ft-bg: #fff;
234
+ --ft-text-color: #202124;
235
+ --ft-header-bg: #f8f9fa;
236
+ --ft-header-hover-bg: #e8eaed;
237
+ --ft-header-text-color: #202124;
238
+ --ft-row-even-bg: #fff;
239
+ --ft-row-odd-bg: #fafafa;
240
+ --ft-row-hover-bg: #f0f4ff;
241
+ --ft-active-color: #1a73e8;
242
+ --ft-selection-bg: #e8f0fe;
243
+ --ft-bool-color: #2196f3;
244
+ --ft-sort-indicator-color: #5f6368;
245
+ --ft-editor-bg: #fff;
246
+ --ft-empty-color: #999;
247
+ }
248
+ ```
249
+
250
+ ## Keyboard Shortcuts
251
+
252
+ | Key | Action |
253
+ |-----|--------|
254
+ | Arrow keys | Navigate cells |
255
+ | Tab / Shift+Tab | Move to next/previous cell |
256
+ | Enter / F2 | Start editing |
257
+ | Escape | Cancel edit / clear selection |
258
+ | Home / End | Row start/end |
259
+ | Ctrl+Home / Ctrl+End | Table start/end |
260
+ | Shift+Arrow | Extend selection range |
261
+ | Ctrl+C / Ctrl+X | Copy/Cut selection as TSV |
262
+ | Ctrl+V | Paste TSV data |
263
+ | Delete / Backspace | Clear selected cells |
264
+ | Ctrl+Z | Undo |
265
+ | Ctrl+Shift+Z / Ctrl+Y | Redo |
266
+ | Alt+ArrowLeft / Alt+ArrowRight | Resize current column (±20px) |
267
+ | Ctrl+Click header | Select entire column |
268
+
269
+ ## Usage Guide
270
+
271
+ ### React
272
+
273
+ Install peer dependencies and import the React wrapper:
274
+
275
+ ```bash
276
+ npm install @iyulab/flex-table @lit/react react
277
+ ```
278
+
279
+ ```tsx
280
+ import { FlexTableReact } from '@iyulab/flex-table/react';
281
+
282
+ function App() {
283
+ const columns = [
284
+ { key: 'name', header: 'Name', type: 'text' },
285
+ { key: 'age', header: 'Age', type: 'number' },
286
+ ];
287
+
288
+ const data = [
289
+ { name: 'Alice', age: 30 },
290
+ { name: 'Bob', age: 25 },
291
+ ];
292
+
293
+ return (
294
+ <FlexTableReact
295
+ columns={columns}
296
+ data={data}
297
+ showRowNumbers
298
+ onCellEditCommit={(e) => console.log('Edited:', e.detail)}
299
+ onSortChange={(e) => console.log('Sort:', e.detail)}
300
+ />
301
+ );
302
+ }
303
+ ```
304
+
305
+ All `<flex-table>` properties are available as React props, and all custom events are mapped to `on*` callbacks (e.g., `cell-edit-commit` → `onCellEditCommit`).
306
+
307
+ ### Custom Editor
308
+
309
+ The `editor` callback lets you provide a fully custom editing UI. The component reads `.value` from the element with class `ft-editor` when committing.
310
+
311
+ ```typescript
312
+ import { html } from 'lit';
313
+
314
+ table.columns = [
315
+ {
316
+ key: 'color',
317
+ header: 'Color',
318
+ type: 'text',
319
+ editor: (value) => html`
320
+ <input class="ft-editor" type="color" .value=${String(value ?? '#000000')}
321
+ @blur=${(e) => e.target.dispatchEvent(new Event('change', { bubbles: true }))}
322
+ @keydown=${(e) => {
323
+ if (e.key === 'Escape') e.target.blur();
324
+ }}>
325
+ `,
326
+ },
327
+ ];
328
+ ```
329
+
330
+ **Key rules:**
331
+ - Must include an element with class `ft-editor` — the component reads its `.value` on commit
332
+ - Clicking another cell auto-commits the editor
333
+ - For Enter/Escape support, handle `@keydown` in your template
334
+ - For blur-to-commit, handle `@blur` in your template
335
+
336
+ ### Validation
337
+
338
+ Use the `validator` callback to validate input before committing. Returns `null` if valid, or an error message:
339
+
340
+ ```typescript
341
+ table.columns = [
342
+ {
343
+ key: 'age',
344
+ header: 'Age',
345
+ type: 'number',
346
+ validator: (value) => {
347
+ const n = Number(value);
348
+ if (n < 0 || n > 150) return 'Age must be 0–150';
349
+ return null;
350
+ },
351
+ },
352
+ ];
353
+ ```
354
+
355
+ When validation fails, the cell displays a red border for 3 seconds and the `validation-error` event fires.
356
+
357
+ ### Pinned Columns
358
+
359
+ Freeze columns on either side during horizontal scroll:
360
+
361
+ ```typescript
362
+ table.columns = [
363
+ { key: 'id', header: 'ID', pinned: 'left' },
364
+ { key: 'name', header: 'Name' },
365
+ // ... many columns ...
366
+ { key: 'actions', header: 'Actions', pinned: 'right' },
367
+ ];
368
+ ```
369
+
370
+ ### Data Mutation
371
+
372
+ The `data` property uses in-place mutation for performance. Direct changes to data objects are **not** automatically detected:
373
+
374
+ ```typescript
375
+ // Will NOT trigger re-render:
376
+ table.data[0].name = 'Alice';
377
+
378
+ // Options to trigger re-render:
379
+ table.refreshData(); // Force re-render
380
+ table.updateRows([ // Recommended — includes undo support
381
+ { row: 0, key: 'name', value: 'Alice' }
382
+ ]);
383
+ ```
384
+
385
+ Use `updateRows()` for programmatic edits — it provides undo/redo and dispatches the `batch-update` event.
386
+
387
+ ### Built-in Filter UI
388
+
389
+ Enable with `show-filters` attribute. Filter dropdowns appear in column headers:
390
+
391
+ - **text**: case-insensitive substring search
392
+ - **number**: min/max range inputs
393
+ - **boolean**: All / True / False select
394
+ - **date**: from/to date range picker (`<input type="date">`)
395
+ - **datetime**: from/to datetime range picker (`<input type="datetime-local">`)
396
+
397
+ Filters set via the UI and the programmatic API (`setFilter()`) share the same filter state. Filter dropdowns automatically flip upward when near the viewport bottom.
398
+
399
+ ### Server-Side Mode
400
+
401
+ Set `data-mode="server"` to disable client-side sorting/filtering. The component dispatches `sort-change` and `filter-change` events but does not recompute data — your server provides pre-sorted/filtered data:
402
+
403
+ ```typescript
404
+ table.dataMode = 'server';
405
+ table.addEventListener('sort-change', (e) => {
406
+ fetchData({ sort: e.detail.criteria }).then(data => {
407
+ table.data = data;
408
+ });
409
+ });
410
+ ```
411
+
412
+ ## Development
413
+
414
+ ```bash
415
+ npm install
416
+ npm run dev # Dev server with demo
417
+ npm test # Run tests (179 tests)
418
+ npm run build # Build library
419
+ npm run lint # ESLint check
420
+ ```
421
+
422
+ ## License
423
+
424
+ MIT