umbral-admin 0.0.12

Auto-generated CRUD admin UI for umbral models.
Documentation
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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
// umbral-admin runtime JS (gaps2 #4).
//
// Pre-fix: ~1080 lines of JS lived inline in wrapper.html across 3
// <script> blocks (lines 500–1178, 1229–1491, 1493–1634). The
// blocks ran at parser-position, but everything they do is "set up
// helpers + register event listeners" — none of it requires
// mid-parse timing. Extracted here as one external file served via
// the framework's StaticFile mechanism (see static_assets.rs).
//
// `umbralAdminBase` is a global set by a small inline bootstrap in
// wrapper.html (`<script>var umbralAdminBase = '{{ admin_base }}';</script>`).
// Every URL-construction site that used to read `{{ admin_base }}`
// now concatenates `umbralAdminBase + '/...'` instead.
//
// Pre-paint code (theme bootstrap, the window.umbral stub) stays
// inline in <head> — moving it here would flash the wrong theme
// during external-script fetch.

  // Extend the early-declared window.umbral stub with the full IIFE exports.
  // The stub was declared in <head> so child-template inline scripts are safe.
  (function() {
    // ----- Ambient CSRF -----
    // htmx requests inherit the X-CSRF-Token header from <body hx-headers>
    // (rendered from the ambient {{ csrf_token }}); raw fetch() writes
    // bypass that inheritance, so they read the (deliberately
    // non-HttpOnly) cookie here instead.
    function csrfHeaders() {
      var m = document.cookie.match(/(?:^|;\s*)umbral_csrf_token=([^;]*)/);
      return m ? { 'X-CSRF-Token': decodeURIComponent(m[1]) } : {};
    }
    // ----- Theme toggle (Bug 4) -----
    // Source of truth: server prefs (data-theme attr set at render time).
    // localStorage mirrors for instant FOUC-free apply on next load.
    function applyTheme(dark) {
      var root = document.documentElement;
      var themeName = dark ? 'dark' : 'light';
      if (dark) {
        root.classList.add('dark');
      } else {
        root.classList.remove('dark');
      }
      root.setAttribute('data-theme', themeName);
      var light = document.getElementById('theme-icon-light');
      var moon  = document.getElementById('theme-icon-dark');
      if (dark) {
        if (light) light.classList.remove('hidden');
        if (moon)  moon.classList.add('hidden');
      } else {
        if (light) light.classList.add('hidden');
        if (moon)  moon.classList.remove('hidden');
      }
    }
    // Initial theme: read from data-theme (server-rendered); fall back to localStorage.
    var serverTheme = document.documentElement.getAttribute('data-theme');
    var storedTheme = localStorage.getItem('umbral-admin-theme');
    var resolvedTheme = storedTheme || serverTheme || 'dark';
    var isDark = resolvedTheme !== 'light';
    applyTheme(isDark);

    function toggleTheme() {
      isDark = !isDark;
      var themeName = isDark ? 'dark' : 'light';
      localStorage.setItem('umbral-admin-theme', themeName);
      applyTheme(isDark);
      queueChartRefresh();
      // Persist to server so the next hard refresh renders the correct class.
      fetch(umbralAdminBase + '/api/prefs', {
        method: 'PUT',
        headers: Object.assign({ 'Content-Type': 'application/json' }, csrfHeaders()),
        body: JSON.stringify({ theme: themeName })
      }).catch(function() { /* ignore; localStorage mirror is sufficient */ });
    }

    // ----- Responsive sidebar -----
    var sidebarCollapsed = localStorage.getItem('umbral-admin-sidebar') === 'collapsed';
    var sidebarMobileOpen = false;

    function isMobileSidebar() {
      return window.matchMedia && window.matchMedia('(max-width: 767px)').matches;
    }

    function applySidebarState() {
      var body = document.body;
      if (!body) return;
      var mobile = isMobileSidebar();
      body.classList.toggle('sidebar-collapsed', !mobile && sidebarCollapsed);
      body.classList.toggle('sidebar-open', mobile && sidebarMobileOpen);

      var toggle = document.getElementById('sidebar-toggle');
      if (toggle) {
        toggle.setAttribute('aria-expanded', mobile ? String(sidebarMobileOpen) : String(!sidebarCollapsed));
        toggle.setAttribute('aria-label', mobile
          ? (sidebarMobileOpen ? 'Close navigation' : 'Open navigation')
          : (sidebarCollapsed ? 'Expand navigation' : 'Collapse navigation'));
      }
      if (mobile || !sidebarCollapsed) hideSidebarTooltip();
    }

    function persistSidebarCollapsed() {
      fetch(umbralAdminBase + '/api/prefs', {
        method: 'PUT',
        headers: Object.assign({ 'Content-Type': 'application/json' }, csrfHeaders()),
        body: JSON.stringify({ sidebar_collapsed: sidebarCollapsed })
      }).catch(function() { /* localStorage is enough for instant UX */ });
    }

    function toggleSidebar() {
      if (isMobileSidebar()) {
        sidebarMobileOpen = !sidebarMobileOpen;
      } else {
        sidebarCollapsed = !sidebarCollapsed;
        localStorage.setItem('umbral-admin-sidebar', sidebarCollapsed ? 'collapsed' : 'expanded');
        persistSidebarCollapsed();
      }
      applySidebarState();
      queueChartRefresh();
    }

    function closeSidebar() {
      if (isMobileSidebar()) {
        sidebarMobileOpen = false;
      } else {
        sidebarCollapsed = true;
        localStorage.setItem('umbral-admin-sidebar', 'collapsed');
        persistSidebarCollapsed();
      }
      applySidebarState();
      queueChartRefresh();
    }

    applySidebarState();
    window.addEventListener('resize', applySidebarState);

    function hideSidebarTooltip() {
      var tooltip = document.getElementById('umbral-sidebar-tooltip');
      if (!tooltip) return;
      tooltip.removeAttribute('data-open');
      tooltip.setAttribute('aria-hidden', 'true');
      tooltip.textContent = '';
    }

    function showSidebarTooltip(trigger) {
      if (isMobileSidebar() || !document.body.classList.contains('sidebar-collapsed')) return;
      var text = trigger.getAttribute('data-sidebar-tooltip') || '';
      var tooltip = document.getElementById('umbral-sidebar-tooltip');
      if (!text || !tooltip) return;
      tooltip.textContent = text;
      tooltip.setAttribute('data-open', 'true');
      tooltip.setAttribute('aria-hidden', 'false');
      var rect = trigger.getBoundingClientRect();
      var y = rect.top + rect.height / 2;
      tooltip.style.transform = 'translateY(-50%)';
      tooltip.style.top = Math.max(18, Math.min(window.innerHeight - 18, y)) + 'px';
    }

    function initSidebarTooltips(root) {
      root = root || document;
      root.querySelectorAll('[data-sidebar-tooltip]:not([data-sidebar-tooltip-init])').forEach(function(el) {
        el.setAttribute('data-sidebar-tooltip-init', '1');
        el.addEventListener('mouseenter', function() { showSidebarTooltip(el); });
        el.addEventListener('focus', function() { showSidebarTooltip(el); });
        el.addEventListener('mouseleave', hideSidebarTooltip);
        el.addEventListener('blur', hideSidebarTooltip);
      });
    }
    initSidebarTooltips();

    // ----- Sidebar live model filter -----
    function sidebarFilter(query) {
      var q = query.trim().toLowerCase();
      var links = document.querySelectorAll('.sidebar-model-link');
      links.forEach(function(link) {
        var name = (link.getAttribute('data-model-name') || '').toLowerCase();
        var visible = q === '' || name.indexOf(q) !== -1;
        link.style.display = visible ? '' : 'none';
      });
      // Hide groups that have no visible models (except the core group).
      document.querySelectorAll('.sidebar-plugin-group').forEach(function(group) {
        var anyVisible = Array.from(group.querySelectorAll('.sidebar-model-link'))
          .some(function(l) { return l.style.display !== 'none'; });
        group.style.display = anyVisible ? '' : 'none';
      });
    }

    // ----- Dashboard charts -----
    function token(name, fallback) {
      var styles = getComputedStyle(document.documentElement);
      var value = styles.getPropertyValue(name);
      return value ? value.trim() : fallback;
    }

    function chartIsDark() {
      return document.documentElement.getAttribute('data-theme') !== 'light';
    }

    function readBarChart(el) {
      var labels = [];
      var values = [];
      el.querySelectorAll('[data-chart-point]').forEach(function(point) {
        var label = point.getAttribute('data-label') || '';
        var value = Number(point.getAttribute('data-value') || 0);
        labels.push(label);
        values.push(Number.isFinite(value) ? value : 0);
      });
      return {
        labels: labels,
        values: values,
        seriesName: el.getAttribute('data-chart-series') || 'entries',
      };
    }

    function barChartOptions(el) {
      var data = readBarChart(el);
      if (data.labels.length === 0) return null;
      var maxValue = Math.max.apply(null, data.values.concat([1]));
      var foreground = token('--on-surface', 'rgb(229 231 235)');
      var onPrimary = token('--on-primary', 'rgb(17 24 39)');
      var muted = token('--outline', 'rgb(148 163 184)');
      var grid = token('--outline-variant', 'rgb(51 65 85)');
      return {
        chart: {
          type: 'bar',
          height: '100%',
          width: '100%',
          background: 'transparent',
          fontFamily: 'Inter, ui-sans-serif, system-ui, sans-serif',
          foreColor: muted,
          parentHeightOffset: 0,
          toolbar: { show: false },
          zoom: { enabled: false },
          animations: {
            enabled: true,
            speed: 320,
            animateGradually: { enabled: false },
            dynamicAnimation: { enabled: true, speed: 220 },
          },
        },
        series: [{
          name: data.seriesName,
          data: data.values,
        }],
        colors: [token('--primary', 'rgb(79 70 229)')],
        plotOptions: {
          bar: {
            horizontal: true,
            borderRadius: 6,
            borderRadiusApplication: 'end',
            barHeight: '58%',
          },
        },
        dataLabels: {
          enabled: true,
          formatter: function(value) { return Math.round(value); },
          style: {
            colors: [onPrimary],
            fontFamily: 'Inter, ui-sans-serif, system-ui, sans-serif',
            fontSize: '11px',
            fontWeight: 600,
          },
          background: {
            enabled: false,
          },
        },
        grid: {
          borderColor: grid,
          strokeDashArray: 3,
          padding: { top: 0, right: 8, bottom: 0, left: 4 },
        },
        xaxis: {
          categories: data.labels,
          min: 0,
          max: maxValue,
          tickAmount: Math.min(4, Math.max(1, maxValue)),
          labels: {
            formatter: function(value) { return Math.round(value); },
            style: {
              colors: muted,
              fontFamily: 'Inter, ui-sans-serif, system-ui, sans-serif',
              fontSize: '11px',
            },
          },
          axisBorder: { show: false },
          axisTicks: { show: false },
        },
        yaxis: {
          labels: {
            align: 'left',
            minWidth: 0,
            maxWidth: 124,
            style: {
              colors: foreground,
              fontFamily: 'Inter, ui-sans-serif, system-ui, sans-serif',
              fontSize: '12px',
              fontWeight: 500,
            },
          },
        },
        tooltip: {
          theme: chartIsDark() ? 'dark' : 'light',
          y: {
            formatter: function(value) {
              var count = Math.round(value);
              return count + (count === 1 ? ' model' : ' models');
            },
          },
        },
        states: {
          hover: { filter: { type: 'lighten', value: 0.04 } },
          active: { filter: { type: 'none' } },
        },
      };
    }

    // Sparkline mode — area chart with chrome stripped. Used by
    // the card widget's trend trail; ApexCharts gives us
    // animation + tooltip + responsive resizing without any of
    // our own SVG plumbing. The colour comes from the card's
    // delta tone (emerald = positive, red = negative, default
    // primary) and is read off `data-spark-color`.
    function sparklineChartOptions(el) {
      var values = [];
      el.querySelectorAll('[data-chart-point]').forEach(function(point) {
        var v = Number(point.getAttribute('data-value') || 0);
        values.push(Number.isFinite(v) ? v : 0);
      });
      if (values.length === 0) return null;
      var color = el.getAttribute('data-spark-color') || token('--primary', 'rgb(99 102 241)');
      return {
        chart: {
          type: 'area',
          // ApexCharts sparkline mode needs an explicit pixel height —
          // `'100%'` evaluates to 0 inside an absolutely-positioned
          // canvas because the parent's computed height hasn't
          // finished layout when ApexCharts measures. 48px matches
          // the card's reserved sparkline strip (h-12 below).
          height: 48,
          width: '100%',
          background: 'transparent',
          sparkline: { enabled: true },
          animations: {
            enabled: true,
            speed: 380,
            animateGradually: { enabled: false },
            dynamicAnimation: { enabled: true, speed: 220 },
          },
        },
        series: [{ name: el.getAttribute('data-chart-series') || 'series', data: values }],
        colors: [color],
        stroke: { curve: 'smooth', width: 2 },
        fill: {
          type: 'gradient',
          gradient: {
            shadeIntensity: 1,
            opacityFrom: 0.35,
            opacityTo: 0,
            stops: [0, 100],
          },
        },
        tooltip: {
          enabled: true,
          theme: chartIsDark() ? 'dark' : 'light',
          fixed: { enabled: false },
          x: { show: false },
          y: { formatter: function(v) { return Math.round(v); } },
          marker: { show: false },
        },
      };
    }

    // Full-size line/area chart for dashboard widgets — like the
    // sparkline but with axes, grid, and tooltip x-labels.
    // Reads (x, y) pairs from `[data-chart-point][data-series][data-x][data-y]`
    // siblings; ApexCharts mounts on `[data-chart-canvas]`. Points
    // without `data-series` default to a single unnamed series, so
    // single-series widgets stay backwards compatible.
    function lineChartOptions(el) {
      var labels = [];
      var labelsSeen = Object.create(null);
      // Preserve insertion order of series so colors/legend match
      // the order the macro emitted them.
      var seriesOrder = [];
      var seriesMap = Object.create(null);
      el.querySelectorAll('[data-chart-point]').forEach(function(point) {
        var name = point.getAttribute('data-series') || 'series';
        var x = point.getAttribute('data-x') || '';
        var y = Number(point.getAttribute('data-y') || 0);
        var yClean = Number.isFinite(y) ? y : 0;
        if (!seriesMap[name]) {
          seriesMap[name] = [];
          seriesOrder.push(name);
        }
        seriesMap[name].push(yClean);
        // X labels — first series's x values define the axis;
        // subsequent series share them in order.
        if (!labelsSeen[x]) {
          labelsSeen[x] = true;
          labels.push(x);
        }
      });
      if (seriesOrder.length === 0) return null;
      var series = seriesOrder.map(function(name) {
        return { name: name, data: seriesMap[name] };
      });
      var primary = token('--primary', 'rgb(99 102 241)');
      var muted   = token('--outline', 'rgb(148 163 184)');
      var grid    = token('--outline-variant', 'rgb(51 65 85)');
      // Default palette for multi-series — emerald / blue / amber /
      // pink. Theme-stable accents (the framework only has
      // `--primary` semantically; everything else uses Tailwind
      // colors directly so it stays readable in light + dark).
      var palette = [primary, '#34d399', '#60a5fa', '#fbbf24', '#f472b6'];
      var isSingleSeries = series.length === 1;
      return {
        chart: {
          type: 'area',
          height: '100%',
          width: '100%',
          background: 'transparent',
          toolbar: { show: false },
          zoom: { enabled: false },
          parentHeightOffset: 0,
          fontFamily: 'Inter, ui-sans-serif, system-ui, sans-serif',
          foreColor: muted,
          animations: {
            enabled: true,
            speed: 380,
            animateGradually: { enabled: false },
            dynamicAnimation: { enabled: true, speed: 220 },
          },
        },
        series: series,
        colors: palette,
        // Single-series stays as the gradient area we had before;
        // multi-series drops the heavy fill so the lines don't
        // overlap into mud (ApexCharts area mode with multi-series
        // stacks fills by default — not what dashboard widgets
        // want; we want overlaid trends).
        stroke: { curve: 'smooth', width: 2 },
        fill: isSingleSeries
          ? {
              type: 'gradient',
              gradient: {
                shadeIntensity: 1,
                opacityFrom: 0.30,
                opacityTo: 0,
                stops: [0, 100],
              },
            }
          : { type: 'solid', opacity: 0.06 },
        dataLabels: { enabled: false },
        // Multi-series gets a legend strip; single-series doesn't
        // need it (the widget title IS the series name).
        legend: {
          show: !isSingleSeries,
          position: 'top',
          horizontalAlign: 'right',
          labels: { colors: muted },
          markers: { width: 8, height: 8, radius: 4 },
          itemMargin: { horizontal: 8 },
        },
        grid: {
          borderColor: grid,
          strokeDashArray: 3,
          padding: { top: 0, right: 8, bottom: 0, left: 4 },
        },
        markers: { size: 0, hover: { size: 4 } },
        xaxis: {
          categories: labels,
          labels: {
            style: { colors: muted, fontSize: '11px' },
            // Show every Nth label for dense series so they don't
            // crowd the axis. 7 ticks reads cleanly across widths.
            rotate: 0,
            hideOverlappingLabels: true,
          },
          axisBorder: { show: false },
          axisTicks: { show: false },
        },
        yaxis: {
          labels: {
            style: { colors: muted, fontSize: '11px' },
            formatter: function(v) { return Math.round(v); },
          },
        },
        tooltip: {
          theme: chartIsDark() ? 'dark' : 'light',
          y: { formatter: function(v) { return Math.round(v); } },
        },
      };
    }

    // Donut chart — labeled slices summing to 100%. Reads
    // (label, value, optional color) from
    // `[data-chart-slice][data-label][data-value][data-color]`
    // siblings. Legend renders on the right; center label
    // shows the total. Best for ≤6 slices — past that the
    // labels collide and a bar chart reads better.
    function donutChartOptions(el) {
      var labels = [];
      var values = [];
      var explicitColors = [];
      var hasAnyColor = false;
      el.querySelectorAll('[data-chart-slice]').forEach(function(slice) {
        labels.push(slice.getAttribute('data-label') || '');
        var v = Number(slice.getAttribute('data-value') || 0);
        values.push(Number.isFinite(v) ? v : 0);
        var c = slice.getAttribute('data-color');
        explicitColors.push(c || null);
        if (c) hasAnyColor = true;
      });
      if (values.length === 0) return null;
      var muted     = token('--outline', 'rgb(148 163 184)');
      var onSurface = token('--on-surface', 'rgb(229 231 235)');
      // Default palette mirrors the line chart — emerald / blue
      // / amber / pink / violet / cyan — readable in both
      // themes since they're explicit accents, not tokens.
      var defaultPalette = ['#34d399', '#60a5fa', '#fbbf24', '#f472b6', '#a78bfa', '#22d3ee'];
      var colors = hasAnyColor
        ? explicitColors.map(function(c, i) { return c || defaultPalette[i % defaultPalette.length]; })
        : defaultPalette;
      return {
        chart: {
          type: 'donut',
          height: '100%',
          width: '100%',
          background: 'transparent',
          fontFamily: 'Inter, ui-sans-serif, system-ui, sans-serif',
          foreColor: muted,
          parentHeightOffset: 0,
          animations: {
            enabled: true,
            speed: 380,
            animateGradually: { enabled: false },
            dynamicAnimation: { enabled: true, speed: 220 },
          },
        },
        series: values,
        labels: labels,
        colors: colors,
        stroke: { width: 0 },
        dataLabels: { enabled: false },
        legend: {
          position: 'right',
          labels: { colors: muted },
          markers: { width: 8, height: 8, radius: 4 },
          itemMargin: { vertical: 4 },
        },
        plotOptions: {
          pie: {
            donut: {
              size: '70%',
              labels: {
                show: true,
                name: {
                  show: true,
                  fontSize: '11px',
                  color: muted,
                  offsetY: -4,
                },
                value: {
                  show: true,
                  fontSize: '20px',
                  fontWeight: 600,
                  color: onSurface,
                  offsetY: 6,
                  formatter: function(v) { return Math.round(Number(v)); },
                },
                total: {
                  show: true,
                  label: 'Total',
                  color: muted,
                  fontSize: '11px',
                  formatter: function(w) {
                    return Math.round(
                      w.globals.seriesTotals.reduce(function(a, b) { return a + b; }, 0)
                    );
                  },
                },
              },
            },
          },
        },
        tooltip: {
          theme: chartIsDark() ? 'dark' : 'light',
          y: { formatter: function(v) { return Math.round(v); } },
        },
        responsive: [{
          breakpoint: 480,
          options: {
            legend: { position: 'bottom' },
          },
        }],
      };
    }

    // Radial gauge — one or more 0–100% tracks as concentric arcs.
    // Reads (label, value, optional color) from
    // `[data-chart-track][data-label][data-value][data-color]`
    // siblings. A single track shows one big ring with the percent
    // in the centre; multiple tracks compare related ratios and the
    // centre shows their average.
    function radialChartOptions(el) {
      var labels = [];
      var values = [];
      var explicitColors = [];
      var hasAnyColor = false;
      el.querySelectorAll('[data-chart-track]').forEach(function(track) {
        labels.push(track.getAttribute('data-label') || '');
        var v = Number(track.getAttribute('data-value') || 0);
        values.push(Number.isFinite(v) ? Math.max(0, Math.min(100, v)) : 0);
        var c = track.getAttribute('data-color');
        explicitColors.push(c || null);
        if (c) hasAnyColor = true;
      });
      if (values.length === 0) return null;
      var muted     = token('--outline', 'rgb(148 163 184)');
      var onSurface = token('--on-surface', 'rgb(229 231 235)');
      // Same accent palette the donut + line charts use — readable in
      // both themes (explicit accents, not tokens).
      var defaultPalette = ['#34d399', '#60a5fa', '#fbbf24', '#f472b6', '#a78bfa', '#22d3ee'];
      var colors = hasAnyColor
        ? explicitColors.map(function(c, i) { return c || defaultPalette[i % defaultPalette.length]; })
        : defaultPalette;
      var single = values.length === 1;
      return {
        chart: {
          type: 'radialBar',
          height: '100%',
          width: '100%',
          background: 'transparent',
          fontFamily: 'Inter, ui-sans-serif, system-ui, sans-serif',
          foreColor: muted,
          parentHeightOffset: 0,
          animations: {
            enabled: true,
            speed: 380,
            animateGradually: { enabled: false },
            dynamicAnimation: { enabled: true, speed: 220 },
          },
        },
        series: values,
        labels: labels,
        colors: colors,
        stroke: { lineCap: 'round' },
        plotOptions: {
          radialBar: {
            hollow: { size: single ? '60%' : '38%' },
            track: {
              background: token('--surface-container-high', 'rgba(148,163,184,0.15)'),
              strokeWidth: '100%',
              margin: 4,
            },
            dataLabels: {
              name: {
                show: true,
                fontSize: '11px',
                color: muted,
                offsetY: single ? -8 : 0,
              },
              value: {
                show: true,
                fontSize: single ? '22px' : '14px',
                fontWeight: 600,
                color: onSurface,
                offsetY: single ? 4 : 0,
                formatter: function(v) { return Math.round(Number(v)) + '%'; },
              },
              total: single ? undefined : {
                show: true,
                label: 'Avg',
                color: muted,
                fontSize: '11px',
                formatter: function(w) {
                  var s = w.globals.series;
                  if (!s.length) return '0%';
                  var sum = s.reduce(function(a, b) { return a + b; }, 0);
                  return Math.round(sum / s.length) + '%';
                },
              },
            },
          },
        },
        legend: single ? { show: false } : {
          show: true,
          position: 'bottom',
          labels: { colors: muted },
          markers: { width: 8, height: 8, radius: 4 },
          itemMargin: { vertical: 2 },
        },
        tooltip: { enabled: false },
      };
    }

    // Heatmap — a 2-D grid colored by magnitude. Reads one
    // `[data-chart-cell][data-row][data-x][data-y]` span per cell and
    // groups them into one ApexCharts series per row, preserving the
    // first-seen row order and the per-row column order. ApexCharts
    // draws series bottom-up, so we reverse to keep the payload's first
    // row at the TOP.
    function heatmapChartOptions(el) {
      var order = [];
      var byRow = {};
      el.querySelectorAll('[data-chart-cell]').forEach(function(cell) {
        var name = cell.getAttribute('data-row') || '';
        if (!byRow[name]) { byRow[name] = []; order.push(name); }
        var y = Number(cell.getAttribute('data-y') || 0);
        byRow[name].push({
          x: cell.getAttribute('data-x') || '',
          y: Number.isFinite(y) ? y : 0,
        });
      });
      if (order.length === 0) return null;
      var series = order.slice().reverse().map(function(name) {
        return { name: name, data: byRow[name] };
      });
      var muted = token('--outline', 'rgb(148 163 184)');
      return {
        chart: {
          type: 'heatmap',
          height: '100%',
          width: '100%',
          background: 'transparent',
          fontFamily: 'Inter, ui-sans-serif, system-ui, sans-serif',
          foreColor: muted,
          parentHeightOffset: 0,
          toolbar: { show: false },
          animations: { enabled: true, speed: 320 },
        },
        series: series,
        dataLabels: { enabled: false },
        stroke: { width: 2, colors: ['transparent'] },
        // Single-hue ramp — ApexCharts shades it by magnitude.
        colors: ['#60a5fa'],
        plotOptions: {
          heatmap: { radius: 4, enableShades: true, shadeIntensity: 0.6 },
        },
        xaxis: {
          type: 'category',
          labels: { style: { colors: muted, fontSize: '10px' } },
          axisBorder: { show: false },
          axisTicks: { show: false },
        },
        yaxis: { labels: { style: { colors: muted, fontSize: '10px' } } },
        grid: { borderColor: 'transparent', padding: { top: 0, right: 0 } },
        tooltip: {
          theme: chartIsDark() ? 'dark' : 'light',
          y: { formatter: function(v) { return Math.round(v); } },
        },
        legend: { show: false },
      };
    }

    function initCharts(root) {
      root = root || document;
      root.querySelectorAll('[data-umbral-chart="bar"]').forEach(function(el) {
        var canvas = el.querySelector('[data-chart-canvas]');
        var fallback = el.querySelector('[data-chart-unavailable]');
        if (!canvas) return;
        if (!window.ApexCharts) {
          if (fallback) fallback.classList.remove('hidden');
          return;
        }
        if (fallback) fallback.classList.add('hidden');
        var options = barChartOptions(el);
        if (!options) return;
        if (canvas._umbralApexChart) {
          canvas._umbralApexChart.updateOptions(options, false, true);
          return;
        }
        canvas._umbralApexChart = new ApexCharts(canvas, options);
        canvas._umbralApexChart.render();
      });
      root.querySelectorAll('[data-umbral-chart="sparkline"]').forEach(function(el) {
        var canvas = el.querySelector('[data-chart-canvas]');
        var fallback = el.querySelector('[data-chart-unavailable]');
        if (!canvas) return;
        if (!window.ApexCharts) {
          if (fallback) fallback.classList.remove('hidden');
          return;
        }
        if (fallback) fallback.classList.add('hidden');
        var options = sparklineChartOptions(el);
        if (!options) return;
        if (canvas._umbralApexChart) {
          canvas._umbralApexChart.updateOptions(options, false, true);
          return;
        }
        canvas._umbralApexChart = new ApexCharts(canvas, options);
        canvas._umbralApexChart.render();
      });
      root.querySelectorAll('[data-umbral-chart="line"]').forEach(function(el) {
        var canvas = el.querySelector('[data-chart-canvas]');
        var fallback = el.querySelector('[data-chart-unavailable]');
        if (!canvas) return;
        if (!window.ApexCharts) {
          if (fallback) fallback.classList.remove('hidden');
          return;
        }
        if (fallback) fallback.classList.add('hidden');
        var options = lineChartOptions(el);
        if (!options) return;
        if (canvas._umbralApexChart) {
          canvas._umbralApexChart.updateOptions(options, false, true);
          return;
        }
        canvas._umbralApexChart = new ApexCharts(canvas, options);
        canvas._umbralApexChart.render();
      });
      root.querySelectorAll('[data-umbral-chart="donut"]').forEach(function(el) {
        var canvas = el.querySelector('[data-chart-canvas]');
        var fallback = el.querySelector('[data-chart-unavailable]');
        if (!canvas) return;
        if (!window.ApexCharts) {
          if (fallback) fallback.classList.remove('hidden');
          return;
        }
        if (fallback) fallback.classList.add('hidden');
        var options = donutChartOptions(el);
        if (!options) return;
        if (canvas._umbralApexChart) {
          canvas._umbralApexChart.updateOptions(options, false, true);
          return;
        }
        canvas._umbralApexChart = new ApexCharts(canvas, options);
        canvas._umbralApexChart.render();
      });
      root.querySelectorAll('[data-umbral-chart="radial"]').forEach(function(el) {
        var canvas = el.querySelector('[data-chart-canvas]');
        var fallback = el.querySelector('[data-chart-unavailable]');
        if (!canvas) return;
        if (!window.ApexCharts) {
          if (fallback) fallback.classList.remove('hidden');
          return;
        }
        if (fallback) fallback.classList.add('hidden');
        var options = radialChartOptions(el);
        if (!options) return;
        if (canvas._umbralApexChart) {
          canvas._umbralApexChart.updateOptions(options, false, true);
          return;
        }
        canvas._umbralApexChart = new ApexCharts(canvas, options);
        canvas._umbralApexChart.render();
      });
      root.querySelectorAll('[data-umbral-chart="heatmap"]').forEach(function(el) {
        var canvas = el.querySelector('[data-chart-canvas]');
        var fallback = el.querySelector('[data-chart-unavailable]');
        if (!canvas) return;
        if (!window.ApexCharts) {
          if (fallback) fallback.classList.remove('hidden');
          return;
        }
        if (fallback) fallback.classList.add('hidden');
        var options = heatmapChartOptions(el);
        if (!options) return;
        if (canvas._umbralApexChart) {
          canvas._umbralApexChart.updateOptions(options, false, true);
          return;
        }
        canvas._umbralApexChart = new ApexCharts(canvas, options);
        canvas._umbralApexChart.render();
      });
    }

    function queueChartRefresh() {
      window.setTimeout(function() {
        initCharts(document);
      }, 220);
    }

    // ----- User menu (placeholder) -----
    function toggleUserMenu() {
      // Phase 4 will wire a real dropdown; for now clicking the avatar
      // navigates to ${admin_base}/logout for simplicity.
    }

    Object.assign(window.umbral, {
      // Exported so the widget-reorder block (a separate IIFE) writes its layout
      // PUT through the SAME CSRF helper. A second hand-rolled copy of the
      // cookie-reading logic is one refactor away from silently drifting.
      csrfHeaders: csrfHeaders,
      toggleTheme: toggleTheme,
      toggleSidebar: toggleSidebar,
      closeSidebar: closeSidebar,
      sidebarFilter: sidebarFilter,
      initCharts: initCharts,
      refreshCharts: queueChartRefresh,
      toggleUserMenu: toggleUserMenu,
    });
  })();

  // Initialise Lucide icons after the DOM is fully painted and after
  // HTMX swaps widget/palette fragments into the page.
  document.addEventListener('DOMContentLoaded', function() {
    if (window.lucide) lucide.createIcons();
    if (window.umbral && umbral.initCharts) umbral.initCharts(document);
  });
  document.body.addEventListener('htmx:afterSwap', function(e) {
    if (window.lucide) lucide.createIcons({ el: e.target });
    if (window.umbral && umbral.initCharts) umbral.initCharts(e.target);
  });
