argus-table 0.2.2 → 0.3.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 +1 -1
- package/dist/argus-column.js +24 -1
- package/dist/argus-column.js.map +1 -1
- package/dist/argus-table.js +1024 -165
- package/dist/argus-table.js.map +1 -1
- package/dist/cdn/argus-table.js +74 -50
- package/dist/cdn/argus-table.js.map +1 -1
- package/dist/controllers/auto-width.js +11 -0
- package/dist/controllers/auto-width.js.map +1 -1
- package/dist/controllers/column-window.js +139 -0
- package/dist/controllers/column-window.js.map +1 -0
- package/dist/controllers/data-controller.js +9 -4
- package/dist/controllers/data-controller.js.map +1 -1
- package/dist/controllers/plugins.js +102 -0
- package/dist/controllers/plugins.js.map +1 -0
- package/dist/controllers/reorder-drag.js +9 -10
- package/dist/controllers/reorder-drag.js.map +1 -1
- package/dist/controllers/row-measure.js +121 -0
- package/dist/controllers/row-measure.js.map +1 -0
- package/dist/controllers/virtual-controller.js +311 -10
- package/dist/controllers/virtual-controller.js.map +1 -1
- package/dist/core/src/columns/column-order.js +14 -10
- package/dist/core/src/columns/column-order.js.map +1 -1
- package/dist/core/src/columns/resolve-columns.js +18 -4
- package/dist/core/src/columns/resolve-columns.js.map +1 -1
- package/dist/core/src/data/page-cache.js +4 -0
- package/dist/core/src/data/page-cache.js.map +1 -1
- package/dist/core/src/filters/filter.js +185 -0
- package/dist/core/src/filters/filter.js.map +1 -0
- package/dist/core/src/state/selection.js +70 -0
- package/dist/core/src/state/selection.js.map +1 -0
- package/dist/core/src/table/create-table.js +239 -64
- package/dist/core/src/table/create-table.js.map +1 -1
- package/dist/core/src/table/filtered-row-model.js +48 -0
- package/dist/core/src/table/filtered-row-model.js.map +1 -0
- package/dist/core/src/table/sorted-row-model.js +13 -2
- package/dist/core/src/table/sorted-row-model.js.map +1 -1
- package/dist/core/src/virtual/column-window.js +72 -0
- package/dist/core/src/virtual/column-window.js.map +1 -0
- package/dist/core/src/virtual/row-pool.js +2 -1
- package/dist/core/src/virtual/row-pool.js.map +1 -1
- package/dist/core/src/virtual/row-sizes.js +156 -0
- package/dist/core/src/virtual/row-sizes.js.map +1 -0
- package/dist/core/src/virtual/scroll-scale.js +41 -3
- package/dist/core/src/virtual/scroll-scale.js.map +1 -1
- package/dist/custom-elements.json +1273 -45
- package/dist/events.js +9 -1
- package/dist/events.js.map +1 -1
- package/dist/index.d.ts +609 -74
- package/dist/index.js +3 -2
- package/dist/interactive.js +22 -0
- package/dist/interactive.js.map +1 -0
- package/dist/max-height.js +22 -8
- package/dist/max-height.js.map +1 -1
- package/dist/render/body.js +47 -7
- package/dist/render/body.js.map +1 -1
- package/dist/render/cells.js +14 -11
- package/dist/render/cells.js.map +1 -1
- package/dist/render/content-directive.js +115 -0
- package/dist/render/content-directive.js.map +1 -0
- package/dist/render/content.js +20 -9
- package/dist/render/content.js.map +1 -1
- package/dist/render/header.js +24 -5
- package/dist/render/header.js.map +1 -1
- package/dist/render/pinned-rows.js +1 -1
- package/dist/render/pinned-rows.js.map +1 -1
- package/dist/styles/base.js +1 -1
- package/dist/styles/base.js.map +1 -1
- package/package.json +1 -1
|
@@ -49,6 +49,17 @@ var AutoWidths = class {
|
|
|
49
49
|
if (kept.length !== Object.keys(this.widths).length) this.widths = Object.fromEntries(kept);
|
|
50
50
|
}
|
|
51
51
|
/**
|
|
52
|
+
* The auto columns still to be measured: never, or without loaded rows yet.
|
|
53
|
+
* With `virtualizeColumns` they render out of view until they are.
|
|
54
|
+
*/
|
|
55
|
+
pending(columns) {
|
|
56
|
+
return columns.filter((c) => {
|
|
57
|
+
if (!c.auto) return false;
|
|
58
|
+
const state = this.#state.get(c.id);
|
|
59
|
+
return state === void 0 || state === "provisional";
|
|
60
|
+
}).map((c) => c.id);
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
52
63
|
* Measures the auto columns that need it. Returns `true` if a width changed;
|
|
53
64
|
* the caller then renders again (the one extra pass of the render cycle).
|
|
54
65
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auto-width.js","names":[],"sources":["../../src/controllers/auto-width.ts"],"sourcesContent":["import type { ColumnSizingState } from '@argus-table/core';\n\n/**\n * The width each column's content needs, in px, from the cells rendered now:\n * the header, the pinned rows and the rendered body rows. Rows that haven't\n * loaded are skipped (their skeleton bars say nothing about the content).\n *\n * Every cell of the columns gets `data-measure`, which sizes it to its\n * `max-content` (base styles), so the browser accounts for padding, the sort\n * indicator and whatever the content is. One forced layout, no paint: the\n * attribute is gone before the frame ends. A column with nothing laid out\n * (the table is hidden) is left out.\n */\nexport function measureColumns(root: ParentNode, ids: Iterable<string>): Map<string, number> {\n const wanted = new Set(ids);\n const widths = new Map<string, number>();\n if (wanted.size === 0) return widths;\n const cells = [...root.querySelectorAll<HTMLElement>('[data-col]')].filter(\n (cell) =>\n wanted.has(cell.dataset.col ?? '') && !cell.parentElement?.matches('[part~=\"row-loading\"]'),\n );\n for (const cell of cells) cell.setAttribute('data-measure', '');\n for (const cell of cells) {\n const id = cell.dataset.col ?? '';\n const px = Math.ceil(cell.getBoundingClientRect().width);\n if (px > 0 && px > (widths.get(id) ?? 0)) widths.set(id, px);\n }\n for (const cell of cells) cell.removeAttribute('data-measure');\n return widths;\n}\n\n/**\n * - `provisional`: measured without loaded body rows (the header and pinned rows only).\n * - `final`: measured with loaded rows; kept until the column goes away.\n * - `fonts`: measured while web fonts were loading; measured again once they are ready.\n */\ntype State = 'provisional' | 'final' | 'fonts';\n\n/**\n * Widths of `width: 'auto'` columns. A column measures once its first loaded\n * rows render, and before that fits the header and pinned rows. So each column\n * is measured at most twice (three times if fonts were still loading), and a\n * table that stays empty doesn't measure on every update. State is keyed by\n * column id, so new `columns` arrays with the same ids don't measure again.\n */\nexport class AutoWidths {\n /** Measured widths by column id; a new object whenever one changes. */\n widths: ColumnSizingState = {};\n readonly #state = new Map<string, State>();\n #fontsPending = false;\n readonly #requestUpdate: () => void;\n\n constructor(requestUpdate: () => void) {\n this.#requestUpdate = requestUpdate;\n }\n\n /** Forgets columns that are gone or no longer `'auto'`, given the ids of the auto columns. */\n sync(ids: Iterable<string>): void {\n const auto = new Set(ids);\n for (const id of this.#state.keys()) {\n if (!auto.has(id)) this.#state.delete(id);\n }\n const kept = Object.entries(this.widths).filter(([id]) => auto.has(id));\n if (kept.length !== Object.keys(this.widths).length) this.widths = Object.fromEntries(kept);\n }\n\n /**\n * Measures the auto columns that need it. Returns `true` if a width changed;\n * the caller then renders again (the one extra pass of the render cycle).\n */\n measure(\n root: ParentNode,\n columns: readonly { id: string; auto: boolean }[],\n hasLoadedRows: boolean,\n ): boolean {\n const due = columns\n .filter((c) => c.auto)\n .map((c) => c.id)\n .filter((id) => {\n const state = this.#state.get(id);\n return state === undefined || (state === 'provisional' && hasLoadedRows);\n });\n if (due.length === 0) return false;\n const measured = measureColumns(root, due);\n const fontsLoading = typeof document !== 'undefined' && document.fonts.status === 'loading';\n let next: ColumnSizingState | undefined;\n for (const [id, px] of measured) {\n this.#state.set(id, fontsLoading ? 'fonts' : hasLoadedRows ? 'final' : 'provisional');\n if (this.widths[id] !== px) (next ??= { ...this.widths })[id] = px;\n }\n if (fontsLoading && measured.size > 0) this.#remeasureAfterFonts();\n if (next) this.widths = next;\n return next !== undefined;\n }\n\n /** Once web fonts are ready, columns measured meanwhile measure again. */\n #remeasureAfterFonts(): void {\n if (this.#fontsPending) return;\n this.#fontsPending = true;\n void document.fonts.ready.then(() => {\n this.#fontsPending = false;\n let any = false;\n for (const [id, state] of this.#state) {\n if (state === 'fonts') {\n this.#state.delete(id);\n any = true;\n }\n }\n if (any) this.#requestUpdate();\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;AAaA,SAAgB,eAAe,MAAkB,KAA4C;CAC3F,MAAM,SAAS,IAAI,IAAI,GAAG;CAC1B,MAAM,yBAAS,IAAI,IAAoB;CACvC,IAAI,OAAO,SAAS,GAAG,OAAO;CAC9B,MAAM,QAAQ,CAAC,GAAG,KAAK,iBAA8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AiB;EAC5D,CAAC;EACH,IAAI,IAAI,WAAW,GAAG,OAAO;EAC7B,MAAM,WAAW,eAAe,MAAM,GAAG;EACzC,MAAM,eAAe,OAAO,aAAa,eAAe,SAAS,MAAM,WAAW;EAClF,IAAI;EACJ,KAAK,MAAM,CAAC,IAAI,OAAO,UAAU;GAC/B,KAAK,OAAO,IAAI,IAAI,eAAe,UAAU,gBAAgB,UAAU,aAAa;GACpF,IAAI,KAAK,OAAO,QAAQ,IAAI,CAAC,SAAS,EAAE,GAAG,KAAK,OAAO,EAAA,CAAG,MAAM;EAClE;EACA,IAAI,gBAAgB,SAAS,OAAO,GAAG,KAAK,qBAAqB;EACjE,IAAI,MAAM,KAAK,SAAS;EACxB,OAAO,SAAS,KAAA;CAClB;;CAGA,uBAA6B;EAC3B,IAAI,KAAK,eAAe;EACxB,KAAK,gBAAgB;EACrB,SAAc,MAAM,MAAM,WAAW;GACnC,KAAK,gBAAgB;GACrB,IAAI,MAAM;GACV,KAAK,MAAM,CAAC,IAAI,UAAU,KAAK,QAC7B,IAAI,UAAU,SAAS;IACrB,KAAK,OAAO,OAAO,EAAE;IACrB,MAAM;GACR;GAEF,IAAI,KAAK,KAAK,eAAe;EAC/B,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"auto-width.js","names":[],"sources":["../../src/controllers/auto-width.ts"],"sourcesContent":["import type { ColumnSizingState } from '@argus-table/core';\n\n/**\n * The width each column's content needs, in px, from the cells rendered now:\n * the header, the pinned rows and the rendered body rows. Rows that haven't\n * loaded are skipped (their skeleton bars say nothing about the content).\n *\n * Every cell of the columns gets `data-measure`, which sizes it to its\n * `max-content` (base styles), so the browser accounts for padding, the sort\n * indicator and whatever the content is. One forced layout, no paint: the\n * attribute is gone before the frame ends. A column with nothing laid out\n * (the table is hidden) is left out.\n */\nexport function measureColumns(root: ParentNode, ids: Iterable<string>): Map<string, number> {\n const wanted = new Set(ids);\n const widths = new Map<string, number>();\n if (wanted.size === 0) return widths;\n const cells = [...root.querySelectorAll<HTMLElement>('[data-col]')].filter(\n (cell) =>\n wanted.has(cell.dataset.col ?? '') && !cell.parentElement?.matches('[part~=\"row-loading\"]'),\n );\n for (const cell of cells) cell.setAttribute('data-measure', '');\n for (const cell of cells) {\n const id = cell.dataset.col ?? '';\n const px = Math.ceil(cell.getBoundingClientRect().width);\n if (px > 0 && px > (widths.get(id) ?? 0)) widths.set(id, px);\n }\n for (const cell of cells) cell.removeAttribute('data-measure');\n return widths;\n}\n\n/**\n * - `provisional`: measured without loaded body rows (the header and pinned rows only).\n * - `final`: measured with loaded rows; kept until the column goes away.\n * - `fonts`: measured while web fonts were loading; measured again once they are ready.\n */\ntype State = 'provisional' | 'final' | 'fonts';\n\n/**\n * Widths of `width: 'auto'` columns. A column measures once its first loaded\n * rows render, and before that fits the header and pinned rows. So each column\n * is measured at most twice (three times if fonts were still loading), and a\n * table that stays empty doesn't measure on every update. State is keyed by\n * column id, so new `columns` arrays with the same ids don't measure again.\n */\nexport class AutoWidths {\n /** Measured widths by column id; a new object whenever one changes. */\n widths: ColumnSizingState = {};\n readonly #state = new Map<string, State>();\n #fontsPending = false;\n readonly #requestUpdate: () => void;\n\n constructor(requestUpdate: () => void) {\n this.#requestUpdate = requestUpdate;\n }\n\n /** Forgets columns that are gone or no longer `'auto'`, given the ids of the auto columns. */\n sync(ids: Iterable<string>): void {\n const auto = new Set(ids);\n for (const id of this.#state.keys()) {\n if (!auto.has(id)) this.#state.delete(id);\n }\n const kept = Object.entries(this.widths).filter(([id]) => auto.has(id));\n if (kept.length !== Object.keys(this.widths).length) this.widths = Object.fromEntries(kept);\n }\n\n /**\n * The auto columns still to be measured: never, or without loaded rows yet.\n * With `virtualizeColumns` they render out of view until they are.\n */\n pending(columns: readonly { id: string; auto: boolean }[]): string[] {\n return columns\n .filter((c) => {\n if (!c.auto) return false;\n const state = this.#state.get(c.id);\n return state === undefined || state === 'provisional';\n })\n .map((c) => c.id);\n }\n\n /**\n * Measures the auto columns that need it. Returns `true` if a width changed;\n * the caller then renders again (the one extra pass of the render cycle).\n */\n measure(\n root: ParentNode,\n columns: readonly { id: string; auto: boolean }[],\n hasLoadedRows: boolean,\n ): boolean {\n const due = columns\n .filter((c) => c.auto)\n .map((c) => c.id)\n .filter((id) => {\n const state = this.#state.get(id);\n return state === undefined || (state === 'provisional' && hasLoadedRows);\n });\n if (due.length === 0) return false;\n const measured = measureColumns(root, due);\n const fontsLoading = typeof document !== 'undefined' && document.fonts.status === 'loading';\n let next: ColumnSizingState | undefined;\n for (const [id, px] of measured) {\n this.#state.set(id, fontsLoading ? 'fonts' : hasLoadedRows ? 'final' : 'provisional');\n if (this.widths[id] !== px) (next ??= { ...this.widths })[id] = px;\n }\n if (fontsLoading && measured.size > 0) this.#remeasureAfterFonts();\n if (next) this.widths = next;\n return next !== undefined;\n }\n\n /** Once web fonts are ready, columns measured meanwhile measure again. */\n #remeasureAfterFonts(): void {\n if (this.#fontsPending) return;\n this.#fontsPending = true;\n void document.fonts.ready.then(() => {\n this.#fontsPending = false;\n let any = false;\n for (const [id, state] of this.#state) {\n if (state === 'fonts') {\n this.#state.delete(id);\n any = true;\n }\n }\n if (any) this.#requestUpdate();\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;AAaA,SAAgB,eAAe,MAAkB,KAA4C;CAC3F,MAAM,SAAS,IAAI,IAAI,GAAG;CAC1B,MAAM,yBAAS,IAAI,IAAoB;CACvC,IAAI,OAAO,SAAS,GAAG,OAAO;CAC9B,MAAM,QAAQ,CAAC,GAAG,KAAK,iBAA8B,YAAY,CAAC,CAAC,CAAC,QACjE,SACC,OAAO,IAAI,KAAK,QAAQ,OAAO,EAAE,KAAK,CAAC,KAAK,eAAe,QAAQ,yBAAuB,CAC9F;CACA,KAAK,MAAM,QAAQ,OAAO,KAAK,aAAa,gBAAgB,EAAE;CAC9D,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,KAAK,KAAK,QAAQ,OAAO;EAC/B,MAAM,KAAK,KAAK,KAAK,KA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O;EAC7B,MAAM,WAAW,eAAe,MAAM,GAAG;EACzC,MAAM,eAAe,OAAO,aAAa,eAAe,SAAS,MAAM,WAAW;EAClF,IAAI;EACJ,KAAK,MAAM,CAAC,IAAI,OAAO,UAAU;GAC/B,KAAK,OAAO,IAAI,IAAI,eAAe,UAAU,gBAAgB,UAAU,aAAa;GACpF,IAAI,KAAK,OAAO,QAAQ,IAAI,CAAC,SAAS,EAAE,GAAG,KAAK,OAAO,EAAA,CAAG,MAAM;EAClE;EACA,IAAI,gBAAgB,SAAS,OAAO,GAAG,KAAK,qBAAqB;EACjE,IAAI,MAAM,KAAK,SAAS;EACxB,OAAO,SAAS,KAAA;CAClB;;CAGA,uBAA6B;EAC3B,IAAI,KAAK,eAAe;EACxB,KAAK,gBAAgB;EACrB,SAAc,MAAM,MAAM,WAAW;GACnC,KAAK,gBAAgB;GACrB,IAAI,MAAM;GACV,KAAK,MAAM,CAAC,IAAI,UAAU,KAAK,QAC7B,IAAI,UAAU,SAAS;IACrB,KAAK,OAAO,OAAO,EAAE;IACrB,MAAM;GACR;GAEF,IAAI,KAAK,KAAK,eAAe;EAC/B,CAAC;CACH;AACF"}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { columnWindow, maxVisibleColumns } from "../core/src/virtual/column-window.js";
|
|
2
|
+
import { RowPool } from "../core/src/virtual/row-pool.js";
|
|
3
|
+
/**
|
|
4
|
+
* Column virtualization (`virtualizeColumns`): which columns render, and which
|
|
5
|
+
* pool slot's DOM each one uses.
|
|
6
|
+
*
|
|
7
|
+
* Off, every column renders in visual order, its slot is its `colIndex` and
|
|
8
|
+
* its cells are keyed by column id: the DOM is what it always was.
|
|
9
|
+
*
|
|
10
|
+
* On, the scrolling columns in view render, plus `COLUMN_OVERSCAN` on each
|
|
11
|
+
* side, and the pinned columns, the checkbox column and the columns the table
|
|
12
|
+
* keeps (the active one, one being dragged, auto widths still to measure)
|
|
13
|
+
* whatever the scroll position. They are pooled like rows (ADR 0001): a column
|
|
14
|
+
* entering the view reuses the cells, slots and content of one that left, so
|
|
15
|
+
* the DOM is updated in place, and the window has one size, so the pool fills
|
|
16
|
+
* on the first render and scrolling only reuses it (in WebKit, new slots
|
|
17
|
+
* while scrolling cut a wheel scroll short; see `steadyWindow`). DOM order is
|
|
18
|
+
* then pool order: each cell is placed in its grid column explicitly, and
|
|
19
|
+
* `aria-colindex` carries the position, as `aria-rowindex` does for rows.
|
|
20
|
+
*/
|
|
21
|
+
var ColumnWindowController = class {
|
|
22
|
+
#host;
|
|
23
|
+
#scroller;
|
|
24
|
+
#pool = new RowPool();
|
|
25
|
+
#attached;
|
|
26
|
+
#resize;
|
|
27
|
+
#enabled = false;
|
|
28
|
+
/** The columns of the last render, and what the window was computed from. */
|
|
29
|
+
#columns = [];
|
|
30
|
+
#scrolling = [];
|
|
31
|
+
#pinnedWidth = 0;
|
|
32
|
+
#maxVisible;
|
|
33
|
+
/** First index and size of the last window rendered. */
|
|
34
|
+
#key = "";
|
|
35
|
+
constructor(host, scroller) {
|
|
36
|
+
this.#host = host;
|
|
37
|
+
this.#scroller = scroller;
|
|
38
|
+
host.addController(this);
|
|
39
|
+
}
|
|
40
|
+
hostConnected() {
|
|
41
|
+
this.#attach();
|
|
42
|
+
}
|
|
43
|
+
hostUpdated() {
|
|
44
|
+
this.#attach();
|
|
45
|
+
}
|
|
46
|
+
hostDisconnected() {
|
|
47
|
+
this.#attached?.removeEventListener("scroll", this.#onScroll);
|
|
48
|
+
this.#resize?.disconnect();
|
|
49
|
+
this.#attached = void 0;
|
|
50
|
+
}
|
|
51
|
+
/** Number of column pool slots created so far. */
|
|
52
|
+
get poolSize() {
|
|
53
|
+
return this.#pool.size;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* The columns to render, given the model's columns in visual order. With
|
|
57
|
+
* `enabled`, `keep` names columns to render wherever they are. Call once per
|
|
58
|
+
* render.
|
|
59
|
+
*/
|
|
60
|
+
compute(columns, enabled, keep) {
|
|
61
|
+
this.#enabled = enabled;
|
|
62
|
+
if (!enabled) {
|
|
63
|
+
this.#pool.clear();
|
|
64
|
+
this.#key = "";
|
|
65
|
+
return columns.map((c) => ({
|
|
66
|
+
...c,
|
|
67
|
+
slot: c.colIndex,
|
|
68
|
+
key: c.id,
|
|
69
|
+
place: void 0
|
|
70
|
+
}));
|
|
71
|
+
}
|
|
72
|
+
if (columns !== this.#columns) {
|
|
73
|
+
this.#columns = columns;
|
|
74
|
+
this.#scrolling = columns.filter((c) => c.kind === "data" && c.pin === void 0);
|
|
75
|
+
this.#pinnedWidth = columns.reduce((sum, c) => c.pin ? sum + c.width : sum, 0);
|
|
76
|
+
}
|
|
77
|
+
const wanted = new Set(keep);
|
|
78
|
+
const window = this.#window();
|
|
79
|
+
for (const i of window) wanted.add(this.#scrolling[i]?.id);
|
|
80
|
+
this.#key = keyOf(window);
|
|
81
|
+
const ids = [];
|
|
82
|
+
const byId = /* @__PURE__ */ new Map();
|
|
83
|
+
for (const c of columns) if (c.pin !== void 0 || c.kind !== "data" || wanted.has(c.id)) {
|
|
84
|
+
ids.push(c.id);
|
|
85
|
+
byId.set(c.id, c);
|
|
86
|
+
}
|
|
87
|
+
const rendered = [];
|
|
88
|
+
for (const { id, slot } of this.#pool.update(ids)) {
|
|
89
|
+
const c = byId.get(id);
|
|
90
|
+
if (c) rendered.push({
|
|
91
|
+
...c,
|
|
92
|
+
slot,
|
|
93
|
+
key: slot,
|
|
94
|
+
place: c.colIndex
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
return rendered;
|
|
98
|
+
}
|
|
99
|
+
/** The window's indexes in the scrolling columns, for the scroller as it is now. */
|
|
100
|
+
#window() {
|
|
101
|
+
const s = this.#attached ?? this.#scroller();
|
|
102
|
+
const view = Math.max(0, (s ?? this.#host).clientWidth - this.#pinnedWidth);
|
|
103
|
+
const columns = this.#scrolling;
|
|
104
|
+
let max = this.#maxVisible;
|
|
105
|
+
if (max?.columns !== this.#columns || max.view !== view) {
|
|
106
|
+
max = {
|
|
107
|
+
columns: this.#columns,
|
|
108
|
+
view,
|
|
109
|
+
value: maxVisibleColumns(columns, view)
|
|
110
|
+
};
|
|
111
|
+
this.#maxVisible = max;
|
|
112
|
+
}
|
|
113
|
+
const offset = Math.abs(s?.scrollLeft ?? 0);
|
|
114
|
+
return columnWindow(columns, offset, view, 2, max.value);
|
|
115
|
+
}
|
|
116
|
+
#attach() {
|
|
117
|
+
const s = this.#scroller();
|
|
118
|
+
if (!s || s === this.#attached) return;
|
|
119
|
+
this.#attached?.removeEventListener("scroll", this.#onScroll);
|
|
120
|
+
this.#attached = s;
|
|
121
|
+
s.addEventListener("scroll", this.#onScroll, { passive: true });
|
|
122
|
+
this.#resize ??= new ResizeObserver(() => {
|
|
123
|
+
this.#onScroll();
|
|
124
|
+
});
|
|
125
|
+
this.#resize.disconnect();
|
|
126
|
+
this.#resize.observe(s);
|
|
127
|
+
}
|
|
128
|
+
/** Renders again when the window moves: not on every scroll event. */
|
|
129
|
+
#onScroll = () => {
|
|
130
|
+
if (!this.#enabled) return;
|
|
131
|
+
if (keyOf(this.#window()) !== this.#key) this.#host.requestUpdate();
|
|
132
|
+
};
|
|
133
|
+
};
|
|
134
|
+
function keyOf(window) {
|
|
135
|
+
return `${String(window[0] ?? -1)}:${String(window.length)}`;
|
|
136
|
+
}
|
|
137
|
+
export { ColumnWindowController };
|
|
138
|
+
|
|
139
|
+
//# sourceMappingURL=column-window.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"column-window.js","names":[],"sources":["../../src/controllers/column-window.ts"],"sourcesContent":["import type { ReactiveController, ReactiveControllerHost } from 'lit';\nimport { columnWindow, maxVisibleColumns, RowPool, type ColumnView } from '@argus-table/core';\nimport type { CellContent } from '../types.js';\n\n/** Scrolling columns rendered beyond each side of the visible ones. */\nexport const COLUMN_OVERSCAN = 2;\n\n/**\n * A rendered column: the column, the slot its cells and light-DOM content use\n * (`h-{slot}`, `c-{row}-{slot}`), the key its cells are rendered by, and with\n * `virtualizeColumns` the grid track it is placed in.\n */\nexport type RenderedColumn<T> = ColumnView<T, CellContent> & {\n slot: number;\n key: unknown;\n /** Grid column the cells are placed in; `undefined`: in DOM order. */\n place: number | undefined;\n};\n\ntype Column<T> = ColumnView<T, CellContent>;\n\n/**\n * Column virtualization (`virtualizeColumns`): which columns render, and which\n * pool slot's DOM each one uses.\n *\n * Off, every column renders in visual order, its slot is its `colIndex` and\n * its cells are keyed by column id: the DOM is what it always was.\n *\n * On, the scrolling columns in view render, plus `COLUMN_OVERSCAN` on each\n * side, and the pinned columns, the checkbox column and the columns the table\n * keeps (the active one, one being dragged, auto widths still to measure)\n * whatever the scroll position. They are pooled like rows (ADR 0001): a column\n * entering the view reuses the cells, slots and content of one that left, so\n * the DOM is updated in place, and the window has one size, so the pool fills\n * on the first render and scrolling only reuses it (in WebKit, new slots\n * while scrolling cut a wheel scroll short; see `steadyWindow`). DOM order is\n * then pool order: each cell is placed in its grid column explicitly, and\n * `aria-colindex` carries the position, as `aria-rowindex` does for rows.\n */\nexport class ColumnWindowController<T> implements ReactiveController {\n readonly #host: ReactiveControllerHost & HTMLElement;\n readonly #scroller: () => HTMLElement | null;\n readonly #pool = new RowPool();\n #attached: HTMLElement | undefined;\n #resize: ResizeObserver | undefined;\n #enabled = false;\n /** The columns of the last render, and what the window was computed from. */\n #columns: readonly Column<T>[] = [];\n #scrolling: Column<T>[] = [];\n #pinnedWidth = 0;\n #maxVisible: { columns: readonly Column<T>[]; view: number; value: number } | undefined;\n /** First index and size of the last window rendered. */\n #key = '';\n\n constructor(host: ReactiveControllerHost & HTMLElement, scroller: () => HTMLElement | null) {\n this.#host = host;\n this.#scroller = scroller;\n host.addController(this);\n }\n\n hostConnected(): void {\n this.#attach();\n }\n\n hostUpdated(): void {\n this.#attach();\n }\n\n hostDisconnected(): void {\n this.#attached?.removeEventListener('scroll', this.#onScroll);\n this.#resize?.disconnect();\n this.#attached = undefined;\n }\n\n /** Number of column pool slots created so far. */\n get poolSize(): number {\n return this.#pool.size;\n }\n\n /**\n * The columns to render, given the model's columns in visual order. With\n * `enabled`, `keep` names columns to render wherever they are. Call once per\n * render.\n */\n compute(\n columns: readonly Column<T>[],\n enabled: boolean,\n keep: Iterable<string | undefined>,\n ): RenderedColumn<T>[] {\n this.#enabled = enabled;\n if (!enabled) {\n this.#pool.clear();\n this.#key = '';\n return columns.map((c) => ({ ...c, slot: c.colIndex, key: c.id, place: undefined }));\n }\n if (columns !== this.#columns) {\n this.#columns = columns;\n this.#scrolling = columns.filter((c) => c.kind === 'data' && c.pin === undefined);\n this.#pinnedWidth = columns.reduce((sum, c) => (c.pin ? sum + c.width : sum), 0);\n }\n const wanted = new Set<string | undefined>(keep);\n const window = this.#window();\n for (const i of window) wanted.add(this.#scrolling[i]?.id);\n this.#key = keyOf(window);\n // In visual order, so the first render's slots (and DOM order) follow the columns.\n const ids: string[] = [];\n const byId = new Map<string, Column<T>>();\n for (const c of columns) {\n if (c.pin !== undefined || c.kind !== 'data' || wanted.has(c.id)) {\n ids.push(c.id);\n byId.set(c.id, c);\n }\n }\n const rendered: RenderedColumn<T>[] = [];\n for (const { id, slot } of this.#pool.update(ids)) {\n const c = byId.get(id);\n if (c) rendered.push({ ...c, slot, key: slot, place: c.colIndex });\n }\n return rendered;\n }\n\n /** The window's indexes in the scrolling columns, for the scroller as it is now. */\n #window(): number[] {\n // Before the first render there is no scroller: the host is as wide.\n const s = this.#attached ?? this.#scroller();\n const view = Math.max(0, (s ?? this.#host).clientWidth - this.#pinnedWidth);\n const columns = this.#scrolling;\n let max = this.#maxVisible;\n if (max?.columns !== this.#columns || max.view !== view) {\n max = { columns: this.#columns, view, value: maxVisibleColumns(columns, view) };\n this.#maxVisible = max;\n }\n // Negative in RTL.\n const offset = Math.abs(s?.scrollLeft ?? 0);\n return columnWindow(columns, offset, view, COLUMN_OVERSCAN, max.value);\n }\n\n #attach(): void {\n const s = this.#scroller();\n if (!s || s === this.#attached) return;\n this.#attached?.removeEventListener('scroll', this.#onScroll);\n this.#attached = s;\n s.addEventListener('scroll', this.#onScroll, { passive: true });\n this.#resize ??= new ResizeObserver(() => {\n this.#onScroll();\n });\n this.#resize.disconnect();\n this.#resize.observe(s);\n }\n\n /** Renders again when the window moves: not on every scroll event. */\n readonly #onScroll = () => {\n if (!this.#enabled) return;\n const window = this.#window();\n if (keyOf(window) !== this.#key) this.#host.requestUpdate();\n };\n}\n\nfunction keyOf(window: readonly number[]): string {\n return `${String(window[0] ?? -1)}:${String(window.length)}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAuCA,IAAa,yBAAb,MAAqE;CACnE;CACA;CACA,QAAiB,IAAI,QAAQ;CAC7B;CACA;CACA,WAAW;;CAEX,WAAiC,CAAC;CAClC,aAA0B,CAAC;CAC3B,eAAe;CACf;;CAEA,OAAO;CAEP,YAAY,MAA4C,UAAoC;EAC1F,KAAK,QAAQ;EACb,KAAK,YAAY;EACjB,KAAK,cAAc,IAAI;CACzB;CAEA,gBAAsB;EACpB,KAAK,QAAQ;CACf;CAEA,cAAoB;EAClB,KAAK,QAAQ;CACf;CAEA,mBAAyB;EACvB,KAAK,WAAW,oBAAoB,UAAU,KAAK,SAAS;EAC5D,KAAK,SAAS,WAAW;EACzB,KAAK,YAAY,KAAA;CACnB;;CAGA,IAAI,WAAmB;EACrB,OAAO,KAAK,MAAM;CACpB;;;;;;CAOA,QACE,SACA,SACA,MACqB;EACrB,KAAK,WAAW;EAChB,IAAI,CAAC,SAAS;GACZ,KAAK,MAAM,MAAM;GACjB,KAAK,OAAO;GACZ,OAAO,QAAQ,KAAK,OAAO;IAAE,GAAG;IAAG,MAAM,EAAE;IAAU,KAAK,EAAE;IAAI,OAAO,KAAA;GAAU,EAAE;EACrF;EACA,IAAI,YAAY,KAAK,UAAU;GAC7B,KAAK,WAAW;GAChB,KAAK,aAAa,QAAQ,QAAQ,MAAM,EAAE,SAAS,UAAU,EAAE,QAAQ,KAAA,CAAS;GAChF,KAAK,eAAe,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AC,KAAK,MAAM,KAAK,WAAW;EAChC,KAAK,WAAW,oBAAoB,UAAU,KAAK,SAAS;EAC5D,KAAK,YAAY;EACjB,EAAE,iBAAiB,UAAU,KAAK,WAAW,EAAE,SAAS,KAAK,CAAC;EAC9D,KAAK,YAAY,IAAI,qBAAqB;GACxC,KAAK,UAAU;EACjB,CAAC;EACD,KAAK,QAAQ,WAAW;EACxB,KAAK,QAAQ,QAAQ,CAAC;CACxB;;CAGA,kBAA2B;EACzB,IAAI,CAAC,KAAK,UAAU;EAEpB,IAAI,MADW,KAAK,QACV,CAAM,MAAM,KAAK,MAAM,KAAK,MAAM,cAAc;CAC5D;AACF;AAEA,SAAS,MAAM,QAAmC;CAChD,OAAO,GAAG,OAAO,OAAO,MAAM,EAAE,EAAE,GAAG,OAAO,OAAO,MAAM;AAC3D"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { PageCache } from "../core/src/data/page-cache.js";
|
|
2
2
|
/**
|
|
3
3
|
* Loads `dataSource` pages for the rendered rows (infinite loading). It owns the
|
|
4
|
-
* page cache: a new source, sort order or row id function starts a fresh one, and
|
|
4
|
+
* page cache: a new source, sort order, filter or row id function starts a fresh one, and
|
|
5
5
|
* answers for an old cache are dropped. Requests wait until the range has been
|
|
6
6
|
* quiet for `LOAD_DEBOUNCE_MS`; pages that scrolled away are aborted.
|
|
7
7
|
*/
|
|
@@ -10,6 +10,8 @@ var DataController = class {
|
|
|
10
10
|
#config = {
|
|
11
11
|
source: void 0,
|
|
12
12
|
sorting: [],
|
|
13
|
+
filters: {},
|
|
14
|
+
quickFilter: "",
|
|
13
15
|
getRowId: void 0
|
|
14
16
|
};
|
|
15
17
|
#cache;
|
|
@@ -34,8 +36,9 @@ var DataController = class {
|
|
|
34
36
|
return this.#cache;
|
|
35
37
|
}
|
|
36
38
|
/**
|
|
37
|
-
* Takes the source, sort order and row id function. Any change starts a
|
|
38
|
-
* cache; a sort or row id change keeps the row count (the rows are the same)
|
|
39
|
+
* Takes the source, sort order, filters and row id function. Any change starts a
|
|
40
|
+
* fresh cache; a sort or row id change keeps the row count (the rows are the same),
|
|
41
|
+
* a new source or filter doesn't (the rows aren't).
|
|
39
42
|
*/
|
|
40
43
|
configure(next) {
|
|
41
44
|
const prev = this.#config;
|
|
@@ -44,7 +47,7 @@ var DataController = class {
|
|
|
44
47
|
this.#reset(void 0);
|
|
45
48
|
return;
|
|
46
49
|
}
|
|
47
|
-
if (next.source !== prev.source || !this.#cache) this.#reset({
|
|
50
|
+
if (next.source !== prev.source || !this.#cache || next.filters !== prev.filters || next.quickFilter !== prev.quickFilter) this.#reset({
|
|
48
51
|
rowCount: void 0,
|
|
49
52
|
totalKnown: false
|
|
50
53
|
});
|
|
@@ -147,6 +150,8 @@ var DataController = class {
|
|
|
147
150
|
start,
|
|
148
151
|
end,
|
|
149
152
|
sorting: this.#config.sorting,
|
|
153
|
+
filters: this.#config.filters,
|
|
154
|
+
quickFilter: this.#config.quickFilter,
|
|
150
155
|
signal: controller.signal
|
|
151
156
|
}));
|
|
152
157
|
} catch (error) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"data-controller.js","names":[],"sources":["../../src/controllers/data-controller.ts"],"sourcesContent":["import type { ReactiveController, ReactiveControllerHost } from 'lit';\nimport {\n PageCache,\n type DataSource,\n type LoadErrorDetail,\n type RowState,\n type SortState,\n} from '@argus-table/core';\n\n/** Rows per request when the data source sets no `pageSize`. */\nexport const DEFAULT_PAGE_SIZE = 100;\n\n/** Quiet time after the last range change before pages load, so fast scrolling loads only where it stops. */\nexport const LOAD_DEBOUNCE_MS = 50;\n\nexport interface DataConfig<T> {\n source: DataSource<T> | undefined;\n sorting: SortState;\n getRowId: ((row: T, index: number) => string) | undefined;\n}\n\n/**\n * Loads `dataSource` pages for the rendered rows (infinite loading). It owns the\n * page cache: a new source, sort order or row id function starts a fresh one, and\n * answers for an old cache are dropped. Requests wait until the range has been\n * quiet for `LOAD_DEBOUNCE_MS`; pages that scrolled away are aborted.\n */\nexport class DataController<T> implements ReactiveController {\n readonly #host: ReactiveControllerHost;\n #config: DataConfig<T> = { source: undefined, sorting: [], getRowId: undefined };\n #cache: PageCache<T> | undefined;\n readonly #requests = new Map<number, AbortController>();\n #range: { start: number; end: number } | undefined;\n #timer: ReturnType<typeof setTimeout> | undefined;\n #errors: LoadErrorDetail[] = [];\n\n constructor(host: ReactiveControllerHost) {\n this.#host = host;\n host.addController(this);\n }\n\n hostDisconnected(): void {\n clearTimeout(this.#timer);\n this.#timer = undefined;\n this.#abortAll();\n }\n\n hostConnected(): void {\n // Requests aborted on disconnect load again on the next range request.\n this.#range = undefined;\n }\n\n /** The page cache, while a data source is set: the model reads rows from it. */\n get rows(): PageCache<T> | undefined {\n return this.#cache;\n }\n\n /**\n * Takes the source, sort order and row id function. Any change starts a fresh\n * cache; a sort or row id change keeps the row count (the rows are the same).\n */\n configure(next: DataConfig<T>): void {\n const prev = this.#config;\n this.#config = next;\n if (!next.source) {\n this.#reset(undefined);\n return;\n }\n if (next.source !== prev.source || !this.#cache) {\n this.#reset({ rowCount: undefined, totalKnown: false });\n } else if (next.sorting !== prev.sorting || next.getRowId !== prev.getRowId) {\n this.#reset({ rowCount: this.#cache.rowCount, totalKnown: this.#cache.totalKnown });\n }\n }\n\n /** Drops every loaded page and loads the rendered ones again. The row count stays until pages answer. */\n refresh(): void {\n if (!this.#cache) return;\n this.#reset({ rowCount: this.#cache.rowCount, totalKnown: false });\n this.#host.requestUpdate();\n }\n\n stateAt(index: number): RowState {\n return this.#cache?.stateAt(index) ?? 'loaded';\n }\n\n /**\n * The rendered rows, `start` to `end` (exclusive). Loads what's missing once the\n * range has been quiet for a moment. Call after every update.\n */\n request(start: number, end: number): void {\n const cache = this.#cache;\n if (!cache) return;\n const prev = this.#range;\n const moved = prev?.start !== start || prev.end !== end;\n this.#range = { start, end };\n if (moved) {\n clearTimeout(this.#timer);\n } else if (this.#timer !== undefined || cache.missingPages(start, end).length === 0) {\n return;\n }\n this.#timer = setTimeout(() => {\n this.#timer = undefined;\n this.#load();\n }, LOAD_DEBOUNCE_MS);\n }\n\n /** Requests the failed page holding row `index` again (the Retry button, or Enter on a failed row). */\n retry(index: number): void {\n const cache = this.#cache;\n const page = cache?.pageOf(index);\n if (!cache || page === undefined || !cache.isFailed(page)) return;\n cache.retry(page);\n this.#range = undefined;\n this.#host.requestUpdate();\n }\n\n /** Load errors since the last call, to fire as `argus-load-error` after the update. */\n takeErrors(): LoadErrorDetail[] {\n const errors = this.#errors;\n this.#errors = [];\n return errors;\n }\n\n #reset(carry: { rowCount: number | undefined; totalKnown: boolean } | undefined): void {\n clearTimeout(this.#timer);\n this.#timer = undefined;\n this.#abortAll();\n this.#range = undefined;\n this.#errors = [];\n const { source, getRowId } = this.#config;\n this.#cache =\n source && carry\n ? new PageCache<T>({\n pageSize: source.pageSize ?? DEFAULT_PAGE_SIZE,\n getRowId,\n rowCount: carry.rowCount,\n totalKnown: carry.totalKnown,\n })\n : undefined;\n }\n\n #abortAll(): void {\n for (const [page, controller] of this.#requests) {\n controller.abort();\n this.#cache?.cancel(page);\n }\n this.#requests.clear();\n }\n\n #load(): void {\n const cache = this.#cache;\n const range = this.#range;\n if (!cache || !range) return;\n // Keep a page of margin, so a small scroll back doesn't abort a page about to land.\n const margin = cache.pageSize;\n for (const page of cache.inFlightOutside(range.start - margin, range.end + margin)) {\n this.#requests.get(page)?.abort();\n this.#requests.delete(page);\n cache.cancel(page);\n }\n cache.evictOutside(range.start, range.end);\n for (const page of cache.missingPages(range.start, range.end)) this.#fetch(cache, page);\n }\n\n #fetch(cache: PageCache<T>, page: number): void {\n const source = this.#config.source;\n if (!source) return;\n const { start, end } = cache.begin(page);\n const controller = new AbortController();\n this.#requests.set(page, controller);\n const current = () => !controller.signal.aborted && cache === this.#cache;\n let pending: Promise<unknown>;\n try {\n pending = Promise.resolve(\n source.getRows({ start, end, sorting: this.#config.sorting, signal: controller.signal }),\n );\n } catch (error) {\n pending = Promise.reject(error instanceof Error ? error : new Error(String(error)));\n }\n pending\n .then((response) => {\n if (!current()) return;\n const { rows, total } = (response ?? {}) as { rows?: unknown; total?: unknown };\n if (!Array.isArray(rows)) {\n throw new TypeError('argus-table: getRows() must resolve to { rows: [], total? }.');\n }\n this.#requests.delete(page);\n cache.resolve(page, rows as T[], typeof total === 'number' ? total : undefined);\n this.#host.requestUpdate();\n })\n .catch((error: unknown) => {\n if (!current()) return;\n this.#requests.delete(page);\n cache.fail(page);\n this.#errors.push({ error, start, end });\n this.#host.requestUpdate();\n });\n }\n}\n"],"mappings":";;;;;;;AA2BA,IAAa,iBAAb,MAA6D;CAC3D;CACA,UAAyB;EAAE,QAAQ,KAAA;EAAW,SAAS,CAAC;EAAG,UAAU,KAAA;CAAU;CAC/E;CACA,4BAAqB,IAAI,IAA6B;CACtD;CACA;CACA,UAA6B,CAAC;CAE9B,YAAY,MAA8B;EACxC,KAAK,QAAQ;EACb,KAAK,cAAc,IAAI;CACzB;CAEA,mBAAyB;EACvB,aAAa,KAAK,MAAM;EACxB,KAAK,SAAS,KAAA;EACd,KAAK,UAAU;CACjB;CAEA,gBAAsB;EAEpB,KAAK,SAAS,KAAA;CAChB;;CAGA,IAAI,OAAiC;EACnC,OAAO,KAAK;CACd;;;;;CAMA,UAAU,MAA2B;EACnC,MAAM,OAAO,KAAK;EAClB,KAAK,UAAU;EACf,IAAI,CAAC,KAAK,QAAQ;GAChB,KAAK,OAAO,KAAA,CAAS;GACrB;EACF;EACA,IAAI,KAAK,WAAW,KAAK,UAAU,CAAC,KAAK,QACvC,KAAK,OAAO;GAAE,UAAU,KAAA;GAAW,YAAY;EAAM,CAAC;OACjD,IAAI,KAAK,YAAY,KAAK,WAAW,KAAK,aAAa,KAAK,UACjE,KAAK,OAAO;GAAE,UAAU,KAAK,OAAO;GAAU,YAAY,KAAK,OAAO;EAAW,CAAC;CAEtF;;CAGA,UAAgB;EACd,IAAI,CAAC,KAAK,QAAQ;EAClB,KAAK,OAAO;GAAE,UAAU,KAAK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,QAAQ,MAAM,MAAa,OAAO,UAAU,WAAW,QAAQ,KAAA,CAAS;GAC9E,KAAK,MAAM,cAAc;EAC3B,CAAC,CAAC,CACD,OAAO,UAAmB;GACzB,IAAI,CAAC,QAAQ,GAAG;GAChB,KAAK,UAAU,OAAO,IAAI;GAC1B,MAAM,KAAK,IAAI;GACf,KAAK,QAAQ,KAAK;IAAE;IAAO;IAAO;GAAI,CAAC;GACvC,KAAK,MAAM,cAAc;EAC3B,CAAC;CACL;AACF"}
|
|
1
|
+
{"version":3,"file":"data-controller.js","names":[],"sources":["../../src/controllers/data-controller.ts"],"sourcesContent":["import type { ReactiveController, ReactiveControllerHost } from 'lit';\nimport {\n PageCache,\n type ColumnFilterState,\n type DataSource,\n type LoadErrorDetail,\n type RowState,\n type SortState,\n} from '@argus-table/core';\n\n/** Rows per request when the data source sets no `pageSize`. */\nexport const DEFAULT_PAGE_SIZE = 100;\n\n/** Quiet time after the last range change before pages load, so fast scrolling loads only where it stops. */\nexport const LOAD_DEBOUNCE_MS = 50;\n\nexport interface DataConfig<T> {\n source: DataSource<T> | undefined;\n sorting: SortState;\n filters: ColumnFilterState;\n quickFilter: string;\n getRowId: ((row: T, index: number) => string) | undefined;\n}\n\n/**\n * Loads `dataSource` pages for the rendered rows (infinite loading). It owns the\n * page cache: a new source, sort order, filter or row id function starts a fresh one, and\n * answers for an old cache are dropped. Requests wait until the range has been\n * quiet for `LOAD_DEBOUNCE_MS`; pages that scrolled away are aborted.\n */\nexport class DataController<T> implements ReactiveController {\n readonly #host: ReactiveControllerHost;\n #config: DataConfig<T> = {\n source: undefined,\n sorting: [],\n filters: {},\n quickFilter: '',\n getRowId: undefined,\n };\n #cache: PageCache<T> | undefined;\n readonly #requests = new Map<number, AbortController>();\n #range: { start: number; end: number } | undefined;\n #timer: ReturnType<typeof setTimeout> | undefined;\n #errors: LoadErrorDetail[] = [];\n\n constructor(host: ReactiveControllerHost) {\n this.#host = host;\n host.addController(this);\n }\n\n hostDisconnected(): void {\n clearTimeout(this.#timer);\n this.#timer = undefined;\n this.#abortAll();\n }\n\n hostConnected(): void {\n // Requests aborted on disconnect load again on the next range request.\n this.#range = undefined;\n }\n\n /** The page cache, while a data source is set: the model reads rows from it. */\n get rows(): PageCache<T> | undefined {\n return this.#cache;\n }\n\n /**\n * Takes the source, sort order, filters and row id function. Any change starts a\n * fresh cache; a sort or row id change keeps the row count (the rows are the same),\n * a new source or filter doesn't (the rows aren't).\n */\n configure(next: DataConfig<T>): void {\n const prev = this.#config;\n this.#config = next;\n if (!next.source) {\n this.#reset(undefined);\n return;\n }\n if (\n next.source !== prev.source ||\n !this.#cache ||\n next.filters !== prev.filters ||\n next.quickFilter !== prev.quickFilter\n ) {\n this.#reset({ rowCount: undefined, totalKnown: false });\n } else if (next.sorting !== prev.sorting || next.getRowId !== prev.getRowId) {\n this.#reset({ rowCount: this.#cache.rowCount, totalKnown: this.#cache.totalKnown });\n }\n }\n\n /** Drops every loaded page and loads the rendered ones again. The row count stays until pages answer. */\n refresh(): void {\n if (!this.#cache) return;\n this.#reset({ rowCount: this.#cache.rowCount, totalKnown: false });\n this.#host.requestUpdate();\n }\n\n stateAt(index: number): RowState {\n return this.#cache?.stateAt(index) ?? 'loaded';\n }\n\n /**\n * The rendered rows, `start` to `end` (exclusive). Loads what's missing once the\n * range has been quiet for a moment. Call after every update.\n */\n request(start: number, end: number): void {\n const cache = this.#cache;\n if (!cache) return;\n const prev = this.#range;\n const moved = prev?.start !== start || prev.end !== end;\n this.#range = { start, end };\n if (moved) {\n clearTimeout(this.#timer);\n } else if (this.#timer !== undefined || cache.missingPages(start, end).length === 0) {\n return;\n }\n this.#timer = setTimeout(() => {\n this.#timer = undefined;\n this.#load();\n }, LOAD_DEBOUNCE_MS);\n }\n\n /** Requests the failed page holding row `index` again (the Retry button, or Enter on a failed row). */\n retry(index: number): void {\n const cache = this.#cache;\n const page = cache?.pageOf(index);\n if (!cache || page === undefined || !cache.isFailed(page)) return;\n cache.retry(page);\n this.#range = undefined;\n this.#host.requestUpdate();\n }\n\n /** Load errors since the last call, to fire as `argus-load-error` after the update. */\n takeErrors(): LoadErrorDetail[] {\n const errors = this.#errors;\n this.#errors = [];\n return errors;\n }\n\n #reset(carry: { rowCount: number | undefined; totalKnown: boolean } | undefined): void {\n clearTimeout(this.#timer);\n this.#timer = undefined;\n this.#abortAll();\n this.#range = undefined;\n this.#errors = [];\n const { source, getRowId } = this.#config;\n this.#cache =\n source && carry\n ? new PageCache<T>({\n pageSize: source.pageSize ?? DEFAULT_PAGE_SIZE,\n getRowId,\n rowCount: carry.rowCount,\n totalKnown: carry.totalKnown,\n })\n : undefined;\n }\n\n #abortAll(): void {\n for (const [page, controller] of this.#requests) {\n controller.abort();\n this.#cache?.cancel(page);\n }\n this.#requests.clear();\n }\n\n #load(): void {\n const cache = this.#cache;\n const range = this.#range;\n if (!cache || !range) return;\n // Keep a page of margin, so a small scroll back doesn't abort a page about to land.\n const margin = cache.pageSize;\n for (const page of cache.inFlightOutside(range.start - margin, range.end + margin)) {\n this.#requests.get(page)?.abort();\n this.#requests.delete(page);\n cache.cancel(page);\n }\n cache.evictOutside(range.start, range.end);\n for (const page of cache.missingPages(range.start, range.end)) this.#fetch(cache, page);\n }\n\n #fetch(cache: PageCache<T>, page: number): void {\n const source = this.#config.source;\n if (!source) return;\n const { start, end } = cache.begin(page);\n const controller = new AbortController();\n this.#requests.set(page, controller);\n const current = () => !controller.signal.aborted && cache === this.#cache;\n let pending: Promise<unknown>;\n try {\n pending = Promise.resolve(\n source.getRows({\n start,\n end,\n sorting: this.#config.sorting,\n filters: this.#config.filters,\n quickFilter: this.#config.quickFilter,\n signal: controller.signal,\n }),\n );\n } catch (error) {\n pending = Promise.reject(error instanceof Error ? error : new Error(String(error)));\n }\n pending\n .then((response) => {\n if (!current()) return;\n const { rows, total } = (response ?? {}) as { rows?: unknown; total?: unknown };\n if (!Array.isArray(rows)) {\n throw new TypeError('argus-table: getRows() must resolve to { rows: [], total? }.');\n }\n this.#requests.delete(page);\n cache.resolve(page, rows as T[], typeof total === 'number' ? total : undefined);\n this.#host.requestUpdate();\n })\n .catch((error: unknown) => {\n if (!current()) return;\n this.#requests.delete(page);\n cache.fail(page);\n this.#errors.push({ error, start, end });\n this.#host.requestUpdate();\n });\n }\n}\n"],"mappings":";;;;;;;AA8BA,IAAa,iBAAb,MAA6D;CAC3D;CACA,UAAyB;EACvB,QAAQ,KAAA;EACR,SAAS,CAAC;EACV,SAAS,CAAC;EACV,aAAa;EACb,UAAU,KAAA;CACZ;CACA;CACA,4BAAqB,IAAI,IAA6B;CACtD;CACA;CACA,UAA6B,CAAC;CAE9B,YAAY,MAA8B;EACxC,KAAK,QAAQ;EACb,KAAK,cAAc,IAAI;CACzB;CAEA,mBAAyB;EACvB,aAAa,KAAK,MAAM;EACxB,KAAK,SAAS,KAAA;EACd,KAAK,UAAU;CACjB;CAEA,gBAAsB;EAEpB,KAAK,SAAS,KAAA;CAChB;;CAGA,IAAI,OAAiC;EACnC,OAAO,KAAK;CACd;;;;;;CAOA,UAAU,MAA2B;EACnC,MAAM,OAAO,KAAK;EAClB,KAAK,UAAU;EACf,IAAI,CAAC,KAAK,QAAQ;GAChB,KAAK,OAAO,KAAA,CAAS;GACrB;EACF;EACA,IACE,KAAK,WAAW,KAAK,UACrB,CAAC,KAAK,UACN,KAAK,YAAY,KAAK,WACtB,KAAK,gBAAgB,KAAK,aAE1B,KAAK,OAAO;GAAE,UAAU,KAAA;GAAW,YAAY;EAAM,CAAC;OACjD,IAAI,KAAK,YAAY,KAAK,WAAW,KAAK,aAAa,KAAK,UACjE,KAAK,OAAO;GAAE,UAAU,KAAK,OAAO;GAAU,YAAY,KAAK,OAAO;EAAW,CAAC;CAEtF;;CAGA,UAAgB;EACd,IAAI,CAAC,KAAK,QAAQ;EAClB,KAAK,OAAO;GAAE,UAAU,KAAK,OAAO;GAAU,YAAY;EAAM,CAAC;EACjE,KAAK,MAAM,cAAc;CAC3B;CAEA,QAAQ,OAAyB;EAC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AAQ,KAAA,CAAS;GAC9E,KAAK,MAAM,cAAc;EAC3B,CAAC,CAAC,CACD,OAAO,UAAmB;GACzB,IAAI,CAAC,QAAQ,GAAG;GAChB,KAAK,UAAU,OAAO,IAAI;GAC1B,MAAM,KAAK,IAAI;GACf,KAAK,QAAQ,KAAK;IAAE;IAAO;IAAO;GAAI,CAAC;GACvC,KAAK,MAAM,cAAc;EAC3B,CAAC;CACL;AACF"}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
// src/controllers/plugins.ts
|
|
2
|
+
/**
|
|
3
|
+
* Runs the table's plugins: connects them while the table is connected (in
|
|
4
|
+
* array order, cleaning up in reverse), chains their column transforms, and
|
|
5
|
+
* offers keys to them before the table handles them. A hook that throws is
|
|
6
|
+
* reported and skipped, so a broken plugin can't break the update.
|
|
7
|
+
*/
|
|
8
|
+
var PluginController = class {
|
|
9
|
+
#host;
|
|
10
|
+
#api;
|
|
11
|
+
#plugins = [];
|
|
12
|
+
/** Connected plugins and their cleanups. */
|
|
13
|
+
#connected = /* @__PURE__ */ new Map();
|
|
14
|
+
/** Plugins whose `connect` threw: off until `plugins` changes. */
|
|
15
|
+
#failed = /* @__PURE__ */ new Set();
|
|
16
|
+
#version = 0;
|
|
17
|
+
#memo;
|
|
18
|
+
constructor(host, api) {
|
|
19
|
+
this.#host = host;
|
|
20
|
+
this.#api = api;
|
|
21
|
+
host.addController(this);
|
|
22
|
+
}
|
|
23
|
+
/** Takes a new plugin list; connects and cleans up to match it if the host is connected. */
|
|
24
|
+
set(plugins) {
|
|
25
|
+
if (plugins === this.#plugins) return;
|
|
26
|
+
this.#plugins = plugins;
|
|
27
|
+
this.#failed.clear();
|
|
28
|
+
if (this.#host.isConnected) this.#sync();
|
|
29
|
+
}
|
|
30
|
+
hostConnected() {
|
|
31
|
+
this.#sync();
|
|
32
|
+
}
|
|
33
|
+
hostDisconnected() {
|
|
34
|
+
for (const plugin of [...this.#connected.keys()].reverse()) this.#disconnect(plugin);
|
|
35
|
+
}
|
|
36
|
+
/** The plugins' `columns` transforms applied in order; the same array while nothing changed. */
|
|
37
|
+
transform(input) {
|
|
38
|
+
const memo = this.#memo;
|
|
39
|
+
if (memo?.input === input && memo.plugins === this.#plugins && memo.version === this.#version) return memo.output;
|
|
40
|
+
let output = input;
|
|
41
|
+
for (const plugin of this.#plugins) {
|
|
42
|
+
if (!plugin.columns || this.#failed.has(plugin)) continue;
|
|
43
|
+
const before = output;
|
|
44
|
+
const result = this.#guard(plugin, "columns", () => plugin.columns?.(before, this.#api));
|
|
45
|
+
if (result.ok && result.value) output = result.value;
|
|
46
|
+
}
|
|
47
|
+
if (memo && sameItems(memo.output, output)) output = memo.output;
|
|
48
|
+
this.#memo = {
|
|
49
|
+
input,
|
|
50
|
+
plugins: this.#plugins,
|
|
51
|
+
version: this.#version,
|
|
52
|
+
output
|
|
53
|
+
};
|
|
54
|
+
return output;
|
|
55
|
+
}
|
|
56
|
+
/** Runs the transforms again on the next `transform()`. */
|
|
57
|
+
invalidate() {
|
|
58
|
+
this.#version++;
|
|
59
|
+
}
|
|
60
|
+
/** Offers a key to the plugins in order; `true` once one claims it. */
|
|
61
|
+
keydown(event, target) {
|
|
62
|
+
for (const plugin of this.#plugins) {
|
|
63
|
+
if (!plugin.keydown || this.#failed.has(plugin)) continue;
|
|
64
|
+
const result = this.#guard(plugin, "keydown", () => plugin.keydown?.(event, target, this.#api));
|
|
65
|
+
if (result.ok && result.value === true) return true;
|
|
66
|
+
}
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
#sync() {
|
|
70
|
+
const wanted = new Set(this.#plugins);
|
|
71
|
+
for (const plugin of [...this.#connected.keys()].reverse()) if (!wanted.has(plugin)) this.#disconnect(plugin);
|
|
72
|
+
for (const plugin of this.#plugins) {
|
|
73
|
+
if (this.#connected.has(plugin) || this.#failed.has(plugin)) continue;
|
|
74
|
+
const result = this.#guard(plugin, "connect", () => plugin.connect?.(this.#api));
|
|
75
|
+
if (result.ok) this.#connected.set(plugin, result.value);
|
|
76
|
+
else this.#failed.add(plugin);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
#disconnect(plugin) {
|
|
80
|
+
const cleanup = this.#connected.get(plugin);
|
|
81
|
+
this.#connected.delete(plugin);
|
|
82
|
+
if (cleanup) this.#guard(plugin, "cleanup", cleanup);
|
|
83
|
+
}
|
|
84
|
+
#guard(plugin, hook, run) {
|
|
85
|
+
try {
|
|
86
|
+
return {
|
|
87
|
+
ok: true,
|
|
88
|
+
value: run()
|
|
89
|
+
};
|
|
90
|
+
} catch (error) {
|
|
91
|
+
console.error(`argus-table: plugin "${plugin.name}" threw in ${hook}`, error);
|
|
92
|
+
return { ok: false };
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
/** Whether two lists hold the same items in the same order. */
|
|
97
|
+
function sameItems(a, b) {
|
|
98
|
+
return a.length === b.length && a.every((item, i) => item === b[i]);
|
|
99
|
+
}
|
|
100
|
+
export { PluginController, sameItems };
|
|
101
|
+
|
|
102
|
+
//# sourceMappingURL=plugins.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plugins.js","names":[],"sources":["../../src/controllers/plugins.ts"],"sourcesContent":["import type { ReactiveController, ReactiveControllerHost } from 'lit';\nimport type { ArgusPlugin, CellTarget, PluginHost } from '../plugins.js';\nimport type { ColumnDef } from '../types.js';\n\ntype Hook = 'connect' | 'cleanup' | 'columns' | 'keydown';\n\n/**\n * Runs the table's plugins: connects them while the table is connected (in\n * array order, cleaning up in reverse), chains their column transforms, and\n * offers keys to them before the table handles them. A hook that throws is\n * reported and skipped, so a broken plugin can't break the update.\n */\nexport class PluginController<T> implements ReactiveController {\n readonly #host: ReactiveControllerHost & HTMLElement;\n readonly #api: PluginHost<T>;\n #plugins: readonly ArgusPlugin<T>[] = [];\n /** Connected plugins and their cleanups. */\n readonly #connected = new Map<ArgusPlugin<T>, (() => void) | undefined>();\n /** Plugins whose `connect` threw: off until `plugins` changes. */\n readonly #failed = new Set<ArgusPlugin<T>>();\n #version = 0;\n #memo:\n | {\n input: readonly ColumnDef<T>[];\n plugins: readonly ArgusPlugin<T>[];\n version: number;\n output: readonly ColumnDef<T>[];\n }\n | undefined;\n\n constructor(host: ReactiveControllerHost & HTMLElement, api: PluginHost<T>) {\n this.#host = host;\n this.#api = api;\n host.addController(this);\n }\n\n /** Takes a new plugin list; connects and cleans up to match it if the host is connected. */\n set(plugins: readonly ArgusPlugin<T>[]): void {\n if (plugins === this.#plugins) return;\n this.#plugins = plugins;\n this.#failed.clear();\n if (this.#host.isConnected) this.#sync();\n }\n\n hostConnected(): void {\n this.#sync();\n }\n\n hostDisconnected(): void {\n for (const plugin of [...this.#connected.keys()].reverse()) this.#disconnect(plugin);\n }\n\n /** The plugins' `columns` transforms applied in order; the same array while nothing changed. */\n transform(input: readonly ColumnDef<T>[]): readonly ColumnDef<T>[] {\n const memo = this.#memo;\n if (memo?.input === input && memo.plugins === this.#plugins && memo.version === this.#version) {\n return memo.output;\n }\n let output = input;\n for (const plugin of this.#plugins) {\n if (!plugin.columns || this.#failed.has(plugin)) continue;\n const before = output;\n const result = this.#guard(plugin, 'columns', () => plugin.columns?.(before, this.#api));\n if (result.ok && result.value) output = result.value;\n }\n // Plugins may return a fresh array each time: keep the old one when its items are the same.\n if (memo && sameItems(memo.output, output)) output = memo.output;\n this.#memo = { input, plugins: this.#plugins, version: this.#version, output };\n return output;\n }\n\n /** Runs the transforms again on the next `transform()`. */\n invalidate(): void {\n this.#version++;\n }\n\n /** Offers a key to the plugins in order; `true` once one claims it. */\n keydown(event: KeyboardEvent, target: CellTarget): boolean {\n for (const plugin of this.#plugins) {\n if (!plugin.keydown || this.#failed.has(plugin)) continue;\n const result = this.#guard(plugin, 'keydown', () =>\n plugin.keydown?.(event, target, this.#api),\n );\n if (result.ok && result.value === true) return true;\n }\n return false;\n }\n\n #sync(): void {\n const wanted = new Set(this.#plugins);\n for (const plugin of [...this.#connected.keys()].reverse()) {\n if (!wanted.has(plugin)) this.#disconnect(plugin);\n }\n for (const plugin of this.#plugins) {\n if (this.#connected.has(plugin) || this.#failed.has(plugin)) continue;\n const result = this.#guard(plugin, 'connect', () => plugin.connect?.(this.#api));\n if (result.ok) this.#connected.set(plugin, result.value);\n else this.#failed.add(plugin);\n }\n }\n\n #disconnect(plugin: ArgusPlugin<T>): void {\n const cleanup = this.#connected.get(plugin);\n this.#connected.delete(plugin);\n if (cleanup) this.#guard(plugin, 'cleanup', cleanup);\n }\n\n #guard<R>(\n plugin: ArgusPlugin<T>,\n hook: Hook,\n run: () => R,\n ): { ok: true; value: R } | { ok: false } {\n try {\n return { ok: true, value: run() };\n } catch (error) {\n console.error(`argus-table: plugin \"${plugin.name}\" threw in ${hook}`, error);\n return { ok: false };\n }\n }\n}\n\n/** Whether two lists hold the same items in the same order. */\nexport function sameItems<V>(a: readonly V[], b: readonly V[]): boolean {\n return a.length === b.length && a.every((item, i) => item === b[i]);\n}\n"],"mappings":";;;;;;;AAYA,IAAa,mBAAb,MAA+D;CAC7D;CACA;CACA,WAAsC,CAAC;;CAEvC,6BAAsB,IAAI,IAA8C;;CAExE,0BAAmB,IAAI,IAAoB;CAC3C,WAAW;CACX;CASA,YAAY,MAA4C,KAAoB;EAC1E,KAAK,QAAQ;EACb,KAAK,OAAO;EACZ,KAAK,cAAc,IAAI;CACzB;;CAGA,IAAI,SAA0C;EAC5C,IAAI,YAAY,KAAK,UAAU;EAC/B,KAAK,WAAW;EAChB,KAAK,QAAQ,MAAM;EACnB,IAAI,KAAK,MAAM,aAAa,KAAK,MAAM;CACzC;CAEA,gBAAsB;EACpB,KAAK,MAAM;CACb;CAEA,mBAAyB;EACvB,KAAK,MAAM,UAAU,CAAC,GAAG,KAAK,WAAW,KAAK,CAAC,CAAC,CAAC,QAAQ,GAAG,KAAK,YAAY,MAAM;CACrF;;CAGA,UAAU,OAAyD;EACjE,MAAM,OAAO,KAAK;EAClB,IAAI,MAAM,UAAU,SAAS,K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AO,KAAK;QAClD,KAAK,QAAQ,IAAI,MAAM;EAC9B;CACF;CAEA,YAAY,QAA8B;EACxC,MAAM,UAAU,KAAK,WAAW,IAAI,MAAM;EAC1C,KAAK,WAAW,OAAO,MAAM;EAC7B,IAAI,SAAS,KAAK,OAAO,QAAQ,WAAW,OAAO;CACrD;CAEA,OACE,QACA,MACA,KACwC;EACxC,IAAI;GACF,OAAO;IAAE,IAAI;IAAM,OAAO,IAAI;GAAE;EAClC,SAAS,OAAO;GACd,QAAQ,MAAM,wBAAwB,OAAO,KAAK,aAAa,QAAQ,KAAK;GAC5E,OAAO,EAAE,IAAI,MAAM;EACrB;CACF;AACF;;AAGA,SAAgB,UAAa,GAAiB,GAA0B;CACtE,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,OAAO,MAAM,MAAM,SAAS,EAAE,EAAE;AACpE"}
|
|
@@ -1,19 +1,19 @@
|
|
|
1
|
+
import "../interactive.js";
|
|
1
2
|
// src/controllers/reorder-drag.ts
|
|
2
3
|
/**
|
|
3
4
|
* The drop target for a pointer at `x`: the gap between headers nearest to it,
|
|
4
5
|
* decided by each header's midpoint. `undefined` where the column would stay
|
|
5
6
|
* put. `direction` is 1 in LTR and -1 in RTL, where the group runs right to left.
|
|
7
|
+
* The slots needn't be next to each other in the order: with
|
|
8
|
+
* `virtualizeColumns`, headers out of view aren't rendered.
|
|
6
9
|
*/
|
|
7
10
|
function dropTarget(slots, draggedId, x, direction) {
|
|
8
|
-
const
|
|
9
|
-
const first = slots[0];
|
|
11
|
+
const dragged = slots.find((s) => s.id === draggedId);
|
|
10
12
|
const last = slots.at(-1);
|
|
11
|
-
if (
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
if (
|
|
15
|
-
const to = first.index + (gap > from ? gap - 1 : gap);
|
|
16
|
-
const at = slots[gap];
|
|
13
|
+
if (!dragged || !last) return void 0;
|
|
14
|
+
const at = slots.find((s) => (x - (s.rect.left + s.rect.right) / 2) * direction < 0);
|
|
15
|
+
const to = at ? at.index > dragged.index ? at.index - 1 : at.index : last.index >= dragged.index ? last.index : last.index + 1;
|
|
16
|
+
if (to === dragged.index) return void 0;
|
|
17
17
|
return at ? {
|
|
18
18
|
to,
|
|
19
19
|
columnId: at.id,
|
|
@@ -29,7 +29,6 @@ var THRESHOLD = 4;
|
|
|
29
29
|
/** Width of the band at the scroll area's edges that scrolls, and the top speed there. */
|
|
30
30
|
var EDGE = 40;
|
|
31
31
|
var MAX_SPEED = 16;
|
|
32
|
-
var INTERACTIVE = "button,input,select,textarea,a[href],label,[contenteditable]";
|
|
33
32
|
/**
|
|
34
33
|
* Whether a press on a header may start a reorder drag: the primary button of a
|
|
35
34
|
* mouse or pen (a touch pans the table instead), not on a resize handle, and not
|
|
@@ -41,7 +40,7 @@ function canStartReorder(down, cell) {
|
|
|
41
40
|
if (target === cell) return true;
|
|
42
41
|
if (!(target instanceof Element)) continue;
|
|
43
42
|
if (target instanceof HTMLElement && target.dataset.resizeCol !== void 0) return false;
|
|
44
|
-
if (target.matches(
|
|
43
|
+
if (target.matches("button,input,select,textarea,a[href],label,[contenteditable],[popover],dialog")) return false;
|
|
45
44
|
}
|
|
46
45
|
return false;
|
|
47
46
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reorder-drag.js","names":[],"sources":["../../src/controllers/reorder-drag.ts"],"sourcesContent":["/** Where a dragged column would land: its new position and the header that shows the drop line. */\nexport interface DropTarget {\n /** Position in the whole column order after the move, 0-based. */\n to: number;\n /** The header that draws the drop line. */\n columnId: string;\n /** The edge of that header the line is on, in logical terms. */\n edge: 'start' | 'end';\n}\n\n/** A header of the dragged column's group, in visual order. */\nexport interface DropSlot {\n id: string;\n /** Its position in the whole column order, 0-based. */\n index: number;\n rect: { left: number; right: number };\n}\n\n/**\n * The drop target for a pointer at `x`: the gap between headers nearest to it,\n * decided by each header's midpoint. `undefined` where the column would stay\n * put. `direction` is 1 in LTR and -1 in RTL, where the group runs right to left.\n */\nexport function dropTarget(\n slots: readonly DropSlot[],\n draggedId: string,\n x: number,\n direction: 1 | -1,\n): DropTarget | undefined {\n const from = slots.findIndex((s) => s.id === draggedId);\n const first = slots[0];\n const last = slots.at(-1);\n if (from < 0 || !first || !last) return undefined;\n // The gap before the first header whose middle is past the pointer, in reading order.\n let gap = slots.findIndex((s) => (x - (s.rect.left + s.rect.right) / 2) * direction < 0);\n if (gap < 0) gap = slots.length;\n if (gap === from || gap === from + 1) return undefined;\n const to = first.index + (gap > from ? gap - 1 : gap);\n const at = slots[gap];\n return at ? { to, columnId: at.id, edge: 'start' } : { to, columnId: last.id, edge: 'end' };\n}\n\nexport interface ReorderDragOptions {\n /** The scroll container: it scrolls while the pointer is near its edges. */\n scroller: HTMLElement;\n /** The drop target for a pointer at `x` (client coordinates). */\n targetAt: (x: number) => DropTarget | undefined;\n /**\n * Where the dragged column's group is visible, in client x, if it can scroll\n * (the scrolling columns). Near these edges the scroller scrolls with the drag.\n */\n scrollArea: () => { left: number; right: number } | undefined;\n onStart: () => void;\n /** The target changed (`undefined`: the column would stay put). */\n onTarget: (target: DropTarget | undefined) => void;\n /** The pointer was released over a target, or `undefined` when it would stay put. */\n onDrop: (target: DropTarget | undefined) => void;\n /** Escape, a cancelled pointer, or a release without a drag. */\n onCancel: () => void;\n}\n\n/** Movement before a press becomes a drag, so a click still sorts. */\nconst THRESHOLD = 4;\n/** Width of the band at the scroll area's edges that scrolls, and the top speed there. */\nconst EDGE = 40;\nconst MAX_SPEED = 16;\n\nconst INTERACTIVE = 'button,input,select,textarea,a[href],label,[contenteditable]';\n\n/**\n * Whether a press on a header may start a reorder drag: the primary button of a\n * mouse or pen (a touch pans the table instead), not on a resize handle, and not\n * in interactive content slotted into the header.\n */\nexport function canStartReorder(down: PointerEvent, cell: HTMLElement): boolean {\n if (down.button !== 0 || down.pointerType === 'touch') return false;\n for (const target of down.composedPath()) {\n if (target === cell) return true;\n if (!(target instanceof Element)) continue;\n if (target instanceof HTMLElement && target.dataset.resizeCol !== undefined) return false;\n if (target.matches(INTERACTIVE)) return false;\n }\n return false;\n}\n\n/**\n * One pointer drag of a column header. It becomes a drag after a few pixels of\n * movement; until then the press is a click. While dragging, the pointer is\n * captured by the header, the target follows the pointer once per frame, and the\n * scroll area scrolls near its edges. Escape cancels. The click that ends a drag\n * is swallowed, so it neither sorts nor counts as a cell click.\n */\nexport function startReorderDrag(\n cell: HTMLElement,\n down: PointerEvent,\n options: ReorderDragOptions,\n): void {\n const view = cell.ownerDocument.defaultView ?? window;\n const startX = down.clientX;\n const startY = down.clientY;\n let x = startX;\n let dragging = false;\n let frame = 0;\n let target: DropTarget | undefined;\n\n const same = (a: DropTarget | undefined, b: DropTarget | undefined) =>\n a?.to === b?.to && a?.columnId === b?.columnId && a?.edge === b?.edge;\n\n const tick = () => {\n frame = 0;\n if (!dragging) return;\n const area = options.scrollArea();\n if (area) {\n const speed =\n x < area.left + EDGE\n ? -Math.min(1, (area.left + EDGE - x) / EDGE)\n : x > area.right - EDGE\n ? Math.min(1, (x - (area.right - EDGE)) / EDGE)\n : 0;\n // A visual delta: scrollLeft runs the same way in LTR and RTL.\n if (speed !== 0) options.scroller.scrollLeft += Math.round(speed * MAX_SPEED);\n // Targets past the visible part would be hidden under pinned columns.\n x = Math.min(Math.max(x, area.left), area.right);\n }\n const next = options.targetAt(x);\n if (!same(next, target)) {\n target = next;\n options.onTarget(target);\n }\n // Keep running while dragging: the view may still be scrolling.\n frame = view.requestAnimationFrame(tick);\n };\n\n const listeners = new AbortController();\n const cleanup = (event?: PointerEvent) => {\n if (frame) view.cancelAnimationFrame(frame);\n frame = 0;\n listeners.abort();\n if (event && cell.hasPointerCapture(event.pointerId)) {\n cell.releasePointerCapture(event.pointerId);\n }\n };\n\n const move = (event: PointerEvent) => {\n if (event.pointerId !== down.pointerId) return;\n x = event.clientX;\n if (!dragging) {\n if (Math.hypot(x - startX, event.clientY - startY) < THRESHOLD) return;\n dragging = true;\n try {\n cell.setPointerCapture(event.pointerId);\n } catch {\n // Synthetic pointers can't be captured; the window listeners still see the moves.\n }\n options.onStart();\n }\n // No text selection while dragging.\n event.preventDefault();\n frame ||= view.requestAnimationFrame(tick);\n };\n\n const up = (event: PointerEvent) => {\n if (event.pointerId !== down.pointerId) return;\n cleanup(event);\n if (!dragging) return;\n x = event.clientX;\n const area = options.scrollArea();\n if (area) x = Math.min(Math.max(x, area.left), area.right);\n swallowClick(view);\n options.onDrop(options.targetAt(x));\n };\n\n const cancel = (event: PointerEvent) => {\n if (event.pointerId !== down.pointerId) return;\n cleanup(event);\n if (dragging) options.onCancel();\n };\n\n const key = (event: KeyboardEvent) => {\n if (!dragging || event.key !== 'Escape') return;\n event.preventDefault();\n event.stopPropagation();\n cleanup();\n // The pointer is still down: its release must not count as a click.\n swallowClick(view, false);\n options.onCancel();\n };\n\n const listen = { capture: true, signal: listeners.signal };\n view.addEventListener('pointermove', move, listen);\n view.addEventListener('pointerup', up, listen);\n view.addEventListener('pointercancel', cancel, listen);\n view.addEventListener('keydown', key, listen);\n}\n\n/**\n * Stops the click that follows the release of a drag, if one comes. It comes in\n * the same task as the release, so the guard goes once that task is over. After\n * Escape the pointer is still down (`released: false`): the guard waits for its release.\n */\nfunction swallowClick(view: Window, released = true): void {\n const stop = (event: MouseEvent) => {\n event.preventDefault();\n event.stopPropagation();\n };\n const remove = () => {\n setTimeout(() => {\n view.removeEventListener('click', stop, { capture: true });\n });\n };\n view.addEventListener('click', stop, { capture: true, once: true });\n if (released) remove();\n else view.addEventListener('pointerup', remove, { capture: true, once: true });\n}\n"],"mappings":";;;;;;AAuBA,SAAgB,WACd,OACA,WACA,GACA,WACwB;CACxB,MAAM,OAAO,MAAM,WAAW,MAAM,EAAE,OAAO,SAAS;CACtD,MAAM,QAAQ,MAAM;CACpB,MAAM,OAAO,MAAM,GAAG,EAAE;CACxB,IAAI,OAAO,KAAK,CAAC,SAAS,CAAC,MAAM,OAAO,KAAA;CAExC,IAAI,MAAM,MAAM,WAAW,OAAO,KAAK,EAAE,KAAK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CACpC;CAEA,MAAM,UAAU,UAAwB;EACtC,IAAI,MAAM,cAAc,KAAK,WAAW;EACxC,QAAQ,KAAK;EACb,IAAI,UAAU,QAAQ,SAAS;CACjC;CAEA,MAAM,OAAO,UAAyB;EACpC,IAAI,CAAC,YAAY,MAAM,QAAQ,UAAU;EACzC,MAAM,eAAe;EACrB,MAAM,gBAAgB;EACtB,QAAQ;EAER,aAAa,MAAM,KAAK;EACxB,QAAQ,SAAS;CACnB;CAEA,MAAM,SAAS;EAAE,SAAS;EAAM,QAAQ,UAAU;CAAO;CACzD,KAAK,iBAAiB,eAAe,MAAM,MAAM;CACjD,KAAK,iBAAiB,aAAa,IAAI,MAAM;CAC7C,KAAK,iBAAiB,iBAAiB,QAAQ,MAAM;CACrD,KAAK,iBAAiB,WAAW,KAAK,MAAM;AAC9C;;;;;;AAOA,SAAS,aAAa,MAAc,WAAW,MAAY;CACzD,MAAM,QAAQ,UAAsB;EAClC,MAAM,eAAe;EACrB,MAAM,gBAAgB;CACxB;CACA,MAAM,eAAe;EACnB,iBAAiB;GACf,KAAK,oBAAoB,SAAS,MAAM,EAAE,SAAS,KAAK,CAAC;EAC3D,CAAC;CACH;CACA,KAAK,iBAAiB,SAAS,MAAM;EAAE,SAAS;EAAM,MAAM;CAAK,CAAC;CAClE,IAAI,UAAU,OAAO;MAChB,KAAK,iBAAiB,aAAa,QAAQ;EAAE,SAAS;EAAM,MAAM;CAAK,CAAC;AAC/E"}
|
|
1
|
+
{"version":3,"file":"reorder-drag.js","names":[],"sources":["../../src/controllers/reorder-drag.ts"],"sourcesContent":["import { INTERACTIVE } from '../interactive.js';\n\n/** Where a dragged column would land: its new position and the header that shows the drop line. */\nexport interface DropTarget {\n /** Position in the whole column order after the move, 0-based. */\n to: number;\n /** The header that draws the drop line. */\n columnId: string;\n /** The edge of that header the line is on, in logical terms. */\n edge: 'start' | 'end';\n}\n\n/** A header of the dragged column's group, in visual order. */\nexport interface DropSlot {\n id: string;\n /** Its position in the whole column order, 0-based. */\n index: number;\n rect: { left: number; right: number };\n}\n\n/**\n * The drop target for a pointer at `x`: the gap between headers nearest to it,\n * decided by each header's midpoint. `undefined` where the column would stay\n * put. `direction` is 1 in LTR and -1 in RTL, where the group runs right to left.\n * The slots needn't be next to each other in the order: with\n * `virtualizeColumns`, headers out of view aren't rendered.\n */\nexport function dropTarget(\n slots: readonly DropSlot[],\n draggedId: string,\n x: number,\n direction: 1 | -1,\n): DropTarget | undefined {\n const dragged = slots.find((s) => s.id === draggedId);\n const last = slots.at(-1);\n if (!dragged || !last) return undefined;\n // The gap before the first header whose middle is past the pointer, in reading order.\n const at = slots.find((s) => (x - (s.rect.left + s.rect.right) / 2) * direction < 0);\n // Taking the column out shifts the ones after it one place back.\n const to = at\n ? at.index > dragged.index\n ? at.index - 1\n : at.index\n : last.index >= dragged.index\n ? last.index\n : last.index + 1;\n if (to === dragged.index) return undefined;\n return at ? { to, columnId: at.id, edge: 'start' } : { to, columnId: last.id, edge: 'end' };\n}\n\nexport interface ReorderDragOptions {\n /** The scroll container: it scrolls while the pointer is near its edges. */\n scroller: HTMLElement;\n /** The drop target for a pointer at `x` (client coordinates). */\n targetAt: (x: number) => DropTarget | undefined;\n /**\n * Where the dragged column's group is visible, in client x, if it can scroll\n * (the scrolling columns). Near these edges the scroller scrolls with the drag.\n */\n scrollArea: () => { left: number; right: number } | undefined;\n onStart: () => void;\n /** The target changed (`undefined`: the column would stay put). */\n onTarget: (target: DropTarget | undefined) => void;\n /** The pointer was released over a target, or `undefined` when it would stay put. */\n onDrop: (target: DropTarget | undefined) => void;\n /** Escape, a cancelled pointer, or a release without a drag. */\n onCancel: () => void;\n}\n\n/** Movement before a press becomes a drag, so a click still sorts. */\nconst THRESHOLD = 4;\n/** Width of the band at the scroll area's edges that scrolls, and the top speed there. */\nconst EDGE = 40;\nconst MAX_SPEED = 16;\n\n/**\n * Whether a press on a header may start a reorder drag: the primary button of a\n * mouse or pen (a touch pans the table instead), not on a resize handle, and not\n * in interactive content slotted into the header.\n */\nexport function canStartReorder(down: PointerEvent, cell: HTMLElement): boolean {\n if (down.button !== 0 || down.pointerType === 'touch') return false;\n for (const target of down.composedPath()) {\n if (target === cell) return true;\n if (!(target instanceof Element)) continue;\n if (target instanceof HTMLElement && target.dataset.resizeCol !== undefined) return false;\n if (target.matches(INTERACTIVE)) return false;\n }\n return false;\n}\n\n/**\n * One pointer drag of a column header. It becomes a drag after a few pixels of\n * movement; until then the press is a click. While dragging, the pointer is\n * captured by the header, the target follows the pointer once per frame, and the\n * scroll area scrolls near its edges. Escape cancels. The click that ends a drag\n * is swallowed, so it neither sorts nor counts as a cell click.\n */\nexport function startReorderDrag(\n cell: HTMLElement,\n down: PointerEvent,\n options: ReorderDragOptions,\n): void {\n const view = cell.ownerDocument.defaultView ?? window;\n const startX = down.clientX;\n const startY = down.clientY;\n let x = startX;\n let dragging = false;\n let frame = 0;\n let target: DropTarget | undefined;\n\n const same = (a: DropTarget | undefined, b: DropTarget | undefined) =>\n a?.to === b?.to && a?.columnId === b?.columnId && a?.edge === b?.edge;\n\n const tick = () => {\n frame = 0;\n if (!dragging) return;\n const area = options.scrollArea();\n if (area) {\n const speed =\n x < area.left + EDGE\n ? -Math.min(1, (area.left + EDGE - x) / EDGE)\n : x > area.right - EDGE\n ? Math.min(1, (x - (area.right - EDGE)) / EDGE)\n : 0;\n // A visual delta: scrollLeft runs the same way in LTR and RTL.\n if (speed !== 0) options.scroller.scrollLeft += Math.round(speed * MAX_SPEED);\n // Targets past the visible part would be hidden under pinned columns.\n x = Math.min(Math.max(x, area.left), area.right);\n }\n const next = options.targetAt(x);\n if (!same(next, target)) {\n target = next;\n options.onTarget(target);\n }\n // Keep running while dragging: the view may still be scrolling.\n frame = view.requestAnimationFrame(tick);\n };\n\n const listeners = new AbortController();\n const cleanup = (event?: PointerEvent) => {\n if (frame) view.cancelAnimationFrame(frame);\n frame = 0;\n listeners.abort();\n if (event && cell.hasPointerCapture(event.pointerId)) {\n cell.releasePointerCapture(event.pointerId);\n }\n };\n\n const move = (event: PointerEvent) => {\n if (event.pointerId !== down.pointerId) return;\n x = event.clientX;\n if (!dragging) {\n if (Math.hypot(x - startX, event.clientY - startY) < THRESHOLD) return;\n dragging = true;\n try {\n cell.setPointerCapture(event.pointerId);\n } catch {\n // Synthetic pointers can't be captured; the window listeners still see the moves.\n }\n options.onStart();\n }\n // No text selection while dragging.\n event.preventDefault();\n frame ||= view.requestAnimationFrame(tick);\n };\n\n const up = (event: PointerEvent) => {\n if (event.pointerId !== down.pointerId) return;\n cleanup(event);\n if (!dragging) return;\n x = event.clientX;\n const area = options.scrollArea();\n if (area) x = Math.min(Math.max(x, area.left), area.right);\n swallowClick(view);\n options.onDrop(options.targetAt(x));\n };\n\n const cancel = (event: PointerEvent) => {\n if (event.pointerId !== down.pointerId) return;\n cleanup(event);\n if (dragging) options.onCancel();\n };\n\n const key = (event: KeyboardEvent) => {\n if (!dragging || event.key !== 'Escape') return;\n event.preventDefault();\n event.stopPropagation();\n cleanup();\n // The pointer is still down: its release must not count as a click.\n swallowClick(view, false);\n options.onCancel();\n };\n\n const listen = { capture: true, signal: listeners.signal };\n view.addEventListener('pointermove', move, listen);\n view.addEventListener('pointerup', up, listen);\n view.addEventListener('pointercancel', cancel, listen);\n view.addEventListener('keydown', key, listen);\n}\n\n/**\n * Stops the click that follows the release of a drag, if one comes. It comes in\n * the same task as the release, so the guard goes once that task is over. After\n * Escape the pointer is still down (`released: false`): the guard waits for its release.\n */\nfunction swallowClick(view: Window, released = true): void {\n const stop = (event: MouseEvent) => {\n event.preventDefault();\n event.stopPropagation();\n };\n const remove = () => {\n setTimeout(() => {\n view.removeEventListener('click', stop, { capture: true });\n });\n };\n view.addEventListener('click', stop, { capture: true, once: true });\n if (released) remove();\n else view.addEventListener('pointerup', remove, { capture: true, once: true });\n}\n"],"mappings":";;;;;;;;;AA2BA,SAAgB,WACd,OACA,WACA,GACA,WACwB;CACxB,MAAM,UAAU,MAAM,MAAM,MAAM,EAAE,OAA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