@omnigrid/core 0.1.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.
@@ -0,0 +1,358 @@
1
+ import type { SlotManager } from "./slots";
2
+ export type RowId = string | number;
3
+ export type SortDirection = "asc" | "desc";
4
+ export type CellAlign = "left" | "center" | "right";
5
+ export type DataProcessor<T> = (data: T[]) => T[];
6
+ export interface RowRenderParams<T> {
7
+ id: RowId;
8
+ index: number;
9
+ data: T;
10
+ }
11
+ export interface RowStyle {
12
+ [property: string]: string | number | undefined;
13
+ }
14
+ /**
15
+ * Dynamic rules for assigning CSS classes to rows.
16
+ *
17
+ * The key is the CSS class name, the value is a predicate that receives row
18
+ * parameters (`RowRenderParams`) and returns `true` when the class should be
19
+ * applied. Rules are dynamic: re-evaluated on every viewport commit and
20
+ * applied in batch to all visible rows at once.
21
+ */
22
+ export type RowClassRules<T> = Record<string, (params: RowRenderParams<T>) => boolean>;
23
+ /**
24
+ * Context passed to every cell-level callback (`cellRenderer`, `getCellStyle`,
25
+ * `cellClass`, `getCellClass`, `cellClassRules`).
26
+ *
27
+ * Shape is the same for all of them. `value` is populated when the engine
28
+ * renders the cell content (`cellRenderer`); the style / class resolution
29
+ * passes may omit it (marks are `value?: unknown` to avoid computing the
30
+ * per-cell value on every presentation pass).
31
+ */
32
+ export interface CellRenderParams<T> {
33
+ id: RowId;
34
+ index: number;
35
+ data: T;
36
+ column: ColumnLeafDef<T>;
37
+ value?: unknown;
38
+ }
39
+ export type CellClassRules<T> = Record<string, (params: CellRenderParams<T>) => boolean>;
40
+ export interface CheckboxRenderParams {
41
+ checked: boolean;
42
+ indeterminate: boolean;
43
+ disabled: boolean;
44
+ ariaLabel: string;
45
+ onChange: (event: {
46
+ shiftKey: boolean;
47
+ ctrlKey: boolean;
48
+ }) => void;
49
+ }
50
+ export interface CheckboxControl extends CheckboxRenderParams {
51
+ type: "@omnigrid/checkbox";
52
+ }
53
+ interface BaseColumnDef<T> {
54
+ id: string;
55
+ header: string;
56
+ pinned?: "left" | "right";
57
+ headerRenderer?: (column: ColumnDef<T>) => unknown;
58
+ }
59
+ export interface ColumnLeafDef<T> extends BaseColumnDef<T> {
60
+ field?: keyof T | string;
61
+ hidden?: boolean;
62
+ flex?: number;
63
+ width?: number;
64
+ minWidth?: number;
65
+ maxWidth?: number;
66
+ sortable?: boolean;
67
+ align?: CellAlign;
68
+ sortState?: SortDirection;
69
+ stopRowClick?: boolean;
70
+ stopHeaderClick?: boolean;
71
+ valueGetter?: (row: T) => unknown;
72
+ valueFormatter?: (value: unknown) => string;
73
+ cellRenderer?: (params: CellRenderParams<T>) => unknown;
74
+ cellStyle?: RowStyle;
75
+ getCellStyle?: (params: CellRenderParams<T>) => RowStyle | undefined;
76
+ cellClass?: string | ((params: CellRenderParams<T>) => string | undefined);
77
+ getCellClass?: (params: CellRenderParams<T>) => string | undefined;
78
+ cellClassRules?: CellClassRules<T>;
79
+ }
80
+ export interface ColumnGroupDef<T> extends BaseColumnDef<T> {
81
+ children: ColumnDef<T>[];
82
+ collapsible?: boolean;
83
+ defaultExpanded?: boolean;
84
+ }
85
+ export type ColumnDef<T> = ColumnLeafDef<T> | ColumnGroupDef<T>;
86
+ export interface GridOptions<T> {
87
+ data?: T[];
88
+ columns: ColumnDef<T>[];
89
+ getRowId?: (row: T, index: number) => RowId;
90
+ rowHeight?: number;
91
+ rowOverscan?: number;
92
+ columnOverscan?: number;
93
+ suppressRowHoverHighlight?: boolean;
94
+ rowStyle?: RowStyle;
95
+ getRowStyle?: (params: RowRenderParams<T>) => RowStyle | undefined;
96
+ rowClass?: string | ((params: RowRenderParams<T>) => string | undefined);
97
+ getRowClass?: (params: RowRenderParams<T>) => string | undefined;
98
+ rowClassRules?: RowClassRules<T>;
99
+ plugins?: GridPlugin<T>[];
100
+ }
101
+ export interface ViewportState {
102
+ width: number;
103
+ height: number;
104
+ scrollTop: number;
105
+ scrollLeft: number;
106
+ }
107
+ /** Ephemeral scroll position — not stored in the Store (no React re-render on scroll). */
108
+ export interface ScrollPosition {
109
+ scrollTop: number;
110
+ scrollLeft: number;
111
+ }
112
+ export interface Range {
113
+ start: number;
114
+ end: number;
115
+ }
116
+ export interface VirtualItem {
117
+ index: number;
118
+ offset: number;
119
+ size: number;
120
+ }
121
+ /**
122
+ * A column group projected onto the flat VISIBLE leaf layout.
123
+ *
124
+ * `startIndex` / `endIndex` address the flat ordering of the visible leaf
125
+ * columns — the same indices reported by the `index` field on `ViewportData`
126
+ * columns. `[startIndex, endIndex)` is the span of leaf columns the group
127
+ * header covers on its header row. `depth` is the nesting level
128
+ * (0 = top header row), and groups are listed in pre-order, so the adapter
129
+ * can reconstruct the group tree when rendering stacked header rows.
130
+ */
131
+ export interface ColumnGroupViewport<T> {
132
+ group: ColumnGroupDef<T>;
133
+ startIndex: number;
134
+ endIndex: number;
135
+ depth: number;
136
+ }
137
+ export interface ViewportData<T> {
138
+ rows: Array<{
139
+ id: RowId;
140
+ data: T;
141
+ index: number;
142
+ offset: number;
143
+ }>;
144
+ /** Scrollable (virtualized) leaf columns of the current horizontal window. */
145
+ columns: Array<{
146
+ column: ColumnLeafDef<T>;
147
+ index: number;
148
+ offset: number;
149
+ width: number;
150
+ }>;
151
+ /** Left-pinned leaf columns — always visible, absolute offsets from 0. */
152
+ pinnedLeftColumns: Array<{
153
+ column: ColumnLeafDef<T>;
154
+ index: number;
155
+ offset: number;
156
+ width: number;
157
+ }>;
158
+ /** Right-pinned leaf columns — always visible, absolute offsets anchored to totalWidth. */
159
+ pinnedRightColumns: Array<{
160
+ column: ColumnLeafDef<T>;
161
+ index: number;
162
+ offset: number;
163
+ width: number;
164
+ }>;
165
+ /**
166
+ * Column groups (definitions with leaf spans) — the data needed to render
167
+ * stacked group header rows. Empty when no groups are defined.
168
+ */
169
+ columnGroups: ColumnGroupViewport<T>[];
170
+ /**
171
+ * Number of group header rows stacked above the leaf header row.
172
+ * Equals `maxGroupDepth + 1` when groups exist, `0` otherwise.
173
+ * The total header height is `(headerRowCount + 1) * rowHeight`.
174
+ */
175
+ headerRowCount: number;
176
+ /**
177
+ * Maps each leaf column's flat visible index (the `index` field on
178
+ * `columns` / `pinnedLeftColumns` / `pinnedRightColumns`) to the deepest
179
+ * group depth that covers it.
180
+ *
181
+ * Adapters use this to determine how many gap rows lie between the deepest
182
+ * covering group and the leaf row — leaf headers for columns with a shallow
183
+ * covering group need to extend upward to fill that gap.
184
+ */
185
+ columnGroupDepth: Map<number, number>;
186
+ rowRange: Range;
187
+ columnRange: Range;
188
+ totalWidth: number;
189
+ totalHeight: number;
190
+ }
191
+ export interface GridState<T> {
192
+ data: T[];
193
+ columns: ColumnDef<T>[];
194
+ viewport: ViewportState;
195
+ rowHeight: number;
196
+ rowOverscan: number;
197
+ columnOverscan: number;
198
+ }
199
+ export interface GridEvents<T> {
200
+ stateChange: GridState<T>;
201
+ viewportChange: ViewportState;
202
+ dataChange: T[];
203
+ headerClick: {
204
+ columnId: string;
205
+ multiSort: boolean;
206
+ };
207
+ rowClick: RowClickEvent<T>;
208
+ rowHover: RowHoverEvent<T>;
209
+ slotsChange: {
210
+ slot: SlotName;
211
+ mounts: SlotMount<T>[];
212
+ };
213
+ }
214
+ /** Opaque token for a row node owned by the adapter. */
215
+ export type RowHost<T> = object;
216
+ /** Data snapshot for binding a row node in the pool. */
217
+ export interface PooledRow<T> {
218
+ index: number;
219
+ rowId: RowId;
220
+ data: T;
221
+ offsetY: number;
222
+ height: number;
223
+ /** Pixel width of the row (sum of all column widths) — used to size the row node. */
224
+ width: number;
225
+ }
226
+ /**
227
+ * Injected node operations. The adapter implements these (e.g. setting
228
+ * `textContent` and `transform: translateY`), while the core decides
229
+ * WHEN and WHICH node to update.
230
+ */
231
+ export interface DomPoolBindings<T> {
232
+ createRow(): RowHost<T>;
233
+ bindRow(host: RowHost<T>, row: PooledRow<T>): void;
234
+ transformRow(host: RowHost<T>, offsetY: number): void;
235
+ recycleRow(host: RowHost<T>): void;
236
+ }
237
+ /** Result of a viewport frame update (informational for tests/debugging). */
238
+ export interface DomPoolUpdate<T> {
239
+ windowStart: number;
240
+ windowEnd: number;
241
+ poolSize: number;
242
+ bound: Array<{
243
+ host: RowHost<T>;
244
+ row: PooledRow<T>;
245
+ }>;
246
+ positioned: Array<{
247
+ host: RowHost<T>;
248
+ offsetY: number;
249
+ }>;
250
+ recycled: RowHost<T>[];
251
+ }
252
+ export interface RowClickEvent<T> extends RowRenderParams<T> {
253
+ ctrlKey: boolean;
254
+ shiftKey: boolean;
255
+ }
256
+ export interface RowHoverEvent<T> extends RowRenderParams<T> {
257
+ hovered: boolean;
258
+ }
259
+ export interface GridPlugin<T> {
260
+ name: string;
261
+ register(api: GridApi<T>): void | (() => void);
262
+ getRowStyle?(params: RowRenderParams<T>): RowStyle | undefined;
263
+ }
264
+ export type SlotName = "top" | "bottom" | "left" | "right";
265
+ export type SlotPosition = "start" | "center" | "end";
266
+ export type SlotNodeEventName = "click" | "change" | "keydown";
267
+ /**
268
+ * Context passed to the slot content provider. Headless: the plugin
269
+ * works only with the core API and state — no DOM or framework code.
270
+ */
271
+ export interface SlotRenderContext<T> {
272
+ api: GridApi<T>;
273
+ state: GridState<T>;
274
+ slot?: SlotName;
275
+ }
276
+ /** Raw HTML fragment (adapter inserts via innerHTML). */
277
+ export interface SlotHtmlContent {
278
+ type: "html";
279
+ html: string;
280
+ }
281
+ /**
282
+ * Declarative DOM node for a slot: the adapter materializes it into a real
283
+ * element and binds handlers. This lets a headless plugin (e.g. pagination)
284
+ * create buttons without depending on React / Vue / Svelte.
285
+ */
286
+ export interface SlotNodeContent<T> {
287
+ type: "node";
288
+ tag: string;
289
+ attrs?: Record<string, string | number | boolean | undefined>;
290
+ on?: Partial<Record<SlotNodeEventName, (context: SlotRenderContext<T>) => void>>;
291
+ children?: SlotContent[];
292
+ }
293
+ /**
294
+ * Request for a native adapter component: the adapter keeps a registry
295
+ * `kind → renderer` and mounts a full component (e.g. a React component)
296
+ * directly into the slot.
297
+ */
298
+ export interface SlotComponentContent {
299
+ type: "component";
300
+ kind: string;
301
+ payload?: unknown;
302
+ }
303
+ /**
304
+ * Headless description of slot content. The value is opaque (just like the
305
+ * result of `cellRenderer`): the core stores and propagates it as `unknown`,
306
+ * and the adapter materializes it according to a documented runtime protocol:
307
+ *
308
+ * - `string | number` → plain text;
309
+ * - `SlotHtmlContent` → HTML fragment;
310
+ * - `SlotNodeContent` → declarative DOM node;
311
+ * - `SlotComponentContent` → component from the adapter registry;
312
+ * - any other object → framework-native value
313
+ * (in the React adapter this is a `ReactNode`, including React components).
314
+ */
315
+ export type SlotContent = unknown;
316
+ /** Static content or a function that computes it on each render. */
317
+ export type SlotProvider<T> = SlotContent | ((context: SlotRenderContext<T>) => SlotContent);
318
+ export interface SlotMountOptions {
319
+ /** Stable identifier (needed for unmount and key-preserving re-render). */
320
+ id?: string;
321
+ /** Order within the slot: lower comes first (default 0). */
322
+ priority?: number;
323
+ /** Alignment group within the slot (default "start"). */
324
+ position?: SlotPosition;
325
+ }
326
+ export interface SlotMount<T> {
327
+ id: string;
328
+ slot: SlotName;
329
+ content: SlotProvider<T>;
330
+ priority: number;
331
+ position: SlotPosition;
332
+ unmount(): void;
333
+ }
334
+ export interface GridApi<T> {
335
+ getState(): GridState<T>;
336
+ getScrollPosition(): ScrollPosition;
337
+ getViewportData(): ViewportData<T>;
338
+ getProcessedData(): T[];
339
+ getRowId(row: T, index: number): RowId;
340
+ setData(data: T[]): void;
341
+ setViewport(viewport: Partial<ViewportState>): void;
342
+ refresh(): void;
343
+ subscribe(listener: () => void): () => void;
344
+ on<EventName extends keyof GridEvents<T>>(event: EventName, listener: (payload: GridEvents<T>[EventName]) => void): () => void;
345
+ registerPlugin(plugin: GridPlugin<T>): () => void;
346
+ registerDataProcessor(processor: DataProcessor<T>): () => void;
347
+ setColumns(columns: ColumnDef<T>[]): void;
348
+ headerClick(columnId: string, multiSort?: boolean): void;
349
+ rowClick(row: RowClickEvent<T>): void;
350
+ rowHover(row: RowHoverEvent<T>): void;
351
+ readonly slots: SlotManager<T>;
352
+ getSlotMounts(slot: SlotName): SlotMount<T>[];
353
+ /** Monotonic counter for structural changes (refresh / data / columns). */
354
+ getRevision(): number;
355
+ destroy(): void;
356
+ isDestroyed(): boolean;
357
+ }
358
+ export {};
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,41 @@
1
+ import type { ColumnLeafDef, Range, VirtualItem } from "./types";
2
+ export interface VirtualizerOptions {
3
+ rowHeight: number;
4
+ rowOverscan: number;
5
+ columnOverscan: number;
6
+ }
7
+ export declare class Virtualizer<T> {
8
+ private readonly options;
9
+ private lastScrollTop;
10
+ private lastRowRange;
11
+ private lastRowCount;
12
+ private lastRowViewportHeight;
13
+ constructor(options: VirtualizerOptions);
14
+ getRowRange(count: number, scrollTop: number, viewportHeight: number): Range;
15
+ /**
16
+ * Column geometry works on the FLAT working set of leaf columns only —
17
+ * groups never reach the Virtualizer (see `Grid.getViewportData()`).
18
+ */
19
+ getColumnRange(columns: ColumnLeafDef<T>[], scrollLeft: number, viewportWidth: number): Range;
20
+ getColumnOffsets(columns: ColumnLeafDef<T>[], viewportWidth?: number): VirtualItem[];
21
+ getTotalHeight(rowCount: number): number;
22
+ getTotalWidth(columns: ColumnLeafDef<T>[], viewportWidth?: number): number;
23
+ private getRange;
24
+ private getColumnWidths;
25
+ /**
26
+ * Snaps fractional (flex-distributed) widths to whole pixels while keeping
27
+ * the exact total width (largest-remainder rounding).
28
+ *
29
+ * Without this the flex↔fixed seam can land on a sub-pixel coordinate:
30
+ * cells round their `left`, but the neighbouring opaque cell may overlap
31
+ * the fractional right edge and cover the 1px border — the border visually
32
+ * disappears at the flex/fixed boundary. Integer geometry guarantees every
33
+ * adjacent cell touches at an exact pixel boundary.
34
+ */
35
+ private quantizeWidths;
36
+ private getBaseColumnWidth;
37
+ private getMinColumnWidth;
38
+ private getMaxColumnWidth;
39
+ private findStart;
40
+ private findEnd;
41
+ }
@@ -0,0 +1,188 @@
1
+ export class Virtualizer {
2
+ constructor(options) {
3
+ this.lastScrollTop = null;
4
+ this.lastRowRange = null;
5
+ this.lastRowCount = 0;
6
+ this.lastRowViewportHeight = 0;
7
+ this.options = options;
8
+ }
9
+ getRowRange(count, scrollTop, viewportHeight) {
10
+ if (count === 0) {
11
+ this.lastScrollTop = null;
12
+ this.lastRowRange = null;
13
+ this.lastRowCount = 0;
14
+ this.lastRowViewportHeight = 0;
15
+ return { start: 0, end: 0 };
16
+ }
17
+ const rowHeight = this.options.rowHeight;
18
+ const visibleStart = Math.floor(Math.max(0, scrollTop) / rowHeight);
19
+ const visibleEnd = Math.ceil((Math.max(0, scrollTop) + Math.max(0, viewportHeight)) / rowHeight);
20
+ // Guaranteed buffer: the visible page + at least one full extra page
21
+ // above and below. Even if a frame is rendered with a one-frame
22
+ // lookahead (rAF viewport update), the visible area is always fully
23
+ // covered by real rows — no blank gaps.
24
+ const visibleRows = Math.max(1, visibleEnd - visibleStart);
25
+ const overscan = Math.max(this.options.rowOverscan, visibleRows);
26
+ const windowed = {
27
+ start: Math.max(0, visibleStart - overscan),
28
+ end: Math.min(count, visibleEnd + overscan),
29
+ };
30
+ // Same data, position, and window size: return the previously computed
31
+ // range (handles StrictMode double-render and redundant re-renders).
32
+ if (scrollTop === this.lastScrollTop && count === this.lastRowCount && viewportHeight === this.lastRowViewportHeight) {
33
+ return this.lastRowRange ?? windowed;
34
+ }
35
+ const previousTop = this.lastScrollTop;
36
+ this.lastScrollTop = scrollTop;
37
+ this.lastRowCount = count;
38
+ this.lastRowViewportHeight = viewportHeight;
39
+ if (previousTop === null) {
40
+ this.lastRowRange = windowed;
41
+ return windowed;
42
+ }
43
+ const prevVisibleStart = Math.floor(Math.max(0, previousTop) / rowHeight);
44
+ const prevVisibleEnd = Math.ceil((Math.max(0, previousTop) + Math.max(0, viewportHeight)) / rowHeight);
45
+ // Normal scroll: the half-page buffer already covers both the old and
46
+ // new positions (scroll delta is smaller than the combined buffer).
47
+ const closeEnough = visibleStart <= prevVisibleEnd + overscan && prevVisibleStart <= visibleEnd + overscan;
48
+ if (closeEnough) {
49
+ this.lastRowRange = windowed;
50
+ return windowed;
51
+ }
52
+ // Teleport (large jump): build a continuous "corridor" from the old
53
+ // position to the new one, capped to avoid spawning hundreds of nodes.
54
+ const corridorCap = visibleRows * 2 + this.options.rowOverscan * 2;
55
+ const corridorStart = Math.max(0, Math.min(prevVisibleStart, visibleStart) - overscan);
56
+ const corridorEnd = Math.min(count, Math.max(prevVisibleEnd, visibleEnd) + overscan);
57
+ if (corridorEnd - corridorStart > corridorCap) {
58
+ this.lastRowRange = windowed;
59
+ return windowed;
60
+ }
61
+ const corridor = { start: corridorStart, end: corridorEnd };
62
+ this.lastRowRange = corridor;
63
+ return corridor;
64
+ }
65
+ /**
66
+ * Column geometry works on the FLAT working set of leaf columns only —
67
+ * groups never reach the Virtualizer (see `Grid.getViewportData()`).
68
+ */
69
+ getColumnRange(columns, scrollLeft, viewportWidth) {
70
+ const offsets = this.getColumnOffsets(columns, viewportWidth);
71
+ const start = this.findStart(offsets, scrollLeft);
72
+ const end = this.findEnd(offsets, scrollLeft + viewportWidth);
73
+ return {
74
+ start: Math.max(0, start - this.options.columnOverscan),
75
+ end: Math.min(columns.length, end + 1 + this.options.columnOverscan),
76
+ };
77
+ }
78
+ getColumnOffsets(columns, viewportWidth = 0) {
79
+ const widths = this.getColumnWidths(columns, viewportWidth);
80
+ let offset = 0;
81
+ return columns.map((column, index) => {
82
+ const size = widths[index];
83
+ const item = { index, offset, size };
84
+ offset += size;
85
+ return item;
86
+ });
87
+ }
88
+ getTotalHeight(rowCount) {
89
+ return rowCount * this.options.rowHeight;
90
+ }
91
+ getTotalWidth(columns, viewportWidth = 0) {
92
+ return this.getColumnOffsets(columns, viewportWidth).reduce((total, item) => total + item.size, 0);
93
+ }
94
+ getRange(count, itemSize, scrollOffset, viewportSize, overscan) {
95
+ if (count === 0)
96
+ return { start: 0, end: 0 };
97
+ const start = Math.floor(Math.max(0, scrollOffset) / itemSize);
98
+ const end = Math.ceil((Math.max(0, scrollOffset) + Math.max(0, viewportSize)) / itemSize);
99
+ return {
100
+ start: Math.max(0, start - overscan),
101
+ end: Math.min(count, end + overscan),
102
+ };
103
+ }
104
+ getColumnWidths(columns, viewportWidth) {
105
+ const widths = columns.map((column) => this.getBaseColumnWidth(column));
106
+ const flexIndexes = columns.map((column, index) => (column.flex && column.flex > 0 ? index : -1)).filter((index) => index >= 0);
107
+ if (flexIndexes.length === 0)
108
+ return widths;
109
+ const fixedWidth = widths.reduce((total, width, index) => (flexIndexes.includes(index) ? total : total + width), 0);
110
+ const minimumFlexWidth = flexIndexes.reduce((total, index) => total + this.getMinColumnWidth(columns[index]), 0);
111
+ let remaining = Math.max(0, viewportWidth - fixedWidth - minimumFlexWidth);
112
+ const activeIndexes = new Set(flexIndexes);
113
+ flexIndexes.forEach((index) => {
114
+ widths[index] = this.getMinColumnWidth(columns[index]);
115
+ });
116
+ while (remaining > 0 && activeIndexes.size > 0) {
117
+ const flexTotal = [...activeIndexes].reduce((total, index) => total + (columns[index].flex ?? 0), 0);
118
+ let distributed = 0;
119
+ activeIndexes.forEach((index) => {
120
+ const column = columns[index];
121
+ const share = (remaining * (column.flex ?? 0)) / flexTotal;
122
+ const available = this.getMaxColumnWidth(column) - widths[index];
123
+ const addition = Math.min(share, Math.max(0, available));
124
+ widths[index] += addition;
125
+ distributed += addition;
126
+ if (addition < share)
127
+ activeIndexes.delete(index);
128
+ });
129
+ if (distributed === 0)
130
+ break;
131
+ remaining -= distributed;
132
+ }
133
+ return this.quantizeWidths(widths);
134
+ }
135
+ /**
136
+ * Snaps fractional (flex-distributed) widths to whole pixels while keeping
137
+ * the exact total width (largest-remainder rounding).
138
+ *
139
+ * Without this the flex↔fixed seam can land on a sub-pixel coordinate:
140
+ * cells round their `left`, but the neighbouring opaque cell may overlap
141
+ * the fractional right edge and cover the 1px border — the border visually
142
+ * disappears at the flex/fixed boundary. Integer geometry guarantees every
143
+ * adjacent cell touches at an exact pixel boundary.
144
+ */
145
+ quantizeWidths(widths) {
146
+ const target = Math.round(widths.reduce((total, width) => total + width, 0));
147
+ let total = 0;
148
+ const remainders = [];
149
+ for (let index = 0; index < widths.length; index += 1) {
150
+ const exact = widths[index];
151
+ const floor = Math.floor(exact);
152
+ widths[index] = floor;
153
+ total += floor;
154
+ const fraction = exact - floor;
155
+ if (fraction > 0)
156
+ remainders.push({ index, fraction });
157
+ }
158
+ // Restore the pixels lost to flooring — largest fractional remainder
159
+ // first — so the widths sum back to the natural total exactly.
160
+ let deficit = target - total;
161
+ remainders.sort((a, b) => b.fraction - a.fraction);
162
+ for (const { index } of remainders) {
163
+ if (deficit <= 0)
164
+ break;
165
+ widths[index] += 1;
166
+ deficit -= 1;
167
+ }
168
+ return widths;
169
+ }
170
+ getBaseColumnWidth(column) {
171
+ if (column.flex && column.flex > 0)
172
+ return this.getMinColumnWidth(column);
173
+ const width = column.width ?? 120;
174
+ return Math.min(this.getMaxColumnWidth(column), Math.max(this.getMinColumnWidth(column), width));
175
+ }
176
+ getMinColumnWidth(column) {
177
+ return Math.max(0, column.minWidth ?? 40);
178
+ }
179
+ getMaxColumnWidth(column) {
180
+ return Math.max(this.getMinColumnWidth(column), column.maxWidth ?? Infinity);
181
+ }
182
+ findStart(items, offset) {
183
+ return items.findIndex((item) => item.offset + item.size > offset) === -1 ? items.length : items.findIndex((item) => item.offset + item.size > offset);
184
+ }
185
+ findEnd(items, offset) {
186
+ return items.findIndex((item) => item.offset >= offset) === -1 ? items.length : items.findIndex((item) => item.offset >= offset);
187
+ }
188
+ }
package/package.json ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "name": "@omnigrid/core",
3
+ "version": "0.1.0",
4
+ "description": "Framework-agnostic core engine for OmniGrid",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "scripts": {
19
+ "build": "npx tsc -p tsconfig.json",
20
+ "lint": "npx tsc --noEmit -p tsconfig.json",
21
+ "test": "vitest run",
22
+ "prepublishOnly": "npm run build"
23
+ },
24
+ "devDependencies": {
25
+ "vitest": "^5.0.2"
26
+ }
27
+ }