@itrocks/table 0.10.0 → 0.13.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 CHANGED
@@ -74,6 +74,23 @@ The callback receives the cell and its zero-based index in the row when the cell
74
74
  Return its focusable control to keep it in the form, `null` to skip the cell, or `undefined` to use the text editor.
75
75
  Clicking the cell background focuses its control and places the caret at the end of text fields.
76
76
 
77
+ ### Loading more rows
78
+
79
+ Add the `TableFeed` plugin and set `data-feed` on the table to the URL that returns the next batch as an HTML table.
80
+ The table emits a `table-feed` event once after inserting each non-empty batch. The event's `detail.rows` array
81
+ contains the inserted `HTMLTableRowElement` instances in DOM order.
82
+
83
+ ```js
84
+ import { TableFeed } from '@itrocks/table/feed.js'
85
+ import { tableByElement } from '@itrocks/table/table.js'
86
+
87
+ const element = document.querySelector('table[data-feed]')
88
+ element.addEventListener('table-feed', ({ detail: { rows } }) => {
89
+ console.log('Rows added', rows)
90
+ })
91
+ tableByElement(element, { plugins: [TableFeed] })
92
+ ```
93
+
77
94
  ## API
78
95
 
79
96
  The public API is intentionally small and focuses on a single `Table`
@@ -245,12 +262,29 @@ Finds all tables matching the CSS selector and returns the corresponding
245
262
  - Implement custom plugins on top of `HasPlugins<Table>` to add domain‑
246
263
  specific features (validation, inline actions, totals rows, etc.).
247
264
 
265
+ ## Resizing columns
266
+
267
+ Include `column-resize.css` and add `TableColumnResize` from `@itrocks/table/column-resize.js` to a table's plugins.
268
+ Use a rectangular table with an unspanned first header row. Drag the edge of a header cell to change its width and
269
+ double-click it to restore automatic sizing. Columns marked with `data-freeze` on the header or corresponding
270
+ `col` are excluded.
271
+
272
+ Use `data-column-width` on a header to initialise its width in pixels. The plugin tracks widths across header moves
273
+ and can use an `identify(header)` callback to preserve them across header replacements. Use `isResizable(header)`
274
+ to restrict eligible columns and `isInResizeZone(header, clientY)` to restrict the vertical area within a header cell.
275
+ `onChange(header, width)` receives the final pixel width or `'auto'`. The consumer owns persistence.
276
+ Use `setWidth(header, width)` to apply a value programmatically without emitting a change.
277
+
248
278
  ## Adding columns
249
279
 
250
280
  Import the public browser entry and stylesheet. Configure `TableColumnAdd` after `TableColumnReorder` and any
251
281
  freeze plugins. The addition plugin consumes opaque string ids and callback-rendered cells; it has no dependency on
252
282
  business objects, selectors, routes or storage.
253
283
 