(function() {
  window.umbral = window.umbral || {};

  umbral.showToast = function(message, level) {
    level = level || 'info';
    var container = document.getElementById('umbral-toast-container');
    if (!container) return;
    var colors = {
      info:    'bg-surface-container border-outline-variant text-on-surface',
      success: 'bg-primary-container/20 border-primary/30 text-primary',
      warning: 'bg-surface-container border-outline text-on-surface-variant',
      error:   'bg-error-container/20 border-error/30 text-error'
    };
    var icons = { info: 'info', success: 'check-circle', warning: 'alert-triangle', error: 'alert-circle' };
    var toast = document.createElement('div');
    toast.className = 'pointer-events-auto flex items-center gap-sm px-lg py-sm rounded-xl border shadow-lg font-label-md text-label-md transition-all duration-300 ' + (colors[level] || colors.info);
    toast.innerHTML = '<i data-lucide="' + (icons[level]||'info') + '" class="w-4 h-4 flex-shrink-0"></i><span>' + message + '</span>';
    container.appendChild(toast);
    if (window.lucide) lucide.createIcons({ el: toast });
    setTimeout(function() {
      toast.style.opacity = '0';
      toast.style.transform = 'translateX(20px)';
      setTimeout(function() { toast.remove(); }, 300);
    }, 4000);
  };

  document.body.addEventListener('htmx:responseError', function(e) {
    // HTMX classifies every 4xx + 5xx as a "response error" — but
    // 400 / 409 / 422 from the admin's form-submit handlers are
    // validation responses that re-render the form with an inline
    // error span ALREADY visible to the user. Firing a generic
    // "Server error" toast on top of that is noise: the user sees
    // both the precise field-level message AND a misleading
    // "server" toast that suggests a crash. Skip the toast for
    // these statuses; swap-bearing validation responses already
    // surface the real message inline. Only 5xx + the catch-all
    // 4xxs that DON'T carry a re-render body get the toast.
    var status = e.detail && e.detail.xhr ? e.detail.xhr.status : 0;
    if (status === 400 || status === 409 || status === 422) {
      return;
    }
    umbral.showToast('Server error', 'error');
  });

  document.body.addEventListener('showToast', function(e) {
    if (e.detail) umbral.showToast(e.detail.message, e.detail.level);
  });

  // MultiChoice — chip checkboxes synced to a hidden CSV input.
  // Idempotent via [data-mc-init]; safe to re-run after HTMX swaps.
  function initMultiChoicePickers(root) {
    root = root || document;
    root.querySelectorAll('.multichoice-picker:not([data-mc-init])').forEach(function(picker) {
      picker.setAttribute('data-mc-init', '1');
      var hidden = picker.querySelector('input[type=hidden]');
      if (!hidden) return;
      function sync() {
        var values = [];
        picker.querySelectorAll('input[type=checkbox][data-mc-value]').forEach(function(cb) {
          if (cb.checked) values.push(cb.getAttribute('data-mc-value'));
        });
        hidden.value = values.join(',');
        picker.querySelectorAll('input[type=checkbox][data-mc-value]').forEach(function(cb) {
          var label = cb.closest('label');
          if (!label) return;
          if (cb.checked) {
            label.classList.add('border-primary', 'text-primary', 'bg-primary/5');
            label.classList.remove('border-outline-variant', 'text-on-surface-variant');
          } else {
            label.classList.remove('border-primary', 'text-primary', 'bg-primary/5');
            label.classList.add('border-outline-variant', 'text-on-surface-variant');
          }
        });
      }
      picker.querySelectorAll('input[type=checkbox][data-mc-value]').forEach(function(cb) {
        cb.addEventListener('change', sync);
      });
    });
  }
  umbral.initMultiChoicePickers = initMultiChoicePickers;
  initMultiChoicePickers();
  document.body.addEventListener('htmx:afterSwap', function() { initMultiChoicePickers(); });

  // FK searchable combobox — idempotent via [data-fk-init].
  function initFkPickers(root) {
    root = root || document;
    root.querySelectorAll('.fk-picker:not([data-fk-init])').forEach(function(picker) {
      picker.setAttribute('data-fk-init', '1');
      var textInput = picker.querySelector('input[type=text]');
      var hiddenInput = picker.querySelector('input[type=hidden]');
      var dropdown = picker.querySelector('.fk-options');
      if (!textInput || !hiddenInput || !dropdown) return;

      function setSelection(value, label) {
        hiddenInput.value = value || '';
        var active = picker.querySelector('[data-fk-active]');
        var activeLabel = picker.querySelector('[data-fk-active-label]');
        var activeValue = picker.querySelector('[data-fk-active-value]');
        if (active) active.classList.toggle('hidden', !value);
        if (activeLabel) activeLabel.textContent = label || 'Selected option';
        if (activeValue) activeValue.textContent = value ? '#' + value : '';
      }

      textInput.addEventListener('focus', function() { dropdown.classList.remove('hidden'); });
      textInput.addEventListener('input', function() {
        if (textInput.value.trim()) dropdown.classList.remove('hidden');
      });
      document.addEventListener('click', function(e) {
        if (!picker.contains(e.target)) dropdown.classList.add('hidden');
      });

      picker.querySelectorAll('[data-fk-clear]').forEach(function(btn) {
        btn.addEventListener('click', function() {
          setSelection('', '');
          textInput.value = '';
          textInput.focus();
        });
      });

      picker.addEventListener('htmx:afterSwap', function() {
        dropdown.classList.remove('hidden');
        dropdown.querySelectorAll('[data-fk-value]').forEach(function(opt) {
          opt.addEventListener('mousedown', function(e) {
            e.preventDefault();
            var value = opt.getAttribute('data-fk-value') || '';
            var label = opt.getAttribute('data-fk-label') || opt.textContent.trim();
            setSelection(value, label);
            textInput.value = '';
            dropdown.classList.add('hidden');
          });
        });
        if (window.lucide) lucide.createIcons({ el: dropdown });
      });
    });
  }
  umbral.fkResolve = function(field, event) {
    try {
      var data = JSON.parse(event.detail.xhr.responseText);
      if (data.items && data.items[0]) {
        var source = event.target || (event.detail && event.detail.elt);
        var picker = source && source.closest ? source.closest('.fk-picker') : null;
        if (!picker) {
          var el = document.getElementById('fk_text_' + field);
          picker = el && el.closest ? el.closest('.fk-picker') : null;
        }
        if (picker) {
          var item = data.items[0];
          var hidden = picker.querySelector('input[type=hidden]');
          var active = picker.querySelector('[data-fk-active]');
          var activeLabel = picker.querySelector('[data-fk-active-label]');
          var activeValue = picker.querySelector('[data-fk-active-value]');
          if (hidden) hidden.value = String(item.value);
          if (active) active.classList.remove('hidden');
          if (activeLabel) activeLabel.textContent = item.label;
          if (activeValue) activeValue.textContent = '#' + item.value;
        }
      }
    } catch(e) {}
  };
  initFkPickers();
  document.body.addEventListener('htmx:afterSwap', function() { initFkPickers(); });

  // M2M checkbox lists — search + selected summary + small client-side pages.
  function initM2MPickers(root) {
    root = root || document;
    root.querySelectorAll('.m2m-field-picker:not([data-m2m-init])').forEach(function(picker) {
      picker.setAttribute('data-m2m-init', '1');
      var search = picker.querySelector('[data-m2m-search]');
      var selected = picker.querySelector('[data-m2m-selected]');
      var selectedEmpty = picker.querySelector('[data-m2m-selected-empty]');
      var count = picker.querySelector('[data-m2m-count]');
      var pageLabel = picker.querySelector('[data-m2m-page]');
      var prev = picker.querySelector('[data-m2m-prev]');
      var next = picker.querySelector('[data-m2m-next]');
      var empty = picker.querySelector('[data-m2m-empty]');
      var options = Array.from(picker.querySelectorAll('[data-m2m-option]'));
      var page = 1;
      var pageSize = parseInt(picker.getAttribute('data-page-size') || '12', 10);

      function labelFor(option) {
        return (option.getAttribute('data-label') || option.textContent || '').trim();
      }

      function checkedOptions() {
        return options.filter(function(option) {
          var cb = option.querySelector('input[type=checkbox]');
          return cb && cb.checked;
        });
      }

      function renderSelected() {
        if (!selected) return;
        selected.innerHTML = '';
        var checked = checkedOptions();
        if (count) count.textContent = checked.length + ' selected';
        if (selectedEmpty) selectedEmpty.classList.toggle('hidden', checked.length > 0);
        checked.slice(0, 8).forEach(function(option) {
          var cb = option.querySelector('input[type=checkbox]');
          var chip = document.createElement('button');
          chip.type = 'button';
          chip.className = 'inline-flex items-center gap-xs rounded-full border border-primary/25 bg-primary-container px-sm py-xs text-label-sm text-on-primary-container';
          var label = document.createElement('span');
          label.className = 'max-w-[160px] truncate';
          label.textContent = labelFor(option);
          var remove = document.createElement('span');
          remove.setAttribute('aria-hidden', 'true');
          remove.textContent = '×';
          chip.appendChild(label);
          chip.appendChild(remove);
          chip.addEventListener('click', function() {
            cb.checked = false;
            render();
          });
          selected.appendChild(chip);
        });
        if (checked.length > 8) {
          var more = document.createElement('span');
          more.className = 'text-label-sm text-outline px-xs py-xs';
          more.textContent = '+' + (checked.length - 8) + ' more';
          selected.appendChild(more);
        }
      }

      function render() {
        var q = search ? search.value.trim().toLowerCase() : '';
        var matches = options.filter(function(option) {
          return !q || labelFor(option).toLowerCase().indexOf(q) !== -1;
        });
        var pages = Math.max(1, Math.ceil(matches.length / pageSize));
        if (page > pages) page = pages;
        var start = (page - 1) * pageSize;
        var visible = new Set(matches.slice(start, start + pageSize));
        options.forEach(function(option) {
          option.classList.toggle('hidden', !visible.has(option));
        });
        if (empty) empty.classList.toggle('hidden', matches.length > 0);
        if (pageLabel) pageLabel.textContent = 'Page ' + page + ' of ' + pages;
        if (prev) prev.disabled = page <= 1;
        if (next) next.disabled = page >= pages;
        renderSelected();
      }

      if (search) {
        search.addEventListener('input', function() {
          page = 1;
          render();
        });
      }
      if (prev) prev.addEventListener('click', function() { page = Math.max(1, page - 1); render(); });
      if (next) next.addEventListener('click', function() { page = page + 1; render(); });
      options.forEach(function(option) {
        var cb = option.querySelector('input[type=checkbox]');
        if (cb) cb.addEventListener('change', render);
      });
      render();
    });
  }
  umbral.initM2MPickers = initM2MPickers;
  initM2MPickers();
  document.body.addEventListener('htmx:afterSwap', function() { initM2MPickers(); });
})();
(function() {
  // ----- Rich field-editor widgets (features.md #4) -----
  // #[umbral(widget = "...")] renders a <textarea data-widget> in the
  // form (see _macros/field_editor.html). Here we progressively enhance
  // each into a real editor:
  //   - "markdown" -> EasyMDE (toolbar + live side-by-side preview).
  //                   Render the stored value with `{{ value | markdown }}`.
  //   - "rte"      -> Quill (snow theme); the editor edits a div, we
  //                   sync its HTML back into the hidden <textarea> so
  //                   the form posts it. Render with `{{ value | sanitize }}`.
  //   - "code"     -> CodeMirror (JSON syntax + line numbers) for JSON /
  //                   structured text on a String / Json column.
  // Previews/loads are SANDBOXED: anything rendered into EasyMDE's
  // preview pane, or loaded into Quill, passes through DOMPurify first,
  // so authored content can't execute script in the admin origin.
  // Libraries LAZY-load from CDN only when a matching textarea is on the
  // page, so list/dashboard pages stay light. With no JS (or a CDN
  // failure) every field degrades to a plain, usable textarea — the
  // stored value is markdown / HTML / JSON text either way.
  window.umbral = window.umbral || {};

  var MD_CSS = 'https://unpkg.com/easymde@2.18.0/dist/easymde.min.css';
  var MD_JS  = 'https://unpkg.com/easymde@2.18.0/dist/easymde.min.js';
  var RTE_CSS = 'https://cdn.jsdelivr.net/npm/quill@2.0.3/dist/quill.snow.css';
  var RTE_JS  = 'https://cdn.jsdelivr.net/npm/quill@2.0.3/dist/quill.js';
  // DOMPurify sandboxes the editor previews: EasyMDE renders markdown
  // with `marked` (no sanitize) and Quill loads existing content via
  // `dangerouslyPasteHTML` — both would otherwise let authored content
  // execute <script>/onerror in the admin's own origin (real risk when
  // an admin previews a moderation-queue submission). Loaded alongside
  // each editor; the server-side `| markdown` / `| sanitize` filters are
  // the matching display-side layer (defense in depth).
  var PURIFY_JS = 'https://cdn.jsdelivr.net/npm/dompurify@3.1.6/dist/purify.min.js';
  // CodeMirror powers the `code` widget (JSON + structured text):
  // highlighting + line numbers. The JSON `mode` script depends on the
  // core being loaded first (see the load sequence in initWidgetEditors).
  var CM_CSS  = 'https://cdn.jsdelivr.net/npm/codemirror@5.65.16/lib/codemirror.min.css';
  var CM_JS   = 'https://cdn.jsdelivr.net/npm/codemirror@5.65.16/lib/codemirror.min.js';
  var CM_MODE = 'https://cdn.jsdelivr.net/npm/codemirror@5.65.16/mode/javascript/javascript.min.js';

  // Sanitize HTML before it lands in a preview pane. Uses DOMPurify when
  // present; if it somehow isn't loaded yet, fail CLOSED (drop all tags)
  // rather than render untrusted HTML.
  function previewClean(html) {
    if (window.DOMPurify) return window.DOMPurify.sanitize(html);
    var d = document.createElement('div');
    d.textContent = html;
    return d.innerHTML;
  }

  // CDN loader — inject each asset once; resolve the script's promise
  // when it's ready so multiple textareas share one load.
  var assets = {};
  function loadCss(url) {
    if (assets[url]) return;
    assets[url] = true;
    var l = document.createElement('link');
    l.rel = 'stylesheet';
    l.href = url;
    document.head.appendChild(l);
  }
  function loadScript(url) {
    if (assets[url]) return assets[url];
    assets[url] = new Promise(function(resolve, reject) {
      var s = document.createElement('script');
      s.src = url;
      s.async = true;
      s.onload = function() { resolve(); };
      s.onerror = function() { reject(new Error('umbral: failed to load ' + url)); };
      document.head.appendChild(s);
    });
    return assets[url];
  }

  // Claim every not-yet-mounted textarea for `selector` synchronously
  // (mark before the async load) so overlapping scans can't double-mount.
  function claim(root, selector) {
    var out = [];
    var nodes = root.querySelectorAll('textarea[data-widget="' + selector + '"]:not([data-widget-mounted])');
    for (var i = 0; i < nodes.length; i++) {
      nodes[i].setAttribute('data-widget-mounted', '1');
      out.push(nodes[i]);
    }
    return out;
  }

  // Registry of mounted editor instances keyed by the backing textarea
  // element. Used by the per-form submit flush below so every editor on
  // the form is guaranteed to have written its content back before HTMX
  // serialises the fields. (gaps2 #41)
  var _mountedEditors = [];

  // Flush all editors whose backing textarea lives inside `form` into
  // their textarea.value immediately before the form is serialised.
  // Registered once per form the first time any editor mounts onto it.
  var _flushRegisteredForms = typeof WeakSet !== 'undefined' ? new WeakSet() : null;
  function registerSubmitFlush(form) {
    if (!form) return;
    // WeakSet is available in every browser that also has EasyMDE/Quill/CM;
    // fall back to a data attribute on the form element for older envs.
    var alreadyRegistered = _flushRegisteredForms
      ? _flushRegisteredForms.has(form)
      : form.hasAttribute('data-umbral-flush-registered');
    if (alreadyRegistered) return;
    if (_flushRegisteredForms) _flushRegisteredForms.add(form);
    else form.setAttribute('data-umbral-flush-registered', '1');

    // htmx:beforeRequest fires synchronously before HTMX serialises the
    // form — use it so the flush runs even when the submit event fires
    // after htmx has already captured field values (a known edge-case in
    // some htmx versions when hx-boost is active on an ancestor).
    form.addEventListener('htmx:beforeRequest', flushEditorsOnForm);
    // Retain the native submit handler as a belt-and-suspenders guarantee
    // for any non-HTMX form posts.
    form.addEventListener('submit', flushEditorsOnForm);
  }

  function flushEditorsOnForm(event) {
    var form = event.currentTarget || event.target;
    _mountedEditors.forEach(function(entry) {
      try {
        // Only flush editors whose textarea is inside this specific form.
        if (form.contains(entry.ta)) entry.flush();
      } catch (e) {
        if (window.console) console.error('umbral: editor flush failed', e);
      }
    });
  }

  function mountMarkdown(ta) {
    var mde = new EasyMDE({
      element: ta,
      spellChecker: false,
      status: false,
      minHeight: '220px',
      autoDownloadFontAwesome: true,
      // Sandbox the live preview: every rendered-HTML chunk EasyMDE is
      // about to inject goes through DOMPurify first.
      renderingConfig: { sanitizerFunction: previewClean },
      // gaps2 #36: paste / drop / select an image and upload it to the
      // admin's staff-gated media endpoint, then insert the returned URL
      // as markdown. Degrades gracefully — when no storage backend is
      // installed the route returns an error and EasyMDE shows it.
      uploadImage: true,
      imageUploadFunction: function(file, onSuccess, onError) {
        var fd = new FormData();
        fd.append('image', file, file.name || 'upload.png');
        // Carry the CSRF token the same way the admin's other raw fetch()
        // writes do: read the (deliberately non-HttpOnly) cookie. Don't set
        // Content-Type — the browser sets the multipart boundary itself.
        var m = document.cookie.match(/(?:^|;\s*)umbral_csrf_token=([^;]*)/);
        var headers = m ? { 'X-CSRF-Token': decodeURIComponent(m[1]) } : {};
        var base = (typeof umbralAdminBase !== 'undefined') ? umbralAdminBase : '/admin';
        fetch(base + '/upload-image', {
          method: 'POST',
          headers: headers,
          body: fd,
          credentials: 'same-origin'
        }).then(function(resp) {
          return resp.json().then(function(data) {
            if (resp.ok && data && data.url) {
              onSuccess(data.url);
            } else {
              onError((data && data.error) || ('upload failed (' + resp.status + ')'));
            }
          });
        }).catch(function(err) {
          onError('upload failed: ' + err);
        });
      },
      toolbar: ['bold', 'italic', 'heading', '|', 'quote', 'unordered-list',
                'ordered-list', '|', 'link', 'image', 'code', 'table', '|',
                'preview', 'side-by-side', 'guide']
    });
    // EasyMDE constructed with `element: ta` wraps that textarea and
    // keeps its CodeMirror content in sync with ta.value on `cm.save()`.
    // We push a continuous sync on every editor change so the textarea
    // value is always current even if the submit flush somehow doesn't
    // run (e.g. a programmatic HTMX trigger that skips the submit event).
    mde.codemirror.on('change', function() { mde.codemirror.save(); });
    var flush = function() { mde.codemirror.save(); };
    _mountedEditors.push({ ta: ta, flush: flush });
    registerSubmitFlush(ta.closest('form'));
  }

  function mountRte(ta) {
    ta.style.display = 'none';
    var wrap = document.createElement('div');
    wrap.className = 'umbral-rte';
    var host = document.createElement('div');
    wrap.appendChild(host);
    ta.parentNode.insertBefore(wrap, ta.nextSibling);

    var quill = new Quill(host, {
      theme: 'snow',
      modules: {
        toolbar: [
          ['bold', 'italic', 'underline', 'strike'],
          ['blockquote', 'code-block'],
          [{ header: [1, 2, 3, false] }],
          [{ list: 'ordered' }, { list: 'bullet' }],
          ['link'],
          ['clean']
        ]
      }
    });
    // Sanitize the stored HTML before loading it into the editor —
    // `dangerouslyPasteHTML` would otherwise run any injected markup.
    if (ta.value) quill.clipboard.dangerouslyPasteHTML(previewClean(ta.value));
    function sync() {
      // Quill's "empty" sentinel is <p><br></p>; store '' so a blank
      // RTE doesn't trip a NOT-NULL / required check with junk markup.
      var html = quill.root.innerHTML;
      ta.value = (html === '<p><br></p>') ? '' : html;
    }
    // Sync on every keystroke/paste so ta.value is always current.
    quill.on('text-change', sync);
    _mountedEditors.push({ ta: ta, flush: sync });
    registerSubmitFlush(ta.closest('form'));
  }

  function mountCode(ta) {
    var cm = CodeMirror.fromTextArea(ta, {
      mode: { name: 'javascript', json: true },
      lineNumbers: true,
      tabSize: 2,
      lineWrapping: true,
      viewportMargin: Infinity
    });
    cm.getWrapperElement().classList.add('umbral-code');
    // Sync on every keystroke so ta.value is always current.
    cm.on('change', function() { cm.save(); });
    var flush = function() { cm.save(); };
    _mountedEditors.push({ ta: ta, flush: flush });
    registerSubmitFlush(ta.closest('form'));
  }

  function mountAll(list, fn, label) {
    list.forEach(function(ta) {
      try {
        fn(ta);
      } catch (e) {
        // Editor mount failed — un-hide the textarea so the field is
        // still editable, and log loudly. Never leave a dead input.
        ta.style.display = '';
        if (window.console) console.error('umbral: ' + label + ' editor mount failed', e);
      }
    });
  }

  function unhide(list) {
    list.forEach(function(t) { t.style.display = ''; });
  }

  function initWidgetEditors(root) {
    root = root || document;
    var mds = claim(root, 'markdown');
    var rtes = claim(root, 'rte');
    var codes = claim(root, 'code');
    if (mds.length) {
      loadCss(MD_CSS);
      // DOMPurify must be present before the preview renders.
      Promise.all([loadScript(PURIFY_JS), loadScript(MD_JS)])
        .then(function() { mountAll(mds, mountMarkdown, 'markdown'); })
        .catch(function(e) { unhide(mds); if (window.console) console.error(e); });
    }
    if (rtes.length) {
      loadCss(RTE_CSS);
      Promise.all([loadScript(PURIFY_JS), loadScript(RTE_JS)])
        .then(function() { mountAll(rtes, mountRte, 'rte'); })
        .catch(function(e) { unhide(rtes); if (window.console) console.error(e); });
    }
    if (codes.length) {
      loadCss(CM_CSS);
      // The JSON mode script extends the already-loaded core, so load
      // core first, then the mode, then mount.
      loadScript(CM_JS)
        .then(function() { return loadScript(CM_MODE); })
        .then(function() { mountAll(codes, mountCode, 'code'); })
        .catch(function(e) { unhide(codes); if (window.console) console.error(e); });
    }
  }

  umbral.initWidgetEditors = initWidgetEditors;
  document.addEventListener('DOMContentLoaded', function() { initWidgetEditors(document); });
  // Forms arrive via htmx (changelist actions, inline edit) and via the
  // sheet stack's innerHTML injection — cover both. The mounted-marker
  // makes re-scans idempotent.
  document.body.addEventListener('htmx:afterSwap', function(e) { initWidgetEditors(e.target); });
})();
(function() {
  // Sheet stack state machine.
  window.umbral = window.umbral || {};
  var stack = [];

  umbral.openSheet = function(html) {
    var slot = document.getElementById('umbral-sheet-slot');
    if (!slot) return;
    stack.push(slot.innerHTML);
    slot.innerHTML = html;
    document.body.classList.add('overflow-hidden');
    if (window.lucide) lucide.createIcons({ el: slot });
    // The sheet form is injected via innerHTML (not an htmx swap), so
    // mount the markdown / RTE editors on it explicitly.
    if (umbral.initWidgetEditors) umbral.initWidgetEditors(slot);
    umbral._applyStackOffsets();
  };

  umbral.popSheet = function() {
    var slot = document.getElementById('umbral-sheet-slot');
    if (!slot) return;
    if (stack.length > 0) {
      slot.innerHTML = stack.pop();
      if (window.lucide) lucide.createIcons({ el: slot });
      if (umbral.initWidgetEditors) umbral.initWidgetEditors(slot);
      umbral._applyStackOffsets();
    } else {
      umbral.closeSheet();
    }
  };

  umbral.closeSheet = function() {
    var slot = document.getElementById('umbral-sheet-slot');
    if (slot) slot.innerHTML = '';
    stack = [];
    document.body.classList.remove('overflow-hidden');
  };

  // HX-Trigger handlers — the update handler emits these after a
  // successful Save (closes the sheet + refreshes the table) so the
  // changelist updates without a full page nav.
  document.body.addEventListener('closeSheet', function() {
    umbral.closeSheet();
  });
  document.body.addEventListener('refreshTable', function() {
    // When we're on a changelist page (#table-body present), re-fetch
    // the rows fragment with the current URL state. The URL bar reflects
    // any active search / sort / filter / pagination because the
    // changelist controls push their state with `hx-push-url="true"`,
    // so reading window.location is the freshest signal — fresher than
    // the search input's `hx-get` attribute (which stays at its initial
    // render value) or a stashed data-* on the tbody.
    //
    // Off the changelist (detail page, dashboard, etc.) there's no
    // table to swap — fall back to a full reload so the page picks up
    // the new values.
    var tbody = document.getElementById('table-body');
    if (!tbody) {
      window.location.reload();
      return;
    }
    // Prefer the authoritative rows endpoint the server stamped onto the
    // tbody (`data-rows-url`) — it's rendered with the real admin base +
    // table, so it's correct regardless of base path, trailing slash, or
    // any locale/prefix segment. Only the query string (search / sort /
    // filter / pagination) is read from window.location, which is the
    // fresh signal because the changelist controls push their state with
    // `hx-push-url="true"`. Fall back to the old pathname synthesis when
    // the attribute is absent (e.g. a custom template predating this).
    var base = tbody.getAttribute('data-rows-url');
    if (!base) {
      base = window.location.pathname.replace(/\/+$/, '') + '/rows';
    }
    var url = base + window.location.search;
    htmx.ajax('GET', url, { target: '#table-body', swap: 'innerHTML' });
  });

  umbral._applyStackOffsets = function() {
    var slot = document.getElementById('umbral-sheet-slot');
    if (!slot) return;
    var panels = slot.querySelectorAll('#umbral-sheet-panel');
    panels.forEach(function(panel, i) {
      panel.style.transform = 'translateX(-' + (i * 40) + 'px)';
    });
  };

  umbral.openNestedSheet = function(table) {
    htmx.ajax('GET', umbralAdminBase + '/' + table + '/new-sheet', {
      handler: function(elt, info) {
        umbral.openSheet(info.xhr.responseText);
      }
    });
  };

  umbral.closeDialog = function() {
    var slot = document.getElementById('umbral-dialog-slot');
    if (slot) slot.innerHTML = '';
  };

  // ---- Change password dialog (gaps2 #3) ----
  //
  // Pre-fix this built ~25 lines of dialog HTML via string concat
  // inside JS. Designers couldn't edit the markup without touching
  // a script tag; Tailwind's content scanner couldn't find every
  // class used in the dialog without scanning the JS literally;
  // every Tailwind class lived twice (here AND in any template that
  // wanted the same styling). The dialog now lives as a
  // `<template id="umbral-change-password-dialog-template">` block
  // higher up in this file. The opener clones the template content
  // and patches only the form's `hx-post` URL — that's the only
  // call-site-varying piece.
  umbral._openChangePasswordDialog = function(table, id) {
    var slot = document.getElementById('umbral-dialog-slot');
    var tpl = document.getElementById('umbral-change-password-dialog-template');
    if (!slot || !tpl || !tpl.content) return;
    var node = tpl.content.cloneNode(true);
    var form = node.querySelector('[data-change-pw-form]');
    if (form) {
      form.setAttribute('hx-post', umbralAdminBase + '/' + table + '/' + id + '/change-password');
    }
    slot.innerHTML = '';
    slot.appendChild(node);
    if (window.lucide) lucide.createIcons({ el: slot });
    htmx.process(slot);
  };

  // Escape: close top sheet only.
  document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
      // Close palette first if open.
      var palSlot = document.getElementById('umbral-palette-slot');
      if (palSlot && palSlot.innerHTML.trim()) { umbral.closePalette && umbral.closePalette(); e.preventDefault(); return; }
      var slot = document.getElementById('umbral-sheet-slot');
      if (slot && slot.innerHTML.trim()) { umbral.popSheet(); e.preventDefault(); }
    }
    // ⌘K / Ctrl-K: open command palette.
    if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
      e.preventDefault();
      var palSlot2 = document.getElementById('umbral-palette-slot');
      if (palSlot2 && palSlot2.innerHTML.trim()) {
        umbral.closePalette && umbral.closePalette();
      } else {
        htmx.ajax('GET', umbralAdminBase + '/api/palette', {
          target: '#umbral-palette-slot',
          swap: 'innerHTML'
        });
      }
    }
  });
})();

