@itrocks/table 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,18 +3,15 @@ import { TableColumnReorder } from './column-reorder.js';
3
3
  import { TableFreeze } from './freeze.js';
4
4
  export class TableColumnReorderFreeze extends Plugin {
5
5
  init() {
6
- const reorder = this.of.plugins.TableColumnReorder;
7
6
  const freeze = this.of.plugins.TableFreeze;
8
- if (!(reorder instanceof TableColumnReorder) || !(freeze instanceof TableFreeze))
7
+ const reorder = this.of.plugins.TableColumnReorder;
8
+ if (!(freeze instanceof TableFreeze) || !(reorder instanceof TableColumnReorder))
9
9
  return;
10
10
  if (reorder.options.isReorderable !== undefined)
11
11
  return;
12
12
  reorder.options.isReorderable = header => {
13
13
  const index = this.of.cellColumnNumber(header);
14
- console.log('freeze', freeze);
15
- const reorderable = (index >= freeze.leftColumnCount) && (index < freeze.columns.length - freeze.rightColumnCount);
16
- console.debug('reorderable of', index, '=', reorderable ? 'true' : 'false');
17
- return reorderable;
14
+ return (index >= freeze.leftColumnCount) && (index < freeze.columns.length - freeze.rightColumnCount);
18
15
  };
19
16
  }
20
17
  }
@@ -2,67 +2,49 @@ import { Plugin } from '../plugin/plugin.js';
2
2
  import { PluginOptions } from '../plugin/plugin.js';
3
3
  import { Table } from './table.js';
4
4
  type Direction = -1 | 0 | 1;