284
+ Listen for `table-column-change` on the table element to receive the cells inserted, replaced or removed by the
285
+ column plugins. `event.detail.cells` contains the affected header and body or footer cells. A replacement includes
286
+ both the previous and replacement cells.
287
+
254
288
  ```ts
255
289
  import { TableColumnAdd } from '@itrocks/table/column-add.js'
256
290
  import { TableColumnReorder } from '@itrocks/table/column-reorder.js'
package/column-add.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Plugin } from '../plugin/plugin.js';
2
2
  import { PluginOptions } from '../plugin/plugin.js';
3
+ import { notifyColumnChange } from './column-change.js';
3
4
  import { TableColumnReorder } from './column-reorder.js';
4
5
  import { TableFreeze } from './freeze.js';
5
6
  export class TableColumnAdd extends Plugin {
@@ -178,9 +179,11 @@ export class TableColumnAdd extends Plugin {
178
179
  if (existing)
179
180
  this.reorder.moveColumn(entry.content.header, entry.initial);
180
181
  else {
181
- for (const cell of [entry.content.header, ...entry.content.cells])
182
+ const cells = [entry.content.header, ...entry.content.cells];
183
+ for (const cell of cells)
182
184
  cell.remove();
183
185
  entry.col?.remove();
186
+ notifyColumnChange(this.of.element, cells);
184
187
  }
185
188
  this.refresh();
186
189
  this.notify(entry, 'cancelled');
@@ -235,6 +238,7 @@ export class TableColumnAdd extends Plugin {
235
238
  }
236
239
  this.mark(entry, 'provisional', true);
237
240
  this.refresh();
241
+ notifyColumnChange(this.of.element, [content.header, ...content.cells]);
238
242
  this.notify(entry, 'provisional');
239
243
  if (source.load)
240
244
  ready = this.load(entry);
@@ -423,6 +427,7 @@ export class TableColumnAdd extends Plugin {
423
427
  if (!removing && entry.effects && entry.transaction.state === 'committed'
424
428
  && this.isLastColumn(content.header))
425
429
  this.scrollToEnd();
430
+ notifyColumnChange(this.of.element, pairs.flat());
426
431
  this.notify(entry, 'loaded');
427
432
  }
428
433
  catch (error) {
@@ -0,0 +1 @@
1
+ export declare function notifyColumnChange(table: HTMLTableElement, cells: readonly HTMLTableCellElement[]): void;
@@ -0,0 +1,3 @@
1
+ export function notifyColumnChange(table, cells) {
2
+ table.dispatchEvent(new CustomEvent('table-column-change', { detail: { cells } }));
3
+ }
@@ -57,6 +57,7 @@ export declare class TableColumnReorder extends Plugin<Table, TableColumnReorder
57
57
  moveColumn(header: HTMLTableCellElement, targetIndex: number): void;
58
58
  /** Remove a reorderable column without committing a header gesture or invoking its callbacks. */
59
59
  removeColumn(header: HTMLTableCellElement): boolean;
60
+ private removeCells;
60
61
  /** Retain the active gesture when asynchronous rendering replaces one of its cells. */
61
62
  replaceCell(previous: HTMLTableCellElement, replacement: HTMLTableCellElement): void;
62
63
  protected finish(commit: boolean): void;
package/column-reorder.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Plugin } from '../plugin/plugin.js';
2
2
  import { PluginOptions } from '../plugin/plugin.js';
3
+ import { notifyColumnChange } from './column-change.js';
3
4
  let activeDrag;
4
5
  const clamp = (value) => Math.max(0, Math.min(1, value));
5
6
  const maxScrollSpeed = 800;
@@ -96,11 +97,16 @@ export class TableColumnReorder extends Plugin {
96
97
  return false;
97
98
  const index = header.cellIndex;
98
99
  const column = this.of.element.querySelectorAll(':scope > colgroup > col')[index];
99
- for (const row of this.rows())
100
- row.cells[index]?.remove();
101
- column?.remove();
100
+ this.removeCells(index, column);
102
101
  return true;
103
102
  }
103
+ removeCells(index, column) {
104
+ const cells = this.rows().map(row => row.cells[index]).filter(Boolean);
105
+ for (const cell of cells)
106
+ cell.remove();
107
+ column?.remove();
108
+ notifyColumnChange(this.of.element, cells);
109
+ }
104
110
  /** Retain the active gesture when asynchronous rendering replaces one of its cells. */
105
111
  replaceCell(previous, replacement) {
106
112
  if (this.press?.header === previous)
@@ -130,10 +136,7 @@ export class TableColumnReorder extends Plugin {
130
136
  this.move(drag, drag.initial);
131
137
  const removed = (commit && drag.remove) || (!commit && drag.adding);
132
138
  if (removed) {
133
- for (const row of this.rows()) {
134
- row.cells[drag.index]?.remove();
135
- }
136
- drag.col?.remove();
139
+ this.removeCells(drag.index, drag.col);
137
140
  }
138
141
  for (const cell of drag.cells) {
139
142
  cell.classList.remove('adding', 'column-reorder', 'moving', 'removing');
@@ -0,0 +1,7 @@
1
+ table.itrocks.column-resize-active, table.itrocks.column-resize-active *,
2
+ table.itrocks .column-resize-hover {
3
+ cursor: col-resize !important;
4
+ }
5
+ table.itrocks.column-resize-active {
6
+ user-select: none;
7
+ }
@@ -0,0 +1,30 @@
1
+ import { Plugin } from '../plugin/plugin.js';
2
+ import { PluginOptions } from '../plugin/plugin.js';
3
+ import { Table } from './table.js';
4
+ export type ColumnWidth = number | 'auto';
5
+ export declare class TableColumnResize extends Plugin<Table, TableColumnResizeOptions> {
6
+ private active?;
7
+ private hovered?;
8
+ private rule;
9
+ private suppressClick;
10
+ private widths;
11
+ defaultOptions(): TableColumnResizeOptions;
12
+ private finish;
13
+ private headers;
14
+ private hit;
15
+ private identify;
16
+ init(): void;
17
+ private isResizable;
18
+ private markHovered;
19
+ private notify;
20
+ setWidth(header: HTMLTableCellElement, width: ColumnWidth): void;
21
+ private start;
22
+ private sync;
23
+ private width;
24
+ }
25
+ export declare class TableColumnResizeOptions extends PluginOptions {
26
+ identify?: (header: HTMLTableCellElement) => string | undefined;
27
+ isInResizeZone?: (header: HTMLTableCellElement, clientY: number) => boolean;
28
+ isResizable?: (header: HTMLTableCellElement) => boolean;
29
+ onChange?: (header: HTMLTableCellElement, width: ColumnWidth) => void;
30
+ }
@@ -0,0 +1,229 @@
1
+ import { Plugin } from '../plugin/plugin.js';
2
+ import { PluginOptions } from '../plugin/plugin.js';
3
+ import { TableFreeze } from './freeze.js';
4
+ const edgeSize = 6;
5
+ const minimumWidth = 32;
6
+ export class TableColumnResize extends Plugin {
7
+ active;
8
+ hovered;
9
+ rule = '';
10
+ suppressClick = false;
11
+ widths = new Map();
12
+ defaultOptions() {
13
+ return new TableColumnResizeOptions();
14
+ }
15
+ finish(commit) {
16
+ const resize = this.active;
17
+ if (!resize)
18
+ return;
19
+ this.active = undefined;
20
+ this.suppressClick = true;
21
+ this.of.element.classList.remove('column-resize-active');
22
+ if (resize.header.hasPointerCapture(resize.id)) {
23
+ resize.header.releasePointerCapture(resize.id);
24
+ }
25
+ if (!commit) {
26
+ this.setWidth(resize.header, resize.original);
27
+ }
28
+ else {
29
+ this.notify(resize.header, resize.original);
30
+ }
31
+ }
32
+ headers() {
33
+ return Array.from(this.of.element.tHead?.rows[0]?.cells ?? []);
34
+ }
35
+ hit(event) {
36
+ const target = event.target;
37
+ if (!(target instanceof Element) || target.closest('a, button, input, select, textarea, [contenteditable]'))
38
+ return undefined;
39
+ const header = target.closest('th, td');
40
+ if (!header || (header.parentElement !== this.of.element.tHead?.rows[0]))
41
+ return undefined;
42
+ if (!this.isResizable(header))
43
+ return undefined;
44
+ const rect = header.getBoundingClientRect();
45
+ const edge = (getComputedStyle(header).direction === 'rtl') ? rect.left : rect.right;
46
+ if ((Math.abs(event.clientX - edge) <= edgeSize)
47
+ && (event.clientY >= rect.top)
48
+ && (event.clientY < rect.bottom)
49
+ && (this.options.isInResizeZone?.(header, event.clientY) ?? true)) {
50
+ return header;
51
+ }
52
+ return undefined;
53
+ }
54
+ identify(header) {
55
+ return this.options.identify?.(header) ?? header;
56
+ }
57
+ init() {
58
+ const table = this.of;
59
+ const element = table.element;
60
+ const capture = { capture: true };
61
+ this.widths.clear();
62
+ this.sync();
63
+ const observer = new MutationObserver(records => {
64
+ if (!records.some(({ target }) => (target === element) || (target === element.tHead) || (target.parentNode === element.tHead)))
65
+ return;
66
+ if (this.active && !element.contains(this.active.header)) {
67
+ this.finish(false);
68
+ }
69
+ this.sync();
70
+ });
71
+ observer.observe(element, { childList: true, subtree: true });
72
+ table.addEventListener(element, 'pointerdown', event => this.start(event), capture);
73
+ table.addEventListener(element, 'pointermove', event => {
74
+ const resize = this.active;
75
+ if (!resize) {
76
+ this.markHovered(this.hit(event));
77
+ return;
78
+ }
79
+ if (resize.id !== event.pointerId)
80
+ return;
81
+ event.preventDefault();
82
+ const delta = Math.round((event.clientX - resize.start) * resize.direction);
83
+ const width = delta ? Math.max(minimumWidth, resize.width + delta) : resize.original;
84
+ this.setWidth(resize.header, width);
85
+ }, capture);
86
+ table.addEventListener(element, 'pointerleave', () => this.markHovered());
87
+ table.addEventListener(element, 'pointerup', event => {
88
+ if (event.pointerId !== this.active?.id)
89
+ return;
90
+ event.stopImmediatePropagation();
91
+ this.finish(true);
92
+ }, capture);
93
+ for (const type of ['pointercancel', 'lostpointercapture']) {
94
+ table.addEventListener(element, type, event => {
95
+ if (event.pointerId === this.active?.id) {
96
+ this.finish(false);
97
+ }
98
+ }, capture);
99
+ }
100
+ table.addEventListener(element, 'click', event => {
101
+ if (!event.detail || (!this.suppressClick && !this.hit(event)))
102
+ return;
103
+ this.suppressClick = false;
104
+ event.preventDefault();
105
+ event.stopImmediatePropagation();
106
+ }, capture);
107
+ table.addEventListener(element, 'dblclick', event => {
108
+ const header = this.hit(event);
109
+ if (!header)
110
+ return;
111
+ event.preventDefault();
112
+ event.stopImmediatePropagation();
113
+ const previous = this.width(header);
114
+ this.setWidth(header, 'auto');
115
+ this.markHovered(this.hit(event));
116
+ this.notify(header, previous);
117
+ }, capture);
118
+ table.onReset.push(() => {
119
+ observer.disconnect();
120
+ this.finish(false);
121
+ this.markHovered();
122
+ this.rule = '';
123
+ this.suppressClick = false;
124
+ });
125
+ }
126
+ isResizable(header) {
127
+ if (header.hidden || header.hasAttribute('data-freeze')
128
+ || header.classList.contains('column-add-provisional') || header.classList.contains('column-remove-highlight')
129
+ || !(this.options.isResizable?.(header) ?? true))
130
+ return false;
131
+ const columns = this.of.element.querySelectorAll(':scope > colgroup > col');
132
+ return !columns[header.cellIndex]?.hasAttribute('data-freeze');
133
+ }
134
+ markHovered(header) {
135
+ if (this.hovered === header)
136
+ return;
137
+ this.hovered?.classList.remove('column-resize-hover');
138
+ header?.classList.add('column-resize-hover');
139
+ this.hovered = header;
140
+ }
141
+ notify(header, previous) {
142
+ const width = this.width(header);
143
+ if (width !== previous) {
144
+ this.options.onChange?.(header, width);
145
+ }
146
+ }
147
+ setWidth(header, width) {
148
+ const id = this.identify(header);
149
+ if (!this.widths.has(id) || (this.widths.get(id) === width))
150
+ return;
151
+ if ((width !== 'auto') && (!Number.isSafeInteger(width) || (width <= 0)))
152
+ return;
153
+ this.widths.set(id, width);
154
+ this.sync();
155
+ }
156
+ start(event) {
157
+ this.suppressClick = false;
158
+ if (this.active || !event.isPrimary || (event.button !== 0))
159
+ return;
160
+ const header = this.hit(event);
161
+ if (!header)
162
+ return;
163
+ event.preventDefault();
164
+ event.stopImmediatePropagation();
165
+ header.setPointerCapture(event.pointerId);
166
+ this.active = {
167
+ direction: (getComputedStyle(header).direction === 'rtl') ? -1 : 1,
168
+ header,
169
+ id: event.pointerId,
170
+ original: this.width(header),
171
+ start: event.clientX,
172
+ width: Math.round(header.getBoundingClientRect().width)
173
+ };
174
+ this.of.element.classList.add('column-resize-active');
175
+ }
176
+ sync() {
177
+ const headers = this.headers();
178
+ const widths = new Map();
179
+ const rules = [];
180
+ for (const header of headers) {
181
+ const id = this.identify(header);
182
+ const stored = Number(header.dataset.columnWidth);
183
+ const width = this.widths.get(id)
184
+ ?? ((Number.isSafeInteger(stored) && (stored > 0)) ? stored : 'auto');
185
+ widths.set(id, width);
186
+ if (width === 'auto') {
187
+ delete header.dataset.columnWidth;
188
+ continue;
189
+ }
190
+ header.dataset.columnWidth = String(width);
191
+ const column = `:is(th, td):nth-child(${header.cellIndex + 1}):not(.column-remove-highlight)`;
192
+ rules.push(`${this.of.selector} > :is(thead, tbody, tfoot) > tr > ${column} {
193
+ box-sizing: border-box;
194
+ width: ${width}px;
195
+ min-width: ${width}px;
196
+ max-width: ${width}px;
197
+ overflow: hidden;
198
+ text-overflow: ellipsis;
199
+ }`);
200
+ }
201
+ this.widths = widths;
202
+ const rule = rules.join('\n');
203
+ if (rule === this.rule)
204
+ return;
205
+ const styles = this.of.styleSheet;
206
+ const previous = styles.indexOf(this.rule);
207
+ if (previous >= 0) {
208
+ styles.splice(previous, 1);
209
+ }
210
+ this.rule = rule;
211
+ if (rule) {
212
+ styles.push(rule);
213
+ }
214
+ const freeze = this.of.plugins.TableFreeze;
215
+ if (freeze instanceof TableFreeze && freeze.columns) {
216
+ freeze.refresh();
217
+ }
218
+ this.of.refreshStyleSheets();
219
+ }
220
+ width(header) {
221
+ return this.widths.get(this.identify(header)) ?? 'auto';
222
+ }
223
+ }
224
+ export class TableColumnResizeOptions extends PluginOptions {
225
+ identify;
226
+ isInResizeZone;
227
+ isResizable;
228
+ onChange;
229
+ }
package/feed.js CHANGED
@@ -17,10 +17,18 @@ export class TableFeed extends Plugin {
17
17
  const container = loaded.querySelector('tbody > tr')?.parentElement ?? loaded.querySelector('tr')?.parentElement;
18
18
  if (!container)
19
19
  return;
20
+ const rows = [];
20
21
  while (container.firstChild) {
21
- tbody.append(container.firstChild);
22
+ const node = container.firstChild;
23
+ tbody.append(node);
24
+ if (node instanceof HTMLTableRowElement) {
25
+ rows.push(node);
26
+ }
22
27
  }
23
28
  this.observe();
29
+ if (rows.length) {
30
+ table.dispatchEvent(new CustomEvent('table-feed', { detail: { rows } }));
31
+ }
24
32
  }
25
33
  fieldSelector(fields) {
26
34
  return fields.split(/\s+/).filter(Boolean).map(field => {
@@ -59,6 +59,10 @@ export class TableFreezeInheritBorder extends Plugin {
59
59
  }
60
60
  `);