/* =====================================================================
 * Dashboard widget reordering (features.md #8)
 * =====================================================================
 * Drag a widget onto another and the grid reorders; the new order is PUT to
 * /api/dashboard/layout, which the server now READS on render (view.rs
 * apply_saved_layout). Before this, the layout endpoint existed and stored a
 * layout that nothing ever applied — dragging appeared to work and silently
 * reset on the next page load.
 *
 * Native HTML5 drag-and-drop: no new dependency for a feature this small.
 * The whole cell is the handle, so there is nothing extra to aim at.
 *
 * The saved layout is a PREFERENCE, never a permission — the server ignores
 * entries for widgets the user may not see, so a hand-edited layout cannot
 * conjure a forbidden widget.
 */
(function () {
  'use strict';

  var dragging = null;

  function cells(grid) {
    return Array.prototype.slice.call(
      grid.querySelectorAll('[data-widget-key]')
    );
  }

  /** Collect every grid on the page into one ordered layout array. */
  function currentLayout() {
    var out = [];
    var grids = document.querySelectorAll('[data-widget-grid]');
    Array.prototype.forEach.call(grids, function (grid) {
      cells(grid).forEach(function (cell) {
        out.push({
          key: cell.getAttribute('data-widget-key'),
          span: {
            cols: parseInt(cell.getAttribute('data-span-cols'), 10) || 3,
            rows: parseInt(cell.getAttribute('data-span-rows'), 10) || 1
          }
        });
      });
    });
    return out;
  }

  function saveLayout() {
    var csrf = (window.umbral && window.umbral.csrfHeaders)
      ? window.umbral.csrfHeaders()
      : {};
    fetch(umbralAdminBase + '/api/dashboard/layout', {
      method: 'PUT',
      credentials: 'same-origin',
      headers: Object.assign({ 'Content-Type': 'application/json' }, csrf),
      body: JSON.stringify(currentLayout())
    }).catch(function (err) {
      // A failed save must not look like a successful one: put the widgets back
      // where the server still thinks they are, rather than leaving the user
      // with an arrangement that evaporates on reload.
      console.error('umbral-admin: could not save dashboard layout', err);
      window.location.reload();
    });
  }

  function bindGrid(grid) {
    if (grid.getAttribute('data-dnd-bound') === '1') { return; }
    grid.setAttribute('data-dnd-bound', '1');

    cells(grid).forEach(function (cell) {
      cell.setAttribute('draggable', 'true');
      cell.style.cursor = 'grab';

      cell.addEventListener('dragstart', function (e) {
        dragging = cell;
        cell.style.opacity = '0.4';
        e.dataTransfer.effectAllowed = 'move';
        // Firefox refuses to start a drag without payload.
        try { e.dataTransfer.setData('text/plain', cell.getAttribute('data-widget-key')); } catch (_) {}
      });

      cell.addEventListener('dragend', function () {
        cell.style.opacity = '';
        dragging = null;
        saveLayout();
      });

      cell.addEventListener('dragover', function (e) {
        if (!dragging || dragging === cell || dragging.parentNode !== cell.parentNode) { return; }
        e.preventDefault();
        e.dataTransfer.dropEffect = 'move';
        // Insert before or after depending on which half we're over, so the
        // drop lands where the pointer is rather than always shifting left.
        var box = cell.getBoundingClientRect();
        var after = (e.clientX - box.left) > box.width / 2;
        cell.parentNode.insertBefore(dragging, after ? cell.nextSibling : cell);
      });

      cell.addEventListener('drop', function (e) { e.preventDefault(); });
    });
  }

  function bindAll() {
    var grids = document.querySelectorAll('[data-widget-grid]');
    Array.prototype.forEach.call(grids, bindGrid);
  }

  document.addEventListener('DOMContentLoaded', bindAll);
  // Widget cells self-load their bodies over htmx; re-bind after a swap so a
  // freshly swapped grid is still draggable.
  document.body && document.body.addEventListener('htmx:afterSwap', bindAll);
})();