5
- interface ArmedState {
6
- header: HTMLTableCellElement;
7
- lastX: number;
8
- pointerId: number;
9
- startX: number;
10
- status: 'armed';
11
- }
12
- interface Grid {
13
- colGroup?: HTMLTableColElement;
14
- columnCount: number;
15
- rows: HTMLTableRowElement[];
16
- sourceCells: HTMLTableCellElement[];
17
- sourceCol?: HTMLTableColElement;
18
- }
19
- interface DraggingState extends Grid {
20
- currentIndex: number;
5
+ interface Drag extends Press {
6
+ cells: HTMLTableCellElement[];
7
+ col?: HTMLTableColElement;
8
+ count: number;
21
9
  direction: Direction;
22
- header: HTMLTableCellElement;
23
- initialIndex: number;
24
- lastFrameTime?: number;
25
- maximumIndex: number;
26
- minimumIndex: number;
27
- pointerId: number;
28
- pointerX: number;
29
- status: 'dragging';
30
- scrollContainer?: HTMLElement;
10
+ index: number;
11
+ initial: number;
12
+ maximum: number;
13
+ minimum: number;
14
+ scroll?: HTMLElement;
15
+ time?: number;
31
16
  }
32
- type ReorderState = ArmedState | DraggingState;
33
- export declare class TableColumnReorderOptions extends PluginOptions {
34
- isReorderable?: (header: HTMLTableCellElement) => boolean;
35
- onReorder?: (header: HTMLTableCellElement) => void;
36
- threshold: number;
17
+ interface Press {
18
+ header: HTMLTableCellElement;
19
+ id: number;
20
+ origin: number;
21
+ x: number;
37
22
  }
38
23
  export declare class TableColumnReorder extends Plugin<Table, TableColumnReorderOptions> {
39
- protected animationFrame?: number;
40
- protected clickTimer?: number;
41
- protected state?: ReorderState;
24
+ protected drag?: Drag;
25
+ protected frame?: number;
26
+ protected press?: Press;
42
27
  protected suppressClick: boolean;
28
+ protected animate(time: number): void;
29
+ protected colGroups(): HTMLTableColElement[];
43
30
  defaultOptions(): TableColumnReorderOptions;
44
- init(): void;
45
- protected autoScroll(state: DraggingState, time: number): Direction;
46
- protected clamp(value: number): number;
47
- protected closestHorizontalScrollable(): HTMLElement | undefined;
48
- protected collectGrid(header: HTMLTableCellElement): Grid | undefined;
49
- protected destroy(): void;
50
31
  protected finish(commit: boolean): void;
51
- protected headerAtPointer(state: DraggingState, direction: Direction): number;
52
- protected moveColumn(state: DraggingState, targetIndex: number): boolean;
53
- protected onAnimationFrame(time: number): void;
54
- protected onClick(event: MouseEvent): void;
55
- protected onKeyDown(event: KeyboardEvent): void;
56
- protected onLostPointerCapture(event: PointerEvent): void;
57
- protected onPointerCancel(event: PointerEvent): void;
58
- protected onPointerDown(event: PointerEvent): void;
59
- protected onPointerMove(event: PointerEvent): void;
60
- protected onPointerUp(event: PointerEvent): void;
32
+ init(): void;
33
+ protected isCurrent(drag: Drag): boolean;
34
+ protected move(drag: Drag, targetIndex: number): void;
35
+ protected onPointer(event: PointerEvent): void;
61
36
  protected requestFrame(): void;
62
- protected startDragging(armed: ArmedState, pointerX: number): boolean;
63
- protected structureIsCurrent(state: DraggingState): boolean;
64
- protected suppressNextClick(): void;
65
- protected tableRows(): HTMLTableRowElement[];
37
+ protected rows(): HTMLTableRowElement[];
38
+ protected scroll(drag: Drag, time: number): Direction;
39
+ protected scrollContainer(): HTMLElement | undefined;
40
+ protected start(press: Press, x: number): void;
41
+ protected target(drag: Drag, direction: Direction): number;
66
42
  protected triggerRow(): HTMLTableRowElement;
43
+ protected updatePointer(x: number): void;
44
+ }
45
+ export declare class TableColumnReorderOptions extends PluginOptions {
46
+ isReorderable?: (header: HTMLTableCellElement) => boolean;
47
+ onReorder?: (header: HTMLTableCellElement) => void;
48
+ threshold: number;
67
49
  }
68
50
  export {};
package/column-reorder.js CHANGED
@@ -1,423 +1,316 @@
1
1
  import { Plugin } from '../plugin/plugin.js';
2
2
  import { PluginOptions } from '../plugin/plugin.js';
3
- const interactiveSelector = [
4
- 'a',
5
- 'button',
6
- 'input',
7
- 'select',
8
- 'textarea',
9
- '[contenteditable]:not([contenteditable="false"])',
10
- '[draggable="true"]'
11
- ].join(', ');
3
+ const clamp = (value) => Math.max(0, Math.min(1, value));
4
+ const interactiveSelector = 'a, button, input, select, textarea, '
5
+ + '[contenteditable]:not([contenteditable="false"]), [draggable="true"]';
12
6
  const maxScrollSpeed = 800;
13
7
  const penetration = 10;
8
+ const rowSelector = ':scope > tbody > tr, :scope > tfoot > tr, :scope > thead > tr';
14
9
  const scrollZone = 50;
15
- let cursorOwner;
16
- export class TableColumnReorderOptions extends PluginOptions {
17
- isReorderable;
18
- onReorder;
19
- threshold = 10;
20
- }
10
+ let activeDrag;
21
11
  export class TableColumnReorder extends Plugin {
22
- animationFrame;
23
- clickTimer;
24
- state;
12
+ drag;
13
+ frame;
14
+ press;
25
15
  suppressClick = false;
16
+ animate(time) {
17
+ this.frame = undefined;
18
+ const drag = this.drag;
19
+ if (!drag)
20
+ return;
21
+ if (!this.isCurrent(drag)) {
22
+ this.finish(false);
23
+ return;
24
+ }
25
+ const pointerDirection = drag.direction;
26
+ drag.direction = 0;
27
+ const scrollDirection = this.scroll(drag, time);
28
+ const direction = pointerDirection || scrollDirection;
29
+ const target = direction ? this.target(drag, direction) : drag.index;
30
+ if (target !== drag.index)
31
+ this.move(drag, target);
32
+ if (scrollDirection)
33
+ this.requestFrame();
34
+ }
35
+ colGroups() {
36
+ return Array.from(this.of.element.children).filter(element => element.tagName === 'COLGROUP');
37
+ }
26
38
  defaultOptions() {
27
39
  return new TableColumnReorderOptions();
28
40
  }
29
- init() {
30
- const table = this.of;
31
- table.styleSheet.push(`
32
- html.column-reorder,
33
- html.column-reorder * {
34
- cursor: ew-resize !important;
35
- }
36
- `);
37
- table.addEventListener(table.element, 'click', event => this.onClick(event), { capture: true });
38
- table.addEventListener(document, 'keydown', event => this.onKeyDown(event), { capture: true });
39
- table.addEventListener(table.element, 'lostpointercapture', event => this.onLostPointerCapture(event));
40
- table.addEventListener(document, 'pointercancel', event => this.onPointerCancel(event), { capture: true });
41
- table.addEventListener(table.element, 'pointerdown', event => this.onPointerDown(event));
42
- table.addEventListener(document, 'pointermove', event => this.onPointerMove(event), { capture: true });
43
- table.addEventListener(document, 'pointerup', event => this.onPointerUp(event), { capture: true });
44
- table.onReset.push(() => this.destroy());
45
- }
46
- autoScroll(state, time) {
47
- const container = state.scrollContainer;
48
- if (!container)
49
- return 0;
50
- const rect = container.getBoundingClientRect();
51
- const leftProximity = 1 - this.clamp((state.pointerX - rect.left) / scrollZone);
52
- const rightProximity = 1 - this.clamp((rect.right - state.pointerX) / scrollZone);
53
- let direction = 0;
54
- let proximity = 0;
55
- if ((leftProximity > 0) || (rightProximity > 0)) {
56
- direction = (rightProximity > leftProximity) ? 1 : -1;
57
- proximity = Math.max(leftProximity, rightProximity);
58
- }
59
- if (!direction) {
60
- state.lastFrameTime = undefined;
61
- return 0;
62
- }
63
- const previousTime = state.lastFrameTime;
64
- state.lastFrameTime = time;
65
- if (previousTime === undefined)
66
- return direction;
67
- const previousScroll = container.scrollLeft;
68
- const elapsed = Math.max(0, time - previousTime) / 1000;
69
- container.scrollLeft += direction * maxScrollSpeed * proximity * elapsed;
70
- if (container.scrollLeft === previousScroll) {
71
- state.lastFrameTime = undefined;
72
- return 0;
41
+ finish(commit) {
42
+ this.press = undefined;
43
+ if (this.frame !== undefined)
44
+ cancelAnimationFrame(this.frame);
45
+ this.frame = undefined;
46
+ const drag = this.drag;
47
+ if (!drag)
48
+ return;
49
+ const changed = drag.index !== drag.initial;
50
+ const current = this.isCurrent(drag);
51
+ if (!current)
52
+ commit = false;
53
+ if (!commit && changed && current)
54
+ this.move(drag, drag.initial);
55
+ for (const cell of drag.cells)
56
+ cell.classList.remove('column-reorder');
57
+ if (activeDrag === this) {
58
+ activeDrag = undefined;
59
+ document.documentElement.classList.remove('column-reorder');
73
60
  }
74
- return direction;
61
+ this.drag = undefined;
62
+ if (this.of.element.hasPointerCapture(drag.id))
63
+ this.of.element.releasePointerCapture(drag.id);
64
+ if (commit && changed)
65
+ this.options.onReorder?.(drag.header);
75
66
  }
76
- clamp(value) {
77
- return Math.max(0, Math.min(1, value));
67
+ init() {
68
+ const table = this.of;
69
+ table.addEventListener(table.element, 'click', event => {
70
+ if (!this.suppressClick)
71
+ return;
72
+ this.suppressClick = false;
73
+ event.preventDefault();
74
+ event.stopImmediatePropagation();
75
+ }, { capture: true });
76
+ table.addEventListener(document, 'keydown', event => {
77
+ if ((event.key !== 'Escape') || !this.drag)
78
+ return;
79
+ event.preventDefault();
80
+ event.stopImmediatePropagation();
81
+ this.finish(false);
82
+ }, { capture: true });
83
+ table.addEventListener(table.element, 'lostpointercapture', event => this.onPointer(event));
84
+ table.addEventListener(document, 'pointercancel', event => this.onPointer(event), { capture: true });
85
+ table.addEventListener(table.element, 'pointerdown', event => this.onPointer(event));
86
+ table.addEventListener(document, 'pointermove', event => this.onPointer(event), { capture: true });
87
+ table.addEventListener(document, 'pointerup', event => this.onPointer(event), { capture: true });
88
+ table.onReset.push(() => {
89
+ this.finish(false);
90
+ this.suppressClick = false;
91
+ });
78
92
  }
79
- closestHorizontalScrollable() {
80
- let element = this.of.element;
81
- while (element) {
82
- const overflow = getComputedStyle(element).overflowX;
83
- if (['auto', 'overlay', 'scroll'].includes(overflow) && (element.scrollWidth > element.clientWidth)) {
84
- return element;
85
- }
86
- element = element.parentElement;
87
- }
88
- return undefined;
93
+ isCurrent(drag) {
94
+ const rows = this.rows();
95
+ if ((drag.header.parentElement !== this.triggerRow()) || (rows.length !== drag.cells.length))
96
+ return false;
97
+ if (rows.some((row, index) => (row !== drag.cells[index].parentElement)
98
+ || (row.cells.length !== drag.count) || (row.cells[drag.index] !== drag.cells[index])))
99
+ return false;
100
+ const groups = this.colGroups();
101
+ if (!drag.col)
102
+ return !groups.length;
103
+ return (groups.length === 1) && (groups[0] === drag.col.parentElement)
104
+ && (groups[0].children.length === drag.count) && (groups[0].children[drag.index] === drag.col);
89
105
  }
90
- collectGrid(header) {
91
- const headerRow = this.triggerRow();
92
- const columnCount = headerRow?.cells.length ?? 0;
93
- if (!headerRow || !columnCount || (header.parentElement !== headerRow))
94
- return undefined;
95
- const initialIndex = Array.from(headerRow.cells).indexOf(header);
96
- const rows = this.tableRows();
97
- if ((initialIndex < 0) || !rows.length)
98
- return undefined;
99
- for (const row of rows) {
100
- if ((row.cells.length !== columnCount) || Array.from(row.cells).some(cell => {
101
- return (cell.colSpan !== 1) || (cell.rowSpan !== 1);
102
- })) {
103
- return undefined;
104
- }
106
+ move(drag, targetIndex) {
107
+ const after = drag.index < targetIndex;
108
+ for (const cell of drag.cells) {
109
+ const target = cell.parentElement.cells[targetIndex];
110
+ after ? target.after(cell) : target.before(cell);
105
111
  }
106
- const colGroups = Array.from(this.of.element.children).filter(element => element.tagName === 'COLGROUP');
107
- if (colGroups.length > 1)
108
- return undefined;
109
- const colGroup = colGroups[0];
110
- let sourceCol;
111
- if (colGroup) {
112
- const columns = Array.from(colGroup.children);
113
- if ((columns.length !== columnCount)
114
- || columns.some(column => (column.tagName !== 'COL') || (column.span !== 1))) {
115
- return undefined;
116
- }
117
- sourceCol = columns[initialIndex];
112
+ if (drag.col) {
113
+ const target = drag.col.parentElement.children[targetIndex];
114
+ after ? target.after(drag.col) : target.before(drag.col);
118
115
  }
119
- return {
120
- colGroup,
121
- columnCount,
122
- rows,
123
- sourceCells: rows.map(row => row.cells[initialIndex]),
124
- sourceCol
125
- };
116
+ drag.index = targetIndex;
126
117
  }
127
- destroy() {
128
- this.finish(false);
129
- if (this.clickTimer !== undefined) {
130
- clearTimeout(this.clickTimer);
131
- this.clickTimer = undefined;
118
+ onPointer(event) {
119
+ if (event.type === 'pointerdown') {
120
+ if (activeDrag || this.drag || this.press || (event.button !== 0) || !event.isPrimary)
121
+ return;
122
+ if (!(event.target instanceof Element))
123
+ return;
124
+ const header = event.target.closest('th, td');
125
+ const interactive = event.target.closest(interactiveSelector);
126
+ if (!header
127
+ || (header.closest('table') !== this.of.element)
128
+ || (header.parentElement !== this.triggerRow())
129
+ || (interactive && header.contains(interactive)))
130
+ return;
131
+ this.press = { header, id: event.pointerId, origin: event.clientX, x: event.clientX };
132
+ return;
132
133
  }
133
- this.suppressClick = false;
134
- }
135
- finish(commit) {
136
- const state = this.state;
137
- if (!state)
134
+ const state = this.drag ?? this.press;
135
+ if (!state || (event.pointerId !== state.id))
136
+ return;
137
+ if (event.type === 'lostpointercapture') {
138
+ if (this.drag)
139
+ this.finish(false);
138
140
  return;
139
- if (this.animationFrame !== undefined) {
140
- cancelAnimationFrame(this.animationFrame);
141
- this.animationFrame = undefined;
142
141
  }
143
- let changed = false;
144
- if (state.status === 'dragging') {
145
- if (!this.structureIsCurrent(state))
146
- commit = false;
147
- changed = state.currentIndex !== state.initialIndex;
148
- if (!commit && changed)
149
- this.moveColumn(state, state.initialIndex);
150
- for (const cell of state.sourceCells)
151
- cell.classList.remove('column-reorder');
152
- if (cursorOwner === this) {
153
- cursorOwner = undefined;
154
- document.documentElement.classList.remove('column-reorder');
142
+ if (event.type === 'pointercancel') {
143
+ if (this.drag) {
144
+ event.preventDefault();
145
+ event.stopImmediatePropagation();
155
146
  }
147
+ this.finish(false);
148
+ return;
156
149
  }
157
- this.state = undefined;
158
- if ((state.status === 'dragging') && this.of.element.hasPointerCapture(state.pointerId)) {
159
- this.of.element.releasePointerCapture(state.pointerId);
160
- }
161
- if (commit && changed && (state.status === 'dragging'))
162
- this.options.onReorder?.(state.header);
163
- }
164
- headerAtPointer(state, direction) {
165
- const headers = Array.from(this.triggerRow()?.cells ?? []);
166
- const sourceRect = headers[state.currentIndex]?.getBoundingClientRect();
167
- if (!sourceRect)
168
- return state.currentIndex;
169
- const sourceCenter = (sourceRect.left + sourceRect.right) / 2;
170
- let distance = 0;
171
- let target = state.currentIndex;
172
- for (let index = state.minimumIndex; index <= state.maximumIndex; index++) {
173
- if (index === state.currentIndex)
174
- continue;
175
- const rect = headers[index].getBoundingClientRect();
176
- const center = (rect.left + rect.right) / 2;
177
- if ((direction > 0) && (center > sourceCenter) && (state.pointerX >= rect.left + penetration)) {
178
- const candidateDistance = center - sourceCenter;
179
- if (candidateDistance > distance) {
180
- distance = candidateDistance;
181
- target = index;
182
- }
150
+ if (event.type === 'pointerup') {
151
+ if (!this.drag) {
152
+ this.press = undefined;
153
+ return;
183
154
  }
184
- if ((direction < 0) && (center < sourceCenter) && (state.pointerX <= rect.right - penetration)) {
185
- const candidateDistance = sourceCenter - center;
186
- if (candidateDistance > distance) {
187
- distance = candidateDistance;
188
- target = index;
189
- }
155
+ event.preventDefault();
156
+ event.stopImmediatePropagation();
157
+ this.updatePointer(event.clientX);
158
+ if ((this.frame !== undefined) || this.drag.direction) {
159
+ if (this.frame !== undefined)
160
+ cancelAnimationFrame(this.frame);
161
+ this.frame = undefined;
162
+ this.animate(performance.now());
190
163
  }
191
- }
192
- return target;
193
- }
194
- moveColumn(state, targetIndex) {
195
- if ((targetIndex === state.currentIndex) || !this.structureIsCurrent(state)) {
196
- return targetIndex === state.currentIndex;
197
- }
198
- const moveAfter = state.currentIndex < targetIndex;
199
- for (let index = 0; index < state.rows.length; index++) {
200
- const source = state.sourceCells[index];
201
- const target = state.rows[index].cells[targetIndex];
202
- moveAfter ? target.after(source) : target.before(source);
203
- }
204
- if (state.sourceCol && state.colGroup) {
205
- const target = state.colGroup.children[targetIndex];
206
- moveAfter ? target.after(state.sourceCol) : target.before(state.sourceCol);
207
- }
208
- state.currentIndex = targetIndex;
209
- return true;
210
- }
211
- onAnimationFrame(time) {
212
- this.animationFrame = undefined;
213
- const state = this.state;
214
- if (!state || (state.status !== 'dragging'))
215
- return;
216
- if (!this.structureIsCurrent(state)) {
217
- this.finish(false);
164
+ this.suppressClick = true;
165
+ setTimeout(() => this.suppressClick = false);
166
+ this.finish(true);
218
167
  return;
219
168
  }
220
- const pointerDirection = state.direction;
221
- state.direction = 0;
222
- const scrollDirection = this.autoScroll(state, time);
223
- const direction = pointerDirection || scrollDirection;
224
- if (direction) {
225
- const targetIndex = this.headerAtPointer(state, direction);
226
- if (targetIndex !== state.currentIndex)
227
- this.moveColumn(state, targetIndex);
169
+ if (!this.drag) {
170
+ if (Math.abs(event.clientX - state.origin) < Math.max(0, this.options.threshold)) {
171
+ state.x = event.clientX;
172
+ return;
173
+ }
174
+ this.press = undefined;
175
+ this.start(state, event.clientX);
228
176
  }
229
- if (scrollDirection)
230
- this.requestFrame();
231
- }
232
- onClick(event) {
233
- if (!this.suppressClick)
177
+ if (!this.drag)
234
178
  return;
235
- this.suppressClick = false;
236
179
  event.preventDefault();
237
- event.stopImmediatePropagation();
180
+ this.updatePointer(event.clientX);
238
181
  }
239
- onKeyDown(event) {
240
- if ((event.key !== 'Escape') || (this.state?.status !== 'dragging'))
241
- return;
242
- event.preventDefault();
243
- event.stopImmediatePropagation();
244
- this.finish(false);
182
+ requestFrame() {
183
+ if (this.frame === undefined)
184
+ this.frame = requestAnimationFrame(time => this.animate(time));
245
185
  }
246
- onLostPointerCapture(event) {
247
- if ((this.state?.status !== 'dragging') || (event.pointerId !== this.state.pointerId))
248
- return;
249
- this.finish(false);
186
+ rows() {
187
+ return Array.from(this.of.element.querySelectorAll(rowSelector));
250
188
  }
251
- onPointerCancel(event) {
252
- if (!this.state || (event.pointerId !== this.state.pointerId))
253
- return;
254
- if (this.state.status === 'dragging') {
255
- event.preventDefault();
256
- event.stopImmediatePropagation();
189
+ scroll(drag, time) {
190
+ const container = drag.scroll;
191
+ if (!container)
192
+ return 0;
193
+ const rect = container.getBoundingClientRect();
194
+ const left = 1 - clamp((drag.x - rect.left) / scrollZone);
195
+ const right = 1 - clamp((rect.right - drag.x) / scrollZone);
196
+ const direction = ((left > 0) || (right > 0)) ? ((right > left) ? 1 : -1) : 0;
197
+ if (!direction) {
198
+ drag.time = undefined;
199
+ return 0;
257
200
  }
258
- this.finish(false);
259
- }
260
- onPointerDown(event) {
261
- if (this.state || cursorOwner || !event.isPrimary || (event.button !== 0))
262
- return;
263
- if (!(event.target instanceof Element))
264
- return;
265
- const header = event.target.closest('th, td');
266
- const row = this.triggerRow();
267
- if (!header || !row || (header.parentElement !== row) || (header.closest('table') !== this.of.element))
268
- return;
269
- const interactive = event.target.closest(interactiveSelector);
270
- if (interactive && header.contains(interactive))
271
- return;
272
- this.state = {
273
- header,
274
- lastX: event.clientX,
275
- pointerId: event.pointerId,
276
- startX: event.clientX,
277
- status: 'armed'
278
- };
201
+ const previousTime = drag.time;
202
+ drag.time = time;
203
+ if (previousTime === undefined)
204
+ return direction;
205
+ const previousScroll = container.scrollLeft;
206
+ container.scrollLeft += direction * maxScrollSpeed * Math.max(left, right) * (time - previousTime) / 1000;
207
+ if (container.scrollLeft !== previousScroll)
208
+ return direction;
209
+ drag.time = undefined;
210
+ return 0;
279
211
  }
280
- onPointerMove(event) {
281
- const state = this.state;
282
- if (!state || (event.pointerId !== state.pointerId))
283
- return;
284
- if (state.status === 'armed') {
285
- if (Math.abs(event.clientX - state.startX) < Math.max(0, this.options.threshold)) {
286
- state.lastX = event.clientX;
287
- return;
212
+ scrollContainer() {
213
+ let element = this.of.element;
214
+ while (element) {
215
+ if (['auto', 'overlay', 'scroll'].includes(getComputedStyle(element).overflowX)
216
+ && (element.scrollWidth > element.clientWidth)) {
217
+ return element;
288
218
  }
289
- if (!this.startDragging(state, event.clientX))
290
- return;
291
- }
292
- const dragging = this.state;
293
- if (!dragging || (dragging.status !== 'dragging'))
294
- return;
295
- event.preventDefault();
296
- if (event.clientX !== dragging.pointerX) {
297
- dragging.direction = (event.clientX > dragging.pointerX) ? 1 : -1;
298
- dragging.pointerX = event.clientX;
299
- this.requestFrame();
219
+ element = element.parentElement;
300
220
  }
221
+ return undefined;
301
222
  }
302
- onPointerUp(event) {
303
- if (!this.state || (event.pointerId !== this.state.pointerId))
223
+ start(press, x) {
224
+ if (activeDrag)
304
225
  return;
305
- if (this.state.status === 'armed') {
306
- this.finish(false);
226
+ const row = this.triggerRow();
227
+ const headers = Array.from(row?.cells ?? []);
228
+ const initial = headers.indexOf(press.header);
229
+ const rows = this.rows();
230
+ if ((initial < 0)
231
+ || !rows.length
232
+ || rows.some(row => (row.cells.length !== headers.length)
233
+ || Array.from(row.cells).some(cell => (cell.colSpan !== 1) || (cell.rowSpan !== 1))))
307
234
  return;
308
- }
309
- event.preventDefault();
310
- event.stopImmediatePropagation();
311
- const dragging = this.state;
312
- if (event.clientX !== dragging.pointerX) {
313
- dragging.direction = (event.clientX > dragging.pointerX) ? 1 : -1;
314
- dragging.pointerX = event.clientX;
315
- }
316
- if ((this.animationFrame !== undefined) || dragging.direction) {
317
- if (this.animationFrame !== undefined) {
318
- cancelAnimationFrame(this.animationFrame);
319
- this.animationFrame = undefined;
320
- }
321
- this.onAnimationFrame(performance.now());
322
- }
323
- this.suppressNextClick();
324
- this.finish(true);
325
- }
326
- requestFrame() {
327
- if (this.animationFrame !== undefined)
235
+ const groups = this.colGroups();
236
+ if (groups.length > 1)
237
+ return;
238
+ const columns = Array.from(groups[0]?.children ?? []);
239
+ if (groups.length
240
+ && ((columns.length !== headers.length)
241
+ || columns.some(column => (column.tagName !== 'COL') || (column.span !== 1))))
328
242
  return;
329
- this.animationFrame = requestAnimationFrame(time => this.onAnimationFrame(time));
330
- }
331
- startDragging(armed, pointerX) {
332
- if (cursorOwner) {
333
- this.finish(false);
334
- return false;
335
- }
336
- const grid = this.collectGrid(armed.header);
337
- if (!grid) {
338
- this.finish(false);
339
- return false;
340
- }
341
- const headerRow = this.triggerRow();
342
- const headers = Array.from(headerRow.cells);
343
- const initialIndex = headers.indexOf(armed.header);
344
243
  const reorderable = headers.map(header => this.options.isReorderable?.(header) ?? true);
345
- if ((initialIndex < 0) || !reorderable[initialIndex]) {
346
- this.finish(false);
347
- return false;
348
- }
349
- let minimumIndex = initialIndex;
350
- let maximumIndex = initialIndex;
351
- while ((minimumIndex > 0) && reorderable[minimumIndex - 1])
352
- minimumIndex--;
353
- while ((maximumIndex < reorderable.length - 1) && reorderable[maximumIndex + 1])
354
- maximumIndex++;
244
+ if (!reorderable[initial])
245
+ return;
246
+ let maximum = initial;
247
+ let minimum = initial;
248
+ while ((maximum < headers.length - 1) && reorderable[maximum + 1])
249
+ maximum++;
250
+ while ((minimum > 0) && reorderable[minimum - 1])
251
+ minimum--;
355
252
  try {
356
- this.of.element.setPointerCapture(armed.pointerId);
253
+ this.of.element.setPointerCapture(press.id);
357
254
  }
358
255
  catch {
359
- this.finish(false);
360
- return false;
256
+ return;
361
257
  }
362
- const direction = Math.sign(pointerX - armed.lastX);
363
- this.state = {
364
- ...grid,
365
- currentIndex: initialIndex,
366
- direction,
367
- header: armed.header,
368
- initialIndex,
369
- maximumIndex,
370
- minimumIndex,
371
- pointerId: armed.pointerId,
372
- pointerX,
373
- scrollContainer: this.closestHorizontalScrollable(),
374
- status: 'dragging'
258
+ const drag = {
259
+ ...press,
260
+ cells: rows.map(row => row.cells[initial]),
261
+ col: columns[initial],
262
+ count: headers.length,
263
+ direction: Math.sign(x - press.x),
264
+ index: initial,
265
+ initial,
266
+ maximum,
267
+ minimum,
268
+ scroll: this.scrollContainer(),
269
+ x
375
270
  };
376
- cursorOwner = this;
271
+ this.drag = drag;
272
+ activeDrag = this;
377
273
  document.documentElement.classList.add('column-reorder');
378
- for (const cell of grid.sourceCells)
274
+ for (const cell of drag.cells)
379
275
  cell.classList.add('column-reorder');
380
276
  this.requestFrame();
381
- return true;
382
277
  }
383
- structureIsCurrent(state) {
384
- const rows = this.tableRows();
385
- if ((this.triggerRow() !== state.header.parentElement) || (state.rows.length !== rows.length)) {
386
- return false;
387
- }
388
- for (let index = 0; index < state.rows.length; index++) {
389
- const row = rows[index];
390
- if ((row !== state.rows[index])
391
- || (row.cells.length !== state.columnCount)
392
- || (row.cells[state.currentIndex] !== state.sourceCells[index])) {
393
- return false;
278
+ target(drag, direction) {
279
+ const headers = Array.from(this.triggerRow()?.cells ?? []);
280
+ const source = headers[drag.index]?.getBoundingClientRect();
281
+ if (!source)
282
+ return drag.index;
283
+ const sourceCenter = (source.left + source.right) / 2;
284
+ let distance = 0;
285
+ let target = drag.index;
286
+ for (let index = drag.minimum; index <= drag.maximum; index++) {
287
+ if (index === drag.index)
288
+ continue;
289
+ const rect = headers[index].getBoundingClientRect();
290
+ const delta = (rect.left + rect.right) / 2 - sourceCenter;
291
+ const edge = direction > 0 ? rect.left : rect.right;
292
+ if ((Math.sign(delta) === direction) && (direction * (drag.x - edge) >= penetration)
293
+ && (Math.abs(delta) > distance)) {
294
+ distance = Math.abs(delta);
295
+ target = index;
394
296
  }
395
297
  }
396
- const colGroups = Array.from(this.of.element.children).filter(element => element.tagName === 'COLGROUP');
397
- if (!state.colGroup)
398
- return colGroups.length === 0;
399
- return (colGroups.length === 1)
400
- && (colGroups[0] === state.colGroup)
401
- && (state.colGroup.children.length === state.columnCount)
402
- && (state.colGroup.children[state.currentIndex] === state.sourceCol);
403
- }
404
- suppressNextClick() {
405
- this.suppressClick = true;
406
- if (this.clickTimer !== undefined)
407
- clearTimeout(this.clickTimer);
408
- this.clickTimer = window.setTimeout(() => {
409
- this.clickTimer = undefined;
410
- this.suppressClick = false;
411
- });
412
- }
413
- tableRows() {
414
- return Array.from(this.of.element.querySelectorAll([
415
- ':scope > thead > tr',
416
- ':scope > tbody > tr',
417
- ':scope > tfoot > tr'
418
- ].join(', ')));
298
+ return target;
419
299
  }
420
300
  triggerRow() {
421
301
  return this.of.element.tHead?.rows[0] ?? this.of.element.tBodies[0]?.rows[0];
422
302
  }
303
+ updatePointer(x) {
304
+ const drag = this.drag;
305
+ if (!drag || (x === drag.x))
306
+ return;
307
+ drag.direction = Math.sign(x - drag.x);
308
+ drag.x = x;
309
+ this.requestFrame();
310
+ }
311
+ }
312
+ export class TableColumnReorderOptions extends PluginOptions {
313
+ isReorderable;
314
+ onReorder;
315
+ threshold = 10;
423
316
  }
package/package.json CHANGED
@@ -52,5 +52,5 @@
52
52
  "scripts": {
53
53
  "build": "tsc && sass --no-source-map demo:demo && ../prepare-module/prepare-module.js"
54
54
  },
55
- "version": "0.2.0"
55
+ "version": "0.2.1"
56
56
  }