gp-grid-react 0.1.6 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,1262 +1 @@
1
- import React, { useCallback, useEffect, useMemo, useReducer, useRef, useState } from "react";
2
- import { GridCore, createClientDataSource, createClientDataSource as createClientDataSource$1, createDataSourceFromArray, createDataSourceFromArray as createDataSourceFromArray$1, createServerDataSource } from "gp-grid-core";
3
- import { Fragment, jsx, jsxs } from "react/jsx-runtime";
4
-
5
- //#region src/styles.ts
6
- const STYLE_ID = "gp-grid-styles";
7
- const gridStyles = `
8
- /* =============================================================================
9
- GP Grid - CSS Variables for Theming
10
- ============================================================================= */
11
-
12
- .gp-grid-container {
13
- /* Colors - Light Mode (default) */
14
- --gp-grid-bg: #ffffff;
15
- --gp-grid-bg-alt: #f8f9fa;
16
- --gp-grid-text: #212529;
17
- --gp-grid-text-secondary: #6c757d;
18
- --gp-grid-text-muted: #adb5bd;
19
- --gp-grid-border: #dee2e6;
20
- --gp-grid-border-light: #e9ecef;
21
-
22
- /* Header */
23
- --gp-grid-header-bg: #f1f3f5;
24
- --gp-grid-header-text: #212529;
25
-
26
- /* Selection */
27
- --gp-grid-primary: #228be6;
28
- --gp-grid-primary-light: #e7f5ff;
29
- --gp-grid-primary-border: #74c0fc;
30
- --gp-grid-hover: #f1f3f5;
31
-
32
- /* Filter */
33
- --gp-grid-filter-bg: #f8f9fa;
34
- --gp-grid-input-bg: #ffffff;
35
- --gp-grid-input-border: #ced4da;
36
-
37
- /* Error */
38
- --gp-grid-error-bg: #fff5f5;
39
- --gp-grid-error-text: #c92a2a;
40
-
41
- /* Loading */
42
- --gp-grid-loading-bg: rgba(255, 255, 255, 0.95);
43
- --gp-grid-loading-text: #495057;
44
-
45
- /* Scrollbar */
46
- --gp-grid-scrollbar-track: #f1f3f5;
47
- --gp-grid-scrollbar-thumb: #ced4da;
48
- --gp-grid-scrollbar-thumb-hover: #adb5bd;
49
- }
50
-
51
- /* Dark Mode */
52
- .gp-grid-container--dark {
53
- --gp-grid-bg: #1a1b1e;
54
- --gp-grid-bg-alt: #25262b;
55
- --gp-grid-text: #c1c2c5;
56
- --gp-grid-text-secondary: #909296;
57
- --gp-grid-text-muted: #5c5f66;
58
- --gp-grid-border: #373a40;
59
- --gp-grid-border-light: #2c2e33;
60
-
61
- /* Header */
62
- --gp-grid-header-bg: #25262b;
63
- --gp-grid-header-text: #c1c2c5;
64
-
65
- /* Selection */
66
- --gp-grid-primary: #339af0;
67
- --gp-grid-primary-light: #1c3d5a;
68
- --gp-grid-primary-border: #1c7ed6;
69
- --gp-grid-hover: #2c2e33;
70
-
71
- /* Filter */
72
- --gp-grid-filter-bg: #25262b;
73
- --gp-grid-input-bg: #1a1b1e;
74
- --gp-grid-input-border: #373a40;
75
-
76
- /* Error */
77
- --gp-grid-error-bg: #2c1a1a;
78
- --gp-grid-error-text: #ff6b6b;
79
-
80
- /* Loading */
81
- --gp-grid-loading-bg: rgba(26, 27, 30, 0.95);
82
- --gp-grid-loading-text: #c1c2c5;
83
-
84
- /* Scrollbar */
85
- --gp-grid-scrollbar-track: #25262b;
86
- --gp-grid-scrollbar-thumb: #373a40;
87
- --gp-grid-scrollbar-thumb-hover: #4a4d52;
88
- }
89
-
90
- /* =============================================================================
91
- GP Grid - Clean Flat Design
92
- ============================================================================= */
93
-
94
- /* Grid Container */
95
- .gp-grid-container {
96
- outline: none;
97
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
98
- font-size: 13px;
99
- line-height: 1.5;
100
- color: var(--gp-grid-text);
101
- background-color: var(--gp-grid-bg);
102
- border: 1px solid var(--gp-grid-border);
103
- border-radius: 6px;
104
- user-select: none;
105
- -webkit-user-select: none;
106
- }
107
-
108
- .gp-grid-container:focus {
109
- outline: none;
110
- border-color: var(--gp-grid-primary);
111
- }
112
-
113
- /* =============================================================================
114
- Header
115
- ============================================================================= */
116
-
117
- .gp-grid-header {
118
- position: sticky;
119
- top: 0;
120
- left: 0;
121
- z-index: 100;
122
- background-color: var(--gp-grid-header-bg);
123
- border-bottom: 1px solid var(--gp-grid-border);
124
- }
125
-
126
- .gp-grid-container .gp-grid-header-cell {
127
- position: absolute;
128
- box-sizing: border-box;
129
- border-right: 1px solid var(--gp-grid-border);
130
- font-weight: 600;
131
- font-size: 12px;
132
- text-transform: uppercase;
133
- letter-spacing: 0.5px;
134
- color: var(--gp-grid-header-text);
135
- cursor: pointer;
136
- user-select: none;
137
- display: flex;
138
- align-items: center;
139
- padding: 0 12px;
140
- background-color: transparent;
141
- transition: background-color 0.1s ease;
142
- }
143
-
144
- .gp-grid-container .gp-grid-header-cell:hover {
145
- background-color: var(--gp-grid-hover);
146
- }
147
-
148
- .gp-grid-container .gp-grid-header-cell:active {
149
- background-color: var(--gp-grid-border-light);
150
- }
151
-
152
- .gp-grid-container .gp-grid-header-text {
153
- flex: 1;
154
- overflow: hidden;
155
- text-overflow: ellipsis;
156
- white-space: nowrap;
157
- color: var(--gp-grid-header-text);
158
- }
159
-
160
- .gp-grid-sort-indicator {
161
- margin-left: 6px;
162
- font-size: 10px;
163
- color: var(--gp-grid-primary);
164
- display: flex;
165
- align-items: center;
166
- }
167
-
168
- .gp-grid-sort-index {
169
- font-size: 9px;
170
- margin-left: 2px;
171
- color: var(--gp-grid-text-secondary);
172
- }
173
-
174
- /* =============================================================================
175
- Filter Row
176
- ============================================================================= */
177
-
178
- .gp-grid-filter-row {
179
- position: sticky;
180
- left: 0;
181
- z-index: 99;
182
- background-color: var(--gp-grid-filter-bg);
183
- border-bottom: 1px solid var(--gp-grid-border);
184
- }
185
-
186
- .gp-grid-filter-cell {
187
- position: absolute;
188
- box-sizing: border-box;
189
- border-right: 1px solid var(--gp-grid-border);
190
- padding: 6px 8px;
191
- display: flex;
192
- align-items: center;
193
- background-color: var(--gp-grid-filter-bg);
194
- }
195
-
196
- .gp-grid-filter-input {
197
- width: 100%;
198
- height: 28px;
199
- padding: 0 10px;
200
- font-family: inherit;
201
- font-size: 12px;
202
- border: 1px solid var(--gp-grid-input-border);
203
- border-radius: 4px;
204
- background-color: var(--gp-grid-input-bg);
205
- color: var(--gp-grid-text);
206
- transition: border-color 0.15s ease;
207
- }
208
-
209
- .gp-grid-filter-input:focus {
210
- outline: none;
211
- border-color: var(--gp-grid-primary);
212
- }
213
-
214
- .gp-grid-filter-input::placeholder {
215
- color: var(--gp-grid-text-muted);
216
- }
217
-
218
- /* =============================================================================
219
- Data Cells
220
- ============================================================================= */
221
-
222
- .gp-grid-row {
223
- position: absolute;
224
- top: 0;
225
- left: 0;
226
- }
227
-
228
- .gp-grid-cell {
229
- position: absolute;
230
- top: 0;
231
- box-sizing: border-box;
232
- padding: 0 12px;
233
- display: flex;
234
- align-items: center;
235
- cursor: cell;
236
- color: var(--gp-grid-text);
237
- border-right: 1px solid var(--gp-grid-border-light);
238
- border-bottom: 1px solid var(--gp-grid-border-light);
239
- background-color: var(--gp-grid-bg);
240
- overflow: hidden;
241
- text-overflow: ellipsis;
242
- white-space: nowrap;
243
- user-select: none;
244
- -webkit-user-select: none;
245
- }
246
-
247
- /* Alternating row colors */
248
- .gp-grid-row--even .gp-grid-cell {
249
- background-color: var(--gp-grid-bg-alt);
250
- }
251
-
252
- .gp-grid-cell:hover {
253
- background-color: var(--gp-grid-hover) !important;
254
- }
255
-
256
- /* Active cell (focused) */
257
- .gp-grid-cell--active {
258
- background-color: var(--gp-grid-primary-light) !important;
259
- border: 2px solid var(--gp-grid-primary) !important;
260
- outline: none;
261
- z-index: 5;
262
- padding: 0 11px;
263
- }
264
-
265
- /* Selected cells (range selection) */
266
- .gp-grid-cell--selected {
267
- background-color: var(--gp-grid-primary-light) !important;
268
- }
269
-
270
- /* Editing cell */
271
- .gp-grid-cell--editing {
272
- background-color: var(--gp-grid-bg) !important;
273
- border: 2px solid var(--gp-grid-primary) !important;
274
- padding: 0 !important;
275
- z-index: 10;
276
- }
277
-
278
- /* =============================================================================
279
- Fill Handle (drag to fill)
280
- ============================================================================= */
281
-
282
- .gp-grid-fill-handle {
283
- position: absolute;
284
- width: 8px;
285
- height: 8px;
286
- background-color: var(--gp-grid-primary);
287
- border: 2px solid var(--gp-grid-bg);
288
- cursor: crosshair;
289
- z-index: 100;
290
- pointer-events: auto;
291
- box-sizing: border-box;
292
- border-radius: 1px;
293
- }
294
-
295
- .gp-grid-fill-handle:hover {
296
- transform: scale(1.2);
297
- }
298
-
299
- /* Fill preview (cells being filled) */
300
- .gp-grid-cell--fill-preview {
301
- background-color: var(--gp-grid-primary-light) !important;
302
- border: 1px dashed var(--gp-grid-primary) !important;
303
- }
304
-
305
- /* =============================================================================
306
- Edit Input
307
- ============================================================================= */
308
-
309
- .gp-grid-edit-input {
310
- width: 100%;
311
- height: 100%;
312
- padding: 0 11px;
313
- font-family: inherit;
314
- font-size: inherit;
315
- color: var(--gp-grid-text);
316
- border: none;
317
- background-color: transparent;
318
- }
319
-
320
- .gp-grid-edit-input:focus {
321
- outline: none;
322
- }
323
-
324
- /* =============================================================================
325
- Loading & Error States
326
- ============================================================================= */
327
-
328
- .gp-grid-loading {
329
- position: absolute;
330
- top: 50%;
331
- left: 50%;
332
- transform: translate(-50%, -50%);
333
- padding: 12px 20px;
334
- background-color: var(--gp-grid-loading-bg);
335
- color: var(--gp-grid-loading-text);
336
- border-radius: 6px;
337
- border: 1px solid var(--gp-grid-border);
338
- font-weight: 500;
339
- font-size: 13px;
340
- z-index: 1000;
341
- display: flex;
342
- align-items: center;
343
- gap: 10px;
344
- }
345
-
346
- .gp-grid-loading-spinner {
347
- width: 16px;
348
- height: 16px;
349
- border: 2px solid var(--gp-grid-border);
350
- border-top-color: var(--gp-grid-primary);
351
- border-radius: 50%;
352
- animation: gp-grid-spin 0.7s linear infinite;
353
- }
354
-
355
- @keyframes gp-grid-spin {
356
- to {
357
- transform: rotate(360deg);
358
- }
359
- }
360
-
361
- .gp-grid-error {
362
- position: absolute;
363
- top: 50%;
364
- left: 50%;
365
- transform: translate(-50%, -50%);
366
- padding: 12px 20px;
367
- background-color: var(--gp-grid-error-bg);
368
- color: var(--gp-grid-error-text);
369
- border-radius: 6px;
370
- border: 1px solid var(--gp-grid-error-text);
371
- font-weight: 500;
372
- font-size: 13px;
373
- z-index: 1000;
374
- max-width: 80%;
375
- text-align: center;
376
- }
377
-
378
- /* =============================================================================
379
- Empty State
380
- ============================================================================= */
381
-
382
- .gp-grid-empty {
383
- position: absolute;
384
- top: 50%;
385
- left: 50%;
386
- transform: translate(-50%, -50%);
387
- color: var(--gp-grid-text-muted);
388
- font-size: 14px;
389
- text-align: center;
390
- }
391
-
392
- /* =============================================================================
393
- Scrollbar Styling
394
- ============================================================================= */
395
-
396
- .gp-grid-container::-webkit-scrollbar {
397
- width: 8px;
398
- height: 8px;
399
- }
400
-
401
- .gp-grid-container::-webkit-scrollbar-track {
402
- background-color: var(--gp-grid-scrollbar-track);
403
- }
404
-
405
- .gp-grid-container::-webkit-scrollbar-thumb {
406
- background-color: var(--gp-grid-scrollbar-thumb);
407
- border-radius: 4px;
408
- }
409
-
410
- .gp-grid-container::-webkit-scrollbar-thumb:hover {
411
- background-color: var(--gp-grid-scrollbar-thumb-hover);
412
- }
413
-
414
- .gp-grid-container::-webkit-scrollbar-corner {
415
- background-color: var(--gp-grid-scrollbar-track);
416
- }
417
- `;
418
- let stylesInjected = false;
419
- /**
420
- * Inject grid styles into the document head.
421
- * This is called automatically when the Grid component mounts.
422
- * Styles are only injected once, even if multiple Grid instances exist.
423
- */
424
- function injectStyles() {
425
- if (stylesInjected) return;
426
- if (typeof document === "undefined") return;
427
- if (document.getElementById(STYLE_ID)) {
428
- stylesInjected = true;
429
- return;
430
- }
431
- const styleElement = document.createElement("style");
432
- styleElement.id = STYLE_ID;
433
- styleElement.textContent = gridStyles;
434
- document.head.appendChild(styleElement);
435
- stylesInjected = true;
436
- }
437
-
438
- //#endregion
439
- //#region src/Grid.tsx
440
- /**
441
- * Apply a single instruction to mutable slot maps and return other state changes.
442
- * This allows batching multiple slot operations efficiently.
443
- */
444
- function applyInstruction(instruction, slots, headers) {
445
- switch (instruction.type) {
446
- case "CREATE_SLOT":
447
- slots.set(instruction.slotId, {
448
- slotId: instruction.slotId,
449
- rowIndex: -1,
450
- rowData: {},
451
- translateY: 0
452
- });
453
- return null;
454
- case "DESTROY_SLOT":
455
- slots.delete(instruction.slotId);
456
- return null;
457
- case "ASSIGN_SLOT": {
458
- const existing = slots.get(instruction.slotId);
459
- if (existing) slots.set(instruction.slotId, {
460
- ...existing,
461
- rowIndex: instruction.rowIndex,
462
- rowData: instruction.rowData
463
- });
464
- return null;
465
- }
466
- case "MOVE_SLOT": {
467
- const existing = slots.get(instruction.slotId);
468
- if (existing) slots.set(instruction.slotId, {
469
- ...existing,
470
- translateY: instruction.translateY
471
- });
472
- return null;
473
- }
474
- case "SET_ACTIVE_CELL": return { activeCell: instruction.position };
475
- case "SET_SELECTION_RANGE": return { selectionRange: instruction.range };
476
- case "START_EDIT": return { editingCell: {
477
- row: instruction.row,
478
- col: instruction.col,
479
- initialValue: instruction.initialValue
480
- } };
481
- case "STOP_EDIT": return { editingCell: null };
482
- case "SET_CONTENT_SIZE": return {
483
- contentWidth: instruction.width,
484
- contentHeight: instruction.height
485
- };
486
- case "UPDATE_HEADER":
487
- headers.set(instruction.colIndex, {
488
- column: instruction.column,
489
- sortDirection: instruction.sortDirection,
490
- sortIndex: instruction.sortIndex
491
- });
492
- return null;
493
- case "DATA_LOADING": return {
494
- isLoading: true,
495
- error: null
496
- };
497
- case "DATA_LOADED": return {
498
- isLoading: false,
499
- totalRows: instruction.totalRows
500
- };
501
- case "DATA_ERROR": return {
502
- isLoading: false,
503
- error: instruction.error
504
- };
505
- default: return null;
506
- }
507
- }
508
- function gridReducer(state, action) {
509
- if (action.type === "RESET") return createInitialState();
510
- const { instructions } = action;
511
- if (instructions.length === 0) return state;
512
- const newSlots = new Map(state.slots);
513
- const newHeaders = new Map(state.headers);
514
- let stateChanges = {};
515
- for (const instruction of instructions) {
516
- const changes = applyInstruction(instruction, newSlots, newHeaders);
517
- if (changes) stateChanges = {
518
- ...stateChanges,
519
- ...changes
520
- };
521
- }
522
- return {
523
- ...state,
524
- ...stateChanges,
525
- slots: newSlots,
526
- headers: newHeaders
527
- };
528
- }
529
- function createInitialState() {
530
- return {
531
- slots: /* @__PURE__ */ new Map(),
532
- activeCell: null,
533
- selectionRange: null,
534
- editingCell: null,
535
- contentWidth: 0,
536
- contentHeight: 0,
537
- headers: /* @__PURE__ */ new Map(),
538
- isLoading: false,
539
- error: null,
540
- totalRows: 0
541
- };
542
- }
543
- /**
544
- * Grid component
545
- * @param props - Grid component props
546
- * @returns Grid React component
547
- */
548
- function Grid(props) {
549
- injectStyles();
550
- const { columns, dataSource: providedDataSource, rowData, rowHeight, headerHeight = rowHeight, overscan = 3, showFilters = false, filterDebounce = 300, darkMode = false, wheelDampening = .1, cellRenderers = {}, editRenderers = {}, headerRenderers = {}, cellRenderer, editRenderer, headerRenderer } = props;
551
- const containerRef = useRef(null);
552
- const coreRef = useRef(null);
553
- const [state, dispatch] = useReducer(gridReducer, null, createInitialState);
554
- const [filterValues, setFilterValues] = useState({});
555
- const filterTimeoutRef = useRef({});
556
- const [isDraggingFill, setIsDraggingFill] = useState(false);
557
- const [fillTarget, setFillTarget] = useState(null);
558
- const [fillSourceRange, setFillSourceRange] = useState(null);
559
- const autoScrollIntervalRef = useRef(null);
560
- const [isDraggingSelection, setIsDraggingSelection] = useState(false);
561
- const filterRowHeight = showFilters ? 40 : 0;
562
- const totalHeaderHeight = headerHeight + filterRowHeight;
563
- const dataSource = useMemo(() => {
564
- if (providedDataSource) return providedDataSource;
565
- if (rowData) return createDataSourceFromArray$1(rowData);
566
- return createClientDataSource$1([]);
567
- }, [providedDataSource, rowData]);
568
- const columnPositions = useMemo(() => {
569
- const positions = [0];
570
- let pos = 0;
571
- for (const col of columns) {
572
- pos += col.width;
573
- positions.push(pos);
574
- }
575
- return positions;
576
- }, [columns]);
577
- const totalWidth = columnPositions[columnPositions.length - 1] ?? 0;
578
- useEffect(() => {
579
- const core = new GridCore({
580
- columns,
581
- dataSource,
582
- rowHeight,
583
- headerHeight: totalHeaderHeight,
584
- overscan
585
- });
586
- coreRef.current = core;
587
- const unsubscribe = core.onBatchInstruction((instructions) => {
588
- dispatch({
589
- type: "BATCH_INSTRUCTIONS",
590
- instructions
591
- });
592
- });
593
- core.initialize();
594
- return () => {
595
- unsubscribe();
596
- coreRef.current = null;
597
- };
598
- }, [
599
- columns,
600
- dataSource,
601
- rowHeight,
602
- totalHeaderHeight,
603
- overscan
604
- ]);
605
- const handleScroll = useCallback(() => {
606
- const container = containerRef.current;
607
- const core = coreRef.current;
608
- if (!container || !core) return;
609
- core.setViewport(container.scrollTop, container.scrollLeft, container.clientWidth, container.clientHeight);
610
- }, []);
611
- const handleWheel = useCallback((e) => {
612
- const container = containerRef.current;
613
- const core = coreRef.current;
614
- if (!container || !core) return;
615
- if (!core.isScalingActive()) return;
616
- e.preventDefault();
617
- container.scrollTop += e.deltaY * wheelDampening;
618
- container.scrollLeft += e.deltaX * wheelDampening;
619
- }, [wheelDampening]);
620
- useEffect(() => {
621
- const container = containerRef.current;
622
- const core = coreRef.current;
623
- if (!container || !core) return;
624
- const resizeObserver = new ResizeObserver(() => {
625
- core.setViewport(container.scrollTop, container.scrollLeft, container.clientWidth, container.clientHeight);
626
- });
627
- resizeObserver.observe(container);
628
- handleScroll();
629
- return () => resizeObserver.disconnect();
630
- }, [handleScroll]);
631
- const handleFilterChange = useCallback((colId, value) => {
632
- setFilterValues((prev) => ({
633
- ...prev,
634
- [colId]: value
635
- }));
636
- if (filterTimeoutRef.current[colId]) clearTimeout(filterTimeoutRef.current[colId]);
637
- filterTimeoutRef.current[colId] = setTimeout(() => {
638
- const core = coreRef.current;
639
- if (core) core.setFilter(colId, value);
640
- }, filterDebounce);
641
- }, [filterDebounce]);
642
- const handleKeyDown = useCallback((e) => {
643
- const core = coreRef.current;
644
- if (!core) return;
645
- if (state.editingCell && e.key !== "Enter" && e.key !== "Escape" && e.key !== "Tab") return;
646
- const { selection } = core;
647
- const isShift = e.shiftKey;
648
- const isCtrl = e.ctrlKey || e.metaKey;
649
- switch (e.key) {
650
- case "ArrowUp":
651
- e.preventDefault();
652
- selection.moveFocus("up", isShift);
653
- break;
654
- case "ArrowDown":
655
- e.preventDefault();
656
- selection.moveFocus("down", isShift);
657
- break;
658
- case "ArrowLeft":
659
- e.preventDefault();
660
- selection.moveFocus("left", isShift);
661
- break;
662
- case "ArrowRight":
663
- e.preventDefault();
664
- selection.moveFocus("right", isShift);
665
- break;
666
- case "Enter":
667
- e.preventDefault();
668
- if (state.editingCell) core.commitEdit();
669
- else if (state.activeCell) core.startEdit(state.activeCell.row, state.activeCell.col);
670
- break;
671
- case "Escape":
672
- e.preventDefault();
673
- if (state.editingCell) core.cancelEdit();
674
- else selection.clearSelection();
675
- break;
676
- case "Tab":
677
- e.preventDefault();
678
- if (state.editingCell) core.commitEdit();
679
- selection.moveFocus(isShift ? "left" : "right", false);
680
- break;
681
- case "a":
682
- if (isCtrl) {
683
- e.preventDefault();
684
- selection.selectAll();
685
- }
686
- break;
687
- case "c":
688
- if (isCtrl) {
689
- e.preventDefault();
690
- selection.copySelectionToClipboard();
691
- }
692
- break;
693
- case "F2":
694
- e.preventDefault();
695
- if (state.activeCell && !state.editingCell) core.startEdit(state.activeCell.row, state.activeCell.col);
696
- break;
697
- case "Delete":
698
- case "Backspace":
699
- if (state.activeCell && !state.editingCell) {
700
- e.preventDefault();
701
- core.startEdit(state.activeCell.row, state.activeCell.col);
702
- }
703
- break;
704
- default:
705
- if (state.activeCell && !state.editingCell && !isCtrl && e.key.length === 1) core.startEdit(state.activeCell.row, state.activeCell.col);
706
- break;
707
- }
708
- }, [state.activeCell, state.editingCell]);
709
- useEffect(() => {
710
- if (!state.activeCell || !containerRef.current || state.editingCell) return;
711
- const { row, col } = state.activeCell;
712
- const container = containerRef.current;
713
- const core = coreRef.current;
714
- if (!core) return;
715
- const { start: visibleStart, end: visibleEnd } = core.getVisibleRowRange();
716
- if (row < visibleStart) container.scrollTop = core.getScrollTopForRow(row);
717
- else if (row > visibleEnd) {
718
- const visibleRows = Math.max(1, visibleEnd - visibleStart);
719
- const targetFirstRow = Math.max(0, row - visibleRows);
720
- container.scrollTop = core.getScrollTopForRow(targetFirstRow);
721
- }
722
- const cellLeft = columnPositions[col] ?? 0;
723
- const cellRight = cellLeft + (columns[col]?.width ?? 0);
724
- const visibleLeft = container.scrollLeft;
725
- const visibleRight = container.scrollLeft + container.clientWidth;
726
- if (cellLeft < visibleLeft) container.scrollLeft = cellLeft;
727
- else if (cellRight > visibleRight) container.scrollLeft = cellRight - container.clientWidth;
728
- }, [
729
- state.activeCell,
730
- state.editingCell,
731
- columnPositions,
732
- columns
733
- ]);
734
- const handleCellMouseDown = useCallback((rowIndex, colIndex, e) => {
735
- const core = coreRef.current;
736
- if (!core || core.getEditState() !== null) return;
737
- if (e.button !== 0) return;
738
- containerRef.current?.focus();
739
- core.selection.startSelection({
740
- row: rowIndex,
741
- col: colIndex
742
- }, {
743
- shift: e.shiftKey,
744
- ctrl: e.ctrlKey || e.metaKey
745
- });
746
- if (!e.shiftKey) setIsDraggingSelection(true);
747
- }, []);
748
- const handleCellDoubleClick = useCallback((rowIndex, colIndex) => {
749
- const core = coreRef.current;
750
- if (!core) return;
751
- core.startEdit(rowIndex, colIndex);
752
- }, []);
753
- const handleHeaderClick = useCallback((colIndex, e) => {
754
- const core = coreRef.current;
755
- if (!core) return;
756
- const column = columns[colIndex];
757
- if (!column) return;
758
- const colId = column.colId ?? column.field;
759
- const currentDirection = state.headers.get(colIndex)?.sortDirection;
760
- let newDirection;
761
- if (!currentDirection) newDirection = "asc";
762
- else if (currentDirection === "asc") newDirection = "desc";
763
- else newDirection = null;
764
- core.setSort(colId, newDirection, e.shiftKey);
765
- }, [columns, state.headers]);
766
- const handleFillHandleMouseDown = useCallback((e) => {
767
- e.preventDefault();
768
- e.stopPropagation();
769
- const core = coreRef.current;
770
- if (!core) return;
771
- const { activeCell, selectionRange } = state;
772
- if (!activeCell && !selectionRange) return;
773
- const sourceRange = selectionRange ?? {
774
- startRow: activeCell.row,
775
- startCol: activeCell.col,
776
- endRow: activeCell.row,
777
- endCol: activeCell.col
778
- };
779
- core.fill.startFillDrag(sourceRange);
780
- setFillSourceRange(sourceRange);
781
- setFillTarget({
782
- row: Math.max(sourceRange.startRow, sourceRange.endRow),
783
- col: Math.max(sourceRange.startCol, sourceRange.endCol)
784
- });
785
- setIsDraggingFill(true);
786
- }, [state.activeCell, state.selectionRange]);
787
- useEffect(() => {
788
- if (!isDraggingFill) return;
789
- const SCROLL_THRESHOLD = 40;
790
- const SCROLL_SPEED = 10;
791
- const handleMouseMove = (e) => {
792
- const core = coreRef.current;
793
- const container = containerRef.current;
794
- if (!core || !container) return;
795
- const rect = container.getBoundingClientRect();
796
- const scrollLeft = container.scrollLeft;
797
- const scrollTop = container.scrollTop;
798
- const mouseX = e.clientX - rect.left + scrollLeft;
799
- const mouseY = e.clientY - rect.top + scrollTop - totalHeaderHeight;
800
- const targetRow = Math.max(0, core.getRowIndexAtDisplayY(mouseY, scrollTop));
801
- let targetCol = 0;
802
- for (let i = 0; i < columnPositions.length - 1; i++) {
803
- if (mouseX >= columnPositions[i] && mouseX < columnPositions[i + 1]) {
804
- targetCol = i;
805
- break;
806
- }
807
- if (mouseX >= columnPositions[columnPositions.length - 1]) targetCol = columnPositions.length - 2;
808
- }
809
- core.fill.updateFillDrag(targetRow, targetCol);
810
- setFillTarget({
811
- row: targetRow,
812
- col: targetCol
813
- });
814
- const mouseYInContainer = e.clientY - rect.top;
815
- const mouseXInContainer = e.clientX - rect.left;
816
- if (autoScrollIntervalRef.current) {
817
- clearInterval(autoScrollIntervalRef.current);
818
- autoScrollIntervalRef.current = null;
819
- }
820
- let scrollDeltaX = 0;
821
- let scrollDeltaY = 0;
822
- if (mouseYInContainer < SCROLL_THRESHOLD + totalHeaderHeight) scrollDeltaY = -SCROLL_SPEED;
823
- else if (mouseYInContainer > rect.height - SCROLL_THRESHOLD) scrollDeltaY = SCROLL_SPEED;
824
- if (mouseXInContainer < SCROLL_THRESHOLD) scrollDeltaX = -SCROLL_SPEED;
825
- else if (mouseXInContainer > rect.width - SCROLL_THRESHOLD) scrollDeltaX = SCROLL_SPEED;
826
- if (scrollDeltaX !== 0 || scrollDeltaY !== 0) autoScrollIntervalRef.current = setInterval(() => {
827
- if (containerRef.current) {
828
- containerRef.current.scrollTop += scrollDeltaY;
829
- containerRef.current.scrollLeft += scrollDeltaX;
830
- }
831
- }, 16);
832
- };
833
- const handleMouseUp = () => {
834
- if (autoScrollIntervalRef.current) {
835
- clearInterval(autoScrollIntervalRef.current);
836
- autoScrollIntervalRef.current = null;
837
- }
838
- const core = coreRef.current;
839
- if (core) {
840
- core.fill.commitFillDrag();
841
- core.refreshSlotData();
842
- }
843
- setIsDraggingFill(false);
844
- setFillTarget(null);
845
- setFillSourceRange(null);
846
- };
847
- document.addEventListener("mousemove", handleMouseMove);
848
- document.addEventListener("mouseup", handleMouseUp);
849
- return () => {
850
- if (autoScrollIntervalRef.current) {
851
- clearInterval(autoScrollIntervalRef.current);
852
- autoScrollIntervalRef.current = null;
853
- }
854
- document.removeEventListener("mousemove", handleMouseMove);
855
- document.removeEventListener("mouseup", handleMouseUp);
856
- };
857
- }, [
858
- isDraggingFill,
859
- totalHeaderHeight,
860
- rowHeight,
861
- columnPositions
862
- ]);
863
- useEffect(() => {
864
- if (!isDraggingSelection) return;
865
- const SCROLL_THRESHOLD = 40;
866
- const SCROLL_SPEED = 10;
867
- const handleMouseMove = (e) => {
868
- const core = coreRef.current;
869
- const container = containerRef.current;
870
- if (!core || !container) return;
871
- const rect = container.getBoundingClientRect();
872
- const scrollLeft = container.scrollLeft;
873
- const scrollTop = container.scrollTop;
874
- const mouseX = e.clientX - rect.left + scrollLeft;
875
- const mouseY = e.clientY - rect.top + scrollTop - totalHeaderHeight;
876
- const targetRow = Math.max(0, Math.min(core.getRowIndexAtDisplayY(mouseY, scrollTop), core.getRowCount() - 1));
877
- let targetCol = 0;
878
- for (let i = 0; i < columnPositions.length - 1; i++) {
879
- if (mouseX >= columnPositions[i] && mouseX < columnPositions[i + 1]) {
880
- targetCol = i;
881
- break;
882
- }
883
- if (mouseX >= columnPositions[columnPositions.length - 1]) targetCol = columnPositions.length - 2;
884
- }
885
- targetCol = Math.max(0, Math.min(targetCol, columns.length - 1));
886
- core.selection.startSelection({
887
- row: targetRow,
888
- col: targetCol
889
- }, { shift: true });
890
- const mouseYInContainer = e.clientY - rect.top;
891
- const mouseXInContainer = e.clientX - rect.left;
892
- if (autoScrollIntervalRef.current) {
893
- clearInterval(autoScrollIntervalRef.current);
894
- autoScrollIntervalRef.current = null;
895
- }
896
- let scrollDeltaX = 0;
897
- let scrollDeltaY = 0;
898
- if (mouseYInContainer < SCROLL_THRESHOLD + totalHeaderHeight) scrollDeltaY = -SCROLL_SPEED;
899
- else if (mouseYInContainer > rect.height - SCROLL_THRESHOLD) scrollDeltaY = SCROLL_SPEED;
900
- if (mouseXInContainer < SCROLL_THRESHOLD) scrollDeltaX = -SCROLL_SPEED;
901
- else if (mouseXInContainer > rect.width - SCROLL_THRESHOLD) scrollDeltaX = SCROLL_SPEED;
902
- if (scrollDeltaX !== 0 || scrollDeltaY !== 0) autoScrollIntervalRef.current = setInterval(() => {
903
- if (containerRef.current) {
904
- containerRef.current.scrollTop += scrollDeltaY;
905
- containerRef.current.scrollLeft += scrollDeltaX;
906
- }
907
- }, 16);
908
- };
909
- const handleMouseUp = () => {
910
- if (autoScrollIntervalRef.current) {
911
- clearInterval(autoScrollIntervalRef.current);
912
- autoScrollIntervalRef.current = null;
913
- }
914
- setIsDraggingSelection(false);
915
- };
916
- document.addEventListener("mousemove", handleMouseMove);
917
- document.addEventListener("mouseup", handleMouseUp);
918
- return () => {
919
- if (autoScrollIntervalRef.current) {
920
- clearInterval(autoScrollIntervalRef.current);
921
- autoScrollIntervalRef.current = null;
922
- }
923
- document.removeEventListener("mousemove", handleMouseMove);
924
- document.removeEventListener("mouseup", handleMouseUp);
925
- };
926
- }, [
927
- isDraggingSelection,
928
- totalHeaderHeight,
929
- columnPositions,
930
- columns.length
931
- ]);
932
- const isSelected = useCallback((row, col) => {
933
- const { selectionRange } = state;
934
- if (!selectionRange) return false;
935
- const minRow = Math.min(selectionRange.startRow, selectionRange.endRow);
936
- const maxRow = Math.max(selectionRange.startRow, selectionRange.endRow);
937
- const minCol = Math.min(selectionRange.startCol, selectionRange.endCol);
938
- const maxCol = Math.max(selectionRange.startCol, selectionRange.endCol);
939
- return row >= minRow && row <= maxRow && col >= minCol && col <= maxCol;
940
- }, [state.selectionRange]);
941
- const isActiveCell = useCallback((row, col) => {
942
- return state.activeCell?.row === row && state.activeCell?.col === col;
943
- }, [state.activeCell]);
944
- const isEditingCell = useCallback((row, col) => {
945
- return state.editingCell?.row === row && state.editingCell?.col === col;
946
- }, [state.editingCell]);
947
- const isInFillPreview = useCallback((row, col) => {
948
- if (!isDraggingFill || !fillSourceRange || !fillTarget) return false;
949
- const srcMinRow = Math.min(fillSourceRange.startRow, fillSourceRange.endRow);
950
- const srcMaxRow = Math.max(fillSourceRange.startRow, fillSourceRange.endRow);
951
- const srcMinCol = Math.min(fillSourceRange.startCol, fillSourceRange.endCol);
952
- const srcMaxCol = Math.max(fillSourceRange.startCol, fillSourceRange.endCol);
953
- const fillDown = fillTarget.row > srcMaxRow;
954
- const fillUp = fillTarget.row < srcMinRow;
955
- if (fillDown) return row > srcMaxRow && row <= fillTarget.row && col >= srcMinCol && col <= srcMaxCol;
956
- if (fillUp) return row < srcMinRow && row >= fillTarget.row && col >= srcMinCol && col <= srcMaxCol;
957
- return false;
958
- }, [
959
- isDraggingFill,
960
- fillSourceRange,
961
- fillTarget
962
- ]);
963
- const getCellValue = useCallback((rowData$1, field) => {
964
- const parts = field.split(".");
965
- let value = rowData$1;
966
- for (const part of parts) {
967
- if (value == null || typeof value !== "object") return null;
968
- value = value[part];
969
- }
970
- return value ?? null;
971
- }, []);
972
- const renderCell = useCallback((column, rowData$1, rowIndex, colIndex) => {
973
- const value = getCellValue(rowData$1, column.field);
974
- const params = {
975
- value,
976
- rowData: rowData$1,
977
- column,
978
- rowIndex,
979
- colIndex,
980
- isActive: isActiveCell(rowIndex, colIndex),
981
- isSelected: isSelected(rowIndex, colIndex),
982
- isEditing: isEditingCell(rowIndex, colIndex)
983
- };
984
- if (column.cellRenderer && typeof column.cellRenderer === "string") {
985
- const renderer = cellRenderers[column.cellRenderer];
986
- if (renderer) return renderer(params);
987
- }
988
- if (cellRenderer) return cellRenderer(params);
989
- return value == null ? "" : String(value);
990
- }, [
991
- getCellValue,
992
- isActiveCell,
993
- isSelected,
994
- isEditingCell,
995
- cellRenderers,
996
- cellRenderer
997
- ]);
998
- const renderEditCell = useCallback((column, rowData$1, rowIndex, colIndex, initialValue) => {
999
- const core = coreRef.current;
1000
- if (!core) return null;
1001
- const params = {
1002
- value: getCellValue(rowData$1, column.field),
1003
- rowData: rowData$1,
1004
- column,
1005
- rowIndex,
1006
- colIndex,
1007
- isActive: true,
1008
- isSelected: true,
1009
- isEditing: true,
1010
- initialValue,
1011
- onValueChange: (newValue) => core.updateEditValue(newValue),
1012
- onCommit: () => core.commitEdit(),
1013
- onCancel: () => core.cancelEdit()
1014
- };
1015
- if (column.editRenderer && typeof column.editRenderer === "string") {
1016
- const renderer = editRenderers[column.editRenderer];
1017
- if (renderer) return renderer(params);
1018
- }
1019
- if (editRenderer) return editRenderer(params);
1020
- return /* @__PURE__ */ jsx("input", {
1021
- className: "gp-grid-edit-input",
1022
- type: "text",
1023
- defaultValue: initialValue == null ? "" : String(initialValue),
1024
- autoFocus: true,
1025
- onFocus: (e) => e.target.select(),
1026
- onChange: (e) => core.updateEditValue(e.target.value),
1027
- onKeyDown: (e) => {
1028
- e.stopPropagation();
1029
- if (e.key === "Enter") core.commitEdit();
1030
- else if (e.key === "Escape") core.cancelEdit();
1031
- else if (e.key === "Tab") {
1032
- e.preventDefault();
1033
- core.commitEdit();
1034
- core.selection.moveFocus(e.shiftKey ? "left" : "right", false);
1035
- }
1036
- },
1037
- onBlur: () => core.commitEdit()
1038
- });
1039
- }, [
1040
- getCellValue,
1041
- editRenderers,
1042
- editRenderer
1043
- ]);
1044
- const renderHeader = useCallback((column, colIndex, sortDirection, sortIndex) => {
1045
- const core = coreRef.current;
1046
- const params = {
1047
- column,
1048
- colIndex,
1049
- sortDirection,
1050
- sortIndex,
1051
- onSort: (direction, addToExisting) => {
1052
- if (core) core.setSort(column.colId ?? column.field, direction, addToExisting);
1053
- }
1054
- };
1055
- if (column.headerRenderer && typeof column.headerRenderer === "string") {
1056
- const renderer = headerRenderers[column.headerRenderer];
1057
- if (renderer) return renderer(params);
1058
- }
1059
- if (headerRenderer) return headerRenderer(params);
1060
- return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("span", {
1061
- className: "gp-grid-header-text",
1062
- children: column.headerName ?? column.field
1063
- }), sortDirection && /* @__PURE__ */ jsxs("span", {
1064
- className: "gp-grid-sort-indicator",
1065
- children: [sortDirection === "asc" ? "▲" : "▼", sortIndex !== void 0 && sortIndex > 0 && /* @__PURE__ */ jsx("span", {
1066
- className: "gp-grid-sort-index",
1067
- children: sortIndex
1068
- })]
1069
- })] });
1070
- }, [headerRenderers, headerRenderer]);
1071
- const slotsArray = useMemo(() => Array.from(state.slots.values()), [state.slots]);
1072
- const fillHandlePosition = useMemo(() => {
1073
- const { activeCell, selectionRange, slots } = state;
1074
- if (!activeCell && !selectionRange) return null;
1075
- let row, col;
1076
- let minCol, maxCol;
1077
- if (selectionRange) {
1078
- row = Math.max(selectionRange.startRow, selectionRange.endRow);
1079
- col = Math.max(selectionRange.startCol, selectionRange.endCol);
1080
- minCol = Math.min(selectionRange.startCol, selectionRange.endCol);
1081
- maxCol = Math.max(selectionRange.startCol, selectionRange.endCol);
1082
- } else if (activeCell) {
1083
- row = activeCell.row;
1084
- col = activeCell.col;
1085
- minCol = col;
1086
- maxCol = col;
1087
- } else return null;
1088
- for (let c = minCol; c <= maxCol; c++) {
1089
- const column = columns[c];
1090
- if (!column || column.editable !== true) return null;
1091
- }
1092
- let cellTop = null;
1093
- for (const slot of slots.values()) if (slot.rowIndex === row) {
1094
- cellTop = slot.translateY;
1095
- break;
1096
- }
1097
- if (cellTop === null) return null;
1098
- const cellLeft = columnPositions[col] ?? 0;
1099
- const cellWidth = columns[col]?.width ?? 0;
1100
- return {
1101
- top: cellTop + rowHeight - 5,
1102
- left: cellLeft + cellWidth - 20
1103
- };
1104
- }, [
1105
- state.activeCell,
1106
- state.selectionRange,
1107
- state.slots,
1108
- rowHeight,
1109
- columnPositions,
1110
- columns
1111
- ]);
1112
- return /* @__PURE__ */ jsx("div", {
1113
- ref: containerRef,
1114
- className: `gp-grid-container${darkMode ? " gp-grid-container--dark" : ""}`,
1115
- style: {
1116
- width: "100%",
1117
- height: "100%",
1118
- overflow: "auto",
1119
- position: "relative"
1120
- },
1121
- onScroll: handleScroll,
1122
- onWheel: handleWheel,
1123
- onKeyDown: handleKeyDown,
1124
- tabIndex: 0,
1125
- children: /* @__PURE__ */ jsxs("div", {
1126
- style: {
1127
- width: Math.max(state.contentWidth, totalWidth),
1128
- height: Math.max(state.contentHeight, totalHeaderHeight),
1129
- position: "relative",
1130
- minWidth: "100%"
1131
- },
1132
- children: [
1133
- /* @__PURE__ */ jsx("div", {
1134
- className: "gp-grid-header",
1135
- style: {
1136
- position: "sticky",
1137
- top: 0,
1138
- left: 0,
1139
- height: headerHeight,
1140
- width: Math.max(state.contentWidth, totalWidth),
1141
- minWidth: "100%",
1142
- zIndex: 100
1143
- },
1144
- children: columns.map((column, colIndex) => {
1145
- const headerInfo = state.headers.get(colIndex);
1146
- return /* @__PURE__ */ jsx("div", {
1147
- className: "gp-grid-header-cell",
1148
- style: {
1149
- position: "absolute",
1150
- left: `${columnPositions[colIndex]}px`,
1151
- top: 0,
1152
- width: `${column.width}px`,
1153
- height: `${headerHeight}px`,
1154
- background: "transparent"
1155
- },
1156
- onClick: (e) => handleHeaderClick(colIndex, e),
1157
- children: renderHeader(column, colIndex, headerInfo?.sortDirection, headerInfo?.sortIndex)
1158
- }, column.colId ?? column.field);
1159
- })
1160
- }),
1161
- showFilters && /* @__PURE__ */ jsx("div", {
1162
- className: "gp-grid-filter-row",
1163
- style: {
1164
- position: "sticky",
1165
- top: headerHeight,
1166
- left: 0,
1167
- height: filterRowHeight,
1168
- width: Math.max(state.contentWidth, totalWidth),
1169
- minWidth: "100%",
1170
- zIndex: 99
1171
- },
1172
- children: columns.map((column, colIndex) => {
1173
- const colId = column.colId ?? column.field;
1174
- return /* @__PURE__ */ jsx("div", {
1175
- className: "gp-grid-filter-cell",
1176
- style: {
1177
- position: "absolute",
1178
- left: `${columnPositions[colIndex]}px`,
1179
- top: 0,
1180
- width: `${column.width}px`,
1181
- height: `${filterRowHeight}px`
1182
- },
1183
- children: /* @__PURE__ */ jsx("input", {
1184
- className: "gp-grid-filter-input",
1185
- type: "text",
1186
- placeholder: `Filter ${column.headerName ?? column.field}...`,
1187
- value: filterValues[colId] ?? "",
1188
- onChange: (e) => handleFilterChange(colId, e.target.value),
1189
- onKeyDown: (e) => e.stopPropagation()
1190
- })
1191
- }, `filter-${colId}`);
1192
- })
1193
- }),
1194
- slotsArray.map((slot) => {
1195
- if (slot.rowIndex < 0) return null;
1196
- return /* @__PURE__ */ jsx("div", {
1197
- className: `gp-grid-row ${slot.rowIndex % 2 === 0 ? "gp-grid-row--even" : ""}`,
1198
- style: {
1199
- position: "absolute",
1200
- top: 0,
1201
- left: 0,
1202
- transform: `translateY(${slot.translateY}px)`,
1203
- width: `${Math.max(state.contentWidth, totalWidth)}px`,
1204
- height: `${rowHeight}px`
1205
- },
1206
- children: columns.map((column, colIndex) => {
1207
- const isEditing = isEditingCell(slot.rowIndex, colIndex);
1208
- const active = isActiveCell(slot.rowIndex, colIndex);
1209
- const selected = isSelected(slot.rowIndex, colIndex);
1210
- const inFillPreview = isInFillPreview(slot.rowIndex, colIndex);
1211
- return /* @__PURE__ */ jsx("div", {
1212
- className: [
1213
- "gp-grid-cell",
1214
- active && "gp-grid-cell--active",
1215
- selected && !active && "gp-grid-cell--selected",
1216
- isEditing && "gp-grid-cell--editing",
1217
- inFillPreview && "gp-grid-cell--fill-preview"
1218
- ].filter(Boolean).join(" "),
1219
- style: {
1220
- position: "absolute",
1221
- left: `${columnPositions[colIndex]}px`,
1222
- top: 0,
1223
- width: `${column.width}px`,
1224
- height: `${rowHeight}px`
1225
- },
1226
- onMouseDown: (e) => handleCellMouseDown(slot.rowIndex, colIndex, e),
1227
- onDoubleClick: () => handleCellDoubleClick(slot.rowIndex, colIndex),
1228
- children: isEditing && state.editingCell ? renderEditCell(column, slot.rowData, slot.rowIndex, colIndex, state.editingCell.initialValue) : renderCell(column, slot.rowData, slot.rowIndex, colIndex)
1229
- }, `${slot.slotId}-${colIndex}`);
1230
- })
1231
- }, slot.slotId);
1232
- }),
1233
- fillHandlePosition && !state.editingCell && /* @__PURE__ */ jsx("div", {
1234
- className: "gp-grid-fill-handle",
1235
- style: {
1236
- position: "absolute",
1237
- top: fillHandlePosition.top,
1238
- left: fillHandlePosition.left,
1239
- zIndex: 200
1240
- },
1241
- onMouseDown: handleFillHandleMouseDown
1242
- }),
1243
- state.isLoading && /* @__PURE__ */ jsxs("div", {
1244
- className: "gp-grid-loading",
1245
- children: [/* @__PURE__ */ jsx("div", { className: "gp-grid-loading-spinner" }), "Loading..."]
1246
- }),
1247
- state.error && /* @__PURE__ */ jsxs("div", {
1248
- className: "gp-grid-error",
1249
- children: ["Error: ", state.error]
1250
- }),
1251
- !state.isLoading && !state.error && state.totalRows === 0 && /* @__PURE__ */ jsx("div", {
1252
- className: "gp-grid-empty",
1253
- children: "No data to display"
1254
- })
1255
- ]
1256
- })
1257
- });
1258
- }
1259
-
1260
- //#endregion
1261
- export { Grid, createClientDataSource, createDataSourceFromArray, createServerDataSource };
1262
- //# sourceMappingURL=index.js.map
1
+ import e,{useCallback as t,useEffect as n,useMemo as r,useReducer as i,useRef as a,useState as o}from"react";import{GridCore as s,buildCellClasses as c,calculateColumnPositions as l,createClientDataSource as u,createClientDataSource as d,createDataSourceFromArray as f,createDataSourceFromArray as p,createMutableClientDataSource as m,createServerDataSource as h,getTotalWidth as g,injectStyles as _,isCellActive as v,isCellEditing as y,isCellInFillPreview as b,isCellSelected as x}from"gp-grid-core";import{Fragment as S,jsx as C,jsxs as w}from"react/jsx-runtime";const T=[{value:`contains`,label:`Contains`},{value:`notContains`,label:`Does not contain`},{value:`equals`,label:`Equals`},{value:`notEquals`,label:`Does not equal`},{value:`startsWith`,label:`Starts with`},{value:`endsWith`,label:`Ends with`},{value:`blank`,label:`Is blank`},{value:`notBlank`,label:`Is not blank`}];function E({distinctValues:e,currentFilter:n,onApply:i,onClose:a}){let s=t(e=>Array.isArray(e)?e.join(`, `):String(e??``),[]),c=r(()=>{let t=e.filter(e=>e!=null&&e!==``&&!(Array.isArray(e)&&e.length===0)).map(e=>s(e));return Array.from(new Set(t)).sort((e,t)=>{let n=parseFloat(e),r=parseFloat(t);return!isNaN(n)&&!isNaN(r)?n-r:e.localeCompare(t,void 0,{numeric:!0,sensitivity:`base`})})},[e,s]),l=c.length>100,[u,d]=o(r(()=>{if(!n?.conditions[0])return l?`condition`:`values`;let e=n.conditions[0];return e.selectedValues&&e.selectedValues.size>0?`values`:`condition`},[n,l])),f=r(()=>n?.conditions[0]?n.conditions[0].selectedValues??new Set:new Set,[n]),p=r(()=>n?.conditions[0]?n.conditions[0].includeBlank??!0:!0,[n]),[m,h]=o(``),[g,_]=o(f),[v,y]=o(p),[b,x]=o(r(()=>{if(!n?.conditions.length)return[{operator:`contains`,value:``,nextOperator:`and`}];let e=n.conditions[0];if(e.selectedValues&&e.selectedValues.size>0)return[{operator:`contains`,value:``,nextOperator:`and`}];let t=n.combination??`and`;return n.conditions.map(e=>{let n=e;return{operator:n.operator,value:n.value??``,nextOperator:n.nextOperator??t}})},[n])),E=r(()=>{if(!m)return c;let e=m.toLowerCase();return c.filter(t=>t.toLowerCase().includes(e))},[c,m]),D=r(()=>e.some(e=>e==null||e===``),[e]),O=r(()=>E.every(e=>g.has(e))&&(!D||v),[E,g,D,v]),k=t(()=>{_(new Set(E)),D&&y(!0)},[E,D]),A=t(()=>{_(new Set),y(!1)},[]),j=t(e=>{_(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),M=t((e,t)=>{x(n=>{let r=[...n];return r[e]={...r[e],...t},r})},[]),N=t(()=>{x(e=>[...e,{operator:`contains`,value:``,nextOperator:`and`}])},[]),P=t(e=>{x(t=>t.filter((t,n)=>n!==e))},[]),F=t(()=>{if(u===`values`){if(c.every(e=>g.has(e))&&(!D||v)){i(null);return}i({conditions:[{type:`text`,operator:`equals`,selectedValues:g,includeBlank:v}],combination:`and`})}else{let e=b.filter(e=>e.operator===`blank`||e.operator===`notBlank`?!0:e.value.trim()!==``);if(e.length===0){i(null);return}i({conditions:e.map(e=>({type:`text`,operator:e.operator,value:e.value,nextOperator:e.nextOperator})),combination:`and`})}},[u,c,g,v,D,b,i]),I=t(()=>{i(null)},[i]);return w(`div`,{className:`gp-grid-filter-content gp-grid-filter-text`,children:[!l&&w(`div`,{className:`gp-grid-filter-mode-toggle`,children:[C(`button`,{type:`button`,className:u===`values`?`active`:``,onClick:()=>d(`values`),children:`Values`}),C(`button`,{type:`button`,className:u===`condition`?`active`:``,onClick:()=>d(`condition`),children:`Condition`})]}),l&&u===`condition`&&w(`div`,{className:`gp-grid-filter-info`,children:[`Too many unique values (`,c.length,`). Use conditions to filter.`]}),u===`values`&&w(S,{children:[C(`input`,{className:`gp-grid-filter-search`,type:`text`,placeholder:`Search...`,value:m,onChange:e=>h(e.target.value),autoFocus:!0}),w(`div`,{className:`gp-grid-filter-actions`,children:[C(`button`,{type:`button`,onClick:k,disabled:O,children:`Select All`}),C(`button`,{type:`button`,onClick:A,children:`Deselect All`})]}),w(`div`,{className:`gp-grid-filter-list`,children:[D&&w(`label`,{className:`gp-grid-filter-option`,children:[C(`input`,{type:`checkbox`,checked:v,onChange:()=>y(!v)}),C(`span`,{className:`gp-grid-filter-blank`,children:`(Blanks)`})]}),E.map(e=>w(`label`,{className:`gp-grid-filter-option`,children:[C(`input`,{type:`checkbox`,checked:g.has(e),onChange:()=>j(e)}),C(`span`,{children:e})]},e))]})]}),u===`condition`&&w(S,{children:[b.map((e,t)=>w(`div`,{className:`gp-grid-filter-condition`,children:[t>0&&w(`div`,{className:`gp-grid-filter-combination`,children:[C(`button`,{type:`button`,className:b[t-1]?.nextOperator===`and`?`active`:``,onClick:()=>M(t-1,{nextOperator:`and`}),children:`AND`}),C(`button`,{type:`button`,className:b[t-1]?.nextOperator===`or`?`active`:``,onClick:()=>M(t-1,{nextOperator:`or`}),children:`OR`})]}),w(`div`,{className:`gp-grid-filter-row`,children:[C(`select`,{value:e.operator,onChange:e=>M(t,{operator:e.target.value}),autoFocus:t===0,children:T.map(e=>C(`option`,{value:e.value,children:e.label},e.value))}),e.operator!==`blank`&&e.operator!==`notBlank`&&C(`input`,{type:`text`,value:e.value,onChange:e=>M(t,{value:e.target.value}),placeholder:`Value`,className:`gp-grid-filter-text-input`}),b.length>1&&C(`button`,{type:`button`,className:`gp-grid-filter-remove`,onClick:()=>P(t),children:`×`})]})]},t)),C(`button`,{type:`button`,className:`gp-grid-filter-add`,onClick:N,children:`+ Add condition`})]}),w(`div`,{className:`gp-grid-filter-buttons`,children:[C(`button`,{type:`button`,className:`gp-grid-filter-btn-clear`,onClick:I,children:`Clear`}),C(`button`,{type:`button`,className:`gp-grid-filter-btn-apply`,onClick:F,children:`Apply`})]})]})}const D=[{value:`=`,label:`=`},{value:`!=`,label:`≠`},{value:`>`,label:`>`},{value:`<`,label:`<`},{value:`>=`,label:`≥`},{value:`<=`,label:`≤`},{value:`between`,label:`↔`},{value:`blank`,label:`Is blank`},{value:`notBlank`,label:`Not blank`}];function O({currentFilter:e,onApply:n,onClose:i}){let[a,s]=o(r(()=>{if(!e?.conditions.length)return[{operator:`=`,value:``,valueTo:``,nextOperator:`and`}];let t=e.combination??`and`;return e.conditions.map(e=>{let n=e;return{operator:n.operator,value:n.value==null?``:String(n.value),valueTo:n.valueTo==null?``:String(n.valueTo),nextOperator:n.nextOperator??t}})},[e])),c=t((e,t)=>{s(n=>{let r=[...n];return r[e]={...r[e],...t},r})},[]),l=t(()=>{s(e=>[...e,{operator:`=`,value:``,valueTo:``,nextOperator:`and`}])},[]),u=t(e=>{s(t=>t.filter((t,n)=>n!==e))},[]),d=t(()=>{let e=a.filter(e=>e.operator===`blank`||e.operator===`notBlank`?!0:e.operator===`between`?e.value!==``&&e.valueTo!==``:e.value!==``);if(e.length===0){n(null);return}n({conditions:e.map(e=>({type:`number`,operator:e.operator,value:e.value?parseFloat(e.value):void 0,valueTo:e.valueTo?parseFloat(e.valueTo):void 0,nextOperator:e.nextOperator})),combination:`and`})},[a,n]),f=t(()=>{n(null)},[n]);return w(`div`,{className:`gp-grid-filter-content gp-grid-filter-number`,children:[a.map((e,t)=>w(`div`,{className:`gp-grid-filter-condition`,children:[t>0&&w(`div`,{className:`gp-grid-filter-combination`,children:[C(`button`,{type:`button`,className:a[t-1]?.nextOperator===`and`?`active`:``,onClick:()=>c(t-1,{nextOperator:`and`}),children:`AND`}),C(`button`,{type:`button`,className:a[t-1]?.nextOperator===`or`?`active`:``,onClick:()=>c(t-1,{nextOperator:`or`}),children:`OR`})]}),w(`div`,{className:`gp-grid-filter-row`,children:[C(`select`,{value:e.operator,onChange:e=>c(t,{operator:e.target.value}),children:D.map(e=>C(`option`,{value:e.value,children:e.label},e.value))}),e.operator!==`blank`&&e.operator!==`notBlank`&&C(`input`,{type:`number`,value:e.value,onChange:e=>c(t,{value:e.target.value}),placeholder:`Value`}),e.operator===`between`&&w(S,{children:[C(`span`,{className:`gp-grid-filter-to`,children:`to`}),C(`input`,{type:`number`,value:e.valueTo,onChange:e=>c(t,{valueTo:e.target.value}),placeholder:`Value`})]}),a.length>1&&C(`button`,{type:`button`,className:`gp-grid-filter-remove`,onClick:()=>u(t),children:`×`})]})]},t)),C(`button`,{type:`button`,className:`gp-grid-filter-add`,onClick:l,children:`+ Add condition`}),w(`div`,{className:`gp-grid-filter-buttons`,children:[C(`button`,{type:`button`,className:`gp-grid-filter-btn-clear`,onClick:f,children:`Clear`}),C(`button`,{type:`button`,className:`gp-grid-filter-btn-apply`,onClick:d,children:`Apply`})]})]})}const k=[{value:`=`,label:`=`},{value:`!=`,label:`≠`},{value:`>`,label:`>`},{value:`<`,label:`<`},{value:`between`,label:`↔`},{value:`blank`,label:`Is blank`},{value:`notBlank`,label:`Not blank`}];function A(e){if(!e)return``;let t=typeof e==`string`?new Date(e):e;return isNaN(t.getTime())?``:t.toISOString().split(`T`)[0]}function j({currentFilter:e,onApply:n,onClose:i}){let[a,s]=o(r(()=>{if(!e?.conditions.length)return[{operator:`=`,value:``,valueTo:``,nextOperator:`and`}];let t=e.combination??`and`;return e.conditions.map(e=>{let n=e;return{operator:n.operator,value:A(n.value),valueTo:A(n.valueTo),nextOperator:n.nextOperator??t}})},[e])),c=t((e,t)=>{s(n=>{let r=[...n];return r[e]={...r[e],...t},r})},[]),l=t(()=>{s(e=>[...e,{operator:`=`,value:``,valueTo:``,nextOperator:`and`}])},[]),u=t(e=>{s(t=>t.filter((t,n)=>n!==e))},[]),d=t(()=>{let e=a.filter(e=>e.operator===`blank`||e.operator===`notBlank`?!0:e.operator===`between`?e.value!==``&&e.valueTo!==``:e.value!==``);if(e.length===0){n(null);return}n({conditions:e.map(e=>({type:`date`,operator:e.operator,value:e.value||void 0,valueTo:e.valueTo||void 0,nextOperator:e.nextOperator})),combination:`and`})},[a,n]),f=t(()=>{n(null)},[n]);return w(`div`,{className:`gp-grid-filter-content gp-grid-filter-date`,children:[a.map((e,t)=>w(`div`,{className:`gp-grid-filter-condition`,children:[t>0&&w(`div`,{className:`gp-grid-filter-combination`,children:[C(`button`,{type:`button`,className:a[t-1]?.nextOperator===`and`?`active`:``,onClick:()=>c(t-1,{nextOperator:`and`}),children:`AND`}),C(`button`,{type:`button`,className:a[t-1]?.nextOperator===`or`?`active`:``,onClick:()=>c(t-1,{nextOperator:`or`}),children:`OR`})]}),w(`div`,{className:`gp-grid-filter-row`,children:[C(`select`,{value:e.operator,onChange:e=>c(t,{operator:e.target.value}),children:k.map(e=>C(`option`,{value:e.value,children:e.label},e.value))}),e.operator!==`blank`&&e.operator!==`notBlank`&&C(`input`,{type:`date`,value:e.value,onChange:e=>c(t,{value:e.target.value})}),e.operator===`between`&&w(S,{children:[C(`span`,{className:`gp-grid-filter-to`,children:`to`}),C(`input`,{type:`date`,value:e.valueTo,onChange:e=>c(t,{valueTo:e.target.value})})]}),a.length>1&&C(`button`,{type:`button`,className:`gp-grid-filter-remove`,onClick:()=>u(t),children:`×`})]})]},t)),C(`button`,{type:`button`,className:`gp-grid-filter-add`,onClick:l,children:`+ Add condition`}),w(`div`,{className:`gp-grid-filter-buttons`,children:[C(`button`,{type:`button`,className:`gp-grid-filter-btn-clear`,onClick:f,children:`Clear`}),C(`button`,{type:`button`,className:`gp-grid-filter-btn-apply`,onClick:d,children:`Apply`})]})]})}function M({column:e,colIndex:r,anchorRect:i,distinctValues:o,currentFilter:s,onApply:c,onClose:l}){let u=a(null);n(()=>{let e=e=>{let t=e.target;t.closest(`.gp-grid-filter-icon`)||u.current&&!u.current.contains(t)&&l()},t=e=>{e.key===`Escape`&&l()};return requestAnimationFrame(()=>{document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t)}),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[l]);let d=t(t=>{c(e.colId??e.field,t),l()},[e,c,l]),f={position:`fixed`,top:i.top+i.height+4,left:i.left,minWidth:Math.max(200,i.width),zIndex:1e4},p=e.cellDataType,m=p===`text`||p===`object`,h=p===`number`,g=p===`date`||p===`dateString`||p===`dateTime`||p===`dateTimeString`;return w(`div`,{ref:u,className:`gp-grid-filter-popup`,style:f,children:[w(`div`,{className:`gp-grid-filter-header`,children:[`Filter: `,e.headerName??e.field]}),m&&C(E,{distinctValues:o,currentFilter:s,onApply:d,onClose:l}),h&&C(O,{currentFilter:s,onApply:d,onClose:l}),g&&C(j,{currentFilter:s,onApply:d,onClose:l}),!m&&!h&&!g&&C(E,{distinctValues:o,currentFilter:s,onApply:d,onClose:l})]})}function N(){return{slots:new Map,activeCell:null,selectionRange:null,editingCell:null,contentWidth:0,contentHeight:0,headers:new Map,filterPopup:null,isLoading:!1,error:null,totalRows:0,visibleRowRange:null}}function P(e,t,n){switch(e.type){case`CREATE_SLOT`:return t.set(e.slotId,{slotId:e.slotId,rowIndex:-1,rowData:{},translateY:0}),null;case`DESTROY_SLOT`:return t.delete(e.slotId),null;case`ASSIGN_SLOT`:{let n=t.get(e.slotId);return n&&t.set(e.slotId,{...n,rowIndex:e.rowIndex,rowData:e.rowData}),null}case`MOVE_SLOT`:{let n=t.get(e.slotId);return n&&t.set(e.slotId,{...n,translateY:e.translateY}),null}case`SET_ACTIVE_CELL`:return{activeCell:e.position};case`SET_SELECTION_RANGE`:return{selectionRange:e.range};case`UPDATE_VISIBLE_RANGE`:return{visibleRowRange:{start:e.start,end:e.end}};case`START_EDIT`:return{editingCell:{row:e.row,col:e.col,initialValue:e.initialValue}};case`STOP_EDIT`:return{editingCell:null};case`SET_CONTENT_SIZE`:return{contentWidth:e.width,contentHeight:e.height};case`UPDATE_HEADER`:return n.set(e.colIndex,{column:e.column,sortDirection:e.sortDirection,sortIndex:e.sortIndex,sortable:e.sortable,filterable:e.filterable,hasFilter:e.hasFilter}),null;case`OPEN_FILTER_POPUP`:return{filterPopup:{isOpen:!0,colIndex:e.colIndex,column:e.column,anchorRect:e.anchorRect,distinctValues:e.distinctValues,currentFilter:e.currentFilter}};case`CLOSE_FILTER_POPUP`:return{filterPopup:null};case`DATA_LOADING`:return{isLoading:!0,error:null};case`DATA_LOADED`:return{isLoading:!1,totalRows:e.totalRows};case`DATA_ERROR`:return{isLoading:!1,error:e.error};case`ROWS_ADDED`:case`ROWS_REMOVED`:return{totalRows:e.totalRows};case`ROWS_UPDATED`:case`TRANSACTION_PROCESSED`:return null;default:return null}}function F(e,t){if(t.type===`RESET`)return N();let{instructions:n}=t;if(n.length===0)return e;let r=new Map(e.slots),i=new Map(e.headers),a={};for(let e of n){let t=P(e,r,i);t&&(a={...a,...t})}return{...e,...a,slots:r,headers:i}}function I(e,t){for(let n of e.values())if(n.rowIndex===t)return n;return null}function L(e,t,n,r,i,a){let o=I(a,n),s=(o?o.translateY:i+n*r)-t.scrollTop,c=s+r,l=i,u=t.clientHeight;if(s<l)t.scrollTop=e.getScrollTopForRow(n);else if(c>u){let a=t.clientHeight-i,o=Math.floor(a/r),s=Math.max(0,n-o+1);t.scrollTop=e.getScrollTopForRow(s)}}function R(e,r,i,s){let{activeCell:c,selectionRange:l,editingCell:u,filterPopupOpen:d,rowHeight:f,headerHeight:p,columnPositions:m,slots:h}=s,g=a(null),[_,v]=o({isDragging:!1,dragType:null,fillSourceRange:null,fillTarget:null});n(()=>{let t=e.current;t?.input&&t.input.updateDeps({getHeaderHeight:()=>p,getRowHeight:()=>f,getColumnPositions:()=>m,getColumnCount:()=>i.length})},[e,p,f,m,i.length]);let y=t((e,t)=>{g.current&&clearInterval(g.current),g.current=setInterval(()=>{let n=r.current;n&&(n.scrollTop+=t,n.scrollLeft+=e)},16)},[r]),b=t(()=>{g.current&&=(clearInterval(g.current),null)},[]),x=t(()=>{let e=r.current;if(!e)return null;let t=e.getBoundingClientRect();return{top:t.top,left:t.left,width:t.width,height:t.height,scrollTop:e.scrollTop,scrollLeft:e.scrollLeft}},[r]),S=e=>({clientX:e.clientX,clientY:e.clientY,button:e.button,shiftKey:e.shiftKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey}),C=t(()=>{let t=t=>{let n=e.current,r=x();if(!n?.input||!r)return;let i=n.input.handleDragMove(S(t),r);i&&(i.autoScroll?y(i.autoScroll.dx,i.autoScroll.dy):b(),v(n.input.getDragState()))},n=()=>{let r=e.current;r?.input&&(r.input.handleDragEnd(),v(r.input.getDragState())),b(),document.removeEventListener(`mousemove`,t),document.removeEventListener(`mouseup`,n)};document.addEventListener(`mousemove`,t),document.addEventListener(`mouseup`,n)},[e,x,y,b]),w=t((t,n,i)=>{let a=e.current;if(!a?.input)return;let o=a.input.handleCellMouseDown(t,n,S(i));o.focusContainer&&r.current?.focus(),o.startDrag===`selection`&&(a.input.startSelectionDrag(),v(a.input.getDragState()),C())},[e,r,C]),T=t((t,n)=>{let r=e.current;r?.input&&r.input.handleCellDoubleClick(t,n)},[e]),E=t(t=>{let n=e.current;if(!n?.input)return;let r=n.input.handleFillHandleMouseDown(c,l,S(t));r.preventDefault&&t.preventDefault(),r.stopPropagation&&t.stopPropagation(),r.startDrag===`fill`&&(v(n.input.getDragState()),C())},[e,c,l,C]),D=t((t,n)=>{let r=e.current;if(!r?.input)return;let a=i[t];if(!a)return;let o=a.colId??a.field;r.input.handleHeaderClick(o,n.shiftKey)},[e,i]),O=t(t=>{let n=e.current,i=r.current;if(!n?.input)return;let a=n.input.handleKeyDown({key:t.key,shiftKey:t.shiftKey,ctrlKey:t.ctrlKey,metaKey:t.metaKey},c,u,d);a.preventDefault&&t.preventDefault(),a.scrollToCell&&i&&L(n,i,a.scrollToCell.row,f,p,h)},[e,r,c,u,d,f,p,h]),k=t((t,n)=>{let i=e.current,a=r.current;if(!i?.input||!a)return;let o=i.input.handleWheel(t.deltaY,t.deltaX,n);o&&(t.preventDefault(),a.scrollTop+=o.dy,a.scrollLeft+=o.dx)},[e,r]);return n(()=>()=>{b()},[b]),{handleCellMouseDown:w,handleCellDoubleClick:T,handleFillHandleMouseDown:E,handleHeaderClick:D,handleKeyDown:O,handleWheel:k,dragState:_}}function z(e,t){let n=t.split(`.`),r=e;for(let e of n){if(typeof r!=`object`||!r)return null;r=r[e]}return r??null}function B(e){let{column:t,rowData:n,rowIndex:r,colIndex:i,isActive:a,isSelected:o,isEditing:s,cellRenderers:c,globalCellRenderer:l}=e,u=z(n,t.field),d={value:u,rowData:n,column:t,rowIndex:r,colIndex:i,isActive:a,isSelected:o,isEditing:s};if(t.cellRenderer&&typeof t.cellRenderer==`string`){let e=c[t.cellRenderer];if(e)return e(d)}return l?l(d):u==null?``:String(u)}function V(e){let{column:t,rowData:n,rowIndex:r,colIndex:i,initialValue:a,coreRef:o,editRenderers:s,globalEditRenderer:c}=e,l=o.current;if(!l)return null;let u={value:z(n,t.field),rowData:n,column:t,rowIndex:r,colIndex:i,isActive:!0,isSelected:!0,isEditing:!0,initialValue:a,onValueChange:e=>l.updateEditValue(e),onCommit:()=>l.commitEdit(),onCancel:()=>l.cancelEdit()};if(t.editRenderer&&typeof t.editRenderer==`string`){let e=s[t.editRenderer];if(e)return e(u)}return c?c(u):C(`input`,{className:`gp-grid-edit-input`,type:`text`,defaultValue:a==null?``:String(a),autoFocus:!0,onFocus:e=>e.target.select(),onChange:e=>l.updateEditValue(e.target.value),onKeyDown:e=>{e.stopPropagation(),e.key===`Enter`?l.commitEdit():e.key===`Escape`?l.cancelEdit():e.key===`Tab`&&(e.preventDefault(),l.commitEdit(),l.selection.moveFocus(e.shiftKey?`left`:`right`,!1))},onBlur:()=>l.commitEdit()})}function H(e){let{column:t,colIndex:n,sortDirection:r,sortIndex:i,sortable:a,filterable:o,hasFilter:s,coreRef:c,containerRef:l,headerRenderers:u,globalHeaderRenderer:d}=e,f=c.current,p={column:t,colIndex:n,sortDirection:r,sortIndex:i,sortable:a,filterable:o,hasFilter:s,onSort:(e,n)=>{f&&a&&f.setSort(t.colId??t.field,e,n)},onFilterClick:()=>{if(f&&o){let e=l.current?.querySelector(`[data-col-index="${n}"]`);if(e){let t=e.getBoundingClientRect();f.openFilterPopup(n,{top:t.top,left:t.left,width:t.width,height:t.height})}}}};if(t.headerRenderer&&typeof t.headerRenderer==`string`){let e=u[t.headerRenderer];if(e)return e(p)}return d?d(p):w(S,{children:[C(`span`,{className:`gp-grid-header-text`,children:t.headerName??t.field}),w(`span`,{className:`gp-grid-header-icons`,children:[a&&w(`span`,{className:`gp-grid-sort-arrows`,children:[w(`span`,{className:`gp-grid-sort-arrows-stack`,children:[C(`svg`,{className:`gp-grid-sort-arrow-up${r===`asc`?` active`:``}`,width:`8`,height:`6`,viewBox:`0 0 8 6`,children:C(`path`,{d:`M4 0L8 6H0L4 0Z`,fill:`currentColor`})}),C(`svg`,{className:`gp-grid-sort-arrow-down${r===`desc`?` active`:``}`,width:`8`,height:`6`,viewBox:`0 0 8 6`,children:C(`path`,{d:`M4 6L0 0H8L4 6Z`,fill:`currentColor`})})]}),i!==void 0&&i>0&&C(`span`,{className:`gp-grid-sort-index`,children:i})]}),o&&C(`span`,{className:`gp-grid-filter-icon${s?` active`:``}`,onMouseDown:e=>{e.stopPropagation(),e.preventDefault(),p.onFilterClick()},onClick:e=>{e.stopPropagation()},children:C(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`currentColor`,children:C(`path`,{d:`M10 18h4v-2h-4v2zM3 6v2h18V6H3zm3 7h12v-2H6v2z`})})})]})]})}function U(e){_();let{columns:o,dataSource:u,rowData:f,rowHeight:m,headerHeight:h=m,overscan:S=3,sortingEnabled:T=!0,darkMode:E=!1,wheelDampening:D=.1,cellRenderers:O={},editRenderers:k={},headerRenderers:A={},cellRenderer:j,editRenderer:P,headerRenderer:I}=e,L=a(null),z=a(null),[U,W]=i(F,null,N),G=h,K=r(()=>u||(f?p(f):d([])),[u,f]),q=r(()=>l(o),[o]),J=g(q),{handleCellMouseDown:Y,handleCellDoubleClick:X,handleFillHandleMouseDown:ee,handleHeaderClick:te,handleKeyDown:ne,handleWheel:re,dragState:Z}=R(z,L,o,{activeCell:U.activeCell,selectionRange:U.selectionRange,editingCell:U.editingCell,filterPopupOpen:U.filterPopup?.isOpen??!1,rowHeight:m,headerHeight:G,columnPositions:q,slots:U.slots});n(()=>{let e=new s({columns:o,dataSource:K,rowHeight:m,headerHeight:G,overscan:S,sortingEnabled:T});z.current=e;let t=e.onBatchInstruction(e=>{W({type:`BATCH_INSTRUCTIONS`,instructions:e})});return e.initialize(),()=>{t(),z.current=null}},[o,K,m,G,S,T]),n(()=>{let e=K;if(e.subscribe)return e.subscribe(()=>{z.current?.refresh()})},[K]);let Q=t(()=>{let e=L.current,t=z.current;!e||!t||t.setViewport(e.scrollTop,e.scrollLeft,e.clientWidth,e.clientHeight)},[]);n(()=>{let e=L.current,t=z.current;if(!e||!t)return;let n=new ResizeObserver(()=>{t.setViewport(e.scrollTop,e.scrollLeft,e.clientWidth,e.clientHeight)});return n.observe(e),Q(),()=>n.disconnect()},[Q]);let ie=t((e,t)=>{let n=z.current;n&&n.setFilter(e,t)},[]),ae=t(()=>{let e=z.current;e&&e.closeFilterPopup()},[]),oe=r(()=>Array.from(U.slots.values()),[U.slots]),$=r(()=>{let{activeCell:e,selectionRange:t,slots:n}=U;if(!e&&!t)return null;let r,i,a,s;if(t)r=Math.max(t.startRow,t.endRow),i=Math.max(t.startCol,t.endCol),a=Math.min(t.startCol,t.endCol),s=Math.max(t.startCol,t.endCol);else if(e)r=e.row,i=e.col,a=i,s=i;else return null;for(let e=a;e<=s;e++){let t=o[e];if(!t||t.editable!==!0)return null}let c=null;for(let e of n.values())if(e.rowIndex===r){c=e.translateY;break}if(c===null)return null;let l=q[i]??0,u=o[i]?.width??0;return{top:c+m-5,left:l+u-20}},[U.activeCell,U.selectionRange,U.slots,m,q,o]);return w(`div`,{ref:L,className:`gp-grid-container${E?` gp-grid-container--dark`:``}`,style:{width:`100%`,height:`100%`,overflow:`auto`,position:`relative`},onScroll:Q,onWheel:e=>re(e,D),onKeyDown:ne,tabIndex:0,children:[w(`div`,{style:{width:Math.max(U.contentWidth,J),height:Math.max(U.contentHeight,G),position:`relative`,minWidth:`100%`},children:[C(`div`,{className:`gp-grid-header`,style:{position:`sticky`,top:0,left:0,height:h,width:Math.max(U.contentWidth,J),minWidth:`100%`,zIndex:100},children:o.map((e,t)=>{let n=U.headers.get(t);return C(`div`,{className:`gp-grid-header-cell`,"data-col-index":t,style:{position:`absolute`,left:`${q[t]}px`,top:0,width:`${e.width}px`,height:`${h}px`,background:`transparent`},onClick:e=>te(t,e),children:H({column:e,colIndex:t,sortDirection:n?.sortDirection,sortIndex:n?.sortIndex,sortable:n?.sortable??!0,filterable:n?.filterable??!0,hasFilter:n?.hasFilter??!1,coreRef:z,containerRef:L,headerRenderers:A,globalHeaderRenderer:I})},e.colId??e.field)})}),oe.map(e=>e.rowIndex<0?null:C(`div`,{className:`gp-grid-row ${e.rowIndex%2==0?`gp-grid-row--even`:``}`,style:{position:`absolute`,top:0,left:0,transform:`translateY(${e.translateY}px)`,width:`${Math.max(U.contentWidth,J)}px`,height:`${m}px`},children:o.map((t,n)=>{let r=y(e.rowIndex,n,U.editingCell),i=v(e.rowIndex,n,U.activeCell),a=x(e.rowIndex,n,U.selectionRange);return C(`div`,{className:c(i,a,r,b(e.rowIndex,n,Z.dragType===`fill`,Z.fillSourceRange,Z.fillTarget)),style:{position:`absolute`,left:`${q[n]}px`,top:0,width:`${t.width}px`,height:`${m}px`},onMouseDown:t=>Y(e.rowIndex,n,t),onDoubleClick:()=>X(e.rowIndex,n),children:r&&U.editingCell?V({column:t,rowData:e.rowData,rowIndex:e.rowIndex,colIndex:n,initialValue:U.editingCell.initialValue,coreRef:z,editRenderers:k,globalEditRenderer:P}):B({column:t,rowData:e.rowData,rowIndex:e.rowIndex,colIndex:n,isActive:i,isSelected:a,isEditing:r,cellRenderers:O,globalCellRenderer:j})},`${e.slotId}-${n}`)})},e.slotId)),$&&!U.editingCell&&C(`div`,{className:`gp-grid-fill-handle`,style:{position:`absolute`,top:$.top,left:$.left,zIndex:200},onMouseDown:ee}),U.isLoading&&w(`div`,{className:`gp-grid-loading`,children:[C(`div`,{className:`gp-grid-loading-spinner`}),`Loading...`]}),U.error&&w(`div`,{className:`gp-grid-error`,children:[`Error: `,U.error]}),!U.isLoading&&!U.error&&U.totalRows===0&&C(`div`,{className:`gp-grid-empty`,children:`No data to display`})]}),U.filterPopup?.isOpen&&U.filterPopup.column&&U.filterPopup.anchorRect&&C(M,{column:U.filterPopup.column,colIndex:U.filterPopup.colIndex,anchorRect:U.filterPopup.anchorRect,distinctValues:U.filterPopup.distinctValues,currentFilter:U.filterPopup.currentFilter,onApply:ie,onClose:ae})]})}export{U as Grid,u as createClientDataSource,f as createDataSourceFromArray,m as createMutableClientDataSource,h as createServerDataSource};