@koeroesi86/canvas-grid 26.11.1 → 26.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,228 +9,17 @@ A fast data grid rendered on `<canvas>`, shipped as a framework-agnostic custom
9
9
  - Written in TypeScript, types included
10
10
  - Optional AG Grid-style adapter (`agApi`) for `setRowData` / `updateRowData` / `setColumnDefs`
11
11
 
12
- ## Install
12
+ Live demo and feature overview: https://koeroesi86.github.io/canvas-grid/
13
13
 
14
- ```sh
15
- npm install @koeroesi86/canvas-grid
16
- ```
14
+ ## Documentation
17
15
 
18
- Importing the package registers the `<canvas-grid>` element:
19
-
20
- ```ts
21
- import '@koeroesi86/canvas-grid';
22
- ```
23
-
24
- Or use the UMD build from a script tag (exposes `window.CanvasGrid`):
25
-
26
- ```html
27
- <script src="https://unpkg.com/@koeroesi86/canvas-grid/build/web-component.js"></script>
28
- ```
29
-
30
- ## Usage
31
-
32
- The element draws into its own box, so give it a size:
33
-
34
- ```html
35
- <style>
36
- canvas-grid { display: block; width: 100%; height: 400px; }
37
- </style>
38
- <canvas-grid></canvas-grid>
39
- ```
40
-
41
- ```ts
42
- import '@koeroesi86/canvas-grid';
43
-
44
- const grid = document.querySelector('canvas-grid')!; // typed as CanvasGridComponent
45
-
46
- grid.font = '12px "Roboto", sans-serif';
47
-
48
- grid.setColumns([
49
- 'name', // shorthand: id and header text
50
- { id: 'price', displayName: 'Price', width: 80, valueFormatter: v => Number(v).toFixed(2) },
51
- ]);
52
-
53
- grid.setValues([
54
- { id: 1, name: 'Apple', price: 1.2 },
55
- { id: 2, name: 'Pear', price: 0.9 },
56
- ]);
57
-
58
- // later: update single rows (batched and throttled internally)
59
- grid.queueUpdate({ id: 2, price: 1.0 });
60
- ```
61
-
62
- Before `setColumns` is called, the grid shows 50 numeric placeholder columns.
63
-
64
- ## API
65
-
66
- ### Data model
67
-
68
- | Concept | Shape |
69
- | --- | --- |
70
- | Row | `{ id: string \| number, [column: string]: unknown }`. `id` identifies the row (see `getRowId`) |
71
- | Column | `string \| number` (used as both id and header text), or an object (below) |
72
-
73
- Column object fields (`ColumnDefinition`):
74
-
75
- | Field | Default | Description |
76
- | --- | --- | --- |
77
- | `id` | required | Key of the row property shown in this column |
78
- | `displayName` | – | Header text. Not derived from `id` for object columns |
79
- | `width` | `100` | Column width in px |
80
- | `valueFormatter` | `String(value)` | Converts the raw value to the displayed string. Runs lazily, only for cells being drawn, and again only when the cell's value changes |
81
- | `renderers` | grid's `cellRenderers` | Renderers drawing a cell of this column, in order. Names of [registered renderers](#custom-renderers-and-layers) or renderer objects |
82
- | `headerRenderer` | `'header'` | Renderer drawing this column's header (name or object) |
83
-
84
- ### Methods
85
-
86
- | Method | Description |
87
- | --- | --- |
88
- | `setColumns(columns)` | Replaces the column set |
89
- | `setValues(rows)` | Replaces all rows. Pending updates are discarded |
90
- | `queueUpdate(row)` | Adds or updates a row (merged by `id`); only the given columns change |
91
- | `queueRemove(row)` | Removes the row with the same `id` |
92
- | `transaction({ add, update, remove })` | Batch form of the above |
93
- | `getRowData(id)` | `{ id, index, height, values }` for a row (`index` is its displayed position, `values` the raw values by column id), or `undefined` |
94
- | `setSortModel(keys)` / `getSortModel()` | Orders the rows, see [Sorting](#sorting). An empty list restores the original order |
95
- | `forceDraw()` | Clears and redraws everything |
96
- | `registerRenderer(name, renderer)` | Makes a [renderer](#custom-renderers-and-layers) available to columns by name; an existing name is replaced |
97
- | `unregisterRenderer(name)` | Removes a registered renderer |
98
- | `addLayer(name, { alpha, before })` | Adds a canvas on top of the others (or below the layer named in `before`) |
99
- | `removeLayer(name)` / `getLayer(name)` | Removes / looks up a layer (`{ name, canvas, ctx }`) |
100
-
101
- Updates are throttled (50 ms) and changed cells flash for `flashInDuration + flashOutDuration`.
102
-
103
- ### Properties
104
-
105
- | Property | Default | Description |
106
- | --- | --- | --- |
107
- | `font` | `'12px monospace'` | Cell font (CSS font shorthand) |
108
- | `headerFont` | `'13px monospace'` | Header font |
109
- | `getRowId` | `(row) => row.id` | Derives the row id; assign your own to key rows differently |
110
- | `showHeaders` | `true` | Show the header row |
111
- | `showRowNumbers` | `true` | Show the row-number column |
112
- | `rowNumbersWidth` | `30` | Width of the row-number column |
113
- | `headerHeight` | `30` | Header row height |
114
- | `cellHeight` | `20` | Row height. Set it before `setValues`, it applies to rows as they are created |
115
- | `fps` | `30` | Maximum redraw rate |
116
- | `cellRenderers` | `['background', 'value']` | Renderers used by columns without their own `renderers` |
117
- | `flashInDuration` | `200` | Fade-in of the update flash in ms |
118
- | `flashOutDuration` | `400` | Fade-out of the update flash in ms |
119
-
120
- ### Sorting
121
-
122
- ```js
123
- grid.setSortModel([
124
- { columnId: 'price', direction: 'desc' },
125
- { columnId: 'name' },
126
- ]);
127
- ```
128
-
129
- Keys apply in priority order; rows equal on every key keep their original order. By default numbers compare numerically, text with `Intl.Collator`, and empty values come last; a key can bring its own `compare(a, b)`. Row numbers follow the displayed order. The order is kept as rows are added or updated: new rows are placed by the model, and an update to a sorted column moves the row (re-sorting runs with the throttled updates, so it costs O(n log n) per batch). `setSortModel` works on raw values, so it does not depend on `valueFormatter`.
130
-
131
- ### Custom renderers and layers
132
-
133
- The grid draws onto stacked canvases called layers: `background`, `content` and `header` out of the box. A renderer draws into one layer and is registered under a name; columns select renderers by name. The built-in ones are `'background'` (fill, borders and the update flash), `'value'` (the text) and `'header'`.
134
-
135
- ```ts
136
- grid.addLayer('badges'); // on top of the existing layers
137
-
138
- grid.registerRenderer('badge', {
139
- layer: 'badges',
140
- draw({ ctx, x, y, width, formatted }) {
141
- ctx.fillStyle = formatted === 'sold out' ? '#c33' : '#3a3';
142
- ctx.fillRect(x + width - 8, y + 4, 4, 4);
143
- },
144
- });
145
-
146
- grid.setColumns([
147
- { id: 'status', renderers: ['background', 'value', 'badge'] },
148
- ]);
149
- ```
150
-
151
- A renderer is an object:
152
-
153
- | Member | Description |
154
- | --- | --- |
155
- | `layer` | Name of the layer its `ctx` belongs to |
156
- | `draw(cell)` | Draws one cell, header or row number |
157
- | `isAnimating?(cell)` | Return `true` while the cell is animating. Cells are only redrawn when something changed (value, scroll, resize) or while a renderer reports animation, plus once after it stops |
158
- | `clearCache?()` | Called when web fonts finish loading |
159
-
160
- `cell` (`CellContext`) is one object reused for every cell, so read what you need while drawing and do not keep a reference to it:
161
-
162
- | Field | Description |
163
- | --- | --- |
164
- | `ctx` | Context of the renderer's layer |
165
- | `x`, `y`, `width`, `height` | Cell rectangle in canvas pixels |
166
- | `row`, `column` | `{ id, index }` of the row and the column header; `row` is undefined for headers, `column` for row numbers |
167
- | `value`, `formatted` | Raw value and the string after the column's `valueFormatter` |
168
- | `updatedAt`, `age` | When the value last changed, and ms since then (`Infinity` if it never did) |
169
- | `now`, `dt` | Frame timestamp and ms since the previous draw (the grid only draws when something changed, so this can be long) |
170
- | `valueChanged` | The formatted value differs from what was drawn last time |
171
- | `forced` | Everything is being redrawn (first draw, resize, scrolling) |
172
- | `isScrolling` | The grid is being scrolled |
173
- | `state` | Object that persists per cell between frames, for your own bookkeeping. Kept for the 2048 most recently drawn rows, so it resets for a row that was scrolled far away |
174
-
175
- A renderer that animates, for example a pulse that lasts one second after a change:
176
-
177
- ```ts
178
- grid.registerRenderer('pulse', {
179
- layer: 'badges',
180
- isAnimating: ({ age }) => age < 1000,
181
- draw({ ctx, x, y, width, height, age }) {
182
- ctx.clearRect(x, y, width, height);
183
- if (age >= 1000) return;
184
- ctx.globalAlpha = 1 - age / 1000;
185
- ctx.fillStyle = '#39f';
186
- ctx.fillRect(x, y, width, height);
187
- ctx.globalAlpha = 1;
188
- },
189
- });
190
- ```
191
-
192
- > `cellRenderer(value, x, y, ...)` and `headerRenderer(header, x)` with positional arguments were replaced by the renderer objects above.
193
-
194
- ### AG Grid-style adapter
195
-
196
- `grid.agApi` mirrors a small part of AG Grid's API for easier migration:
197
-
198
- ```ts
199
- grid.agApi.setColumnDefs(columns);
200
- grid.agApi.setRowData(rows);
201
- grid.agApi.updateRowData({ add: [], update: [], remove: [] });
202
- grid.agApi.getRowNodeId = row => row.key;
203
- ```
204
-
205
- ### TypeScript
206
-
207
- Types ship with the package. Besides the element class (default export) it exports `ColumnHeader`, `ColumnDefinition`, `Transaction`, `CellRenderer`, `CellContext`, `CellState`, `RendererRef`, `LayerOptions`, `SortKey` and `SortDirection`, and registers `canvas-grid` in `HTMLElementTagNameMap`, so `document.querySelector('canvas-grid')` is typed.
208
-
209
- > The declarations are single-format. Bundler-style resolution (`moduleResolution: "bundler"`) works; strict Node16 ESM resolution may report the types as CommonJS.
210
-
211
- ## Browser support
212
-
213
- Modern evergreen browsers with Custom Elements v1 and Canvas 2D.
214
-
215
- ## Development
216
-
217
- Requires Node.js 22.18+ (the Node-side scripts are TypeScript run through Node's native type stripping).
218
-
219
- ```sh
220
- npm ci
221
- npm run dev # Vite dev server with a random-data websocket source, http://localhost:3000
222
- npm run build # type-check, then bundle (UMD + ESM) and emit declarations into build/
223
- npm test # type-check, release-script tests and data store unit tests
224
- npm run bench # data store benchmarks (BENCH_ROWS=1000,1000000 to change sizes)
225
- npm run bench:scroll # scroll FPS and frame-time p95 in headless Chromium (needs `npx playwright install chromium`)
226
- npm run serve-local # run only the example data server
227
- ```
228
-
229
- `DEV_PORT` (env or `.env`) changes the dev port.
230
-
231
- Releases are published to npm from CI when a `vX.Y.Z` tag is pushed (see `.github/workflows/publish.yml`).
232
-
233
- Pull requests also run the scroll benchmark against the base commit in CI (`.github/workflows/benchmark.yml`): base and head alternate three times on the same runner, and the job summary shows the median change. It fails on a regression of more than 30% in FPS or p95 frame time. Locally: `node scripts/compare-benchmarks.mts <path-to-base-checkout>`.
16
+ - [Getting started](docs/getting-started.md): install, usage, browser support
17
+ - [API reference](docs/api.md): data model, methods, properties
18
+ - [Sorting](docs/sorting.md)
19
+ - [Custom renderers and layers](docs/renderers.md)
20
+ - [AG Grid-style adapter](docs/ag-grid-adapter.md)
21
+ - [TypeScript](docs/typescript.md)
22
+ - [Development](docs/development.md): scripts, demo site, releases, benchmarks
234
23
 
235
24
  ## Security
236
25
 
@@ -1,6 +1,8 @@
1
1
  export interface LayerOptions {
2
2
  /** Transparent canvas. Opaque layers (`false`) draw faster; keep the bottom layer opaque. */
3
3
  alpha?: boolean;
4
+ /** Lets the browser present frames without syncing to the compositor: lower latency, but may tear. Off by default. */
5
+ desynchronized?: boolean;
4
6
  /** Name of an existing layer to stack this one below; defaults to the top. */
5
7
  before?: string;
6
8
  }
@@ -9,7 +11,7 @@ declare class Layer {
9
11
  readonly name: string;
10
12
  readonly canvas: HTMLCanvasElement;
11
13
  readonly ctx: CanvasRenderingContext2D;
12
- constructor(name: string, { alpha }?: Pick<LayerOptions, 'alpha'>);
14
+ constructor(name: string, { alpha, desynchronized }?: Pick<LayerOptions, 'alpha' | 'desynchronized'>);
13
15
  /** Size in CSS pixels; the backing store is `pixelRatio` times larger. */
14
16
  width: number;
15
17
  height: number;
@@ -110,7 +110,7 @@ declare class CanvasGridComponent extends HTMLElement {
110
110
  getLayer(name: string): Layer | undefined;
111
111
  private requireLayer;
112
112
  /** Adds a canvas on top of the existing layers, or below the layer named in `before`. */
113
- addLayer(name: string, { alpha, before }?: LayerOptions): Layer;
113
+ addLayer(name: string, { alpha, desynchronized, before }?: LayerOptions): Layer;
114
114
  removeLayer(name: string): void;
115
115
  /** Makes a renderer available to columns under `name`; registering an existing name replaces it. */
116
116
  registerRenderer(name: string, renderer: CellRenderer): void;
@@ -1,2 +1,2 @@
1
- (function(e,t){typeof exports==`object`&&typeof module<`u`?module.exports=t():typeof define==`function`&&define.amd?define([],t):(e=typeof globalThis<`u`?globalThis:e||self,e.CanvasGrid=t())})(this,function(){var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,o)=>(o=n==null?{}:e(i(n)),s(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n)),l=o(((e,t)=>{var n=`Expected a function`,r=NaN,i=/^\s+|\s+$/g,a=/^[-+]0x[0-9a-f]+$/i,o=/^0b[01]+$/i,s=/^0o[0-7]+$/i,c=parseInt,l=typeof global==`object`&&global&&global.Object===Object&&global,u=typeof self==`object`&&self&&self.Object===Object&&self,d=l||u||Function(`return this`)(),f=Object.prototype.toString,p=Math.max,m=Math.min,h=function(){return d.Date.now()};function g(e,t,r){var i,a,o,s,c,l,u=0,d=!1,f=!1,g=!0;if(typeof e!=`function`)throw TypeError(n);t=x(t)||0,v(r)&&(d=!!r.leading,f=`maxWait`in r,o=f?p(x(r.maxWait)||0,t):o,g=`trailing`in r?!!r.trailing:g);function _(t){var n=i,r=a;return i=a=void 0,u=t,s=e.apply(r,n),s}function y(e){return u=e,c=setTimeout(C,t),d?_(e):s}function b(e){var n=e-l,r=e-u,i=t-n;return f?m(i,o-r):i}function S(e){var n=e-l,r=e-u;return l===void 0||n>=t||n<0||f&&r>=o}function C(){var e=h();if(S(e))return w(e);c=setTimeout(C,b(e))}function w(e){return c=void 0,g&&i?_(e):(i=a=void 0,s)}function T(){c!==void 0&&clearTimeout(c),u=0,i=l=a=c=void 0}function E(){return c===void 0?s:w(h())}function D(){var e=h(),n=S(e);if(i=arguments,a=this,l=e,n){if(c===void 0)return y(l);if(f)return c=setTimeout(C,t),_(l)}return c===void 0&&(c=setTimeout(C,t)),s}return D.cancel=T,D.flush=E,D}function _(e,t,r){var i=!0,a=!0;if(typeof e!=`function`)throw TypeError(n);return v(r)&&(i=`leading`in r?!!r.leading:i,a=`trailing`in r?!!r.trailing:a),g(e,t,{leading:i,maxWait:t,trailing:a})}function v(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function y(e){return!!e&&typeof e==`object`}function b(e){return typeof e==`symbol`||y(e)&&f.call(e)==`[object Symbol]`}function x(e){if(typeof e==`number`)return e;if(b(e))return r;if(v(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=v(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=e.replace(i,``);var n=o.test(e);return n||s.test(e)?c(e.slice(2),n?2:8):a.test(e)?r:+e}t.exports=_})),u=o(((e,t)=>{var n=NaN,r=/^\s+|\s+$/g,i=/^[-+]0x[0-9a-f]+$/i,a=/^0b[01]+$/i,o=/^0o[0-7]+$/i,s=parseInt,c=typeof global==`object`&&global&&global.Object===Object&&global,l=typeof self==`object`&&self&&self.Object===Object&&self,u=c||l||Function(`return this`)(),d=Object.prototype.toString,f=Math.max,p=Math.min,m=function(){return u.Date.now()};function h(e,t,n){var r,i,a,o,s,c,l=0,u=!1,d=!1,h=!0;if(typeof e!=`function`)throw TypeError(`Expected a function`);t=y(t)||0,g(n)&&(u=!!n.leading,d=`maxWait`in n,a=d?f(y(n.maxWait)||0,t):a,h=`trailing`in n?!!n.trailing:h);function _(t){var n=r,a=i;return r=i=void 0,l=t,o=e.apply(a,n),o}function v(e){return l=e,s=setTimeout(S,t),u?_(e):o}function b(e){var n=e-c,r=e-l,i=t-n;return d?p(i,a-r):i}function x(e){var n=e-c,r=e-l;return c===void 0||n>=t||n<0||d&&r>=a}function S(){var e=m();if(x(e))return C(e);s=setTimeout(S,b(e))}function C(e){return s=void 0,h&&r?_(e):(r=i=void 0,o)}function w(){s!==void 0&&clearTimeout(s),l=0,r=c=i=s=void 0}function T(){return s===void 0?o:C(m())}function E(){var e=m(),n=x(e);if(r=arguments,i=this,c=e,n){if(s===void 0)return v(c);if(d)return s=setTimeout(S,t),_(c)}return s===void 0&&(s=setTimeout(S,t)),o}return E.cancel=w,E.flush=T,E}function g(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function _(e){return!!e&&typeof e==`object`}function v(e){return typeof e==`symbol`||_(e)&&d.call(e)==`[object Symbol]`}function y(e){if(typeof e==`number`)return e;if(v(e))return n;if(g(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=g(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=e.replace(r,``);var c=a.test(e);return c||o.test(e)?s(e.slice(2),c?2:8):i.test(e)?n:+e}t.exports=h})),d=c(l()),f=c(u()),p=class{entries=new Map;constructor(){this.get=this.get.bind(this),this.set=this.set.bind(this),this.clear=this.clear.bind(this),this.forEach=this.forEach.bind(this)}get keys(){return Array.from(this.entries.values(),e=>e.key)}get(e){return this.entries.get(String(e))?.value}set(e,t){let n=this.entries.get(String(e));n?n.value=t:this.entries.set(String(e),{key:e,value:t})}add(e){this.set(this.entries.size,e)}delete(e){this.entries.delete(String(e))}clear(e){typeof e==`function`?this.entries.forEach(({key:t,value:n},r)=>{e(n,t)&&this.entries.delete(r)}):this.entries.clear()}forEach(e){this.entries.forEach(({key:t,value:n})=>e(n,t))}get length(){return this.entries.size}},m=class{values;updatedAt=void 0;constructor(e=0){this.values=Array(e).fill(void 0)}get(e){return this.values[e]}getUpdatedAt(e){return this.updatedAt?.[e]||void 0}set(e,t,n){for(;this.values.length<e;)this.values.push(void 0);if(this.values[e]=t,n!==void 0||this.updatedAt!==void 0){for(this.updatedAt??=Array(this.values.length).fill(0);this.updatedAt.length<this.values.length;)this.updatedAt.push(0);this.updatedAt[e]=n??0}}removeSlots(e){if(e.length===0)return;let t=t=>{let n=0,r=0;for(let i=0;i<t.length;i++)r<e.length&&e[r]===i?r++:t[n++]=t[i];t.length=n};t(this.values),this.updatedAt&&t(this.updatedAt)}},h=class{items=[];indexById=new Map;tops=[];end=0;get length(){return this.items.length}get totalHeight(){return this.end}get keys(){return this.items.map(e=>e.id)}get(e){let t=this.indexById.get(String(e));return t===void 0?void 0:this.items[t]}at(e){return this.items[e]}topOf(e){return this.tops[e]??this.end}indexAt(e){if(e<=0)return 0;if(e>=this.end)return this.length;let t=0,n=this.items.length-1;for(;t<n;){let r=Math.ceil((t+n)/2);this.tops[r]<=e?t=r:n=r-1}return t}set(e){let t=this.indexById.get(String(e.id));if(t!==void 0){this.items[t]={...e,index:t,slot:this.items[t].slot},this.reindexFrom(t);return}let n=this.items.length;this.items.push({...e,index:n,slot:n}),this.indexById.set(String(e.id),n),this.tops.push(this.end),this.end+=Math.round(e.height)}removeMany(e){let t=new Set;if(e.forEach(e=>{let n=this.get(e);n&&t.add(n)}),t.size===0)return[];let n=Array.from(t,e=>e.slot).sort((e,t)=>e-t),r=Array.from(t).reduce((e,t)=>Math.min(e,t.index),1/0);t.forEach(e=>this.indexById.delete(String(e.id))),this.items=this.items.filter(e=>!t.has(e));let i=new Int32Array(this.items.length+n.length);for(let e=0,t=0;e<i.length;e++)n[t]===e&&t++,i[e]=t;return this.items.forEach(e=>{e.slot-=i[e.slot]}),this.reindexFrom(r),n}sort(e){this.items.sort(e),this.reindexFrom(0)}clear(){this.items=[],this.indexById.clear(),this.tops=[],this.end=0}reindexFrom(e){this.tops.length=this.items.length;let t=e===0?0:this.tops[e-1]+Math.round(this.items[e-1].height);for(let n=e;n<this.items.length;n++){let e=this.items[n];e.index=n,this.indexById.set(String(e.id),n),this.tops[n]=t,t+=Math.round(e.height)}this.end=t}},g=()=>new Date().valueOf(),_=(e,t)=>e.id,v=new Intl.Collator,y=e=>e==null?3:typeof e==`number`||typeof e==`bigint`?0:typeof e==`string`?1:2,b=(e,t)=>{let n=y(e)-y(t);return n===0?y(e)===3?0:y(e)===0?Number(e)-Number(t):v.compare(String(e),String(t)):n},x=class{rows=new h;columns=new Map;pending=[];sortModel=[];sortDirty=!1;environment;constructor(e){this.environment=e}get hasPending(){return this.pending.length>0}getSortModel(){return this.sortModel}setSortModel(e){this.sortModel=[...e],this.sort()}getValue(e,t){let n=this.rows.get(e);return n?this.columns.get(String(t))?.get(n.slot):void 0}getUpdatedAt(e,t){let n=this.rows.get(e);return n?this.columns.get(String(t))?.getUpdatedAt(n.slot):void 0}queueUpdate(e){this.pending.push({type:`update`,row:e})}queueRemove(e){this.pending.push({type:`remove`,row:e})}clear(){this.rows.clear(),this.columns.clear()}setRows(e){this.pending=[],this.clear(),e.forEach((e,t)=>this.addRow(this.environment.getRowId(e,t),e,void 0)),this.sort()}flush(e=g()){let t=this.pending;this.pending=[];let n=[],r=!1,i=()=>{r=this.removeRows(n)||r,n.length=0};return t.forEach(({type:t,row:r})=>{t===`remove`?n.push(this.environment.getRowId(r)):(i(),this.applyUpdate(r,e))}),i(),this.sortDirty?(this.sort(),!0):r}column(e){let t=this.columns.get(e);return t||(t=new m(this.rows.length),this.columns.set(e,t)),t}addRow(e,t,n){this.rows.set({id:e,height:this.environment.getCellHeight()});let r=this.rows.get(e)?.slot??0;Object.keys(t).forEach(e=>this.column(e).set(r,t[e],n)),this.markSortDirty(Object.keys(t))}removeRows(e){if(e.length===0)return!1;let t=this.rows.removeMany(e);return this.columns.forEach(e=>e.removeSlots(t)),t.length>0}applyUpdate(e,t){let n=this.environment.getRowId(e),r=this.rows.get(n);r?Object.keys(e).forEach(n=>this.applyValue(r.slot,n,e[n],t)):this.addRow(n,e,t)}applyValue(e,t,n,r){let i=this.column(t),a=i.get(e);a!==n&&(i.set(e,n,a===void 0?void 0:r),this.markSortDirty([t]))}markSortDirty(e){this.sortModel.some(({columnId:t})=>e.includes(String(t)))&&(this.sortDirty=!0)}sort(){this.sortDirty=!1;let e=this.sortModel.map(({columnId:e,direction:t=`asc`,compare:n=b})=>({values:this.columns.get(String(e))?.values,compare:n,sign:t===`desc`?-1:1}));this.rows.sort((t,n)=>{for(let{values:r,compare:i,sign:a}of e){let e=r?i(r[t.slot],r[n.slot]):0;if(e!==0)return e*a}return t.slot-n.slot})}},S=class{entries=new Map;limit;constructor(e){this.limit=e}get(e){let t=this.entries.get(e);if(t!==void 0)return this.entries.delete(e),this.entries.set(e,t),t}set(e,t){this.entries.delete(e),this.entries.set(e,t);let[n]=this.entries.keys();this.entries.size>this.limit&&n!==void 0&&this.entries.delete(n)}clear(){this.entries.clear()}get size(){return this.entries.size}},C=`canvas-grid{display:block;position:relative}canvas-grid,canvas-grid *{box-sizing:border-box;margin:0;padding:0}canvas-grid .drawingLayer{width:100%;height:100%;position:absolute;top:0;left:0}canvas-grid .scrollArea{z-index:10;backface-visibility:hidden;will-change:transform;width:100%;height:100%;position:absolute;top:0;left:0;overflow:auto}canvas-grid .scrollArea>div{will-change:scroll-position, transform}`,w=e=>!!e,T=e=>t=>({draw:(n,r,i)=>e(n,t,r,i)}),E=({x:e=0,y:t=0,children:n})=>({draw:(r,i,a)=>[n].flat(2).filter(w).forEach(n=>n.draw(r,i+e,a+t))}),D={createElement(e,t,...n){return e(Object.assign({},t,{children:n}))}},O=class{options;constructor(e){this.options={...e}}update(e){let t={...this.options};Object.assign(this.options,e),this.optionsUpdated(t)}optionsUpdated(e){}clearCache(){}},k=class extends O{bitmaps=new S(4096);cacheKey(e){}pixelRatio=1;clearCache(){this.bitmaps.clear()}paint(e,t,n,r){let i=this.cacheKey(t),a=(i===void 0?void 0:this.bitmaps.get(i))??this.renderBitmap(t,i);a.width<=0||a.height<=0||e.drawImage(a,n+(t.x??0),r+(t.y??0),a.width/this.pixelRatio,a.height/this.pixelRatio)}element=T((e,t,n,r)=>this.paint(e,t,n,r));renderBitmap(e,t){let n=this.render(e);if(t===void 0||n.width<=0||n.height<=0)return n;let r=document.createElement(`canvas`);return r.width=n.width,r.height=n.height,r.getContext(`2d`)?.drawImage(n,0,0),this.bitmaps.set(t,r),r}},A=(e,t)=>{let n=e.getContext(`2d`,t);if(!n)throw Error(`2D canvas context is not available`);return n},j=class extends O{ctx;offCanvas=document.createElement(`canvas`);offCtx;rotation=Math.PI/180*270;speed=6;count=75;constructor(e){super(e),this.ctx=this.options.ctx,this.offCanvas.width=250,this.offCanvas.height=250,this.offCtx=A(this.offCanvas),this.offCtx.lineWidth=.5,this.offCtx.strokeStyle=`rgba(255, 255, 255, 0.75)`}updateLoader(){this.rotation+=this.speed/100}renderLoader(){this.offCtx.save(),this.offCtx.globalCompositeOperation=`source-over`,this.offCtx.translate(125,125),this.offCtx.rotate(this.rotation);let e=this.count;for(;e--;)this.offCtx.beginPath(),this.offCtx.arc(0,0,e+Math.random()*35,Math.random(),Math.PI/3+Math.random()/12,!1),this.offCtx.stroke();this.offCtx.restore()}render(){this.offCtx.globalCompositeOperation=`destination-out`,this.offCtx.fillStyle=`rgba(255, 255, 255, 0.03)`,this.offCtx.fillRect(0,0,250,250),this.updateLoader(),this.renderLoader();let e=Math.round((this.ctx.canvas.width-this.offCanvas.width)/2),t=Math.round((this.ctx.canvas.height-this.offCanvas.height)/2);return this.ctx.clearRect(e,t,250,250),this.ctx.drawImage(this.offCanvas,e,t),this.offCanvas}},M=class{name;canvas=document.createElement(`canvas`);ctx;constructor(e,{alpha:t=!0}={}){this.name=e,this.canvas.className=`drawingLayer ${e}`,this.ctx=A(this.canvas,{alpha:t})}width=0;height=0;pixelRatio=1;resize(e,t,n=1){return e===this.width&&t===this.height&&n===this.pixelRatio?!1:(this.width=e,this.height=t,this.pixelRatio=n,this.canvas.width=Math.round(e*n),this.canvas.height=Math.round(t*n),this.ctx.setTransform(n,0,0,n,0,0),!0)}clear(){this.ctx.clearRect(0,0,this.width,this.height)}},N=class{renderers=new Map;warned=new Set;register(e,t){this.renderers.set(e,t),this.warned.delete(e)}unregister(e){this.renderers.delete(e)}get(e){return this.renderers.get(e)}resolve(e){if(typeof e!=`string`)return e;let t=this.renderers.get(e);return!t&&!this.warned.has(e)&&(this.warned.add(e),console.warn(`canvas-grid: no renderer registered as "${e}"`)),t}clearCaches(){this.renderers.forEach(e=>e.clearCache?.())}},P=T((e,{x:t=0,y:n=0,width:r,height:i,color:a,alpha:o=1},s,c)=>{let l=Math.trunc(r),u=Math.trunc(i);!a||l<=0||u<=0||o<=0||(e.fillStyle=a,o>=1?e.fillRect(s+t,c+n,l,u):(e.globalAlpha=o,e.fillRect(s+t,c+n,l,u),e.globalAlpha=1))}),F=class e extends O{static defaultOptions={layer:`background`,enableFlashing:!0,background:`#333`,flashInDuration:200,flashOutDuration:400,flashRGB:`214, 144, 13`,borderRightWidth:0,borderRightColor:`#fff`,borderBottomWidth:0,borderBottomColor:`#fff`};constructor(t={}){super({...e.defaultOptions,...t})}get layer(){return this.options.layer}isAnimating({age:e}){return this.options.enableFlashing&&e<=this.options.flashInDuration+this.options.flashOutDuration}getFlashAlpha(e){if(!this.options.enableFlashing)return 0;let{flashInDuration:t,flashOutDuration:n}=this.options,r=e<t?e/t:(t+n-e)/n;return Math.max(0,Math.round(r*1e3)/1e3)}draw({ctx:e,x:t,y:n,width:r,height:i,age:a}){let{background:o,flashRGB:s,borderRightWidth:c,borderRightColor:l,borderBottomWidth:u,borderBottomColor:d}=this.options,f=this.getFlashAlpha(a);D.createElement(E,null,D.createElement(P,{width:r,height:i,color:o}),f>0&&D.createElement(P,{width:r,height:i,color:`rgb(${s})`,alpha:f}),c>0&&D.createElement(P,{x:r-c,width:c,height:i,color:l}),u>0&&D.createElement(P,{y:i-u,width:r,height:u,color:d})).draw(e,t,n)}},I=class e extends k{static defaultOptions={font:`12px monospace`,color:`#fff`,alpha:!0,clearBeforeRender:!0};charWidthCache=new p;canvas=document.createElement(`canvas`);ctx;constructor(t={}){super({...e.defaultOptions,...t}),this.ctx=A(this.canvas,{alpha:this.options.alpha}),this.ctx.textAlign=`left`,this.ctx.textBaseline=`top`}set font(e){this.options.font!==e&&(this.options.font=e)}set color(e){this.options.color=e}clearCache(){super.clearCache(),this.charWidthCache.clear()}cacheKey({value:e=``,height:t=0}){return`${this.options.font}|${this.options.color}|${this.pixelRatio}|${t}|${e}`}getCharacterWidth(e=``){let t=this.charWidthCache.get(e);if(t)return t;this.ctx.font!==this.options.font&&(this.ctx.font=this.options.font,this.ctx.textAlign=`left`,this.ctx.textBaseline=`top`);let n=Math.ceil(this.ctx.measureText(e).width);return this.charWidthCache.set(e,n),n}render({value:e=``,height:t=0}){let{pixelRatio:n}=this;return this.canvas.width=Math.round(this.getCharacterWidth(e)*n),this.canvas.height=Math.round(t*n),this.ctx.setTransform(n,0,0,n,0,0),this.ctx.font=this.options.font,this.ctx.textAlign=`left`,this.ctx.textBaseline=`top`,this.ctx.fillStyle!==this.options.color&&(this.ctx.fillStyle=this.options.color),this.ctx.fillText(e,0,0),this.canvas}},L=class e extends O{static defaultOptions={ellipsis:`…`,cellPadding:{top:3,right:3,bottom:3,left:3},font:`12px monospace`,color:`#fff`,isEllipsisRight:!0};characterRenderer;constructor(t={}){super({...e.defaultOptions,...t}),this.characterRenderer=new I({font:this.options.font,color:this.options.color})}set font(e){this.options.font!==e&&(this.options.font=e,this.characterRenderer.font=e,this.clearCache())}get font(){return this.options.font}set color(e){this.options.color=e,this.characterRenderer.color=e}get color(){return this.options.color}set pixelRatio(e){this.characterRenderer.pixelRatio=e}get pixelRatio(){return this.characterRenderer.pixelRatio}clearCache(){this.characterRenderer.clearCache()}getTextWidth(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charAt(n);t+=this.characterRenderer.getCharacterWidth(r)}return t}paint(e,{value:t=``,x:n=0,y:r=0,width:i=0,height:a=0},o,s){let c=this.characterRenderer.getCharacterWidth(this.options.ellipsis),l=this.options.cellPadding.left+this.options.cellPadding.right,u=i-c-l,d=o+n,f=s+r+this.options.cellPadding.top,p=a-this.options.cellPadding.top-this.options.cellPadding.bottom,m=this.options.cellPadding.left,h=0;for(let n=0;n<t.length;n++){let r=t.charAt(n),i=Math.round(this.characterRenderer.getCharacterWidth(r));if(Math.ceil(h+i)>=u){this.characterRenderer.paint(e,{value:this.options.ellipsis,height:p},d+m,f);break}this.characterRenderer.paint(e,{value:r,height:p},d+m,f),h+=i,m+=i}}element=T((e,t,n,r)=>this.paint(e,t,n,r))},R=class e extends O{static defaultOptions={layer:`header`,background:`#333`,font:`13px monospace`,color:`#fff`,borderRightWidth:1,borderRightColor:`#fff`,borderBottomWidth:1,borderBottomColor:`#fff`};textRenderer;constructor(t={}){super({...e.defaultOptions,...t}),this.textRenderer=new L({font:this.options.font,color:this.options.color})}get layer(){return this.options.layer}set font(e){this.options.font=e,this.textRenderer.font=e}get font(){return this.textRenderer.font}set pixelRatio(e){this.textRenderer.pixelRatio=e}get pixelRatio(){return this.textRenderer.pixelRatio}clearCache(){this.textRenderer.clearCache()}draw({ctx:e,x:t,y:n,width:r,height:i,formatted:a}){if(r===0||i===0)return;let{background:o,borderRightWidth:s,borderRightColor:c,borderBottomWidth:l,borderBottomColor:u}=this.options;D.createElement(E,null,D.createElement(P,{width:r,height:i,color:o}),s>0&&D.createElement(P,{x:r-s,width:s,height:i,color:c}),l>0&&D.createElement(P,{y:i-l,width:r,height:l,color:u}),D.createElement(this.textRenderer.element,{value:a,width:r,height:i})).draw(e,t,n)}},z=class e extends O{static defaultOptions={layer:`content`,font:`12px monospace`,color:`#fff`};renderer;constructor(t={}){super({...e.defaultOptions,...t}),this.renderer=new L({font:this.options.font,color:this.options.color})}get layer(){return this.options.layer}set font(e){this.options.font=e,this.renderer.font=e}get font(){return this.options.font}set color(e){this.options.color=e,this.renderer.color=e}get color(){return this.options.color}set pixelRatio(e){this.renderer.pixelRatio=e}get pixelRatio(){return this.renderer.pixelRatio}clearCache(){this.renderer.clearCache()}draw({ctx:e,x:t,y:n,width:r,height:i,formatted:a,valueChanged:o,forced:s}){(o||s)&&(e.clearRect(t,n,r,i),D.createElement(this.renderer.element,{value:a,width:r,height:i}).draw(e,t,n))}},B={scrollArea:`scrollArea`},V={background:`background`,content:`content`,header:`header`,backgroundRenderer:`background`,valueRenderer:`value`,headerRenderer:`header`},H=`canvas-grid-styles`,U=()=>{if(document.getElementById(H))return;let e=document.createElement(`style`);e.id=H,e.textContent=C,document.head.appendChild(e)},W=class extends HTMLElement{fps=30;_font=`12px monospace`;_headerFont=`13px monospace`;headerHeight=30;cellHeight=20;cellPadding={top:3,right:3,bottom:3,left:3};showRowNumbers=!0;showHeaders=!0;rowNumbersWidth=30;ellipsis=`…`;_backgroundColor=`#333`;_headerBackgroundColor=`#222`;textColor=`#efefef`;dataStore=new x({getRowId:(e,t)=>this.getRowId(e,t),getCellHeight:()=>this.cellHeight});_dataCollection=this.dataStore.rows;cellEntries=new S(2048);getRowId=_;headers=new p;animationFrame=void 0;scrollYOffset=0;prevScrollYOffset=0;scrollXOffset=0;prevScrollXOffset=0;lastRender=new Date().valueOf();lastDraw=this.lastRender;isScrolling=!1;scrollHelper=document.createElement(`div`);scrollArea=this.createScrollArea();layers=[];layersByName=new Map;warnedLayers=new Set;renderers=new N;cellRenderers=[V.backgroundRenderer,V.valueRenderer];cellBackgroundRenderer=new F({layer:V.background,background:this._backgroundColor,enableFlashing:!0,flashInDuration:200,flashOutDuration:400,flashRGB:`214, 144, 13`,borderRightWidth:1,borderRightColor:`#3f3f3f`,borderBottomWidth:1,borderBottomColor:`#3f3f3f`});cellValueRenderer=new z({layer:V.content,font:this._font,color:this.textColor});headerCellRenderer=new R({layer:V.header,font:this._headerFont,color:this.textColor,background:`#222`,borderRightWidth:1,borderRightColor:`#2f2f2f`,borderBottomWidth:1,borderBottomColor:`#2f2f2f`});loadingIndicator;cell;placeholderState={};throttleTransation=(0,d.default)(()=>{let e=this.totalHeight,t=this.dataStore.flush();e!==this.totalHeight&&this.refreshScrollbar(),t&&this.forceDraw(),this.requestRender()},50);agApi;constructor(){super(),this.resize=this.resize.bind(this),this.setValues=this.setValues.bind(this),this.setColumns=this.setColumns.bind(this),this.clearValues=this.clearValues.bind(this),this.updateLastRender=this.updateLastRender.bind(this),this.transaction=this.transaction.bind(this),this.queueUpdate=this.queueUpdate.bind(this),this.addLayer(V.background,{alpha:!1}),this.addLayer(V.content),this.addLayer(V.header),this.registerRenderer(V.backgroundRenderer,this.cellBackgroundRenderer),this.registerRenderer(V.valueRenderer,this.cellValueRenderer),this.registerRenderer(V.headerRenderer,this.headerCellRenderer),this.loadingIndicator=new j({ctx:this.requireLayer(V.header).ctx}),this.cell={ctx:this.requireLayer(V.content).ctx,x:0,y:0,width:0,height:0,row:void 0,column:void 0,value:void 0,formatted:``,updatedAt:void 0,age:1/0,now:0,dt:0,valueChanged:!1,forced:!1,isScrolling:!1,state:{}};let e=this;this.agApi={setRowData:this.setValues,updateRowData:this.transaction,setColumnDefs:this.setColumns,get getRowNodeId(){return e.getRowId},set getRowNodeId(t){typeof t==`function`&&(e.getRowId=t)}}}get canvas(){return this.requireLayer(V.content).canvas}get flashInDuration(){return this.cellBackgroundRenderer.options.flashInDuration}set flashInDuration(e){this.cellBackgroundRenderer.update({flashInDuration:e})}get flashOutDuration(){return this.cellBackgroundRenderer.options.flashOutDuration}set flashOutDuration(e){this.cellBackgroundRenderer.update({flashOutDuration:e})}getLayer(e){return this.layersByName.get(e)}requireLayer(e){let t=this.getLayer(e);if(!t)throw Error(`canvas-grid: no layer named "${e}"`);return t}addLayer(e,{alpha:t=!0,before:n}={}){if(this.getLayer(e))throw Error(`canvas-grid: layer "${e}" already exists`);let r=new M(e,{alpha:t}),i=n===void 0?void 0:this.requireLayer(n);return this.layers.splice(i?this.layers.indexOf(i):this.layers.length,0,r),this.layersByName.set(e,r),this.scrollArea.parentElement===this&&(this.insertBefore(r.canvas,i?.canvas??this.scrollArea),r.resize(this.clientWidth,this.clientHeight,this.pixelRatio),this.forceDraw()),r}removeLayer(e){let t=this.requireLayer(e);this.layers=this.layers.filter(e=>e!==t),this.layersByName.delete(e),t.canvas.remove()}registerRenderer(e,t){this.renderers.register(e,t)}unregisterRenderer(e){this.renderers.unregister(e)}createScrollArea(){let e=document.createElement(`div`);return e.className=B.scrollArea,e.appendChild(this.scrollHelper),e}set font(e){this._font!==e&&(this._font=e,this.cellValueRenderer.font=e)}get font(){return this._font}set headerFont(e){this._headerFont!==e&&(this._headerFont=e,this.headerCellRenderer.font=e)}get headerFont(){return this._headerFont}connectedCallback(){this.layers.forEach(e=>this.appendChild(e.canvas)),this.appendChild(this.scrollArea),this.updateLastRender(),this.resize(),this.headers.length===0&&this.setColumns(Array(50).fill(1).map((e,t)=>t)),document.addEventListener(`visibilitychange`,this.onVisibilityChange),this.observeSize(),this.pixelRatioQuery=window.matchMedia(`(resolution: ${this.pixelRatio}dppx)`),this.pixelRatioQuery.addEventListener(`change`,this.watchPixelRatio,{once:!0}),document.fonts?document.fonts.addEventListener(`loadingdone`,this.onFontsLoaded):this.fontsTimeout=setTimeout(this.onFontsLoaded,2e3);let e=(0,f.default)(()=>{this.isScrolling=!1},200),t=(0,d.default)((t,n)=>{this.scrollXOffset=Math.round(n),this.scrollYOffset=Math.round(t),e(),this.requestRender()},10);this.scrollArea.addEventListener(`scroll`,()=>{let{scrollTop:e,scrollLeft:n}=this.scrollArea;this.isScrolling=!0,t(e,n)})}fontsTimeout=void 0;onVisibilityChange=()=>{document.visibilityState===`hidden`?this.cancelRender():this.resize()};onFontsLoaded=()=>{this.renderers.clearCaches(),this.resize()};cancelRender(){this.animationFrame!==void 0&&cancelAnimationFrame(this.animationFrame),this.animationFrame=void 0}requestRender(){this.animationFrame??=requestAnimationFrame(()=>this.render())}updateLastRender(){this.lastRender=new Date().valueOf()}render(){this.animationFrame=void 0,new Date().valueOf()-this.lastRender<1e3/this.fps?this.requestRender():(this.draw(),this.updateLastRender())}hasScrolled(){return this.hasXScrolled()||this.hasYScrolled()}hasYScrolled(){return this.prevScrollYOffset!==this.scrollYOffset}hasXScrolled(){return this.prevScrollXOffset!==this.scrollXOffset}isInViewport(e=0,t=0,n=0,r=0){return!(e>this.viewportWidth||t>this.viewportHeight||e+n<0||t+r<0)}describe(e,t,n,r,i){return Object.assign(this.cell,{x:e,y:t,width:n,height:r,row:void 0,column:void 0,value:void 0,formatted:``,updatedAt:void 0,age:1/0,valueChanged:!0,forced:!0,state:this.placeholderState},i)}paint(e){let t=this.renderers.resolve(e),n=t&&this.layersByName.get(t.layer);t&&!n&&!this.warnedLayers.has(t.layer)&&(this.warnedLayers.add(t.layer),console.warn(`canvas-grid: renderer draws on missing layer "${t.layer}"`)),t&&n&&(this.cell.ctx=n.ctx,t.draw(this.cell))}paintAll(e){e.forEach(e=>this.paint(e))}isAnimating(e){return e.some(e=>this.renderers.resolve(e)?.isAnimating?.(this.cell)===!0)}draw(e=!1){let t=new Date().valueOf(),n=e||this.hasScrolled();this.cell.now=t,this.cell.dt=t-this.lastDraw,this.cell.isScrolling=this.isScrolling,this.lastDraw=t;let r=this._dataCollection.length===0;if((e||this.hasXScrolled())&&this.showHeaders&&this.renderHeaders(),e&&this.showRowNumbers&&this._dataCollection.length===0)for(let e=0;e<=200;e++)this.renderRowNumber({index:e},e*this.cellHeight+(this.showHeaders?this.headerHeight:0)-this.scrollYOffset);if(this._dataCollection.length===0){this.loadingIndicator.render();for(let e=0;e<=200;e++)this.headers.forEach(t=>{this.describe(Math.round(t.index*t.width+(this.showRowNumbers?this.rowNumbersWidth:0)-this.scrollXOffset),Math.round(e*this.cellHeight+(this.showHeaders?this.headerHeight:0)-this.scrollYOffset),t.width,this.cellHeight,{column:t,valueChanged:!1}),this.paintAll(t.renderers??this.cellRenderers)})}let i=Math.round((this.showHeaders?this.headerHeight:0)-this.scrollYOffset),a=Math.round((this.showRowNumbers?this.rowNumbersWidth:0)-this.scrollXOffset),o=this._dataCollection.indexAt(-i),s=this.getVisibleColumns(a);for(let a=o;a<this._dataCollection.length;a++){let o=this._dataCollection.at(a),c=i+this._dataCollection.topOf(a);if(!o||c>=this.viewportHeight)break;let{id:l,slot:u}=o;if((e||this.hasYScrolled())&&this.showRowNumbers&&this.renderRowNumber(o,c),o.height+c>0){let e=this.cellEntries.get(String(l));e||(e={},this.cellEntries.set(String(l),e));let i={id:l,index:o.index};for(let{header:a,id:l,x:d,store:f}of s){let s=f?.get(u);if(s===void 0)continue;let p=e[l]??={value:void 0,formatted:void 0,animating:!1,state:{}},m=p.formatted!==void 0&&p.value===s?p.formatted:a.valueFormatter(s),h=p.formatted!==m,g=f?.getUpdatedAt(u),{cell:_}=this;_.x=d,_.y=c,_.width=a.width,_.height=o.height,_.row=i,_.column=a,_.value=s,_.formatted=m,_.updatedAt=g,_.age=g===void 0?1/0:t-g,_.valueChanged=h,_.forced=n,_.state=p.state;let v=a.renderers??this.cellRenderers,y=this.isAnimating(v);(n||h||y||p.animating)&&this.paintAll(v),p.animating=y,p.value=s,p.formatted=m,r||=y}}}(this.scrollYOffset>0||this.scrollXOffset>0)&&this.renderBrick(),this.prevScrollYOffset=this.scrollYOffset,this.prevScrollXOffset=this.scrollXOffset,r&&this.requestRender()}getVisibleColumns(e){let t=[],n=e;return this.headers.forEach((e,r)=>{this.isInViewport(n,0,e.width,0)&&t.push({header:e,id:String(r),x:n,store:this.dataStore.columns.get(String(r))}),n+=Math.round(e.width)}),t}renderRowNumber(e,t){this.isInViewport(0,t,this.rowNumbersWidth,e.height)&&(this.describe(0,Math.ceil(t),this.rowNumbersWidth,e.height??0,{row:{id:e.index,index:e.index},formatted:`${e.index+1}`}),this.paint(V.headerRenderer))}forceDraw(){this.layers.forEach(e=>e.clear()),this.draw(!0)}viewportWidth=0;viewportHeight=0;get pixelRatio(){return window.devicePixelRatio||1}resize(){this.cancelRender();let{pixelRatio:e}=this;this.viewportWidth=this.clientWidth,this.viewportHeight=this.clientHeight,this.layers.forEach(t=>t.resize(this.clientWidth,this.clientHeight,e)),this.cellValueRenderer.pixelRatio!==e&&this.renderers.clearCaches(),this.cellValueRenderer.pixelRatio=e,this.headerCellRenderer.pixelRatio=e,this.forceDraw()}observeSize(){this.resizeObserver??=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(this)}watchPixelRatio=()=>{this.pixelRatioQuery?.removeEventListener(`change`,this.watchPixelRatio),this.pixelRatioQuery=window.matchMedia(`(resolution: ${this.pixelRatio}dppx)`),this.pixelRatioQuery.addEventListener(`change`,this.watchPixelRatio,{once:!0}),this.resize()};resizeObserver=void 0;pixelRatioQuery=void 0;getRowData(e){let t=this._dataCollection.get(e);if(!t)return;let n={};return this.dataStore.columns.forEach((e,r)=>{let i=e.get(t.slot);i!==void 0&&(n[r]=i)}),{id:t.id,index:t.index,height:t.height,values:n}}setSortModel(e){this.dataStore.setSortModel(e),this.forceDraw()}getSortModel(){return this.dataStore.getSortModel()}renderBrick(){this.showHeaders&&this.showRowNumbers&&this._headerBackgroundColor&&(this.describe(0,0,this.rowNumbersWidth,this.headerHeight,{}),this.paint(V.headerRenderer))}renderHeaders(){let e=(this.showRowNumbers?this.rowNumbersWidth:0)-this.scrollXOffset;this.headers.forEach(t=>{this.isInViewport(e,0,t.width,this.headerHeight)&&(this.describe(e,0,t.width,this.headerHeight,{column:t,formatted:t.displayName??``}),this.paint(t.headerRenderer)),e+=t.width}),this.scrollXOffset+this.rowNumbersWidth>0&&this.renderBrick()}getColumnHeader(e){return this.headers.get(e)}get totalHeight(){return this._dataCollection.totalHeight}refreshScrollbar(){let e=this.totalHeight+this.headerHeight;this.scrollHelper.style.height=`${e}px`;let t=0;this.headers.forEach(e=>{t+=Math.round(e.width)}),this.scrollHelper.style.width=`${t}px`}queueUpdate(e){this.dataStore.queueUpdate(e),this.throttleTransation()}queueRemove(e){this.dataStore.queueRemove(e),this.throttleTransation()}transaction({add:e=[],remove:t=[],update:n=[]}){Array.isArray(e)&&e.forEach(e=>this.queueUpdate(e)),Array.isArray(n)&&n.forEach(e=>this.queueUpdate(e)),Array.isArray(t)&&t.forEach(e=>this.queueRemove(e))}clearValues(){this.dataStore.clear(),this.cellEntries.clear()}formatValue(e,t){return this.headers.get(e)?.valueFormatter(t)??String(t)}setValues(e){this.throttleTransation.cancel(),this.clearValues(),Array.isArray(e)&&(this.dataStore.setRows(e),this.refreshScrollbar(),this.forceDraw())}setColumns(e){if(Array.isArray(e)){this.headers.clear(),this.cellEntries.clear();let t={width:100,valueFormatter:e=>String(e),headerRenderer:V.headerRenderer};e.forEach((e,n)=>{if(typeof e==`string`||typeof e==`number`){let r=e+``;this.headers.set(r,{...t,index:n,id:e,displayName:r})}typeof e==`object`&&this.headers.set(e.id+``,{...t,index:n,...e})}),this.refreshScrollbar(),this.forceDraw()}}disconnectedCallback(){this.cancelRender(),document.removeEventListener(`visibilitychange`,this.onVisibilityChange),this.resizeObserver?.disconnect(),this.pixelRatioQuery?.removeEventListener(`change`,this.watchPixelRatio),document.fonts?.removeEventListener(`loadingdone`,this.onFontsLoaded),clearTimeout(this.fontsTimeout)}};return window&&window.customElements&&(U(),customElements.define(`canvas-grid`,W)),W});
1
+ (function(e,t){typeof exports==`object`&&typeof module<`u`?module.exports=t():typeof define==`function`&&define.amd?define([],t):(e=typeof globalThis<`u`?globalThis:e||self,e.CanvasGrid=t())})(this,function(){var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,o)=>(o=n==null?{}:e(i(n)),s(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n)),l=o(((e,t)=>{var n=`Expected a function`,r=NaN,i=/^\s+|\s+$/g,a=/^[-+]0x[0-9a-f]+$/i,o=/^0b[01]+$/i,s=/^0o[0-7]+$/i,c=parseInt,l=typeof global==`object`&&global&&global.Object===Object&&global,u=typeof self==`object`&&self&&self.Object===Object&&self,d=l||u||Function(`return this`)(),f=Object.prototype.toString,p=Math.max,m=Math.min,h=function(){return d.Date.now()};function g(e,t,r){var i,a,o,s,c,l,u=0,d=!1,f=!1,g=!0;if(typeof e!=`function`)throw TypeError(n);t=x(t)||0,v(r)&&(d=!!r.leading,f=`maxWait`in r,o=f?p(x(r.maxWait)||0,t):o,g=`trailing`in r?!!r.trailing:g);function _(t){var n=i,r=a;return i=a=void 0,u=t,s=e.apply(r,n),s}function y(e){return u=e,c=setTimeout(C,t),d?_(e):s}function b(e){var n=e-l,r=e-u,i=t-n;return f?m(i,o-r):i}function S(e){var n=e-l,r=e-u;return l===void 0||n>=t||n<0||f&&r>=o}function C(){var e=h();if(S(e))return w(e);c=setTimeout(C,b(e))}function w(e){return c=void 0,g&&i?_(e):(i=a=void 0,s)}function T(){c!==void 0&&clearTimeout(c),u=0,i=l=a=c=void 0}function E(){return c===void 0?s:w(h())}function D(){var e=h(),n=S(e);if(i=arguments,a=this,l=e,n){if(c===void 0)return y(l);if(f)return c=setTimeout(C,t),_(l)}return c===void 0&&(c=setTimeout(C,t)),s}return D.cancel=T,D.flush=E,D}function _(e,t,r){var i=!0,a=!0;if(typeof e!=`function`)throw TypeError(n);return v(r)&&(i=`leading`in r?!!r.leading:i,a=`trailing`in r?!!r.trailing:a),g(e,t,{leading:i,maxWait:t,trailing:a})}function v(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function y(e){return!!e&&typeof e==`object`}function b(e){return typeof e==`symbol`||y(e)&&f.call(e)==`[object Symbol]`}function x(e){if(typeof e==`number`)return e;if(b(e))return r;if(v(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=v(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=e.replace(i,``);var n=o.test(e);return n||s.test(e)?c(e.slice(2),n?2:8):a.test(e)?r:+e}t.exports=_})),u=o(((e,t)=>{var n=NaN,r=/^\s+|\s+$/g,i=/^[-+]0x[0-9a-f]+$/i,a=/^0b[01]+$/i,o=/^0o[0-7]+$/i,s=parseInt,c=typeof global==`object`&&global&&global.Object===Object&&global,l=typeof self==`object`&&self&&self.Object===Object&&self,u=c||l||Function(`return this`)(),d=Object.prototype.toString,f=Math.max,p=Math.min,m=function(){return u.Date.now()};function h(e,t,n){var r,i,a,o,s,c,l=0,u=!1,d=!1,h=!0;if(typeof e!=`function`)throw TypeError(`Expected a function`);t=y(t)||0,g(n)&&(u=!!n.leading,d=`maxWait`in n,a=d?f(y(n.maxWait)||0,t):a,h=`trailing`in n?!!n.trailing:h);function _(t){var n=r,a=i;return r=i=void 0,l=t,o=e.apply(a,n),o}function v(e){return l=e,s=setTimeout(S,t),u?_(e):o}function b(e){var n=e-c,r=e-l,i=t-n;return d?p(i,a-r):i}function x(e){var n=e-c,r=e-l;return c===void 0||n>=t||n<0||d&&r>=a}function S(){var e=m();if(x(e))return C(e);s=setTimeout(S,b(e))}function C(e){return s=void 0,h&&r?_(e):(r=i=void 0,o)}function w(){s!==void 0&&clearTimeout(s),l=0,r=c=i=s=void 0}function T(){return s===void 0?o:C(m())}function E(){var e=m(),n=x(e);if(r=arguments,i=this,c=e,n){if(s===void 0)return v(c);if(d)return s=setTimeout(S,t),_(c)}return s===void 0&&(s=setTimeout(S,t)),o}return E.cancel=w,E.flush=T,E}function g(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function _(e){return!!e&&typeof e==`object`}function v(e){return typeof e==`symbol`||_(e)&&d.call(e)==`[object Symbol]`}function y(e){if(typeof e==`number`)return e;if(v(e))return n;if(g(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=g(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=e.replace(r,``);var c=a.test(e);return c||o.test(e)?s(e.slice(2),c?2:8):i.test(e)?n:+e}t.exports=h})),d=c(l()),f=c(u()),p=class{entries=new Map;constructor(){this.get=this.get.bind(this),this.set=this.set.bind(this),this.clear=this.clear.bind(this),this.forEach=this.forEach.bind(this)}get keys(){return Array.from(this.entries.values(),e=>e.key)}get(e){return this.entries.get(String(e))?.value}set(e,t){let n=this.entries.get(String(e));n?n.value=t:this.entries.set(String(e),{key:e,value:t})}add(e){this.set(this.entries.size,e)}delete(e){this.entries.delete(String(e))}clear(e){typeof e==`function`?this.entries.forEach(({key:t,value:n},r)=>{e(n,t)&&this.entries.delete(r)}):this.entries.clear()}forEach(e){this.entries.forEach(({key:t,value:n})=>e(n,t))}get length(){return this.entries.size}},m=class{values;updatedAt=void 0;constructor(e=0){this.values=Array(e).fill(void 0)}get(e){return this.values[e]}getUpdatedAt(e){return this.updatedAt?.[e]||void 0}set(e,t,n){for(;this.values.length<e;)this.values.push(void 0);if(this.values[e]=t,n!==void 0||this.updatedAt!==void 0){for(this.updatedAt??=Array(this.values.length).fill(0);this.updatedAt.length<this.values.length;)this.updatedAt.push(0);this.updatedAt[e]=n??0}}removeSlots(e){if(e.length===0)return;let t=t=>{let n=0,r=0;for(let i=0;i<t.length;i++)r<e.length&&e[r]===i?r++:t[n++]=t[i];t.length=n};t(this.values),this.updatedAt&&t(this.updatedAt)}},h=class{items=[];indexById=new Map;tops=[];end=0;get length(){return this.items.length}get totalHeight(){return this.end}get keys(){return this.items.map(e=>e.id)}get(e){let t=this.indexById.get(String(e));return t===void 0?void 0:this.items[t]}at(e){return this.items[e]}topOf(e){return this.tops[e]??this.end}indexAt(e){if(e<=0)return 0;if(e>=this.end)return this.length;let t=0,n=this.items.length-1;for(;t<n;){let r=Math.ceil((t+n)/2);this.tops[r]<=e?t=r:n=r-1}return t}set(e){let t=this.indexById.get(String(e.id));if(t!==void 0){this.items[t]={...e,index:t,slot:this.items[t].slot},this.reindexFrom(t);return}let n=this.items.length;this.items.push({...e,index:n,slot:n}),this.indexById.set(String(e.id),n),this.tops.push(this.end),this.end+=Math.round(e.height)}removeMany(e){let t=new Set;if(e.forEach(e=>{let n=this.get(e);n&&t.add(n)}),t.size===0)return[];let n=Array.from(t,e=>e.slot).sort((e,t)=>e-t),r=Array.from(t).reduce((e,t)=>Math.min(e,t.index),1/0);t.forEach(e=>this.indexById.delete(String(e.id))),this.items=this.items.filter(e=>!t.has(e));let i=new Int32Array(this.items.length+n.length);for(let e=0,t=0;e<i.length;e++)n[t]===e&&t++,i[e]=t;return this.items.forEach(e=>{e.slot-=i[e.slot]}),this.reindexFrom(r),n}sort(e){this.items.sort(e),this.reindexFrom(0)}clear(){this.items=[],this.indexById.clear(),this.tops=[],this.end=0}reindexFrom(e){this.tops.length=this.items.length;let t=e===0?0:this.tops[e-1]+Math.round(this.items[e-1].height);for(let n=e;n<this.items.length;n++){let e=this.items[n];e.index=n,this.indexById.set(String(e.id),n),this.tops[n]=t,t+=Math.round(e.height)}this.end=t}},g=()=>new Date().valueOf(),_=(e,t)=>e.id,v=new Intl.Collator,y=e=>e==null?3:typeof e==`number`||typeof e==`bigint`?0:typeof e==`string`?1:2,b=(e,t)=>{let n=y(e)-y(t);return n===0?y(e)===3?0:y(e)===0?Number(e)-Number(t):v.compare(String(e),String(t)):n},x=class{rows=new h;columns=new Map;pending=[];sortModel=[];sortDirty=!1;environment;constructor(e){this.environment=e}get hasPending(){return this.pending.length>0}getSortModel(){return this.sortModel}setSortModel(e){this.sortModel=[...e],this.sort()}getValue(e,t){let n=this.rows.get(e);return n?this.columns.get(String(t))?.get(n.slot):void 0}getUpdatedAt(e,t){let n=this.rows.get(e);return n?this.columns.get(String(t))?.getUpdatedAt(n.slot):void 0}queueUpdate(e){this.pending.push({type:`update`,row:e})}queueRemove(e){this.pending.push({type:`remove`,row:e})}clear(){this.rows.clear(),this.columns.clear()}setRows(e){this.pending=[],this.clear(),e.forEach((e,t)=>this.addRow(this.environment.getRowId(e,t),e,void 0)),this.sort()}flush(e=g()){let t=this.pending;this.pending=[];let n=[],r=!1,i=()=>{r=this.removeRows(n)||r,n.length=0};return t.forEach(({type:t,row:r})=>{t===`remove`?n.push(this.environment.getRowId(r)):(i(),this.applyUpdate(r,e))}),i(),this.sortDirty?(this.sort(),!0):r}column(e){let t=this.columns.get(e);return t||(t=new m(this.rows.length),this.columns.set(e,t)),t}addRow(e,t,n){this.rows.set({id:e,height:this.environment.getCellHeight()});let r=this.rows.get(e)?.slot??0;Object.keys(t).forEach(e=>this.column(e).set(r,t[e],n)),this.markSortDirty(Object.keys(t))}removeRows(e){if(e.length===0)return!1;let t=this.rows.removeMany(e);return this.columns.forEach(e=>e.removeSlots(t)),t.length>0}applyUpdate(e,t){let n=this.environment.getRowId(e),r=this.rows.get(n);r?Object.keys(e).forEach(n=>this.applyValue(r.slot,n,e[n],t)):this.addRow(n,e,t)}applyValue(e,t,n,r){let i=this.column(t),a=i.get(e);a!==n&&(i.set(e,n,a===void 0?void 0:r),this.markSortDirty([t]))}markSortDirty(e){this.sortModel.some(({columnId:t})=>e.includes(String(t)))&&(this.sortDirty=!0)}sort(){this.sortDirty=!1;let e=this.sortModel.map(({columnId:e,direction:t=`asc`,compare:n=b})=>({values:this.columns.get(String(e))?.values,compare:n,sign:t===`desc`?-1:1}));this.rows.sort((t,n)=>{for(let{values:r,compare:i,sign:a}of e){let e=r?i(r[t.slot],r[n.slot]):0;if(e!==0)return e*a}return t.slot-n.slot})}},S=class{entries=new Map;limit;constructor(e){this.limit=e}get(e){let t=this.entries.get(e);if(t!==void 0)return this.entries.delete(e),this.entries.set(e,t),t}set(e,t){this.entries.delete(e),this.entries.set(e,t);let[n]=this.entries.keys();this.entries.size>this.limit&&n!==void 0&&this.entries.delete(n)}clear(){this.entries.clear()}get size(){return this.entries.size}},C=`canvas-grid{isolation:isolate;display:block;position:relative}canvas-grid,canvas-grid *{box-sizing:border-box;margin:0;padding:0}canvas-grid .drawingLayer{contain:strict;width:100%;height:100%;position:absolute;top:0;left:0}canvas-grid .scrollArea{z-index:10;backface-visibility:hidden;will-change:transform;width:100%;height:100%;position:absolute;top:0;left:0;overflow:auto}canvas-grid .scrollArea>div{will-change:scroll-position, transform}`,w=e=>!!e,T=e=>t=>({draw:(n,r,i)=>e(n,t,r,i)}),E=({x:e=0,y:t=0,children:n})=>({draw:(r,i,a)=>[n].flat(2).filter(w).forEach(n=>n.draw(r,i+e,a+t))}),D={createElement(e,t,...n){return e(Object.assign({},t,{children:n}))}},O=class{options;constructor(e){this.options={...e}}update(e){let t={...this.options};Object.assign(this.options,e),this.optionsUpdated(t)}optionsUpdated(e){}clearCache(){}},k=class extends O{bitmaps=new S(4096);cacheKey(e){}pixelRatio=1;clearCache(){this.bitmaps.clear()}paint(e,t,n,r){let i=this.cacheKey(t),a=(i===void 0?void 0:this.bitmaps.get(i))??this.renderBitmap(t,i);a.width<=0||a.height<=0||e.drawImage(a,n+(t.x??0),r+(t.y??0),a.width/this.pixelRatio,a.height/this.pixelRatio)}element=T((e,t,n,r)=>this.paint(e,t,n,r));renderBitmap(e,t){let n=this.render(e);if(t===void 0||n.width<=0||n.height<=0)return n;let r=document.createElement(`canvas`);return r.width=n.width,r.height=n.height,r.getContext(`2d`)?.drawImage(n,0,0),this.bitmaps.set(t,r),r}},A=(e,t)=>{let n=e.getContext(`2d`,t);if(!n)throw Error(`2D canvas context is not available`);return n},j=class extends O{ctx;offCanvas=document.createElement(`canvas`);offCtx;rotation=Math.PI/180*270;speed=6;count=75;constructor(e){super(e),this.ctx=this.options.ctx,this.offCanvas.width=250,this.offCanvas.height=250,this.offCtx=A(this.offCanvas),this.offCtx.lineWidth=.5,this.offCtx.strokeStyle=`rgba(255, 255, 255, 0.75)`}updateLoader(){this.rotation+=this.speed/100}renderLoader(){this.offCtx.save(),this.offCtx.globalCompositeOperation=`source-over`,this.offCtx.translate(125,125),this.offCtx.rotate(this.rotation);let e=this.count;for(;e--;)this.offCtx.beginPath(),this.offCtx.arc(0,0,e+Math.random()*35,Math.random(),Math.PI/3+Math.random()/12,!1),this.offCtx.stroke();this.offCtx.restore()}render(){this.offCtx.globalCompositeOperation=`destination-out`,this.offCtx.fillStyle=`rgba(255, 255, 255, 0.03)`,this.offCtx.fillRect(0,0,250,250),this.updateLoader(),this.renderLoader();let e=Math.round((this.ctx.canvas.width-this.offCanvas.width)/2),t=Math.round((this.ctx.canvas.height-this.offCanvas.height)/2);return this.ctx.clearRect(e,t,250,250),this.ctx.drawImage(this.offCanvas,e,t),this.offCanvas}},M=class{name;canvas=document.createElement(`canvas`);ctx;constructor(e,{alpha:t=!0,desynchronized:n=!1}={}){this.name=e,this.canvas.className=`drawingLayer ${e}`,this.ctx=A(this.canvas,{alpha:t,desynchronized:n})}width=0;height=0;pixelRatio=1;resize(e,t,n=1){return e===this.width&&t===this.height&&n===this.pixelRatio?!1:(this.width=e,this.height=t,this.pixelRatio=n,this.canvas.width=Math.round(e*n),this.canvas.height=Math.round(t*n),this.ctx.setTransform(n,0,0,n,0,0),!0)}clear(){this.ctx.clearRect(0,0,this.width,this.height)}},N=class{renderers=new Map;warned=new Set;register(e,t){this.renderers.set(e,t),this.warned.delete(e)}unregister(e){this.renderers.delete(e)}get(e){return this.renderers.get(e)}resolve(e){if(typeof e!=`string`)return e;let t=this.renderers.get(e);return!t&&!this.warned.has(e)&&(this.warned.add(e),console.warn(`canvas-grid: no renderer registered as "${e}"`)),t}clearCaches(){this.renderers.forEach(e=>e.clearCache?.())}},P=T((e,{x:t=0,y:n=0,width:r,height:i,color:a,alpha:o=1},s,c)=>{let l=Math.trunc(r),u=Math.trunc(i);!a||l<=0||u<=0||o<=0||(e.fillStyle=a,o>=1?e.fillRect(s+t,c+n,l,u):(e.globalAlpha=o,e.fillRect(s+t,c+n,l,u),e.globalAlpha=1))}),F=class e extends O{static defaultOptions={layer:`background`,enableFlashing:!0,background:`#333`,flashInDuration:200,flashOutDuration:400,flashRGB:`214, 144, 13`,borderRightWidth:0,borderRightColor:`#fff`,borderBottomWidth:0,borderBottomColor:`#fff`};constructor(t={}){super({...e.defaultOptions,...t})}get layer(){return this.options.layer}isAnimating({age:e}){return this.options.enableFlashing&&e<=this.options.flashInDuration+this.options.flashOutDuration}getFlashAlpha(e){if(!this.options.enableFlashing)return 0;let{flashInDuration:t,flashOutDuration:n}=this.options,r=e<t?e/t:(t+n-e)/n;return Math.max(0,Math.round(r*1e3)/1e3)}draw({ctx:e,x:t,y:n,width:r,height:i,age:a}){let{background:o,flashRGB:s,borderRightWidth:c,borderRightColor:l,borderBottomWidth:u,borderBottomColor:d}=this.options,f=this.getFlashAlpha(a);D.createElement(E,null,D.createElement(P,{width:r,height:i,color:o}),f>0&&D.createElement(P,{width:r,height:i,color:`rgb(${s})`,alpha:f}),c>0&&D.createElement(P,{x:r-c,width:c,height:i,color:l}),u>0&&D.createElement(P,{y:i-u,width:r,height:u,color:d})).draw(e,t,n)}},I=class e extends k{static defaultOptions={font:`12px monospace`,color:`#fff`,alpha:!0,clearBeforeRender:!0};charWidthCache=new p;canvas=document.createElement(`canvas`);ctx;constructor(t={}){super({...e.defaultOptions,...t}),this.ctx=A(this.canvas,{alpha:this.options.alpha}),this.ctx.textAlign=`left`,this.ctx.textBaseline=`top`}set font(e){this.options.font!==e&&(this.options.font=e)}set color(e){this.options.color=e}clearCache(){super.clearCache(),this.charWidthCache.clear()}cacheKey({value:e=``,height:t=0}){return`${this.options.font}|${this.options.color}|${this.pixelRatio}|${t}|${e}`}getCharacterWidth(e=``){let t=this.charWidthCache.get(e);if(t)return t;this.ctx.font!==this.options.font&&(this.ctx.font=this.options.font,this.ctx.textAlign=`left`,this.ctx.textBaseline=`top`);let n=Math.ceil(this.ctx.measureText(e).width);return this.charWidthCache.set(e,n),n}render({value:e=``,height:t=0}){let{pixelRatio:n}=this;return this.canvas.width=Math.round(this.getCharacterWidth(e)*n),this.canvas.height=Math.round(t*n),this.ctx.setTransform(n,0,0,n,0,0),this.ctx.font=this.options.font,this.ctx.textAlign=`left`,this.ctx.textBaseline=`top`,this.ctx.fillStyle!==this.options.color&&(this.ctx.fillStyle=this.options.color),this.ctx.fillText(e,0,0),this.canvas}},L=class e extends O{static defaultOptions={ellipsis:`…`,cellPadding:{top:3,right:3,bottom:3,left:3},font:`12px monospace`,color:`#fff`,isEllipsisRight:!0};characterRenderer;constructor(t={}){super({...e.defaultOptions,...t}),this.characterRenderer=new I({font:this.options.font,color:this.options.color})}set font(e){this.options.font!==e&&(this.options.font=e,this.characterRenderer.font=e,this.clearCache())}get font(){return this.options.font}set color(e){this.options.color=e,this.characterRenderer.color=e}get color(){return this.options.color}set pixelRatio(e){this.characterRenderer.pixelRatio=e}get pixelRatio(){return this.characterRenderer.pixelRatio}clearCache(){this.characterRenderer.clearCache()}getTextWidth(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charAt(n);t+=this.characterRenderer.getCharacterWidth(r)}return t}paint(e,{value:t=``,x:n=0,y:r=0,width:i=0,height:a=0},o,s){let c=this.characterRenderer.getCharacterWidth(this.options.ellipsis),l=this.options.cellPadding.left+this.options.cellPadding.right,u=i-c-l,d=o+n,f=s+r+this.options.cellPadding.top,p=a-this.options.cellPadding.top-this.options.cellPadding.bottom,m=this.options.cellPadding.left,h=0;for(let n=0;n<t.length;n++){let r=t.charAt(n),i=Math.round(this.characterRenderer.getCharacterWidth(r));if(Math.ceil(h+i)>=u){this.characterRenderer.paint(e,{value:this.options.ellipsis,height:p},d+m,f);break}this.characterRenderer.paint(e,{value:r,height:p},d+m,f),h+=i,m+=i}}element=T((e,t,n,r)=>this.paint(e,t,n,r))},R=class e extends O{static defaultOptions={layer:`header`,background:`#333`,font:`13px monospace`,color:`#fff`,borderRightWidth:1,borderRightColor:`#fff`,borderBottomWidth:1,borderBottomColor:`#fff`};textRenderer;constructor(t={}){super({...e.defaultOptions,...t}),this.textRenderer=new L({font:this.options.font,color:this.options.color})}get layer(){return this.options.layer}set font(e){this.options.font=e,this.textRenderer.font=e}get font(){return this.textRenderer.font}set pixelRatio(e){this.textRenderer.pixelRatio=e}get pixelRatio(){return this.textRenderer.pixelRatio}clearCache(){this.textRenderer.clearCache()}draw({ctx:e,x:t,y:n,width:r,height:i,formatted:a}){if(r===0||i===0)return;let{background:o,borderRightWidth:s,borderRightColor:c,borderBottomWidth:l,borderBottomColor:u}=this.options;D.createElement(E,null,D.createElement(P,{width:r,height:i,color:o}),s>0&&D.createElement(P,{x:r-s,width:s,height:i,color:c}),l>0&&D.createElement(P,{y:i-l,width:r,height:l,color:u}),D.createElement(this.textRenderer.element,{value:a,width:r,height:i})).draw(e,t,n)}},z=class e extends O{static defaultOptions={layer:`content`,font:`12px monospace`,color:`#fff`};renderer;constructor(t={}){super({...e.defaultOptions,...t}),this.renderer=new L({font:this.options.font,color:this.options.color})}get layer(){return this.options.layer}set font(e){this.options.font=e,this.renderer.font=e}get font(){return this.options.font}set color(e){this.options.color=e,this.renderer.color=e}get color(){return this.options.color}set pixelRatio(e){this.renderer.pixelRatio=e}get pixelRatio(){return this.renderer.pixelRatio}clearCache(){this.renderer.clearCache()}draw({ctx:e,x:t,y:n,width:r,height:i,formatted:a,valueChanged:o,forced:s}){(o||s)&&(e.clearRect(t,n,r,i),D.createElement(this.renderer.element,{value:a,width:r,height:i}).draw(e,t,n))}},B={scrollArea:`scrollArea`},V={background:`background`,content:`content`,header:`header`,backgroundRenderer:`background`,valueRenderer:`value`,headerRenderer:`header`},H=`canvas-grid-styles`,U=()=>{if(document.getElementById(H))return;let e=document.createElement(`style`);e.id=H,e.textContent=C,document.head.appendChild(e)},W=class extends HTMLElement{fps=30;_font=`12px monospace`;_headerFont=`13px monospace`;headerHeight=30;cellHeight=20;cellPadding={top:3,right:3,bottom:3,left:3};showRowNumbers=!0;showHeaders=!0;rowNumbersWidth=30;ellipsis=`…`;_backgroundColor=`#333`;_headerBackgroundColor=`#222`;textColor=`#efefef`;dataStore=new x({getRowId:(e,t)=>this.getRowId(e,t),getCellHeight:()=>this.cellHeight});_dataCollection=this.dataStore.rows;cellEntries=new S(2048);getRowId=_;headers=new p;animationFrame=void 0;scrollYOffset=0;prevScrollYOffset=0;scrollXOffset=0;prevScrollXOffset=0;lastRender=new Date().valueOf();lastDraw=this.lastRender;isScrolling=!1;scrollHelper=document.createElement(`div`);scrollArea=this.createScrollArea();layers=[];layersByName=new Map;warnedLayers=new Set;renderers=new N;cellRenderers=[V.backgroundRenderer,V.valueRenderer];cellBackgroundRenderer=new F({layer:V.background,background:this._backgroundColor,enableFlashing:!0,flashInDuration:200,flashOutDuration:400,flashRGB:`214, 144, 13`,borderRightWidth:1,borderRightColor:`#3f3f3f`,borderBottomWidth:1,borderBottomColor:`#3f3f3f`});cellValueRenderer=new z({layer:V.content,font:this._font,color:this.textColor});headerCellRenderer=new R({layer:V.header,font:this._headerFont,color:this.textColor,background:`#222`,borderRightWidth:1,borderRightColor:`#2f2f2f`,borderBottomWidth:1,borderBottomColor:`#2f2f2f`});loadingIndicator;cell;placeholderState={};throttleTransation=(0,d.default)(()=>{let e=this.totalHeight,t=this.dataStore.flush();e!==this.totalHeight&&this.refreshScrollbar(),t&&this.forceDraw(),this.requestRender()},50);agApi;constructor(){super(),this.resize=this.resize.bind(this),this.setValues=this.setValues.bind(this),this.setColumns=this.setColumns.bind(this),this.clearValues=this.clearValues.bind(this),this.updateLastRender=this.updateLastRender.bind(this),this.transaction=this.transaction.bind(this),this.queueUpdate=this.queueUpdate.bind(this),this.addLayer(V.background,{alpha:!1}),this.addLayer(V.content),this.addLayer(V.header),this.registerRenderer(V.backgroundRenderer,this.cellBackgroundRenderer),this.registerRenderer(V.valueRenderer,this.cellValueRenderer),this.registerRenderer(V.headerRenderer,this.headerCellRenderer),this.loadingIndicator=new j({ctx:this.requireLayer(V.header).ctx}),this.cell={ctx:this.requireLayer(V.content).ctx,x:0,y:0,width:0,height:0,row:void 0,column:void 0,value:void 0,formatted:``,updatedAt:void 0,age:1/0,now:0,dt:0,valueChanged:!1,forced:!1,isScrolling:!1,state:{}};let e=this;this.agApi={setRowData:this.setValues,updateRowData:this.transaction,setColumnDefs:this.setColumns,get getRowNodeId(){return e.getRowId},set getRowNodeId(t){typeof t==`function`&&(e.getRowId=t)}}}get canvas(){return this.requireLayer(V.content).canvas}get flashInDuration(){return this.cellBackgroundRenderer.options.flashInDuration}set flashInDuration(e){this.cellBackgroundRenderer.update({flashInDuration:e})}get flashOutDuration(){return this.cellBackgroundRenderer.options.flashOutDuration}set flashOutDuration(e){this.cellBackgroundRenderer.update({flashOutDuration:e})}getLayer(e){return this.layersByName.get(e)}requireLayer(e){let t=this.getLayer(e);if(!t)throw Error(`canvas-grid: no layer named "${e}"`);return t}addLayer(e,{alpha:t=!0,desynchronized:n=!1,before:r}={}){if(this.getLayer(e))throw Error(`canvas-grid: layer "${e}" already exists`);let i=new M(e,{alpha:t,desynchronized:n}),a=r===void 0?void 0:this.requireLayer(r);return this.layers.splice(a?this.layers.indexOf(a):this.layers.length,0,i),this.layersByName.set(e,i),this.scrollArea.parentElement===this&&(this.insertBefore(i.canvas,a?.canvas??this.scrollArea),i.resize(this.clientWidth,this.clientHeight,this.pixelRatio),this.forceDraw()),i}removeLayer(e){let t=this.requireLayer(e);this.layers=this.layers.filter(e=>e!==t),this.layersByName.delete(e),t.canvas.remove()}registerRenderer(e,t){this.renderers.register(e,t)}unregisterRenderer(e){this.renderers.unregister(e)}createScrollArea(){let e=document.createElement(`div`);return e.className=B.scrollArea,e.appendChild(this.scrollHelper),e}set font(e){this._font!==e&&(this._font=e,this.cellValueRenderer.font=e)}get font(){return this._font}set headerFont(e){this._headerFont!==e&&(this._headerFont=e,this.headerCellRenderer.font=e)}get headerFont(){return this._headerFont}connectedCallback(){this.layers.forEach(e=>this.appendChild(e.canvas)),this.appendChild(this.scrollArea),this.updateLastRender(),this.resize(),this.headers.length===0&&this.setColumns(Array(50).fill(1).map((e,t)=>t)),document.addEventListener(`visibilitychange`,this.onVisibilityChange),this.observeSize(),this.pixelRatioQuery=window.matchMedia(`(resolution: ${this.pixelRatio}dppx)`),this.pixelRatioQuery.addEventListener(`change`,this.watchPixelRatio,{once:!0}),document.fonts?document.fonts.addEventListener(`loadingdone`,this.onFontsLoaded):this.fontsTimeout=setTimeout(this.onFontsLoaded,2e3);let e=(0,f.default)(()=>{this.isScrolling=!1},200),t=(0,d.default)((t,n)=>{this.scrollXOffset=Math.round(n),this.scrollYOffset=Math.round(t),e(),this.requestRender()},10);this.scrollArea.addEventListener(`scroll`,()=>{let{scrollTop:e,scrollLeft:n}=this.scrollArea;this.isScrolling=!0,t(e,n)})}fontsTimeout=void 0;onVisibilityChange=()=>{document.visibilityState===`hidden`?this.cancelRender():this.resize()};onFontsLoaded=()=>{this.renderers.clearCaches(),this.resize()};cancelRender(){this.animationFrame!==void 0&&cancelAnimationFrame(this.animationFrame),this.animationFrame=void 0}requestRender(){this.animationFrame??=requestAnimationFrame(()=>this.render())}updateLastRender(){this.lastRender=new Date().valueOf()}render(){this.animationFrame=void 0,new Date().valueOf()-this.lastRender<1e3/this.fps?this.requestRender():(this.draw(),this.updateLastRender())}hasScrolled(){return this.hasXScrolled()||this.hasYScrolled()}hasYScrolled(){return this.prevScrollYOffset!==this.scrollYOffset}hasXScrolled(){return this.prevScrollXOffset!==this.scrollXOffset}isInViewport(e=0,t=0,n=0,r=0){return!(e>this.viewportWidth||t>this.viewportHeight||e+n<0||t+r<0)}describe(e,t,n,r,i){return Object.assign(this.cell,{x:e,y:t,width:n,height:r,row:void 0,column:void 0,value:void 0,formatted:``,updatedAt:void 0,age:1/0,valueChanged:!0,forced:!0,state:this.placeholderState},i)}paint(e){let t=this.renderers.resolve(e),n=t&&this.layersByName.get(t.layer);t&&!n&&!this.warnedLayers.has(t.layer)&&(this.warnedLayers.add(t.layer),console.warn(`canvas-grid: renderer draws on missing layer "${t.layer}"`)),t&&n&&(this.cell.ctx=n.ctx,t.draw(this.cell))}paintAll(e){e.forEach(e=>this.paint(e))}isAnimating(e){return e.some(e=>this.renderers.resolve(e)?.isAnimating?.(this.cell)===!0)}draw(e=!1){let t=new Date().valueOf(),n=e||this.hasScrolled();this.cell.now=t,this.cell.dt=t-this.lastDraw,this.cell.isScrolling=this.isScrolling,this.lastDraw=t;let r=this._dataCollection.length===0;if((e||this.hasXScrolled())&&this.showHeaders&&this.renderHeaders(),e&&this.showRowNumbers&&this._dataCollection.length===0)for(let e=0;e<=200;e++)this.renderRowNumber({index:e},e*this.cellHeight+(this.showHeaders?this.headerHeight:0)-this.scrollYOffset);if(this._dataCollection.length===0){this.loadingIndicator.render();for(let e=0;e<=200;e++)this.headers.forEach(t=>{this.describe(Math.round(t.index*t.width+(this.showRowNumbers?this.rowNumbersWidth:0)-this.scrollXOffset),Math.round(e*this.cellHeight+(this.showHeaders?this.headerHeight:0)-this.scrollYOffset),t.width,this.cellHeight,{column:t,valueChanged:!1}),this.paintAll(t.renderers??this.cellRenderers)})}let i=Math.round((this.showHeaders?this.headerHeight:0)-this.scrollYOffset),a=Math.round((this.showRowNumbers?this.rowNumbersWidth:0)-this.scrollXOffset),o=this._dataCollection.indexAt(-i),s=this.getVisibleColumns(a);for(let a=o;a<this._dataCollection.length;a++){let o=this._dataCollection.at(a),c=i+this._dataCollection.topOf(a);if(!o||c>=this.viewportHeight)break;let{id:l,slot:u}=o;if((e||this.hasYScrolled())&&this.showRowNumbers&&this.renderRowNumber(o,c),o.height+c>0){let e=this.cellEntries.get(String(l));e||(e={},this.cellEntries.set(String(l),e));let i={id:l,index:o.index};for(let{header:a,id:l,x:d,store:f}of s){let s=f?.get(u);if(s===void 0)continue;let p=e[l]??={value:void 0,formatted:void 0,animating:!1,state:{}},m=p.formatted!==void 0&&p.value===s?p.formatted:a.valueFormatter(s),h=p.formatted!==m,g=f?.getUpdatedAt(u),{cell:_}=this;_.x=d,_.y=c,_.width=a.width,_.height=o.height,_.row=i,_.column=a,_.value=s,_.formatted=m,_.updatedAt=g,_.age=g===void 0?1/0:t-g,_.valueChanged=h,_.forced=n,_.state=p.state;let v=a.renderers??this.cellRenderers,y=this.isAnimating(v);(n||h||y||p.animating)&&this.paintAll(v),p.animating=y,p.value=s,p.formatted=m,r||=y}}}(this.scrollYOffset>0||this.scrollXOffset>0)&&this.renderBrick(),this.prevScrollYOffset=this.scrollYOffset,this.prevScrollXOffset=this.scrollXOffset,r&&this.requestRender()}getVisibleColumns(e){let t=[],n=e;return this.headers.forEach((e,r)=>{this.isInViewport(n,0,e.width,0)&&t.push({header:e,id:String(r),x:n,store:this.dataStore.columns.get(String(r))}),n+=Math.round(e.width)}),t}renderRowNumber(e,t){this.isInViewport(0,t,this.rowNumbersWidth,e.height)&&(this.describe(0,Math.ceil(t),this.rowNumbersWidth,e.height??0,{row:{id:e.index,index:e.index},formatted:`${e.index+1}`}),this.paint(V.headerRenderer))}forceDraw(){this.layers.forEach(e=>e.clear()),this.draw(!0)}viewportWidth=0;viewportHeight=0;get pixelRatio(){return window.devicePixelRatio||1}resize(){this.cancelRender();let{pixelRatio:e}=this;this.viewportWidth=this.clientWidth,this.viewportHeight=this.clientHeight,this.layers.forEach(t=>t.resize(this.clientWidth,this.clientHeight,e)),this.cellValueRenderer.pixelRatio!==e&&this.renderers.clearCaches(),this.cellValueRenderer.pixelRatio=e,this.headerCellRenderer.pixelRatio=e,this.forceDraw()}observeSize(){this.resizeObserver??=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(this)}watchPixelRatio=()=>{this.pixelRatioQuery?.removeEventListener(`change`,this.watchPixelRatio),this.pixelRatioQuery=window.matchMedia(`(resolution: ${this.pixelRatio}dppx)`),this.pixelRatioQuery.addEventListener(`change`,this.watchPixelRatio,{once:!0}),this.resize()};resizeObserver=void 0;pixelRatioQuery=void 0;getRowData(e){let t=this._dataCollection.get(e);if(!t)return;let n={};return this.dataStore.columns.forEach((e,r)=>{let i=e.get(t.slot);i!==void 0&&(n[r]=i)}),{id:t.id,index:t.index,height:t.height,values:n}}setSortModel(e){this.dataStore.setSortModel(e),this.forceDraw()}getSortModel(){return this.dataStore.getSortModel()}renderBrick(){this.showHeaders&&this.showRowNumbers&&this._headerBackgroundColor&&(this.describe(0,0,this.rowNumbersWidth,this.headerHeight,{}),this.paint(V.headerRenderer))}renderHeaders(){let e=(this.showRowNumbers?this.rowNumbersWidth:0)-this.scrollXOffset;this.headers.forEach(t=>{this.isInViewport(e,0,t.width,this.headerHeight)&&(this.describe(e,0,t.width,this.headerHeight,{column:t,formatted:t.displayName??``}),this.paint(t.headerRenderer)),e+=t.width}),this.scrollXOffset+this.rowNumbersWidth>0&&this.renderBrick()}getColumnHeader(e){return this.headers.get(e)}get totalHeight(){return this._dataCollection.totalHeight}refreshScrollbar(){let e=this.totalHeight+this.headerHeight;this.scrollHelper.style.height=`${e}px`;let t=0;this.headers.forEach(e=>{t+=Math.round(e.width)}),this.scrollHelper.style.width=`${t}px`}queueUpdate(e){this.dataStore.queueUpdate(e),this.throttleTransation()}queueRemove(e){this.dataStore.queueRemove(e),this.throttleTransation()}transaction({add:e=[],remove:t=[],update:n=[]}){Array.isArray(e)&&e.forEach(e=>this.queueUpdate(e)),Array.isArray(n)&&n.forEach(e=>this.queueUpdate(e)),Array.isArray(t)&&t.forEach(e=>this.queueRemove(e))}clearValues(){this.dataStore.clear(),this.cellEntries.clear()}formatValue(e,t){return this.headers.get(e)?.valueFormatter(t)??String(t)}setValues(e){this.throttleTransation.cancel(),this.clearValues(),Array.isArray(e)&&(this.dataStore.setRows(e),this.refreshScrollbar(),this.forceDraw())}setColumns(e){if(Array.isArray(e)){this.headers.clear(),this.cellEntries.clear();let t={width:100,valueFormatter:e=>String(e),headerRenderer:V.headerRenderer};e.forEach((e,n)=>{if(typeof e==`string`||typeof e==`number`){let r=e+``;this.headers.set(r,{...t,index:n,id:e,displayName:r})}typeof e==`object`&&this.headers.set(e.id+``,{...t,index:n,...e})}),this.refreshScrollbar(),this.forceDraw()}}disconnectedCallback(){this.cancelRender(),document.removeEventListener(`visibilitychange`,this.onVisibilityChange),this.resizeObserver?.disconnect(),this.pixelRatioQuery?.removeEventListener(`change`,this.watchPixelRatio),document.fonts?.removeEventListener(`loadingdone`,this.onFontsLoaded),clearTimeout(this.fontsTimeout)}};return window&&window.customElements&&(U(),customElements.define(`canvas-grid`,W)),W});
2
2
  //# sourceMappingURL=web-component.js.map