File size: 25,543 Bytes
f51553f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
/* eslint-disable no-undef */
// CSV Editor State and Logic
(() => {
  // DOM references
  const gridEl = document.getElementById('grid');
  const datasetInfoEl = document.getElementById('datasetInfo');
  const renderInfoEl = document.getElementById('renderInfo');
  const fileInput = document.getElementById('fileInput');
  const exportBtn = document.getElementById('exportBtn');
  const clearBtn = document.getElementById('clearBtn');

  const searchInput = document.getElementById('searchInput');
  const caseSensitive = document.getElementById('caseSensitive');

  const toggleFiltersBtn = document.getElementById('toggleFiltersBtn');
  const resetFiltersBtn = document.getElementById('resetFiltersBtn');

  const freezeLeftCount = document.getElementById('freezeLeftCount');
  const applyFreezeBtn = document.getElementById('applyFreezeBtn');
  const freezeRightCount = document.getElementById('freezeRightCount');
  const applyFreezeRightBtn = document.getElementById('applyFreezeRightBtn');

  // State
  const state = {
    rawHeaders: [],
    headers: [],
    rows: [],          // Array<Array<string>>
    allRows: [],       // Original dataset (for reset)
    colWidth: 120,
    rowHeight: 32,
    headerHeight: 40,
    freezeLeft: 0,
    freezeRight: 0,
    filtersEnabled: false,
    colFilters: {},    // { colIndex: Set(values) } include mode
    globalSearch: '',
    globalSearchRegex: null,
    caseSensitive: false,
    // render cache
    totalWidth: 0,
    nCols: 0,
    nRows: 0,
    lastSync: 0
  };

  // Utils
  const debounce = (fn, ms = 250) => {
    let t;
    return (...args) => {
      clearTimeout(t);
      t = setTimeout(() => fn(...args), ms);
    };
  };

  function normalizeHeaders(headers) {
    const result = [];
    const seen = new Map();
    for (let i = 0; i < headers.length; i++) {
      let name = headers[i] != null ? String(headers[i]).trim() : `Column ${i+1}`;
      if (name.length === 0) name = `Column ${i+1}`;
      if (seen.has(name)) {
        const count = seen.get(name) + 1;
        seen.set(name, count);
        name = `${name} (${count})`;
      } else {
        seen.set(name, 1);
      }
      result.push(name);
    }
    return result;
  }

  function computeUniqueSample(values, max = 2000) {
    // Returns a Set of up to `max` unique values
    const set = new Set();
    for (const v of values) {
      if (set.size >= max) break;
      const s = v == null ? '' : String(v);
      if (!set.has(s)) set.add(s);
    }
    return set;
  }

  function escapeCSV(value) {
    const s = value == null ? '' : String(value);
    if (/[",\n]/.test(s)) {
      return `"${s.replace(/"/g, '""')}"`;
    }
    return s;
  }

  function toCSV(headers, rows) {
    const lines = [];
    lines.push(headers.map(escapeCSV).join(','));
    for (const row of rows) {
      lines.push(row.map(escapeCSV).join(','));
    }
    return lines.join('\n');
  }

  function recalcDimensions() {
    state.nCols = state.headers.length;
    state.nRows = state.rows.length;
    state.totalWidth = state.nCols * state.colWidth;
    const stickyLeftW = Math.min(state.freezeLeft, state.nCols) * state.colWidth;
    const stickyRightW = Math.min(state.freezeRight, state.nCols) * state.colWidth;
    document.documentElement.style.setProperty('--sticky-left-w', `${stickyLeftW}px`);
    document.documentElement.style.setProperty('--sticky-right-w', `${stickyRightW}px`);
  }

  function updateDatasetInfo() {
    const total = state.allRows.length;
    const filtered = state.rows.length;
    const filterActive = state.filtersEnabled || (state.globalSearch && state.globalSearch.length > 0);
    datasetInfoEl.textContent = `${filtered} 行 × ${state.nCols} 列${filterActive ? `(共 ${total})` : ''}`;
  }

  // Filtering logic
  function applyAllFilters() {
    const start = performance.now();
    const nCols = state.nCols;
    const caseSensitive = state.caseSensitive;

    const globalSearch = state.globalSearch || '';
    let globalRegex = null;
    if (globalSearch.length > 0) {
      try {
        globalRegex = new RegExp(globalSearch, caseSensitive ? '' : 'i');
      } catch (e) {
        renderInfoEl.textContent = '正则表达式错误';
        return;
      }
    }

    const colFilterEntries = Object.entries(state.colFilters);
    // Pre-build col filter sets for speed
    const colFilters = {};
    for (const [idxStr, set] of colFilterEntries) {
      const idx = Number(idxStr);
      colFilters[idx] = new Set(set); // copy
    }

    const includeRow = (row) => {
      // Column filter: row[j] must be in set for each filtered column j
      for (const jStr in colFilters) {
        const j = Number(jStr);
        const val = row[j] == null ? '' : String(row[j]);
        if (!colFilters[j].has(val)) return false;
      }
      // Global search: row includes the regex anywhere
      if (globalRegex) {
        let hit = false;
        for (let j = 0; j < nCols; j++) {
          const v = row[j] == null ? '' : String(row[j]);
          if (globalRegex.test(v)) { hit = true; break; }
        }
        if (!hit) return false;
      }
      return true;
    };

    state.rows = state.allRows.filter(includeRow);
    recalcDimensions();
    updateDatasetInfo();
    renderGrid(true);
    const dur = Math.round(performance.now() - start);
    renderInfoEl.textContent = `筛选用时 ${dur}ms`;
  }

  const applyAllFiltersDebounced = debounce(applyAllFilters, 200);

  // Rendering
  function clearGrid() {
    gridEl.innerHTML = '';
  }

  function buildHeaderContent(scrollerEl, colStart, colEnd, isLeft = false, isRight = false) {
    scrollerEl.innerHTML = '';

    const headerRow = document.createElement('div');
    headerRow.style.display = 'flex';
    headerRow.style.alignItems = 'stretch';
    headerRow.className = 'grid-header flex';

    for (let j = colStart; j < colEnd; j++) {
      const div = document.createElement('div');
      div.className = `grid-cell flex items-center justify-between px-2 ${isLeft || isRight ? 'sticky-left' : ''} ${j === state.freezeLeft - 1 ? 'frozen-edge' : ''} ${j === state.nCols - state.freezeRight ? 'frozen-edge' : ''}`;
      div.dataset.col = String(j);

      const title = document.createElement('div');
      title.className = 'truncate text-xs font-medium text-slate-700';
      title.textContent = state.headers[j];

      const actions = document.createElement('div');
      actions.className = 'flex items-center gap-1';

      const filterBtn = document.createElement('button');
      filterBtn.className = 'btn-ghost p-1 rounded';
      filterBtn.title = '筛选该列';
      filterBtn.innerHTML = `
        <svg class="w-4 h-4 text-slate-500" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path stroke-linecap="round" stroke-linejoin="round" d="M3 5h18M6 12h12M10 19h4"/>
        </svg>`;
      filterBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        toggleFilterPopover(j, filterBtn);
      });

      actions.appendChild(filterBtn);
      div.appendChild(title);
      div.appendChild(actions);

      headerRow.appendChild(div);
    }

    scrollerEl.appendChild(headerRow);
  }

  function toggleFilterPopover(colIndex, anchorEl) {
    // Close existing popover
    const existing = document.querySelector('.popover[data-role="filter-popover"]');
    if (existing) existing.remove();

    if (!state.filtersEnabled) {
      // enable and apply
      state.filtersEnabled = true;
    }

    const rect = anchorEl.getBoundingClientRect();
    const pop = document.createElement('div');
    pop.className = 'popover w-80 p-3';
    pop.dataset.role = 'filter-popover';
    pop.style.left = `${Math.max(8, rect.left - 260)}px`;
    pop.style.top = `${Math.min(window.innerHeight - 320, rect.bottom + 8)}px`;

    // Build unique set from original data for better fidelity
    const uniques = new Set();
    for (const row of state.allRows) {
      const v = row[colIndex] == null ? '' : String(row[colIndex]);
      uniques.add(v);
      if (uniques.size > 2000) break;
    }

    const current = state.colFilters[colIndex] || new Set();

    const header = document.createElement('div');
    header.className = 'flex items-center justify-between mb-2';
    header.innerHTML = `
      <div class="font-medium text-sm text-slate-700">筛选列:${state.headers[colIndex]}</div>
      <button class="btn-ghost p-1" data-action="close">
        <svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12"/></svg>
      </button>`;

    const search = document.createElement('input');
    search.className = 'input mb-2';
    search.placeholder = '搜索选项...';

    const listWrap = document.createElement('div');
    listWrap.className = 'border border-slate-200 rounded-lg max-h-60 overflow-auto';
    const list = document.createElement('div');
    listWrap.appendChild(list);

    function renderList() {
      list.innerHTML = '';
      const term = search.value.trim().toLowerCase();
      const values = Array.from(uniques).sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));
      let count = 0;
      for (const v of values) {
        const show = term.length === 0 || String(v).toLowerCase().includes(term);
        if (!show) continue;
        count++;
        if (count > 1000) { // safety
          break;
        }
        const rowEl = document.createElement('label');
        rowEl.className = 'flex items-center gap-2 px-3 py-2 hover:bg-slate-50';
        rowEl.innerHTML = `
          <input type="checkbox" class="rounded border-slate-300 text-primary focus:ring-primary" ${current.has(v) ? 'checked' : ''}/>
          <span class="flex-1 truncate">${v === '' ? '<空>' : v}</span>
          <span class="text-xs text-slate-400">包含</span>
        `;
        const checkbox = rowEl.querySelector('input[type=checkbox]');
        checkbox.addEventListener('change', () => {
          const set = state.colFilters[colIndex] || new Set();
          if (checkbox.checked) set.add(v);
          else set.delete(v);
          if (set.size === 0) delete state.colFilters[colIndex];
          else state.colFilters[colIndex] = set;
          applyAllFiltersDebounced();
        });
        list.appendChild(rowEl);
      }
      if (count === 0) {
        const empty = document.createElement('div');
        empty.className = 'p-3 text-sm text-slate-500';
        empty.textContent = '无匹配项';
        list.appendChild(empty);
      }
    }

    search.addEventListener('input', renderList);

    const footer = document.createElement('div');
    footer.className = 'flex items-center gap-2 mt-3';
    const btnAll = document.createElement('button');
    btnAll.className = 'btn';
    btnAll.textContent = '全选';
    btnAll.addEventListener('click', () => {
      state.colFilters[colIndex] = new Set(uniques);
      renderList();
      applyAllFiltersDebounced();
    });
    const btnNone = document.createElement('button');
    btnNone.className = 'btn';
    btnNone.textContent = '清空';
    btnNone.addEventListener('click', () => {
      delete state.colFilters[colIndex];
      renderList();
      applyAllFiltersDebounced();
    });
    footer.appendChild(btnAll);
    footer.appendChild(btnNone);

    pop.appendChild(header);
    pop.appendChild(search);
    pop.appendChild(listWrap);
    pop.appendChild(footer);

    header.querySelector('[data-action="close"]').addEventListener('click', () => pop.remove());
    document.body.appendChild(pop);
    renderList();
  }

  function renderGrid(forceRebuild = false) {
    clearGrid();

    if (state.nCols === 0 || state.nRows === 0) {
      const empty = document.createElement('div');
      empty.className = 'p-8 text-center text-slate-500';
      empty.innerHTML = '暂无数据。请导入 CSV 文件。';
      gridEl.appendChild(empty);
      return;
    }

    const viewport = gridEl.getBoundingClientRect();
    const viewWidth = Math.max(320, viewport.width);
    const viewHeight = Math.max(300, window.innerHeight - 300);

    // Set CSS vars
    document.documentElement.style.setProperty('--header-h', `${state.headerHeight}px`);
    document.documentElement.style.setProperty('--row-h', `${state.rowHeight}px`);
    document.documentElement.style.setProperty('--cell-w', `${state.colWidth}px`);

    // Layout:
    // Two rows: header row and body row.
    // Each row has three panes: left sticky, middle scrollable, right sticky.
    const headerRow = document.createElement('div');
    headerRow.className = 'flex w-full';

    const bodyRow = document.createElement('div');
    bodyRow.className = 'flex w-full';

    // Measure visible columns
    // For simplicity, we'll render a virtual window horizontally across all columns (like vertically),
    // but we still split into left/middle/right panes so frozen columns are visible.
    const totalCols = state.nCols;
    const colWidth = state.colWidth;
    const stickyLeftW = Math.min(state.freezeLeft, totalCols) * colWidth;
    const stickyRightW = Math.min(state.freezeRight, totalCols) * colWidth;
    const allColsRange = [0, totalCols];

    // Header containers
    const headerLeft = document.createElement('div');
    headerLeft.className = 'sticky-left border-r';
    headerLeft.style.width = `${stickyLeftW}px`;

    const headerScroll = document.createElement('div');
    headerScroll.className = 'header-scroller overflow-x-auto overflow-y-hidden border-r';
    headerScroll.style.flex = '1 1 auto';

    const headerRight = document.createElement('div');
    headerRight.className = 'sticky-right';
    headerRight.style.width = `${stickyRightW}px`;

    // Body containers
    const bodyLeft = document.createElement('div');
    bodyLeft.className = 'sticky-left border-r';
    bodyLeft.style.width = `${stickyLeftW}px`;

    const bodyScroll = document.createElement('div');
    bodyScroll.className = 'row-scroller overflow-auto';
    bodyScroll.style.flex = '1 1 auto';

    const bodyRight = document.createElement('div');
    bodyRight.className = 'sticky-right';
    bodyRight.width = `${stickyRightW}px`;
    bodyRight.style.width = `${stickyRightW}px`;

    // Build content
    buildHeaderContent(headerLeft, 0, Math.min(state.freezeLeft, totalCols), true, false);
    buildHeaderContent(headerScroll, 0, totalCols, false, false);
    buildHeaderContent(headerRight, Math.max(0, totalCols - state.freezeRight), totalCols, false, true);

    // Body virtual content
    const spacer = document.createElement('div');
    spacer.style.width = `${state.totalWidth}px`;
    spacer.style.height = `${state.nRows * state.rowHeight}px`;
    spacer.style.position = 'relative';

    function renderVisibleRows() {
      // Clean existing cells
      headerLeft.innerHTML = '';
      headerScroll.innerHTML = '';
      headerRight.innerHTML = '';
      bodyLeft.innerHTML = '';
      bodyRight.innerHTML = '';
      spacer.innerHTML = '';

      // Rebuild headers (fast)
      buildHeaderContent(headerLeft, 0, Math.min(state.freezeLeft, totalCols), true, false);
      buildHeaderContent(headerScroll, 0, totalCols, false, false);
      buildHeaderContent(headerRight, Math.max(0, totalCols - state.freezeRight), totalCols, false, true);

      // Visible rows by scroll
      const y = bodyScroll.scrollTop;
      const x = bodyScroll.scrollLeft;
      const startRow = Math.max(0, Math.floor(y / state.rowHeight) - 10);
      const endRow = Math.min(state.nRows, startRow + Math.ceil(viewHeight / state.rowHeight) + 20);
      const topOffset = startRow * state.rowHeight;

      // Build left frozen rows
      const leftFrag = document.createDocumentFragment();
      for (let r = startRow; r < endRow; r++) {
        const rowLeft = document.createElement('div');
        rowLeft.className = 'flex';
        rowLeft.style.position = 'absolute';
        rowLeft.style.top = `${r * state.rowHeight}px`;
        rowLeft.style.height = `${state.rowHeight}px`;

        for (let j = 0; j < Math.min(state.freezeLeft, totalCols); j++) {
          rowLeft.appendChild(buildCell(r, j, true, false));
        }
        leftFrag.appendChild(rowLeft);
      }

      // Build middle rows (all columns)
      const midFrag = document.createDocumentFragment();
      for (let r = startRow; r < endRow; r++) {
        const rowDiv = document.createElement('div');
        rowDiv.className = 'flex';
        rowDiv.style.position = 'absolute';
        rowDiv.style.top = `${r * state.rowHeight}px`;
        rowDiv.style.height = `${state.rowHeight}px`;

        for (let j = 0; j < totalCols; j++) {
          rowDiv.appendChild(buildCell(r, j, false, false));
        }
        midFrag.appendChild(rowDiv);
      }

      // Build right frozen rows
      const rightFrag = document.createDocumentFragment();
      for (let r = startRow; r < endRow; r++) {
        const rowRight = document.createElement('div');
        rowRight.className = 'flex';
        rowRight.style.position = 'absolute';
        rowRight.style.top = `${r * state.rowHeight}px`;
        rowRight.style.height = `${state.rowHeight}px`;

        const rightStart = Math.max(0, totalCols - state.freezeRight);
        for (let j = rightStart; j < totalCols; j++) {
          rowRight.appendChild(buildCell(r, j, false, true));
        }
        rightFrag.appendChild(rowRight);
      }

      bodyLeft.appendChild(leftFrag);
      spacer.appendChild(midFrag);
      bodyRight.appendChild(rightFrag);
    }

    function buildCell(r, c, isLeft, isRight) {
      const div = document.createElement('div');
      div.className = `grid-cell flex items-center px-2 ${isLeft ? 'sticky-left' : ''} ${isRight ? 'sticky-right' : ''} ${c === state.freezeLeft - 1 ? 'frozen-edge' : ''} ${c === state.nCols - state.freezeRight ? 'frozen-edge' : ''}`;
      div.dataset.row = String(r);
      div.dataset.col = String(c);

      const val = state.rows[r][c] == null ? '' : String(state.rows[r][c]);
      const span = document.createElement('div');
      span.className = 'truncate text-[13px] text-slate-800 w-full';
      span.textContent = val;
      div.appendChild(span);

      // Edit on double click or enter
      div.tabIndex = -1;
      div.addEventListener('dblclick', () => startEdit(div));
      div.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') {
          e.preventDefault();
          startEdit(div);
        }
      });

      return div;
    }

    function startEdit(cellEl) {
      const r = Number(cellEl.dataset.row);
      const c = Number(cellEl.dataset.col);
      const original = state.rows[r][c] == null ? '' : String(state.rows[r][c]);

      const input = document.createElement('input');
      input.type = 'text';
      input.value = original;
      input.className = 'input w-full h-full border-0 outline-none bg-transparent px-0';
      cellEl.innerHTML = '';
      cellEl.appendChild(input);
      cellEl.classList.add('cell-editing');
      input.focus();
      input.setSelectionRange(original.length, original.length);

      const commit = () => {
        state.rows[r][c] = input.value;
        cellEl.classList.remove('cell-editing');
        const span = document.createElement('div');
        span.className = 'truncate text-[13px] text-slate-800 w-full';
        span.textContent = input.value;
        cellEl.innerHTML = '';
        cellEl.appendChild(span);
        renderInfoEl.textContent = `已编辑单元格 (${r + 1}, ${c + 1})`;
      };

      input.addEventListener('blur', commit, { once: true });
      input.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') {
          e.preventDefault();
          input.blur();
        } else if (e.key === 'Escape') {
          e.preventDefault();
          cellEl.classList.remove('cell-editing');
          const span = document.createElement('div');
          span.className = 'truncate text-[13px] text-slate-800 w-full';
          span.textContent = original;
          cellEl.innerHTML = '';
          cellEl.appendChild(span);
        }
      });
    }

    // Assemble
    headerRow.appendChild(headerLeft);
    headerRow.appendChild(headerScroll);
    headerRow.appendChild(headerRight);

    bodyRow.appendChild(bodyLeft);
    bodyRow.appendChild(bodyScroll);
    bodyRow.appendChild(bodyRight);

    gridEl.appendChild(headerRow);
    gridEl.appendChild(bodyRow);

    bodyScroll.appendChild(spacer);

    // Sync scroll
    const syncHorizontal = (src, dests) => {
      src.addEventListener('scroll', () => {
        for (const d of dests) d.scrollLeft = src.scrollLeft;
      });
    };
    syncHorizontal(bodyScroll, [headerScroll]);
    syncHorizontal(headerScroll, [bodyScroll]);

    // Initial render of visible rows
    renderVisibleRows();

    // Render on scroll with rAF
    let ticking = false;
    const onScroll = () => {
      if (!ticking) {
        requestAnimationFrame(() => {
          renderVisibleRows();
          ticking = false;
        });
        ticking = true;
      }
    };
    bodyScroll.addEventListener('scroll', onScroll);
    window.addEventListener('resize', debounce(() => {
      renderVisibleRows();
    }, 100));

    renderInfoEl.textContent = `可见行渲染范围取决于滚动位置`;
  }

  // Data import
  function importCSVFromFile(file) {
    renderInfoEl.textContent = '正在解析 CSV...';
    Papa.parse(file, {
      worker: true,
      skipEmptyLines: 'greedy',
      delimiter: '', // auto-detect
      complete: (res) => {
        if (res.errors && res.errors.length) {
          console.warn('CSV parse errors:', res.errors.slice(0, 5));
        }
        let data = res.data;
        // Trim trailing empty rows
        while (data.length && data[data.length - 1].every(v => String(v).trim() === '')) {
          data.pop();
        }
        if (data.length === 0) {
          renderInfoEl.textContent = 'CSV 为空';
          return;
        }
        // Assume first row as header
        const rawHeaders = data[0].map(v => v == null ? '' : String(v));
        const headers = normalizeHeaders(rawHeaders);
        const rows = data.slice(1).map(row => {
          const arr = new Array(headers.length);
          for (let i = 0; i < headers.length; i++) {
            arr[i] = row[i] == null ? '' : String(row[i]);
          }
          return arr;
        });

        state.rawHeaders = rawHeaders;
        state.headers = headers;
        state.allRows = rows;
        state.rows = rows.slice();
        state.filtersEnabled = false;
        state.colFilters = {};
        state.globalSearch = '';
        state.freezeLeft = 0;
        state.freezeRight = 0;

        recalcDimensions();
        updateDatasetInfo();
        renderGrid(true);
        renderInfoEl.textContent = `已加载 ${rows.length} 行 × ${headers.length} 列`;
        // Update freeze inputs
        freezeLeftCount.value = state.freezeLeft;
        freezeRightCount.value = state.freezeRight;
        searchInput.value = '';
      },
      error: (err) => {
        console.error(err);
        renderInfoEl.textContent = 'CSV 解析失败';
      }
    });
  }

  // Events
  fileInput.addEventListener('change', (e) => {
    const file = e.target.files?.[0];
    if (file) importCSVFromFile(file);
    fileInput.value = '';
  });

  exportBtn.addEventListener('click', () => {
    if (state.nCols === 0) {
      renderInfoEl.textContent = '没有可导出的数据';
      return;
    }
    const csv = toCSV(state.headers, state.rows);
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = 'export.csv';
    a.click();
    URL.revokeObjectURL(a.href);
  });

  clearBtn.addEventListener('click', () => {
    state.rawHeaders = [];
    state.headers = [];
    state.rows = [];
    state.allRows = [];
    state.nCols = 0;
    state.nRows = 0;
    state.filtersEnabled = false;
    state.colFilters = {};
    state.globalSearch = '';
    state.freezeLeft = 0;
    state.freezeRight = 0;
    searchInput.value = '';
    freezeLeftCount.value = 0;
    freezeRightCount.value = 0;
    clearGrid();
    updateDatasetInfo();
    renderInfoEl.textContent = '已清空';
  });

  searchInput.addEventListener('input', debounce(() => {
    state.globalSearch = searchInput.value || '';
    applyAllFiltersDebounced();
  }, 200));

  caseSensitive.addEventListener('change', () => {
    state.caseSensitive = caseSensitive.checked;
    applyAllFiltersDebounced();
  });

  toggleFiltersBtn.addEventListener('click', () => {
    state.filtersEnabled = !state.filtersEnabled;
    applyAllFiltersDebounced();
  });

  resetFiltersBtn.addEventListener('click', () => {
    state.filtersEnabled = false;
    state.colFilters = {};
    state.globalSearch = '';
    searchInput.value = '';
    applyAllFilters();
    renderInfoEl.textContent = '筛选已重置';
  });

  applyFreezeBtn.addEventListener('click', () => {
    let n = Number(freezeLeftCount.value || 0);
    if (!Number.isFinite(n) || n < 0) n = 0;
    n = Math.min(n, state.nCols);
    state.freezeLeft = n;
    recalcDimensions();
    renderGrid(true);
  });

  applyFreezeRightBtn.addEventListener('click', () => {
    let n = Number(freezeRightCount.value || 0);
    if (!Number.isFinite(n) || n < 0) n = 0;
    n = Math.min(n, state.nCols);
    state.freezeRight = n;
    recalcDimensions();
    renderGrid(true);
  });