@itrocks/table 0.8.2 → 0.11.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
@@ -54,6 +54,26 @@ const table = tableByElement(element)
54
54
  For more advanced usage (plugins, styling, demos), check out the
55
55
  [GitHub demo folder](https://github.com/itrocks-ts/table/tree/master/demo).
56
56
 
57
+ ### Form controls in cells
58
+
59
+ Use `TableEdit` with a `control` callback to select existing controls already rendered in the cells.
60
+ For example, a form can render an input in its first column and a textarea in its second column.
61
+
62
+ ```ts
63
+ import { TableEdit } from '@itrocks/table/edit.js'
64
+ import { tableBySelector } from '@itrocks/table/table.js'
65
+
66
+ tableBySelector('.js-form-table', {
67
+ plugins: [new TableEdit({
68
+ control: (cell, column) => cell.querySelector<HTMLElement>(column === 0 ? 'input:not([type=hidden])' : 'textarea')
69
+ })]
70
+ })
71
+ ```
72
+
73
+ The callback receives the cell and its zero-based index in the row when the cell is selected or receives focus.
74
+ Return its focusable control to keep it in the form, `null` to skip the cell, or `undefined` to use the text editor.
75
+ Clicking the cell background focuses its control and places the caret at the end of text fields.
76
+
57
77
  ## API
58
78
 
59
79
  The public API is intentionally small and focuses on a single `Table`
@@ -225,6 +245,19 @@ Finds all tables matching the CSS selector and returns the corresponding
225
245
  - Implement custom plugins on top of `HasPlugins<Table>` to add domain‑
226
246
  specific features (validation, inline actions, totals rows, etc.).
227
247
 
248
+ ## Resizing columns
249
+
250
+ Include `column-resize.css` and add `TableColumnResize` from `@itrocks/table/column-resize.js` to a table's plugins.
251
+ Use a rectangular table with an unspanned first header row. Drag the edge of a header cell to change its width and
252
+ double-click it to restore automatic sizing. Columns marked with `data-freeze` on the header or corresponding
253
+ `col` are excluded.
254
+
255
+ Use `data-column-width` on a header to initialise its width in pixels. The plugin tracks widths across header moves
256
+ and can use an `identify(header)` callback to preserve them across header replacements. Use `isResizable(header)`
257
+ to restrict eligible columns and `isInResizeZone(header, clientY)` to restrict the vertical area within a header cell.
258
+ `onChange(header, width)` receives the final pixel width or `'auto'`. The consumer owns persistence.
259
+ Use `setWidth(header, width)` to apply a value programmatically without emitting a change.
260
+
228
261
  ## Adding columns
229
262
 
230
263
  Import the public browser entry and stylesheet. Configure `TableColumnAdd` after `TableColumnReorder` and any
@@ -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/edit.d.ts CHANGED
@@ -1,6 +1,10 @@
1
1
  import { HTMLEditableElement } from '../contenteditable/contenteditable.js';
2
2
  import { Plugin } from '../plugin/plugin.js';
3
+ import { PluginOptions } from '../plugin/plugin.js';
3
4
  import { Table } from './table.js';
5
+ declare class Options extends PluginOptions {
6
+ control?: (cell: HTMLTableCellElement, column: number) => HTMLElement | null | undefined;
7
+ }
4
8
  export declare class RangeCopy {
5
9
  commonAncestorContainer: Node;
6
10
  endContainer: Node;
@@ -10,11 +14,12 @@ export declare class RangeCopy {
10
14
  constructor(range: Range);
11
15
  toRange(): Range;
12
16
  }
13
- export declare class TableEdit extends Plugin<Table> {
17
+ export declare class TableEdit extends Plugin<Table, Options> {
14
18
  zIndex: string;
15
19
  init(): void;
16
20
  closestEditable(node: Node | Range | RangeCopy): HTMLDivElement;
17
21
  closestEditableCell(target: any): HTMLTableCellElement | undefined;
22
+ private controlOf;
18
23
  createEditable(selected: HTMLTableCellElement, selectedStyle: CSSStyleDeclaration): HTMLEditableElement;
19
24
  editable(): HTMLEditableElement | undefined;
20
25
  editableEndRange(node: Node | Range | RangeCopy): Range;
@@ -26,7 +31,7 @@ export declare class TableEdit extends Plugin<Table> {
26
31
  selectCell(cell: HTMLTableCellElement): void;
27
32
  /** Returns the currently selected cell, or undefined if no cell is selected */
28
33
  selected(): HTMLTableCellElement | undefined;
29
- /** Sets selected cell to this cell, and set its content to div[contenteditable] */
34
+ /** Selects the cell and focuses its control or opens the text editor. */
30
35
  setSelectedCell(cell: HTMLTableCellElement): void;
31
36
  protected setSelectedText(newText: string): void;
32
37
  setSelectionRange(range: Range): void;
@@ -34,3 +39,4 @@ export declare class TableEdit extends Plugin<Table> {
34
39
  textContentBeforeRange(): string;
35
40
  unselectCell(): void;
36
41
  }
42
+ export {};
package/edit.js CHANGED
@@ -1,6 +1,11 @@
1
1
  import { ContentEditable } from '../contenteditable/contenteditable.js';
2
2
  import { Plugin } from '../plugin/plugin.js';
3
+ import { PluginOptions } from '../plugin/plugin.js';
4
+ class Options extends PluginOptions {
5
+ control;
6
+ }
3
7
  let editable;
8
+ let editing;
4
9
  let selected;
5
10
  let selectedStyle;
6
11
  let selectedText;
@@ -38,7 +43,29 @@ export class TableEdit extends Plugin {
38
43
  const cell = this.closestEditableCell(event.target);
39
44
  if (!cell)
40
45
  return;
41
- this.selectCell(cell);
46
+ const control = this.controlOf(cell);
47
+ if (control === undefined) {
48
+ this.selectCell(cell);
49
+ }
50
+ else if (control && event.target === cell) {
51
+ event.preventDefault();
52
+ control.focus();
53
+ if (((control instanceof HTMLInputElement) || (control instanceof HTMLTextAreaElement))
54
+ && (control.selectionEnd !== null)) {
55
+ control.setSelectionRange(control.value.length, control.value.length);
56
+ }
57
+ }
58
+ });
59
+ table.addEventListener(table.element, 'focusin', event => {
60
+ const cell = this.closestEditableCell(event.target);
61
+ if (!cell || cell === selected || !this.controlOf(cell))
62
+ return;
63
+ this.unselectCell();
64
+ selected = cell;
65
+ });
66
+ table.onReset.push(() => {
67
+ if (selected?.closest('table') === table.element)
68
+ this.unselectCell();
42
69
  });
43
70
  }
44
71
  closestEditable(node) {
@@ -55,9 +82,13 @@ export class TableEdit extends Plugin {
55
82
  return parent;
56
83
  }
57
84
  closestEditableCell(target) {
58
- return (target instanceof Element)
59
- ? target.closest('table.itrocks > * > tr > *, table.itrocks > * > tr > *') ?? undefined
85
+ const cell = (target instanceof Element)
86
+ ? target.closest('td, th')
60
87
  : undefined;
88
+ return (cell?.closest('table') === this.of.element) ? (cell ?? undefined) : undefined;
89
+ }
90
+ controlOf(cell) {
91
+ return this.options.control?.(cell, cell.cellIndex);
61
92
  }
62
93
  createEditable(selected, selectedStyle) {
63
94
  const contentEditable = new ContentEditable(document.createElement('div'));
@@ -144,21 +175,27 @@ export class TableEdit extends Plugin {
144
175
  selected() {
145
176
  return selected;
146
177
  }
147
- /** Sets selected cell to this cell, and set its content to div[contenteditable] */
178
+ /** Selects the cell and focuses its control or opens the text editor. */
148
179
  setSelectedCell(cell) {
180
+ const control = this.controlOf(cell);
181
+ if (control === null)
182
+ return;
183
+ if (control) {
184
+ this.unselectCell();
185
+ selected = cell;
186
+ control.focus();
187
+ return;
188
+ }
149
189
  selected = cell;
150
190
  selectedText = selected.innerHTML;
151
191
  const originSelectedStyle = getComputedStyle(selected);
152
192
  selectedStyle = selected.getAttribute('style') ?? '';
153
193
  selected.setAttribute('contenteditable', '');
154
- setTimeout(() => {
155
- if (!selected) {
156
- console.error('cell:', cell);
157
- throw 'Unexpected failure: cell was unselected before contenteditable was effective';
158
- }
194
+ editing = setTimeout(() => {
195
+ editing = undefined;
159
196
  const range = new RangeCopy(this.getSelectionRange());
160
- selected.removeAttribute('contenteditable');
161
- editable = this.createEditable(selected, originSelectedStyle);
197
+ cell.removeAttribute('contenteditable');
198
+ editable = this.createEditable(cell, originSelectedStyle);
162
199
  this.setSelectionRange(this.inEditable(range) ? range.toRange() : this.editableFullRange(editable));
163
200
  });
164
201
  }
@@ -194,15 +231,22 @@ export class TableEdit extends Plugin {
194
231
  return this.rangeTextContent(previous);
195
232
  }
196
233
  unselectCell() {
197
- if (!editable || !selected)
234
+ if (!selected)
198
235
  return;
199
- editable.editable.deactivate();
200
- selected.innerHTML = editable.innerHTML;
201
- selectedStyle.length
202
- ? selected.setAttribute('style', selectedStyle)
203
- : selected.removeAttribute('style');
204
- this.setSelectedText(selected.innerHTML);
205
- editable = undefined;
236
+ if (editing !== undefined) {
237
+ clearTimeout(editing);
238
+ editing = undefined;
239
+ selected.removeAttribute('contenteditable');
240
+ }
241
+ if (editable) {
242
+ editable.editable.deactivate();
243
+ selected.innerHTML = editable.innerHTML;
244
+ selectedStyle.length
245
+ ? selected.setAttribute('style', selectedStyle)
246
+ : selected.removeAttribute('style');
247
+ this.setSelectedText(selected.innerHTML);
248
+ editable = undefined;
249
+ }
206
250
  selected = undefined;
207
251
  }
208
252
  }
@@ -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.8.2"
57
+ "version": "0.11.0"
57
58
  }