61
61
  }
62
+ // Measure offsets with the same border layout used for later refreshes.
63
+ if (tableFreeze.columns) {
64
+ tableFreeze.refresh();
65
+ }
62
66
  }
63
67
  position(position, counter, colCell, side) {
64
68
  const width = parseFloat(getComputedStyle(colCell).borderWidth) / 2;
package/freeze.js CHANGED
@@ -81,23 +81,23 @@ export class TableFreeze extends Plugin {
81
81
  }
82
82
  freezeHeadRows() {
83
83
  const table = this.of;
84
- if (!table.element.tHead?.rows.length)
84
+ const element = table.element;
85
+ const rows = element.tHead?.rows;
86
+ if (!rows?.length)
85
87
  return;
86
- // Header measurements are in scrolled coordinates after refresh removes the sticky rules.
87
- let counter = 1;
88
- let top = .0;
89
- let previousTop = table.element.getBoundingClientRect().top - table.element.scrollTop;
90
- table.element.tHead.querySelectorAll(':scope > tr').forEach(row => {
91
- const actualTop = row.getBoundingClientRect().top;
92
- top += actualTop - previousTop;
93
- previousTop = actualTop;
88
+ for (const row of rows) {
89
+ const counter = row.sectionRowIndex + 1;
90
+ // Layout offsets are already in CSS pixels and unaffected by scrolling or sticky cells.
91
+ const top = row.offsetParent === element
92
+ ? row.offsetTop
93
+ : Math.round((row.getBoundingClientRect().top - element.getBoundingClientRect().top)
94
+ / (element.currentCSSZoom ?? 1) + element.scrollTop);
94
95
  table.styleSheet.push(`
95
96
  ${table.selector} > thead > tr:nth-child(${counter}) > * {
96
- top: ${this.position(Math.ceil(top), counter, row.firstElementChild, 'top')};
97
+ top: ${this.position(top, counter, row.firstElementChild, 'top')};
97
98
  }
98
99
  `);
99
- counter++;
100
- });
100
+ }
101
101
  const zIndex = this.full ? `z-index: ${this.full.row};` : '';
102
102
  table.styleSheet.push(`
103
103
  ${table.selector} > thead > tr > * {
package/package.json CHANGED
@@ -16,6 +16,7 @@
16
16
  "files": [
17
17
  "LICENSE",
18
18
  "column-add.css",
19
+ "column-resize.css",
19
20
  "README.md",
20
21
  "**/*.d.ts",
21
22
  "**/*.js",
@@ -51,7 +52,7 @@
51
52
  "url": "git+https://github.com/itrocks-ts/table.git"
52
53
  },
53
54
  "scripts": {
54
- "build": "tsc && sass --no-source-map src/column-add.scss:column-add.css && node ../prepare-module/prepare-module.js && tsc -p tsconfig.demo.json && sass --no-source-map demo:demo"
55
+ "build": "tsc && sass --no-source-map src/column-add.scss:column-add.css src/column-resize.scss:column-resize.css && node ../prepare-module/prepare-module.js && tsc -p tsconfig.demo.json && sass --no-source-map demo:demo"
55
56
  },
56
- "version": "0.10.0"
57
+ "version": "0.13.0"
57
58
  }