laterite-admin 0.9.21

Laterite CMF admin surface: the Axum router, session middleware, and login shell
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
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
// Laterite admin: shared behaviour and the widget (island) lifecycle.

function latModeGlyph(m) {
  return m === 'light' ? '☀' : m === 'dark' ? '☾' : '◐';
}
// The admin's own control over the shared mechanism: `laterite_core::theme`
// owns storing and applying a mode, this only decides what the button does next
// and which glyph it shows. A site builds its own control the same way.
function latCycleMode() {
  var o = latMode();
  var n = o === 'light' ? 'dark' : o === 'dark' ? 'auto' : 'light';
  latSetMode(n);
  var e = document.getElementById('lat-mode-ico');
  if (e) e.textContent = latModeGlyph(n);
}

// The drawer: opened by the burger and closed by it, the backdrop or Escape.
// Focus moves to the first link when it opens and back to the burger when it
// closes, and Tab stays inside while it is open.
var latDrawerOpener = null;
function latToggleMenu() {
  var m = document.getElementById('lat-menu');
  if (!m) return;
  var open = !m.classList.contains('is-open');
  m.classList.toggle('is-open', open);
  var burger = document.querySelector('[data-lat-drawer][aria-controls="lat-menu"]');
  if (burger) burger.setAttribute('aria-expanded', open ? 'true' : 'false');
  if (open) {
    latDrawerOpener = document.activeElement;
    var first = m.querySelector('a, button');
    if (first) first.focus();
  } else if (latDrawerOpener && latDrawerOpener.focus) {
    latDrawerOpener.focus();
    latDrawerOpener = null;
  }
}
document.addEventListener('keydown', function (e) {
  var m = document.getElementById('lat-menu');
  if (!m || !m.classList.contains('is-open')) return;
  if (e.key === 'Escape') { e.preventDefault(); latToggleMenu(); return; }
  if (e.key !== 'Tab') return;
  var items = m.querySelectorAll('a, button');
  if (!items.length) return;
  var first = items[0], last = items[items.length - 1];
  if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
  else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
});
// The chrome's own controls bind here, never through an inline handler: the
// content security policy allows no inline script.
document.addEventListener('click', function (e) {
  if (!e.target.closest) return;
  var dismiss = e.target.closest('[data-lat-dismiss]');
  if (dismiss) { latDismissFlash(dismiss); return; }
  if (e.target.closest('[data-lat-drawer]')) { latToggleMenu(); return; }
  if (e.target.closest('[data-lat-mode]')) { latCycleMode(); }
});
function flashText(toast) {
  var label = toast.querySelector('.lat-flash__text');
  return label ? label.textContent : '';
}
function latDismissFlash(btn) {
  var t = btn.closest('.lat-flash');
  if (!t) return;
  window.lat.emit(t, 'flash:dismissed', { text: flashText(t) });
  t.classList.add('is-leaving');
  setTimeout(function () { t.remove(); }, 180);
}

// htmx ignores a non-2xx response by default, so a form that failed validation
// would post and appear to do nothing. A 422 is our "here is the form again,
// with errors": let it swap, into the element that asked.
document.addEventListener('htmx:beforeSwap', function (e) {
  if (e.detail.xhr.status === 422) {
    e.detail.shouldSwap = true;
    e.detail.isError = false;
  }
});

// Widget (island) registry: register an initialiser by name; every element with
// a matching data-lat-widget is initialised exactly once, on first load and
// after an htmx swap (swapped fragments carry their own widgets).
//
// Islands speak through DOM events named `lat:<component>:<event>`, bubbling
// from the island's root with a detail object, and an island may hand back a
// controller (its methods) from its initialiser. Both are public: `lat.on`
// listens, `lat.emit` announces, `lat.get` finds a controller.
(function () {
  var registry = {};
  var controllers = new WeakMap();
  var lat = (window.lat = window.lat || {});
  lat.widget = function (name, init) {
    registry[name] = init;
    scan(document);
  };
  // The controller the island at `el` (or around it) handed back when it
  // started, or undefined for one with none.
  lat.get = function (el) {
    var root = el && el.closest ? el.closest('[data-lat-widget]') : null;
    return root ? controllers.get(root) : undefined;
  };
  // Announces `lat:<name>` from `el`. Returns false when the event was
  // cancelable and a listener called preventDefault(), which is how a
  // `before-` event stops the action it announces.
  lat.emit = function (el, name, detail, cancelable) {
    return (el || document).dispatchEvent(new CustomEvent('lat:' + name, {
      bubbles: true,
      cancelable: !!cancelable,
      detail: detail || {}
    }));
  };
  // Listens for `lat:<name>` anywhere on the page, including content that
  // arrives with a swap. The handler gets the detail, then the event. Returns
  // the function that stops listening.
  lat.on = function (name, handler) {
    function listener(e) { handler(e.detail, e); }
    document.addEventListener('lat:' + name, listener);
    return function () { document.removeEventListener('lat:' + name, listener); };
  };
  lat.assets = {
    // Idempotently load a stylesheet or script (for fragments whose assets are
    // not already on the page).
    ensure: function (url) {
      if (document.querySelector('[data-lat-asset="' + url + '"]')) return;
      var el;
      if (/\.css(\?|$)/.test(url)) {
        el = document.createElement('link');
        el.rel = 'stylesheet';
        el.href = url;
      } else {
        el = document.createElement('script');
        el.src = url;
        el.defer = true;
      }
      el.setAttribute('data-lat-asset', url);
      document.head.appendChild(el);
    }
  };
  var unstarted = '[data-lat-widget]:not([data-lat-ready])';
  function start(el) {
    var init = registry[el.getAttribute('data-lat-widget')];
    if (!init) return;
    el.setAttribute('data-lat-ready', '1');
    var controller = init(el);
    if (!controller) return;
    controllers.set(el, controller);
    // An island that builds markup around its element names that markup as
    // `root`, so `lat.get` finds it from inside the markup too.
    if (controller.root && controller.root !== el) {
      controller.root.setAttribute('data-lat-widget', el.getAttribute('data-lat-widget'));
      controller.root.setAttribute('data-lat-ready', '1');
      controllers.set(controller.root, controller);
    }
  }
  // Starts every island in `root` that has not started, `root` included: a
  // swapped-in fragment is often the island itself.
  function scan(root) {
    var scope = root && root.querySelectorAll ? root : document;
    if (scope.matches && scope.matches(unstarted)) start(scope);
    scope.querySelectorAll(unstarted).forEach(start);
  }
  lat.scan = scan;
  document.addEventListener('DOMContentLoaded', function () {
    scan(document);
    var e = document.getElementById('lat-mode-ico');
    if (e) e.textContent = latModeGlyph(latMode());
  });
  document.addEventListener('htmx:load', function (ev) { scan(ev.target); });
})();

// Raises a toast from script, matching the server-rendered flash markup so both
// look and dismiss the same.
window.lat.flash = function (text, level) {
  var box = document.querySelector('.lat-flashes');
  if (!box) {
    box = document.createElement('div');
    box.className = 'lat-flashes';
    box.setAttribute('role', 'status');
    box.setAttribute('aria-live', 'polite');
    document.body.insertBefore(box, document.body.firstChild);
  }
  var toast = document.createElement('div');
  toast.className = 'lat-flash is-' + (level || 'error');
  toast.setAttribute('data-lat-widget', 'flash');
  var label = document.createElement('span');
  label.className = 'lat-flash__text';
  label.textContent = text;
  var close = document.createElement('button');
  close.type = 'button';
  close.className = 'lat-flash__close';
  close.innerHTML = '&times;';
  close.addEventListener('click', function () { latDismissFlash(close); });
  toast.appendChild(label);
  toast.appendChild(close);
  box.appendChild(toast);
  // Started as the island a server-rendered message is, so it announces itself
  // and leaves on the same terms.
  window.lat.scan(toast);
};

// A response htmx will not swap is otherwise swallowed, so a 500 or a dropped
// connection leaves the click with no outcome. The 422 above marks itself
// not-an-error, so a form's own validation errors never reach this.
function latRequestFailed() {
  window.lat.flash(document.body.getAttribute('data-lat-request-error') || 'Request failed.', 'error');
}
document.addEventListener('htmx:responseError', latRequestFailed);
document.addEventListener('htmx:sendError', latRequestFailed);

// Top progress bar: shown while any htmx request is in flight. The bar creeps
// toward the right while waiting, since the real duration is unknown.
(function () {
  var inflight = 0;
  var bar = null;
  var timer = null;
  function element() {
    if (!bar) {
      bar = document.createElement('div');
      bar.className = 'lat-progress';
      // A decoration for sighted readers; the busy state is announced on the
      // document while a request is in flight.
      bar.setAttribute('aria-hidden', 'true');
      document.body.appendChild(bar);
    }
    return bar;
  }
  document.addEventListener('htmx:beforeRequest', function () {
    inflight++;
    clearTimeout(timer);
    var b = element();
    b.classList.remove('is-done');
    b.classList.add('is-active');
    document.body.setAttribute('aria-busy', 'true');
  });
  document.addEventListener('htmx:afterRequest', function () {
    inflight = Math.max(0, inflight - 1);
    if (inflight > 0) return;
    var b = element();
    b.classList.add('is-done');
    document.body.removeAttribute('aria-busy');
    timer = setTimeout(function () { b.classList.remove('is-active', 'is-done'); }, 220);
  });
})();

// Confirm dialog: a control carrying data-lat-confirm asks before it acts. A
// modal rather than window.confirm, because a native dialog blocks the page and
// cannot be styled or localized with the rest of the admin.
(function () {
  var pending = null;
  // The callback of a question asked from script, while it is open.
  var asked = null;

  function box() {
    var el = document.getElementById('lat-confirm');
    if (el) return el;
    el = document.createElement('div');
    el.id = 'lat-confirm';
    el.className = 'lat-modal';
    el.setAttribute('role', 'dialog');
    el.setAttribute('aria-modal', 'true');
    el.innerHTML =
      '<div class="lat-modal__backdrop" data-lat-close></div>' +
      '<div class="lat-modal__panel">' +
      '<p class="lat-modal__text"></p>' +
      '<div class="lat-modal__actions">' +
      '<button type="button" class="lat-btn lat-btn--ghost" data-lat-close></button>' +
      '<button type="button" class="lat-btn lat-btn--danger" data-lat-go></button>' +
      '</div></div>';
    document.body.appendChild(el);
    el.addEventListener('click', function (e) {
      if (e.target.hasAttribute('data-lat-close')) close();
      if (e.target.hasAttribute('data-lat-go')) go();
    });
    return el;
  }

  function close() {
    if (answer(false)) return;
    if (pending) window.lat.emit(pending, 'confirm:cancelled', {});
    hide();
  }

  function hide() {
    pending = null;
    var el = document.getElementById('lat-confirm');
    if (el) el.classList.remove('is-open');
  }

  // Asks from script, with no control behind the question: `done` hears true
  // or false. `labels.go` and `labels.cancel` name the two buttons, and
  // `labels.focus: 'cancel'` puts the cursor on the one that changes nothing.
  window.lat.confirm = function (text, labels, done) {
    labels = labels || {};
    asked = done;
    pending = null;
    var modal = box();
    modal.querySelector('.lat-modal__text').textContent = text;
    modal.querySelector('[data-lat-go]').textContent = labels.go || 'OK';
    modal.querySelector('[data-lat-close]:not(.lat-modal__backdrop)').textContent =
      labels.cancel || document.body.getAttribute('data-lat-cancel') || 'Cancel';
    modal.classList.add('is-open');
    modal.querySelector(
      labels.focus === 'cancel' ? '.lat-modal__actions [data-lat-close]' : '[data-lat-go]'
    ).focus();
    window.lat.emit(document, 'confirm:opened', { text: text });
  };

  function answer(yes) {
    var done = asked;
    asked = null;
    if (!done) return false;
    hide();
    window.lat.emit(document, yes ? 'confirm:confirmed' : 'confirm:cancelled', {});
    done(yes);
    return true;
  }

  function go() {
    if (answer(true)) return;
    var el = pending;
    hide();
    if (!el) return;
    window.lat.emit(el, 'confirm:confirmed', {});
    // Marked so the second pass through the handler lets it through.
    el.setAttribute('data-lat-confirmed', '1');
    el.click();
    el.removeAttribute('data-lat-confirmed');
  }

  document.addEventListener('keydown', function (e) {
    if (e.key === 'Escape') close();
  });

  // Capture phase, so the click never reaches htmx or the form until confirmed.
  document.addEventListener('click', function (e) {
    var el = e.target.closest ? e.target.closest('[data-lat-confirm]') : null;
    if (!el || el.hasAttribute('data-lat-confirmed')) return;
    e.preventDefault();
    e.stopPropagation();
    pending = el;
    var modal = box();
    modal.querySelector('.lat-modal__text').textContent = el.getAttribute('data-lat-confirm');
    modal.querySelector('[data-lat-go]').textContent = el.textContent.trim() || 'OK';
    modal.querySelector('[data-lat-close]:not(.lat-modal__backdrop)').textContent =
      document.body.getAttribute('data-lat-cancel') || 'Cancel';
    modal.classList.add('is-open');
    modal.querySelector('[data-lat-go]').focus();
    window.lat.emit(el, 'confirm:opened', { text: el.getAttribute('data-lat-confirm') });
  }, true);
})();

// Dialogs: a control carrying data-lat-dialog opens the <dialog> it names,
// one carrying data-lat-dialog-close closes the dialog it sits in, and a click
// on the backdrop closes too. Native, so Escape and focus containment need no
// code here. `data-lat-dialog-set="field=value"` fills a field before opening,
// so one dialog serves several openers (a New button per group).
(function () {
  document.addEventListener('click', function (e) {
    if (!e.target.closest) return;
    var opener = e.target.closest('[data-lat-dialog]');
    if (opener) {
      var dialog = document.getElementById(opener.getAttribute('data-lat-dialog'));
      if (!dialog || typeof dialog.showModal !== 'function') return;
      e.preventDefault();
      (opener.getAttribute('data-lat-dialog-set') || '').split(';').forEach(function (pair) {
        var at = pair.indexOf('=');
        if (at < 1) return;
        var field = dialog.querySelector('[name="' + pair.slice(0, at).trim() + '"]');
        if (field) field.value = pair.slice(at + 1).trim();
      });
      dialog.showModal();
      var first = dialog.querySelector('[autofocus], input:not([type=hidden]):not([readonly]), select, textarea');
      if (first) first.focus();
      window.lat.emit(dialog, 'dialog:opened', {});
      return;
    }
    var closer = e.target.closest('[data-lat-dialog-close]');
    if (closer) {
      var open = closer.closest('dialog');
      if (open) open.close();
      return;
    }
    // With no padding of its own, a click that lands on the dialog element
    // itself landed on the backdrop.
    if (e.target.matches && e.target.matches('dialog.lat-dialog')) e.target.close();
  });
})();

// The uploader: a drop zone over a file input. Given data-upload-url it sends
// each picked or dropped file itself, one request per file, with the request
// token first in the body as the upload guard requires and data-upload-fields
// ("folder=3") before the file; a row per file shows progress and the outcome,
// and the page reloads once every file is stored. Without the URL it is the
// styled field of an ordinary form: it names what was picked and the form
// submits as it always did.
window.lat.widget('upload', function (root) {
  var input = root.querySelector('input[type=file]');
  var list = root.querySelector('.lat-upload__list');
  var url = root.getAttribute('data-upload-url');
  var form = root.closest('form');
  if (!input || !list) return;
  var words = {
    uploading: root.getAttribute('data-lat-uploading') || 'Uploading',
    stored: root.getAttribute('data-lat-stored') || 'Stored',
    failed: root.getAttribute('data-lat-failed') || 'Could not be stored',
  };
  var pending = 0;
  var failures = 0;

  function size(n) {
    if (n < 1024) return n + ' B';
    if (n < 1048576) return (n / 1024).toFixed(0) + ' KB';
    return (n / 1048576).toFixed(1) + ' MB';
  }

  function row(file) {
    var li = document.createElement('li');
    li.className = 'lat-upload__item';
    li.innerHTML =
      '<span class="lat-upload__name"></span><span class="lat-upload__size"></span>' +
      (url ? '<span class="lat-upload__bar"><i></i></span><span class="lat-upload__status"></span>' : '');
    li.querySelector('.lat-upload__name').textContent = file.name;
    li.querySelector('.lat-upload__size').textContent = size(file.size);
    list.appendChild(li);
    return li;
  }

  function finish(li, ok, text) {
    li.classList.add(ok ? 'is-done' : 'is-failed');
    li.querySelector('.lat-upload__status').textContent = text;
    if (!ok) failures += 1;
    pending -= 1;
    window.lat.emit(root, ok ? 'upload:stored' : 'upload:failed', { name: li.querySelector('.lat-upload__name').textContent, reason: text });
    if (pending === 0) {
      window.lat.emit(root, 'upload:done', { failed: failures });
      if (failures === 0) setTimeout(function () { location.reload(); }, 350);
    }
  }

  // The ordinary path: the file in a multipart POST to the upload URL.
  function post(file, li, bar, status) {
    var body = new FormData();
    var token = form && form.querySelector('input[name="_csrf"]');
    if (token) body.append('_csrf', token.value);
    (root.getAttribute('data-upload-fields') || '').split(';').forEach(function (pair) {
      var at = pair.indexOf('=');
      if (at > 0) body.append(pair.slice(0, at).trim(), pair.slice(at + 1).trim());
    });
    body.append(input.name || 'file', file, file.name);
    var xhr = new XMLHttpRequest();
    xhr.upload.addEventListener('progress', function (e) {
      if (e.lengthComputable) bar.style.width = Math.round((e.loaded / e.total) * 100) + '%';
    });
    xhr.addEventListener('load', function () {
      var out = null;
      try { out = JSON.parse(xhr.responseText); } catch (e) { out = null; }
      var stored = out && out.stored && out.stored[0];
      var refused = out && out.refused && out.refused[0];
      if (xhr.status === 200 && stored) finish(li, true, words.stored);
      else finish(li, false, (refused && refused.reason) || words.failed);
    });
    xhr.addEventListener('error', function () { finish(li, false, words.failed); });
    xhr.open('POST', url);
    xhr.setRequestHeader('X-Requested-With', 'fetch');
    xhr.send(body);
  }

  // The direct path: the server hands out a PUT URL under a quarantine prefix,
  // the browser puts the bytes there with progress, and the server is told to
  // hash, promote and record them. A disk that cannot presign says so and the
  // file takes the ordinary path.
  function direct(file, li, bar, status, ask) {
    var token = form && form.querySelector('input[name="_csrf"]');
    var fields = {};
    (root.getAttribute('data-upload-fields') || '').split(';').forEach(function (pair) {
      var at = pair.indexOf('=');
      if (at > 0) fields[pair.slice(0, at).trim()] = pair.slice(at + 1).trim();
    });
    var start = new FormData();
    if (token) start.append('_csrf', token.value);
    start.append('name', file.name);
    start.append('content_type', file.type || 'application/octet-stream');
    start.append('size', String(file.size));
    fetch(ask, { method: 'POST', body: start, credentials: 'same-origin', headers: { 'X-Requested-With': 'fetch' } })
      .then(function (r) { return r.ok ? r.json() : { direct: false }; })
      .catch(function () { return { direct: false }; })
      .then(function (plan) {
        if (!plan || !plan.direct || !plan.url) { post(file, li, bar, status); return; }
        var xhr = new XMLHttpRequest();
        xhr.upload.addEventListener('progress', function (e) {
          if (e.lengthComputable) bar.style.width = Math.round((e.loaded / e.total) * 95) + '%';
        });
        xhr.addEventListener('load', function () {
          if (xhr.status < 200 || xhr.status >= 300) { finish(li, false, words.failed); return; }
          var done = new FormData();
          if (token) done.append('_csrf', token.value);
          done.append('path', plan.path);
          done.append('name', file.name);
          Object.keys(fields).forEach(function (k) { done.append(k, fields[k]); });
          fetch(ask + '/complete', { method: 'POST', body: done, credentials: 'same-origin', headers: { 'X-Requested-With': 'fetch' } })
            .then(function (r) { return r.json(); })
            .then(function (out) {
              var stored = out && out.stored && out.stored[0];
              var refused = out && out.refused && out.refused[0];
              if (stored) finish(li, true, words.stored);
              else finish(li, false, (refused && refused.reason) || words.failed);
            })
            .catch(function () { finish(li, false, words.failed); });
        });
        xhr.addEventListener('error', function () { finish(li, false, words.failed); });
        xhr.open('PUT', plan.url);
        Object.keys(plan.headers || {}).forEach(function (h) { xhr.setRequestHeader(h, plan.headers[h]); });
        xhr.send(file);
      });
  }

  function send(file, li) {
    var bar = li.querySelector('.lat-upload__bar i');
    var status = li.querySelector('.lat-upload__status');
    status.textContent = words.uploading;
    var ask = root.getAttribute('data-upload-direct');
    if (ask) direct(file, li, bar, status, ask); else post(file, li, bar, status);
  }

  function take(files) {
    var picked = Array.prototype.slice.call(files || []);
    if (!picked.length) return;
    if (!url) {
      list.innerHTML = '';
      picked.forEach(row);
      window.lat.emit(root, 'upload:picked', { count: picked.length });
      return;
    }
    if (!window.lat.emit(root, 'upload:before-send', { count: picked.length }, true)) return;
    picked.forEach(function (file) {
      pending += 1;
      send(file, row(file));
    });
  }

  if (url) {
    // The zone sends, so the form's own button and requirement step aside.
    input.required = false;
    var submit = form && form.querySelector('[data-upload-submit]');
    if (submit) submit.hidden = true;
  }
  input.addEventListener('change', function () {
    take(input.files);
    if (url) input.value = '';
  });
  ['dragenter', 'dragover'].forEach(function (name) {
    root.addEventListener(name, function (e) { e.preventDefault(); root.classList.add('is-dragging'); });
  });
  ['dragleave', 'drop'].forEach(function (name) {
    root.addEventListener(name, function (e) { e.preventDefault(); root.classList.remove('is-dragging'); });
  });
  root.addEventListener('drop', function (e) {
    var files = e.dataTransfer && e.dataTransfer.files;
    if (!files || !files.length) return;
    if (url) {
      take(files);
    } else {
      // Dropped into the field: the form submits them as if picked.
      try { input.files = files; } catch (err) { /* an older engine: pick instead */ }
      take(input.files);
    }
  });
  return { take: take };
});

// The media field: a hidden input of ids, tiles drawn from the resolve
// endpoint, and a picker dialog that loads the library's browser as a
// fragment. Folder links and the search inside the fragment refetch it; a
// tile click chooses (one file closes the dialog, several toggle and a
// footer button confirms). With no script the hidden input keeps its ids.
// The library picker: a dialog that browses the media library through the
// `/media/pick` fragments (folders, search, kind) and hands the chosen files
// to `onDone(items)`, each `{ id, name, kind, thumb, url, is_image }`. One
// click chooses in single mode; in multiple mode tiles toggle and "Use
// selected" finishes. Shared by the media field and the rich editor's image
// button, so there is one way to choose a file.
window.lat.mediaPicker = function (opts) {
  var multiple = !!opts.multiple;
  var words = {
    title: opts.words.title || 'Choose from the library',
    use: opts.words.use || 'Use selected',
    cancel: opts.words.cancel || document.body.getAttribute('data-lat-cancel') || 'Cancel'
  };
  var dialog = null;
  var chosen = [];

  function box() {
    if (dialog) return dialog;
    dialog = document.createElement('dialog');
    dialog.className = 'lat-dialog lat-dialog--pick';
    dialog.innerHTML =
      '<div class="lat-dialog__head"><h2></h2><button type="button" class="lat-dialog__close" data-lat-dialog-close aria-label="' + words.cancel + '">&times;</button></div>' +
      '<div class="lat-dialog__body lat-dialog__body--flush" data-pick-body></div>' +
      '<div class="lat-dialog__actions"><button type="button" class="lat-btn lat-btn--ghost" data-lat-dialog-close></button><button type="button" class="lat-btn lat-btn--primary" data-pick-use hidden></button></div>';
    dialog.querySelector('h2').textContent = words.title;
    dialog.querySelector('.lat-dialog__actions [data-lat-dialog-close]').textContent = words.cancel;
    var use = dialog.querySelector('[data-pick-use]');
    use.textContent = words.use;
    use.hidden = !multiple;
    use.addEventListener('click', function () { finish(chosen); });
    document.body.appendChild(dialog);
    dialog.addEventListener('click', function (e) {
      if (!e.target.closest) return;
      var go = e.target.closest('[data-pick-go]');
      if (go) { e.preventDefault(); show(go.getAttribute('href')); return; }
      var file = e.target.closest('[data-pick-file]');
      if (file) {
        var item = {
          id: file.getAttribute('data-id'),
          name: file.getAttribute('data-name'),
          kind: file.getAttribute('data-kind'),
          thumb: file.getAttribute('data-thumb'),
          url: file.getAttribute('data-url'),
          is_image: file.getAttribute('data-is-image') === '1',
        };
        if (!multiple) { finish([item]); return; }
        var on = file.getAttribute('aria-pressed') === 'true';
        file.setAttribute('aria-pressed', on ? 'false' : 'true');
        chosen = on ? chosen.filter(function (c) { return c.id !== item.id; }) : chosen.concat([item]);
      }
    });
    dialog.addEventListener('submit', function (e) {
      var form = e.target.closest ? e.target.closest('[data-pick-search]') : null;
      if (!form) return;
      e.preventDefault();
      var params = new URLSearchParams(new FormData(form));
      show(form.getAttribute('action') + '?' + params.toString());
    });
    return dialog;
  }
  function show(url) {
    var body = box().querySelector('[data-pick-body]');
    fetch(url, { credentials: 'same-origin', headers: { 'X-Requested-With': 'fetch' } })
      .then(function (r) { return r.text(); })
      .then(function (html) {
        body.innerHTML = html;
        // Tiles already chosen stay marked across folder changes.
        chosen.forEach(function (c) {
          var el = body.querySelector('[data-pick-file][data-id="' + c.id + '"]');
          if (el) el.setAttribute('aria-pressed', 'true');
        });
        if (!dialog.open) dialog.showModal();
      });
  }
  function finish(items) {
    if (items.length) opts.onDone(items);
    chosen = [];
    if (dialog) dialog.close();
  }
  return {
    open: function (url) { chosen = []; show(url); },
    close: function () { if (dialog) dialog.close(); }
  };
};

window.lat.widget('media-field', function (root) {
  var input = root.querySelector('[data-mediafield-value]');
  var tiles = root.querySelector('[data-mediafield-tiles]');
  var pickBtn = root.querySelector('[data-mediafield-pick]');
  var clearBtn = root.querySelector('[data-mediafield-clear]');
  if (!input || !tiles || !pickBtn) return;
  var max = parseInt(root.getAttribute('data-max') || '1', 10);
  var multiple = max !== 1;
  var words = {
    select: root.getAttribute('data-lat-select') || 'Select',
    replace: root.getAttribute('data-lat-replace') || 'Replace',
    use: root.getAttribute('data-lat-use') || 'Use selected',
    title: root.getAttribute('data-lat-title') || 'Choose from the library',
    cancel: document.body.getAttribute('data-lat-cancel') || 'Cancel',
  };

  function ids() {
    return input.value.split(',').map(function (s) { return s.trim(); }).filter(Boolean);
  }
  function write(list) {
    input.value = list.join(',');
    input.dispatchEvent(new Event('change', { bubbles: true }));
    pickBtn.textContent = list.length && !multiple ? words.replace : words.select;
    if (clearBtn) clearBtn.hidden = list.length === 0;
    window.lat.emit(root, 'media:changed', { ids: list.slice() });
  }
  function tile(item) {
    var el = document.createElement('div');
    el.className = 'lat-mediafield__tile';
    el.setAttribute('data-id', item.id);
    el.innerHTML =
      '<span class="lat-media-card__thumb"></span>' +
      '<span class="lat-media-card__name"></span>' +
      '<button type="button" class="lat-mediafield__remove">&times;</button>';
    var thumb = el.querySelector('.lat-media-card__thumb');
    if (item.is_image) {
      var img = document.createElement('img');
      img.src = item.thumb;
      img.alt = '';
      thumb.appendChild(img);
    } else {
      var kind = document.createElement('span');
      kind.className = 'lat-media-card__kind';
      kind.textContent = item.kind;
      thumb.appendChild(kind);
    }
    el.querySelector('.lat-media-card__name').textContent = item.name;
    el.querySelector('.lat-media-card__name').title = item.name;
    el.querySelector('.lat-mediafield__remove').addEventListener('click', function () {
      el.remove();
      write(ids().filter(function (id) { return id !== String(item.id); }));
    });
    return el;
  }
  function draw(items) {
    tiles.innerHTML = '';
    items.forEach(function (item) { tiles.appendChild(tile(item)); });
  }
  function load() {
    var list = ids();
    if (!list.length) { draw([]); return; }
    fetch(root.getAttribute('data-resolve') + '?ids=' + encodeURIComponent(list.join(',')), { credentials: 'same-origin', headers: { 'X-Requested-With': 'fetch' } })
      .then(function (r) { return r.ok ? r.json() : []; })
      .then(draw)
      .catch(function () { draw([]); });
  }

  function finish(items) {
    var current = multiple ? ids() : [];
    var merged = current.slice();
    var existing = {};
    tiles.querySelectorAll('[data-id]').forEach(function (t) { existing[t.getAttribute('data-id')] = true; });
    items.forEach(function (item) {
      if (merged.indexOf(String(item.id)) === -1) {
        if (max > 1 && merged.length >= max) return;
        merged.push(String(item.id));
      }
      if (!existing[String(item.id)]) tiles.appendChild(tile(item));
    });
    if (!multiple) {
      tiles.innerHTML = '';
      tiles.appendChild(tile(items[0]));
    }
    write(merged);
  }
  var picker = window.lat.mediaPicker({
    multiple: multiple,
    words: { title: words.title, use: words.use, cancel: words.cancel },
    onDone: finish
  });

  pickBtn.addEventListener('click', function () {
    var mode = root.getAttribute('data-mode');
    picker.open(root.getAttribute('data-pick') + (mode && mode !== 'file' ? '?mode=' + mode : ''));
  });
  if (clearBtn) {
    clearBtn.addEventListener('click', function () { draw([]); write([]); });
  }
  load();
  return { ids: ids, set: write };
});

// The crop tool: a box over the image that is dragged to move and pulled by
// its handle to resize, kept inside the image and to the chosen aspect. The
// box lives in displayed pixels; the hidden inputs carry the rectangle in the
// image's own pixels, which is what the server crops.
window.lat.widget('crop', function (root) {
  var stage = root.querySelector('[data-crop-stage]');
  var img = root.querySelector('[data-crop-image]');
  var box = root.querySelector('[data-crop-box]');
  var handle = root.querySelector('[data-crop-handle]');
  var aspectSel = root.querySelector('[data-crop-aspect]');
  var reset = root.querySelector('[data-crop-reset]');
  var size = root.querySelector('[data-crop-size]');
  var inputs = {
    x: root.querySelector('[data-crop-x]'), y: root.querySelector('[data-crop-y]'),
    w: root.querySelector('[data-crop-w]'), h: root.querySelector('[data-crop-h]'),
  };
  if (!stage || !img || !box) return;
  var full = { w: parseInt(root.getAttribute('data-width') || '0', 10), h: parseInt(root.getAttribute('data-height') || '0', 10) };
  var sel = { x: 0, y: 0, w: 0, h: 0 };
  var aspect = 0;

  function frame() {
    var r = img.getBoundingClientRect();
    var s = stage.getBoundingClientRect();
    return { left: r.left - s.left, top: r.top - s.top, w: r.width, h: r.height };
  }
  function scale() {
    var f = frame();
    return f.w ? full.w / f.w : 1;
  }
  function clamp() {
    var f = frame();
    sel.w = Math.max(8, Math.min(sel.w, f.w));
    sel.h = Math.max(8, Math.min(sel.h, f.h));
    if (aspect) {
      if (sel.w / sel.h > aspect) sel.w = sel.h * aspect; else sel.h = sel.w / aspect;
    }
    sel.x = Math.max(0, Math.min(sel.x, f.w - sel.w));
    sel.y = Math.max(0, Math.min(sel.y, f.h - sel.h));
  }
  function draw() {
    clamp();
    var f = frame();
    box.style.left = (f.left + sel.x) + 'px';
    box.style.top = (f.top + sel.y) + 'px';
    box.style.width = sel.w + 'px';
    box.style.height = sel.h + 'px';
    var k = scale();
    var out = {
      x: Math.round(sel.x * k), y: Math.round(sel.y * k),
      w: Math.max(1, Math.round(sel.w * k)), h: Math.max(1, Math.round(sel.h * k)),
    };
    if (out.x + out.w > full.w) out.w = full.w - out.x;
    if (out.y + out.h > full.h) out.h = full.h - out.y;
    Object.keys(out).forEach(function (key) { if (inputs[key]) inputs[key].value = out[key]; });
    if (size) size.textContent = out.w + ' \u00d7 ' + out.h;
    window.lat.emit(root, 'crop:changed', out);
  }
  function whole() {
    // A record measured before sizes were kept reads its size from the image.
    if (!full.w || !full.h) full = { w: img.naturalWidth, h: img.naturalHeight };
    var f = frame();
    sel = { x: 0, y: 0, w: f.w, h: f.h };
    if (aspect) {
      if (f.w / f.h > aspect) { sel.w = f.h * aspect; sel.x = (f.w - sel.w) / 2; }
      else { sel.h = f.w / aspect; sel.y = (f.h - sel.h) / 2; }
    }
    draw();
  }

  var drag = null;
  function point(e) {
    var s = stage.getBoundingClientRect();
    return { x: e.clientX - s.left, y: e.clientY - s.top };
  }
  box.addEventListener('pointerdown', function (e) {
    var p = point(e);
    var f = frame();
    drag = e.target === handle
      ? { mode: 'size', px: p.x, py: p.y, w: sel.w, h: sel.h }
      : { mode: 'move', px: p.x, py: p.y, x: sel.x, y: sel.y, f: f };
    box.setPointerCapture(e.pointerId);
    e.preventDefault();
  });
  box.addEventListener('pointermove', function (e) {
    if (!drag) return;
    var p = point(e);
    if (drag.mode === 'move') {
      sel.x = drag.x + (p.x - drag.px);
      sel.y = drag.y + (p.y - drag.py);
    } else {
      sel.w = drag.w + (p.x - drag.px);
      sel.h = drag.h + (p.y - drag.py);
    }
    draw();
  });
  ['pointerup', 'pointercancel'].forEach(function (name) {
    box.addEventListener(name, function () { drag = null; });
  });
  // A new box drawn on the bare image.
  stage.addEventListener('pointerdown', function (e) {
    if (e.target !== stage && e.target !== img) return;
    var p = point(e);
    var f = frame();
    sel = { x: p.x - f.left, y: p.y - f.top, w: 8, h: 8 };
    drag = { mode: 'size', px: p.x, py: p.y, w: 8, h: 8 };
    box.setPointerCapture(e.pointerId);
    draw();
    e.preventDefault();
  });
  if (aspectSel) {
    aspectSel.addEventListener('change', function () {
      var v = aspectSel.value;
      aspect = v === 'original' ? (full.h ? full.w / full.h : 0) : parseFloat(v) || 0;
      whole();
    });
  }
  if (reset) reset.addEventListener('click', whole);
  // The stage lays out once the dialog is open, so the box is placed then.
  var dialog = root.closest('dialog');
  if (dialog) dialog.addEventListener('lat:dialog:opened', function () { setTimeout(whole, 0); });
  if (img.complete) setTimeout(whole, 0); else img.addEventListener('load', whole);
  window.addEventListener('resize', draw);
  return { selection: function () { return sel; }, whole: whole };
});

// Dropdown dismissal. A <details> stays open until its own summary is clicked
// again, which is not what a dropdown is expected to do: choosing an item or
// clicking away should close it. Bound once at the document, so a menu that
// arrives with a swap is covered without re-binding.
//
// A menu that must survive a click declares data-lat-keep-open.
(function () {
  function closeAll(except) {
    document.querySelectorAll('details.lat-menu[open]').forEach(function (m) {
      if (m !== except && !m.hasAttribute('data-lat-keep-open')) m.open = false;
    });
  }

  document.addEventListener('click', function (e) {
    if (!e.target.closest) return;
    var menu = e.target.closest('details.lat-menu');
    // Inside a panel only a link ends the interaction. Ticking a box in the
    // column picker is the operator still choosing, so it must stay open.
    var chose = menu && e.target.closest('.lat-menu__panel') && e.target.closest('a,button');
    closeAll(chose ? null : menu);
  });

  // Escape closes the open menu and hands focus back to what opened it, which
  // is where the keyboard was before.
  document.addEventListener('keydown', function (e) {
    if (e.key !== 'Escape') return;
    var open = document.querySelector('details.lat-menu[open]');
    if (!open || open.hasAttribute('data-lat-keep-open')) return;
    open.open = false;
    var summary = open.querySelector('summary');
    if (summary) summary.focus();
  });
})();

// Flash toasts: auto-dismiss non-error messages after a few seconds.
window.lat.widget('flash', function (el) {
  var level = (el.className.match(/is-(success|error|info)/) || [])[1] || 'info';
  window.lat.emit(el, 'flash:shown', { text: flashText(el), level: level });
  // Errors stay until dismissed, and so does anything marked to persist.
  if (el.classList.contains('is-error') || el.hasAttribute('data-lat-persist')) return;
  setTimeout(function () { latDismissFlash(el); }, 5000);
});

// Repeater: add and remove rows. Rows are renumbered after every change so the
// submitted indices read 0,1,2; the server sorts the indices it finds rather
// than counting, so this is tidiness, not correctness.
window.lat.widget('repeater', function (root) {
  var rows = root.querySelector('.lat-repeater__rows');
  var blank = root.querySelector('.lat-repeater__blank');
  var add = root.querySelector('.lat-repeater__add');
  if (!rows || !blank || !add) return;
  var reorder = root.getAttribute('data-lat-reorder') !== 'off';
  var duplicate = root.getAttribute('data-lat-duplicate') !== 'off';
  // The placeholder a row with no name shows, as the server wrote it.
  var untitled = blank.content.querySelector('.lat-repeater__untitled');
  untitled = untitled ? untitled.textContent : 'Untitled';

  function all() {
    return Array.prototype.slice.call(rows.querySelectorAll(':scope > .lat-repeater__row'));
  }

  // Indices read 0,1,2 after every change, and the first row cannot move up
  // nor the last down.
  function renumber() {
    var list = all();
    list.forEach(function (row, index) {
      row.querySelectorAll('[name]').forEach(function (control) {
        control.name = control.name.replace(/\[[^\]]*\]/, '[' + index + ']');
      });
      var up = row.querySelector('.lat-repeater__up');
      var down = row.querySelector('.lat-repeater__down');
      if (up) up.disabled = index === 0;
      if (down) down.disabled = index === list.length - 1;
    });
  }

  // The line that names a collapsed row, kept current as the operator types.
  // Without this a new row would read as untitled until the page reloaded.
  var summaryIndex = parseInt(add.getAttribute('data-lat-summary-index'), 10) || 0;

  function retitle(row) {
    var title = row.querySelector('.lat-repeater__title');
    if (!title) return;
    var control = row.querySelectorAll('.lat-repeater__fields [name]')[summaryIndex];
    var text = control ? String(control.value || '').split('\n')[0].trim() : '';
    if (text) {
      title.textContent = text;
    } else {
      title.textContent = '';
      var span = document.createElement('span');
      span.className = 'lat-repeater__untitled';
      span.textContent = untitled;
      title.appendChild(span);
    }
  }

  // The controls that need the script, shown once it runs.
  function reveal(scope) {
    scope.querySelectorAll('.lat-repeater__up, .lat-repeater__down, .lat-repeater__duplicate').forEach(function (b) {
      b.hidden = false;
    });
  }

  function fresh(after) {
    var row = blank.content.cloneNode(true).firstElementChild;
    if (after) after.insertAdjacentElement('afterend', row); else rows.appendChild(row);
    renumber();
    reveal(row);
    window.lat.scan(row);
    return row;
  }

  function addRow() {
    if (!window.lat.emit(root, 'repeater:before-add', { count: all().length }, true)) return null;
    var added = fresh(null);
    // A details row is added open, so focus lands where the operator is looking.
    var first = added.querySelector('.lat-repeater__fields [name], [name]');
    if (first) first.focus();
    var list = all();
    window.lat.emit(root, 'repeater:added', { row: added, index: list.length - 1, count: list.length });
    return added;
  }

  function removeRow(row) {
    var index = all().indexOf(row);
    if (index < 0) return false;
    if (!window.lat.emit(root, 'repeater:before-remove', { row: row, index: index, count: all().length }, true)) {
      return false;
    }
    row.remove();
    renumber();
    window.lat.emit(root, 'repeater:removed', { index: index, count: all().length });
    return true;
  }

  function moveRow(from, to) {
    var list = all();
    var row = list[from];
    var target = list[to];
    if (!row || !target || from === to) return false;
    if (to > from) target.insertAdjacentElement('afterend', row);
    else target.insertAdjacentElement('beforebegin', row);
    renumber();
    var focus = row.querySelector(to > from ? '.lat-repeater__down' : '.lat-repeater__up');
    if (focus && !focus.disabled) focus.focus();
    window.lat.emit(root, 'repeater:moved', { row: row, from: from, to: to, count: list.length });
    return true;
  }

  // Values by position: a fresh row has the same controls in the same order,
  // so a picker's hidden id and its box both copy across.
  function copyValues(from, to) {
    var sources = from.querySelectorAll('input, select, textarea');
    var targets = to.querySelectorAll('input, select, textarea');
    sources.forEach(function (source, i) {
      var target = targets[i];
      if (!target || target.tagName !== source.tagName || target.type !== source.type) return;
      if (source.type === 'checkbox' || source.type === 'radio') target.checked = source.checked;
      else target.value = source.value;
      target.dispatchEvent(new Event('input', { bubbles: true }));
      target.dispatchEvent(new Event('change', { bubbles: true }));
    });
    // A picker keeps its choice in its island as well as its inputs.
    var pickers = from.querySelectorAll('[data-lat-widget="ref-picker"]');
    to.querySelectorAll('[data-lat-widget="ref-picker"]').forEach(function (picker, i) {
      var origin = pickers[i] && window.lat.get(pickers[i]);
      var mine = window.lat.get(picker);
      if (origin && mine && origin.value()) mine.choose({ id: origin.value(), label: origin.label() });
    });
  }

  function duplicateRow(index) {
    var list = all();
    var source = list[index];
    if (!source) return null;
    if (!window.lat.emit(root, 'repeater:before-add', { count: list.length }, true)) return null;
    var row = fresh(source);
    copyValues(source, row);
    if (row.tagName === 'DETAILS') {
      retitle(row);
      row.open = true;
    }
    var first = row.querySelector('.lat-repeater__fields [name], [name]');
    if (first) first.focus();
    window.lat.emit(root, 'repeater:duplicated', { row: row, index: index + 1, count: all().length });
    return row;
  }

  add.addEventListener('click', addRow);

  root.addEventListener('input', function (e) {
    var row = e.target.closest('.lat-repeater__row');
    if (row && row.tagName === 'DETAILS') retitle(row);
  });

  root.addEventListener('click', function (e) {
    var button = e.target.closest('button');
    var row = button && button.closest('.lat-repeater__row');
    if (!row || !rows.contains(row)) return;
    var index = all().indexOf(row);
    if (button.classList.contains('lat-repeater__remove')) removeRow(row);
    else if (reorder && button.classList.contains('lat-repeater__up')) moveRow(index, index - 1);
    else if (reorder && button.classList.contains('lat-repeater__down')) moveRow(index, index + 1);
    else if (duplicate && button.classList.contains('lat-repeater__duplicate')) duplicateRow(index);
    else return;
    // A button in a summary must not toggle the row.
    e.preventDefault();
  });

  if (reorder || duplicate) reveal(rows);
  renumber();

  return {
    add: addRow,
    remove: function (index) {
      var row = all()[index];
      return row ? removeRow(row) : false;
    },
    move: moveRow,
    duplicate: duplicateRow,
    count: function () { return all().length; }
  };
});

// Checklist: boxes in groups. The markup submits and the groups open and close
// without this; the island adds what needs a script. A group's box is ticked
// when all of its boxes are, clear when none is and in between otherwise, and
// ticking it ticks the group. Counts follow the ticks. Select all, select none
// and a group's box act on what the search is showing, so narrowing the list
// and ticking what is left is two steps. Every change is announced once as
// `checklist:changed`, with the ticked values.
window.lat.widget('checklist', function (root) {
  var pattern = root.getAttribute('data-lat-count') || '{n} / {total}';
  var bar = root.querySelector('.lat-checklist__bar');
  var search = root.querySelector('[data-lat-checklist-search]');
  var total = root.querySelector('[data-lat-checklist-total]');
  var empty = root.querySelector('.lat-checklist__empty');

  function list(scope, selector) {
    return Array.prototype.slice.call(scope.querySelectorAll(selector));
  }
  function boxes(scope) { return list(scope || root, '.lat-checklist__item input[type="checkbox"]'); }
  function groups() { return list(root, '.lat-checklist__group'); }
  function shown(box) { return !box.closest('.lat-checklist__item').hidden; }
  function own(group, selector) {
    var summary = group.firstElementChild;
    return summary ? summary.querySelector(selector) : null;
  }
  function ticked(all) { return all.filter(function (b) { return b.checked; }); }
  function values() { return ticked(boxes()).map(function (b) { return b.value; }); }
  function count(n, of) { return pattern.replace('{n}', n).replace('{total}', of); }

  function refresh() {
    groups().forEach(function (group) {
      var all = boxes(group);
      var on = ticked(all).length;
      var parent = own(group, '.lat-checklist__parent');
      var label = own(group, '.lat-checklist__count');
      if (parent) {
        parent.checked = all.length > 0 && on === all.length;
        parent.indeterminate = on > 0 && on < all.length;
        parent.disabled = !all.some(function (b) { return !b.disabled; });
      }
      if (label) label.textContent = count(on, all.length);
    });
    if (total) total.textContent = count(ticked(boxes()).length, boxes().length);
  }

  function changed() {
    refresh();
    var on = values();
    window.lat.emit(root, 'checklist:changed', { values: on, count: on.length, total: boxes().length });
  }

  // Ticks or clears every box that may change. True when any did.
  function put(all, on) {
    var moved = false;
    all.forEach(function (box) {
      if (box.disabled || box.checked === on) return;
      box.checked = on;
      moved = true;
    });
    return moved;
  }

  function filter(text) {
    var query = (text || '').trim().toLowerCase();
    boxes().forEach(function (box) {
      var item = box.closest('.lat-checklist__item');
      item.hidden = query !== '' && item.textContent.toLowerCase().indexOf(query) === -1;
    });
    var any = false;
    groups().forEach(function (group) {
      var matches = boxes(group).some(shown);
      any = any || matches;
      group.hidden = !matches;
      if (query === '') {
        // Back to how the group stood before the search opened it.
        if (group.hasAttribute('data-lat-was')) {
          group.open = group.getAttribute('data-lat-was') === 'open';
          group.removeAttribute('data-lat-was');
        }
      } else {
        if (!group.hasAttribute('data-lat-was')) {
          group.setAttribute('data-lat-was', group.open ? 'open' : 'closed');
        }
        group.open = matches;
      }
    });
    any = any || boxes().some(shown);
    if (empty) empty.hidden = any || boxes().length === 0;
  }

  root.addEventListener('change', function (e) {
    var target = e.target;
    if (target.classList.contains('lat-checklist__parent')) {
      put(boxes(target.closest('.lat-checklist__group')).filter(shown), target.checked);
      changed();
    } else if (target.matches('.lat-checklist__item input[type="checkbox"]')) {
      changed();
    }
  });

  root.addEventListener('click', function (e) {
    var all = e.target.closest('[data-lat-checklist-all]');
    var none = e.target.closest('[data-lat-checklist-none]');
    if (!all && !none) return;
    if (put(boxes().filter(shown), !!all)) changed();
  });

  if (search) {
    search.addEventListener('input', function () { filter(search.value); });
    // Escape clears the search first, and only then reaches anything outside.
    search.addEventListener('keydown', function (e) {
      if (e.key !== 'Escape' || search.value === '') return;
      e.stopPropagation();
      search.value = '';
      filter('');
    });
  }

  list(root, '.lat-checklist__parent').forEach(function (parent) { parent.hidden = false; });
  if (bar) bar.hidden = false;
  refresh();

  return {
    values: values,
    count: function () { return values().length; },
    // Ticks exactly `wanted`, leaving locked boxes as they are.
    set: function (wanted) {
      var moved = false;
      boxes().forEach(function (box) {
        var on = wanted.indexOf(box.value) !== -1;
        if (box.disabled || box.checked === on) return;
        box.checked = on;
        moved = true;
      });
      if (moved) changed();
    },
    all: function () { if (put(boxes(), true)) changed(); },
    none: function () { if (put(boxes(), false)) changed(); },
    search: function (text) {
      if (search) search.value = text || '';
      filter(text);
    }
  };
});

// Select-all checkbox in a list header: ticks every row box in its table. Bound
// by structure, and re-bound after a swap because the header comes back with it.
window.lat.widget('pick-all', function (box) {
  var table = box.closest('table');
  if (!table) return;
  box.addEventListener('change', function () {
    table.querySelectorAll('tbody input[type="checkbox"][name="id"]').forEach(function (row) {
      row.checked = box.checked;
    });
    latSelectionChanged(table);
  });
});

// A click on a row box with Shift held ticks, or clears, every box between it
// and the box clicked before it, to the state of the one just clicked. The
// click runs before the change the browser fires for the clicked box, so that
// change announces the whole range once.
document.addEventListener('click', function (e) {
  var box = e.target;
  if (!box.matches || !box.matches('tbody input[type="checkbox"][name="id"]')) return;
  var table = box.closest('table');
  if (!table) return;
  var all = Array.prototype.slice.call(table.querySelectorAll('tbody input[type="checkbox"][name="id"]'));
  var last = table._latLastPick;
  var from = all.indexOf(last);
  if (e.shiftKey && from !== -1 && last !== box) {
    var to = all.indexOf(box);
    all.slice(Math.min(from, to), Math.max(from, to) + 1).forEach(function (other) {
      other.checked = box.checked;
    });
  }
  table._latLastPick = box;
});

// The rows ticked in a list, announced whenever they change.
function latSelectionChanged(table) {
  var ids = Array.prototype.map.call(
    table.querySelectorAll('tbody input[type="checkbox"][name="id"]:checked'),
    function (box) { return box.value; }
  );
  window.lat.emit(table, 'selection:changed', { ids: ids, count: ids.length });
}
document.addEventListener('change', function (e) {
  if (!e.target.matches || !e.target.matches('tbody input[type="checkbox"][name="id"]')) return;
  var table = e.target.closest('table');
  if (table) latSelectionChanged(table);
});

// Bulk Delete: it sits in the action row, outside the table it acts on, so no
// markup can tell it whether anything is selected. It starts disabled and
// follows the row checkboxes, which come back fresh with every swap.
window.lat.widget('bulk-delete', function (btn) {
  function sync() {
    btn.disabled = !document.querySelector('input[type="checkbox"][name="id"]:checked');
  }
  // The select-all box ticks rows without firing their change events, so listen
  // for it too rather than for the rows alone.
  document.addEventListener('change', function (e) {
    if (e.target.matches('input[name="id"], [data-lat-widget="pick-all"]')) sync();
  });
  document.addEventListener('htmx:load', sync);
  sync();
});

// Copy button: copies its input group's value, with brief confirmation. Binds by
// structure (closest group), so it survives repeater path-ids.
window.lat.widget('copy', function (btn) {
  var label = btn.textContent;
  btn.addEventListener('click', function () {
    var group = btn.closest('.lat-input-group');
    var input = group && group.querySelector('input');
    if (!input || !navigator.clipboard) return;
    navigator.clipboard.writeText(input.value).then(function () {
      window.lat.emit(btn, 'copy:copied', { value: input.value });
      btn.classList.add('is-copied');
      btn.textContent = 'Copied';
      setTimeout(function () {
        btn.classList.remove('is-copied');
        btn.textContent = label;
      }, 1200);
    });
  });
});

// Enter policy. One rule per scope, framework-wide, so every form behaves the
// way people expect without each screen wiring it:
//   * a single-line field: Enter submits (the browser's implicit submission;
//     every rendered form carries a submit button, which that needs);
//   * a textarea: Enter is a newline, Cmd/Ctrl+Enter submits;
//   * inside `[data-lat-enter-scope]` (a picker, a repeater): Enter acts there
//     and never submits the form around it;
//   * `data-lat-enter="off"` on a form or a field stops Enter submitting;
//     `data-lat-enter="next"` on a field moves focus to the next one.
(function () {
  var NOT_TEXT = /^(checkbox|radio|file|button|submit|reset|image|range|color)$/;
  function isSingleLine(el) {
    return el.tagName === 'INPUT' && !NOT_TEXT.test(el.type);
  }
  function rule(el) {
    var carrier = el.closest('[data-lat-enter]');
    return carrier ? carrier.getAttribute('data-lat-enter') : 'submit';
  }
  function focusables(root) {
    return Array.prototype.filter.call(
      root.querySelectorAll('input, select, textarea, button, [tabindex]'),
      function (f) { return !f.disabled && f.type !== 'hidden' && f.offsetParent !== null; }
    );
  }
  function focusNext(el, root) {
    var list = focusables(root);
    var i = list.indexOf(el);
    if (i < 0 || i + 1 >= list.length) return false;
    list[i + 1].focus();
    return true;
  }
  // A repeater: the next field in the row, or a new row from the last one.
  function withinRows(el, scope) {
    var row = el.closest('.lat-repeater__row');
    if (row && focusNext(el, row)) return;
    var add = scope.querySelector(':scope > .lat-repeater__add');
    if (add) add.click();
  }
  document.addEventListener('keydown', function (e) {
    if (e.key !== 'Enter' || e.isComposing || e.defaultPrevented) return;
    var el = e.target;
    if (!el || !el.closest) return;
    var form = el.form || el.closest('form');
    if (e.metaKey || e.ctrlKey) {
      if (!form) return;
      e.preventDefault();
      form.requestSubmit();
      return;
    }
    if (!isSingleLine(el)) return;
    var scope = el.closest('[data-lat-enter-scope]');
    if (scope && form && form.contains(scope)) {
      e.preventDefault();
      var kind = scope.getAttribute('data-lat-enter-scope');
      var target = scope.getAttribute('data-lat-enter-target');
      if (kind === 'rows') withinRows(el, scope);
      else if (target) { var t = scope.querySelector(target); if (t) t.click(); }
      return;
    }
    var what = rule(el);
    if (what === 'off') e.preventDefault();
    else if (what === 'next') { e.preventDefault(); focusNext(el, form || document); }
  }, true);
})();

// Form: two things every content form does. It asks before the operator leaves
// with changes unsaved, and it puts the cursor where they will type next: the
// first field of a new record, or the first field a save refused.
//
// Changed means different from how the form opened, so typing and undoing it
// is not a change. A form that came back refused (`data-lat-refused`) opens
// changed, since what it holds was never saved.
// `data-lat-confirm-leave="off"` stops the question;
// `data-lat-focus="off"` leaves the cursor alone.
(function () {
  var guarded = [];
  var leaving = false;

  function snapshot(form) {
    var parts = [];
    new FormData(form).forEach(function (value, key) {
      if (key === '_csrf') return;
      parts.push(key + '=' + (typeof value === 'string' ? value : value.name));
    });
    return parts.join('&');
  }

  function changed() {
    return guarded.some(function (g) {
      return document.body.contains(g.form) && !g.sent && (g.refused || snapshot(g.form) !== g.opened);
    });
  }

  window.lat.widget('form', function (form) {
    var refused = form.hasAttribute('data-lat-refused');
    var state = { form: form, opened: snapshot(form), refused: refused, sent: false };
    if (form.getAttribute('data-lat-confirm-leave') !== 'off') {
      guarded = guarded.filter(function (g) { return document.body.contains(g.form); });
      guarded.push(state);
    }
    form.addEventListener('submit', function () { state.sent = true; });
    // A request that never arrived leaves the form as unsaved as it was.
    form.addEventListener('htmx:sendError', function () { state.sent = false; });
    form.addEventListener('htmx:responseError', function () { state.sent = false; });

    var focus = form.getAttribute('data-lat-focus');
    if (focus !== 'off') {
      var field = refused ? form.querySelector('.lat-field__error') : null;
      var scope = field ? field.closest('.lat-field') : (refused || focus === 'first' ? form : null);
      var control = scope && scope.querySelector(
        'input:not([type="hidden"]):not([disabled]):not([readonly]), select:not([disabled]), textarea:not([disabled]):not([readonly])'
      );
      if (control) {
        control.focus({ preventScroll: !refused });
        if (refused && control.scrollIntoView) control.scrollIntoView({ block: 'center' });
      }
    }

    return {
      changed: function () { return !state.sent && (state.refused || snapshot(form) !== state.opened); },
      // Takes the form as it stands for saved, so leaving asks nothing.
      settle: function () { state.refused = false; state.opened = snapshot(form); }
    };
  });

  // Closing the tab, reloading and the back button: only the browser can ask.
  window.addEventListener('beforeunload', function (e) {
    if (leaving || !changed()) return;
    e.preventDefault();
    e.returnValue = '';
  });

  // A link inside the admin: the admin asks, in its own dialog.
  document.addEventListener('click', function (e) {
    if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
    var link = e.target.closest ? e.target.closest('a[href]') : null;
    if (!link || link.target === '_blank' || link.hasAttribute('download')) return;
    var href = link.getAttribute('href');
    if (!href || href.charAt(0) === '#' || /^javascript:/i.test(href)) return;
    if (!changed()) return;
    e.preventDefault();
    var body = document.body;
    window.lat.confirm(
      body.getAttribute('data-lat-leave') || 'You have unsaved changes. Leave without saving?',
      {
        go: body.getAttribute('data-lat-leave-go') || 'Leave',
        cancel: body.getAttribute('data-lat-leave-stay') || 'Stay',
        // Enter on a question about losing work should keep the work.
        focus: 'cancel'
      },
      function (yes) {
        if (!yes) return;
        leaving = true;
        window.location.href = link.href;
      }
    );
  });
})();

// Counter: a field a rule limits shows how much of the limit is used. With
// `data-lat-counter="auto"` it appears once four fifths are used, which is when
// the limit starts to matter; with `on` it is always there.
(function () {
  function counter(control) {
    var next = control.closest('.lat-input-group') || control;
    var el = next.nextElementSibling;
    if (el && el.classList.contains('lat-counter')) return el;
    el = document.createElement('p');
    el.className = 'lat-counter';
    el.setAttribute('aria-live', 'polite');
    next.parentNode.insertBefore(el, next.nextSibling);
    return el;
  }
  function update(control) {
    var max = parseInt(control.getAttribute('maxlength'), 10);
    if (!max) return;
    var used = control.value.length;
    var el = counter(control);
    el.textContent = used + ' / ' + max;
    el.classList.toggle('is-full', used >= max);
    el.hidden = control.getAttribute('data-lat-counter') === 'auto' && used < max * 0.8;
  }
  function all(root) {
    var scope = root && root.querySelectorAll ? root : document;
    scope.querySelectorAll('[data-lat-counter]').forEach(update);
  }
  document.addEventListener('input', function (e) {
    if (e.target.hasAttribute && e.target.hasAttribute('data-lat-counter')) update(e.target);
  });
  document.addEventListener('DOMContentLoaded', function () { all(document); });
  document.addEventListener('htmx:load', function (e) { all(e.target); });
})();

// Textarea: grows with what is typed, up to the height the stylesheet allows,
// so nothing is read through a slot. The stylesheet does this alone where the
// browser can; this is for the ones that cannot. `data-lat-grow="off"` keeps
// the height it was given.
(function () {
  if (window.CSS && CSS.supports && CSS.supports('field-sizing', 'content')) return;
  function fit(area) {
    if (area.getAttribute('data-lat-grow') === 'off') return;
    area.style.height = 'auto';
    area.style.height = (area.scrollHeight + 2) + 'px';
  }
  function all(root) {
    var scope = root && root.querySelectorAll ? root : document;
    scope.querySelectorAll('textarea.lat-input').forEach(fit);
  }
  document.addEventListener('input', function (e) {
    if (e.target.matches && e.target.matches('textarea.lat-input')) fit(e.target);
  });
  document.addEventListener('DOMContentLoaded', function () { all(document); });
  document.addEventListener('htmx:load', function (e) { all(e.target); });
})();

// Reveal: shows what was typed into a password field, and hides it again. The
// button starts hidden, so a page with no script has no button that does
// nothing. What is shown is hidden again when the form is sent.
window.lat.widget('reveal', function (btn) {
  var group = btn.closest('.lat-input-group');
  var input = group && group.querySelector('input');
  if (!input) return;
  function show(on) {
    input.type = on ? 'text' : 'password';
    btn.setAttribute('aria-pressed', on ? 'true' : 'false');
    window.lat.emit(btn, on ? 'reveal:shown' : 'reveal:hidden', {});
  }
  btn.hidden = false;
  btn.addEventListener('click', function () { show(input.type === 'password'); });
  if (input.form) {
    input.form.addEventListener('submit', function () {
      if (input.type !== 'password') show(false);
    });
  }
  return { show: function () { show(true); }, hide: function () { show(false); } };
});

// Preset: a field follows another as it is typed, shaped on the way (a slug
// from a title), until the operator edits it. Clearing it hands it back to
// the source. The wrapper carries `data-lat-preset="<field>"` and
// `data-lat-preset-type="exact|slug|url|file"`.
(function () {
  var LETTERS = { 'ß': 'ss', 'æ': 'ae', 'ø': 'o', 'œ': 'oe', 'đ': 'd', 'ł': 'l', 'þ': 'th' };
  function slug(text) {
    return text
      .toLowerCase()
      .replace(/[ßæøœđłþ]/g, function (c) { return LETTERS[c]; })
      .normalize('NFD').replace(/[\u0300-\u036f]/g, '')
      .replace(/[^a-z0-9]+/g, '-')
      .replace(/^-+|-+$/g, '');
  }
  function shape(text, kind) {
    if (text.trim() === '') return '';
    if (kind === 'exact') return text;
    if (kind === 'url') return '/' + slug(text);
    if (kind === 'file') return text.trim().replace(/\s+/g, '-');
    return slug(text);
  }
  function control(wrapper) {
    return wrapper.querySelector('input:not([type="hidden"]), textarea');
  }
  function followers(form, name) {
    return Array.prototype.filter.call(form.querySelectorAll('[data-lat-preset]'), function (w) {
      return w.getAttribute('data-lat-preset') === name;
    });
  }
  document.addEventListener('input', function (e) {
    var source = e.target;
    var form = source.form;
    if (!form || !source.name) return;
    // Editing a follower takes it over; emptying it hands it back.
    var own = source.closest('[data-lat-preset]');
    if (own && control(own) === source && !source._latPreset) {
      own._latTaken = source.value !== '';
    }
    followers(form, source.name).forEach(function (wrapper) {
      var target = control(wrapper);
      if (!target || wrapper._latTaken) return;
      var value = shape(source.value, wrapper.getAttribute('data-lat-preset-type'));
      if (target.value === value) return;
      target.value = value;
      target._latPreset = true;
      target.dispatchEvent(new Event('input', { bubbles: true }));
      target._latPreset = false;
      window.lat.emit(target, 'preset:filled', { from: source.name, value: value });
    });
  });
  // A follower that opens with a value of its own is already taken.
  function settle(root) {
    var scope = root && root.querySelectorAll ? root : document;
    scope.querySelectorAll('[data-lat-preset]').forEach(function (wrapper) {
      var target = control(wrapper);
      if (target && target.value !== '') wrapper._latTaken = true;
    });
  }
  document.addEventListener('DOMContentLoaded', function () { settle(document); });
  document.addEventListener('htmx:load', function (e) { settle(e.target); });
})();

// Trigger: a field changes when another field's state meets a condition. The
// wrapper carries `data-lat-trigger-action` (`show`, `hide`, `enable`,
// `disable`, `empty`, `fill[value]`, joined by `|`), `data-lat-trigger-field`
// (`name`, or `name[]` for every value of a checklist) and
// `data-lat-trigger-condition` (`checked`, `unchecked`, `value[..]`).
(function () {
  function values(form, field) {
    var many = /\[\]$/.test(field);
    var name = field.replace(/\[\]$/, '');
    var out = [];
    var controls = form.querySelectorAll('[name]');
    Array.prototype.forEach.call(controls, function (c) {
      var mine = many ? (c.name === name || c.name.indexOf(name + '[') === 0) : c.name === name;
      if (!mine) return;
      if (c.type === 'checkbox' || c.type === 'radio') {
        if (c.checked) out.push(c.value);
      } else if (c.tagName === 'SELECT' && c.multiple) {
        Array.prototype.forEach.call(c.selectedOptions, function (o) { out.push(o.value); });
      } else {
        out.push(c.value);
      }
    });
    return out;
  }
  function ticked(form, field) {
    var name = field.replace(/\[\]$/, '');
    return Array.prototype.some.call(form.querySelectorAll('[name]'), function (c) {
      return (c.type === 'checkbox' || c.type === 'radio') && (c.name === name || c.name.indexOf(name + '[') === 0) && c.checked;
    });
  }
  // `value[a][b*]` lists what counts; `value[]` is empty and `value[*]` anything.
  function wanted(condition) {
    var list = [];
    var re = /\[([^\]]*)\]/g, m;
    while ((m = re.exec(condition))) list.push(m[1]);
    return list;
  }
  function matches(want, have) {
    if (want === '*') return have !== '';
    if (want.indexOf('*') === -1) return want === have;
    var head = want.split('*')[0], tail = want.split('*').slice(1).join('*');
    return have.indexOf(head) === 0 && (tail === '' || have.slice(-tail.length) === tail);
  }
  function met(form, wrapper) {
    var field = wrapper.getAttribute('data-lat-trigger-field');
    var condition = wrapper.getAttribute('data-lat-trigger-condition');
    if (condition === 'checked') return ticked(form, field);
    if (condition === 'unchecked') return !ticked(form, field);
    var have = values(form, field);
    var want = wanted(condition);
    if (want.length === 0 || (want.length === 1 && want[0] === '')) return have.every(function (v) { return v === ''; });
    return have.some(function (v) { return want.some(function (w) { return matches(w, v); }); });
  }
  // A hidden field is left out of the submission, so a required one cannot
  // hold the form back from behind its own trigger.
  function conceal(wrapper, controls, hidden) {
    wrapper.hidden = hidden;
    controls.forEach(function (c) {
      if (hidden && !c.disabled) { c.disabled = true; c._latConcealed = true; }
      else if (!hidden && c._latConcealed) { c.disabled = false; c._latConcealed = false; }
    });
  }
  function apply(form, wrapper) {
    var on = met(form, wrapper);
    var controls = wrapper.querySelectorAll('input:not([type="hidden"]), select, textarea, button');
    wrapper.getAttribute('data-lat-trigger-action').split('|').forEach(function (action) {
      if (action === 'show') conceal(wrapper, controls, !on);
      else if (action === 'hide') conceal(wrapper, controls, on);
      else if (action === 'enable') controls.forEach(function (c) { c.disabled = !on; });
      else if (action === 'disable') controls.forEach(function (c) { c.disabled = on; });
      else if (on && action === 'empty') controls.forEach(function (c) {
        if (c.type === 'checkbox' || c.type === 'radio') c.checked = false;
        else if (c.tagName !== 'BUTTON') c.value = '';
      });
      else if (on && action.indexOf('fill[') === 0) {
        var value = action.slice(5, -1);
        controls.forEach(function (c) {
          if (c.type === 'checkbox' || c.type === 'radio') c.checked = c.value === value;
          else if (c.tagName !== 'BUTTON') c.value = value;
        });
      }
    });
    if (wrapper._latMet !== on) {
      wrapper._latMet = on;
      window.lat.emit(wrapper, 'trigger:changed', { field: wrapper.getAttribute('data-lat-trigger-field'), met: on });
    }
  }
  function all(form) {
    form.querySelectorAll('[data-lat-trigger-field]').forEach(function (w) { apply(form, w); });
  }
  function watching(e) {
    var form = e.target.form || (e.target.closest && e.target.closest('form'));
    if (form && form.querySelector('[data-lat-trigger-field]')) all(form);
  }
  document.addEventListener('change', watching);
  document.addEventListener('input', watching);
  function start(root) {
    var scope = root && root.querySelectorAll ? root : document;
    var forms = Array.prototype.slice.call(scope.querySelectorAll('form'));
    // A swapped-in fragment is often the form itself.
    if (scope.matches && scope.matches('form')) forms.push(scope);
    forms.forEach(function (form) {
      if (form.querySelector('[data-lat-trigger-field]')) all(form);
    });
  }
  document.addEventListener('DOMContentLoaded', function () { start(document); });
  document.addEventListener('htmx:load', function (e) { start(e.target); });
})();

// Rows: a row that names its record (`data-lat-href`) opens it on a click or
// Enter, as its Edit link would. A click on a control in the row is that
// control's, and text being selected is left to be copied. A modified click
// or a middle click opens the record in a new tab. `row_click: none` on the
// list renders rows without the attribute.
(function () {
  function target(e) {
    var row = e.target.closest ? e.target.closest('tr[data-lat-href]') : null;
    if (!row) return null;
    if (e.target.closest('a, button, input, select, textarea, label, form, [data-lat-widget]')) return null;
    return row;
  }
  function open(url, newTab) {
    if (newTab) window.open(url, '_blank', 'noopener');
    else window.location.href = url;
  }
  document.addEventListener('click', function (e) {
    if (e.defaultPrevented || e.button !== 0) return;
    var row = target(e);
    if (!row) return;
    var selection = window.getSelection ? window.getSelection() : null;
    if (selection && String(selection) !== '' && row.contains(selection.anchorNode)) return;
    open(row.getAttribute('data-lat-href'), e.metaKey || e.ctrlKey);
  });
  document.addEventListener('auxclick', function (e) {
    if (e.button !== 1) return;
    var row = target(e);
    if (!row) return;
    e.preventDefault();
    open(row.getAttribute('data-lat-href'), true);
  });
  document.addEventListener('keydown', function (e) {
    var row = e.target;
    if (e.key !== 'Enter' || !row.matches || !row.matches('tr[data-lat-href]')) return;
    e.preventDefault();
    open(row.getAttribute('data-lat-href'), e.metaKey || e.ctrlKey);
  });
})();

// Reorder: a list in its own order carries a grip on every row. Dragging a
// row drops it before or after another and posts the move; the arrows beside
// the grip are the keyboard path and post the same way. The island sits on
// the header cell, outside the rows, so a row click stays the row's. After
// the region swaps back in, focus returns to the arrow that was pressed.
(function () {
  var pending = null;
  window.lat.widget('reorder', function (th) {
    var table = th.closest('table');
    var path = th.getAttribute('data-reorder-path');
    var region = th.getAttribute('data-reorder-region');
    if (!table || !path || !window.htmx) return;
    var dragging = null;
    function rows() { return Array.prototype.slice.call(table.querySelectorAll('tbody tr[data-lat-id]')); }
    function clear() {
      rows().forEach(function (r) { r.classList.remove('is-drop-before', 'is-drop-after'); });
    }
    // Under a tree, a child's siblings come back as rows: the old ones go
    // and the response lands after the parent, which stays expanded.
    function siblings(row) {
      var parent = row.getAttribute('data-lat-parent');
      if (!parent) return null;
      var parentRow = table.querySelector('tr[data-lat-id="' + parent + '"]');
      if (!parentRow) return null;
      var depth = +parentRow.getAttribute('data-lat-depth') || 0;
      var next = parentRow.nextElementSibling;
      while (next && (+next.getAttribute('data-lat-depth') || 0) > depth) {
        var gone = next;
        next = next.nextElementSibling;
        gone.remove();
      }
      return parentRow;
    }
    function post(values, row) {
      values._csrf = th.getAttribute('data-reorder-csrf');
      values.page = th.getAttribute('data-reorder-page');
      values.parent = row.getAttribute('data-lat-parent') || '';
      values.depth = row.getAttribute('data-lat-depth') || '';
      var parentRow = siblings(row);
      if (parentRow) {
        window.htmx.ajax('POST', path, { target: parentRow, swap: 'afterend', values: values });
      } else {
        window.htmx.ajax('POST', path, { target: '#' + region, swap: 'outerHTML', values: values });
      }
    }
    table.addEventListener('dragstart', function (e) {
      var grip = e.target.closest ? e.target.closest('.lat-grip') : null;
      var row = grip && grip.closest('tr[data-lat-id]');
      if (!row) return;
      dragging = row;
      row.classList.add('is-dragging');
      e.dataTransfer.effectAllowed = 'move';
      e.dataTransfer.setData('text/plain', row.getAttribute('data-lat-id'));
    });
    table.addEventListener('dragover', function (e) {
      if (!dragging) return;
      var row = e.target.closest ? e.target.closest('tr[data-lat-id]') : null;
      if (!row || row === dragging) return;
      e.preventDefault();
      var box = row.getBoundingClientRect();
      var before = e.clientY < box.top + box.height / 2;
      clear();
      row.classList.add(before ? 'is-drop-before' : 'is-drop-after');
    });
    table.addEventListener('drop', function (e) {
      if (!dragging) return;
      var row = e.target.closest ? e.target.closest('tr[data-lat-id]') : null;
      e.preventDefault();
      if (row && row !== dragging && row.getAttribute('data-lat-parent') === dragging.getAttribute('data-lat-parent')) {
        var before = row.classList.contains('is-drop-before');
        var values = { id: dragging.getAttribute('data-lat-id') };
        values[before ? 'before' : 'after'] = row.getAttribute('data-lat-id');
        post(values, dragging);
      }
      clear();
    });
    table.addEventListener('dragend', function () {
      if (dragging) dragging.classList.remove('is-dragging');
      dragging = null;
      clear();
    });
    // Remember which arrow was pressed, to focus it again after the swap. An
    // arrow under a tree parent posts through the island, so the response
    // replaces the siblings rather than the whole region.
    table.addEventListener('submit', function (e) {
      var form = e.target;
      if (!form.classList.contains('lat-grip__moves')) return;
      var button = form.querySelector('.lat-grip__move:focus') || e.submitter;
      var row = form.closest('tr[data-lat-id]');
      if (button && row) pending = { id: row.getAttribute('data-lat-id'), move: button.value };
      if (row && row.getAttribute('data-lat-parent') && button) {
        e.preventDefault();
        post({ id: row.getAttribute('data-lat-id'), move: button.value }, row);
      }
    });
    if (pending) {
      var row = table.querySelector('tr[data-lat-id="' + pending.id + '"]');
      var button = row && row.querySelector('.lat-grip__move[value="' + pending.move + '"]');
      pending = null;
      if (button) (button.disabled ? button.form.querySelector('.lat-grip__move:not(:disabled)') : button).focus();
    }
  });
})();

// Tree: a row with children carries a toggle that loads them in place; the
// same toggle takes them out again. The toggle is a link, so with scripting
// off it opens the children as a page of their own. The island sits on the
// first header cell, outside the rows, so a row click stays the row's.
(function () {
  window.lat.widget('tree', function (th) {
    var table = th.closest('table');
    if (!table || !window.htmx) return;
    table.addEventListener('click', function (e) {
      var toggle = e.target.closest ? e.target.closest('.lat-tree__toggle') : null;
      if (!toggle || !table.contains(toggle)) return;
      e.preventDefault();
      var row = toggle.closest('tr[data-lat-id]');
      if (!row) return;
      var depth = +row.getAttribute('data-lat-depth') || 0;
      if (toggle.getAttribute('aria-expanded') === 'true') {
        var next = row.nextElementSibling;
        while (next && (+next.getAttribute('data-lat-depth') || 0) > depth) {
          var gone = next;
          next = next.nextElementSibling;
          gone.remove();
        }
        toggle.setAttribute('aria-expanded', 'false');
        toggle.classList.remove('is-expanded');
        return;
      }
      toggle.setAttribute('aria-expanded', 'true');
      toggle.classList.add('is-expanded');
      window.htmx.ajax('GET', toggle.getAttribute('href'), { source: toggle, target: row, swap: 'afterend' });
    });
  });
})();

// Editable cell: the form saves itself on change, so the Save button is for
// a page without scripting. Starting the island marks the form ready, and the
// stylesheet hides the button on a ready cell; the button's own display rule
// would beat the hidden attribute.
window.lat.widget('cell', function () {});

// Menu order: the top bar's tabs drag into the order the operator wants, and
// the order is kept with their preferences, so it follows them. Dashboard and
// Settings stay put; the others move among themselves.
window.lat.widget('menu-order', function (nav) {
  var post = nav.getAttribute('data-menu-post');
  if (!post) return;
  var dragging = null;
  function tabs() { return Array.prototype.slice.call(nav.querySelectorAll('[data-lat-key]')); }
  function clear() { tabs().forEach(function (t) { t.classList.remove('is-drop-before', 'is-drop-after'); }); }
  nav.addEventListener('dragstart', function (e) {
    var tab = e.target.closest ? e.target.closest('[draggable="true"]') : null;
    if (!tab) return;
    dragging = tab;
    tab.classList.add('is-dragging');
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/plain', tab.getAttribute('data-lat-key'));
  });
  nav.addEventListener('dragover', function (e) {
    if (!dragging) return;
    var tab = e.target.closest ? e.target.closest('[draggable="true"]') : null;
    if (!tab || tab === dragging) return;
    e.preventDefault();
    var box = tab.getBoundingClientRect();
    clear();
    var before = nav.hasAttribute('data-menu-vertical')
      ? e.clientY < box.top + box.height / 2
      : e.clientX < box.left + box.width / 2;
    tab.classList.add(before ? 'is-drop-before' : 'is-drop-after');
  });
  nav.addEventListener('drop', function (e) {
    if (!dragging) return;
    var tab = e.target.closest ? e.target.closest('[draggable="true"]') : null;
    e.preventDefault();
    if (tab && tab !== dragging) {
      tab.insertAdjacentElement(tab.classList.contains('is-drop-before') ? 'beforebegin' : 'afterend', dragging);
      var order = tabs().map(function (t) { return t.getAttribute('data-lat-key'); }).join(',');
      var body = new URLSearchParams();
      body.set('_csrf', nav.getAttribute('data-menu-csrf') || '');
      body.set('order', order);
      if (nav.getAttribute('data-menu-hierarchy')) body.set('hierarchy', nav.getAttribute('data-menu-hierarchy'));
      fetch(post, { method: 'POST', body: body, credentials: 'same-origin', headers: { 'X-Requested-With': 'fetch' } })
        .catch(function () { window.lat.flash && window.lat.flash('The menu order could not be saved.', 'error'); });
    }
    clear();
  });
  nav.addEventListener('dragend', function () {
    if (dragging) dragging.classList.remove('is-dragging');
    dragging = null;
    clear();
  });
});

// Command palette: one box that finds a page, a setting or a record and goes
// there. The search button opens it, as does Ctrl+K (Cmd+K on a Mac); the
// arrows move, Enter goes, Escape closes. Without scripting the button is a
// link to the same finder as a page.
window.lat.widget('palette', function (button) {
  var url = button.getAttribute('data-palette-url');
  if (!url) return;
  var overlay = document.createElement('div');
  overlay.className = 'lat-palette';
  overlay.setAttribute('role', 'dialog');
  overlay.setAttribute('aria-modal', 'true');
  overlay.innerHTML =
    '<div class="lat-palette__backdrop" data-palette-close></div>' +
    '<div class="lat-palette__panel">' +
    '<input class="lat-palette__input" type="text" autocomplete="off" role="combobox" aria-expanded="true" aria-autocomplete="list" aria-label="' + (button.getAttribute('data-palette-placeholder') || 'Go to').replace(/"/g, '&quot;') + '">' +
    '<ul class="lat-palette__list" role="listbox"></ul>' +
    '</div>';
  document.body.appendChild(overlay);
  var input = overlay.querySelector('input');
  var list = overlay.querySelector('ul');
  input.placeholder = button.getAttribute('data-palette-placeholder') || '';
  var active = -1;
  var timer = null;
  var latest = 0;
  function items() { return Array.prototype.slice.call(list.querySelectorAll('.lat-palette__hit')); }
  function mark(index) {
    var all = items();
    if (!all.length) { active = -1; return; }
    active = (index + all.length) % all.length;
    all.forEach(function (a, i) { a.classList.toggle('is-active', i === active); });
    all[active].scrollIntoView({ block: 'nearest' });
  }
  function show(found) {
    list.innerHTML = '';
    if (!found.length) {
      var empty = document.createElement('li');
      empty.className = 'lat-palette__empty';
      empty.textContent = button.getAttribute('data-palette-empty') || '';
      list.appendChild(empty);
      active = -1;
      return;
    }
    found.forEach(function (hit) {
      var li = document.createElement('li');
      var a = document.createElement('a');
      a.className = 'lat-palette__hit';
      a.href = hit.href;
      a.setAttribute('role', 'option');
      var label = document.createElement('span');
      label.className = 'lat-palette__label';
      label.textContent = hit.label;
      a.appendChild(label);
      if (hit.hint) {
        var hint = document.createElement('span');
        hint.className = 'lat-palette__hint';
        hint.textContent = hit.hint;
        a.appendChild(hint);
      }
      li.appendChild(a);
      list.appendChild(li);
    });
    mark(0);
  }
  function search() {
    var seq = ++latest;
    fetch(url + '?q=' + encodeURIComponent(input.value), { credentials: 'same-origin', headers: { 'X-Requested-With': 'fetch' } })
      .then(function (r) { return r.json(); })
      .then(function (data) { if (seq === latest) show(data.items || []); })
      .catch(function () { if (seq === latest) show([]); });
  }
  function open() {
    overlay.classList.add('is-open');
    input.value = '';
    input.focus();
    search();
  }
  function close() {
    overlay.classList.remove('is-open');
    button.focus();
  }
  button.addEventListener('click', function (e) { e.preventDefault(); open(); });
  overlay.addEventListener('click', function (e) {
    if (e.target.closest('[data-palette-close]')) close();
  });
  input.addEventListener('input', function () {
    clearTimeout(timer);
    timer = setTimeout(search, 150);
  });
  input.addEventListener('keydown', function (e) {
    if (e.key === 'ArrowDown') { e.preventDefault(); mark(active + 1); }
    else if (e.key === 'ArrowUp') { e.preventDefault(); mark(active - 1); }
    else if (e.key === 'Enter') {
      var all = items();
      if (active >= 0 && all[active]) { e.preventDefault(); window.location.href = all[active].href; }
    } else if (e.key === 'Escape') { e.preventDefault(); close(); }
  });
  document.addEventListener('keydown', function (e) {
    if ((e.metaKey || e.ctrlKey) && !e.shiftKey && !e.altKey && (e.key === 'k' || e.key === 'K')) {
      e.preventDefault();
      if (overlay.classList.contains('is-open')) close(); else open();
    }
  });
});

// Toolbars: one tab stop each, the arrow keys moving between controls, Home
// and End jumping to the ends, so a long toolbar is not a long row of stops.
(function () {
  function controls(bar) {
    return Array.prototype.filter.call(bar.querySelectorAll('button, select, a[href], input'), function (c) {
      return !c.disabled && !c.hidden && c.offsetParent !== null;
    });
  }
  function arm(bar) {
    if (bar.getAttribute('data-lat-toolbar') === '1') return;
    bar.setAttribute('data-lat-toolbar', '1');
    var items = controls(bar);
    items.forEach(function (c, i) { c.setAttribute('tabindex', i === 0 ? '0' : '-1'); });
    bar.addEventListener('focusin', function (e) {
      controls(bar).forEach(function (c) { c.setAttribute('tabindex', c === e.target ? '0' : '-1'); });
    });
    bar.addEventListener('keydown', function (e) {
      if (['ArrowRight', 'ArrowLeft', 'Home', 'End'].indexOf(e.key) === -1) return;
      if (e.target.tagName === 'SELECT' && (e.key === 'ArrowLeft' || e.key === 'ArrowRight')) return;
      var list = controls(bar);
      var at = list.indexOf(e.target);
      if (at === -1) return;
      e.preventDefault();
      var next = e.key === 'Home' ? 0 : e.key === 'End' ? list.length - 1
        : e.key === 'ArrowRight' ? (at + 1) % list.length : (at - 1 + list.length) % list.length;
      list[next].focus();
    });
  }
  function all(root) {
    var scope = root && root.querySelectorAll ? root : document;
    scope.querySelectorAll('[role="toolbar"]').forEach(arm);
  }
  document.addEventListener('DOMContentLoaded', function () { all(document); });
  document.addEventListener('htmx:load', function (e) { all(e.target); });
  document.addEventListener('lat:richeditor:ready', function (e) { all(e.target); });
  document.addEventListener('lat:markdown:ready', function (e) { all(e.target); });
})();

// The dashboard's Manage dialog: the arrows move a row, and the form posts the
// rows in the order they stand, which is the order the widgets take.
window.lat.widget('dashlist', function (form) {
  form.addEventListener('click', function (e) {
    var btn = e.target.closest ? e.target.closest('[data-move]') : null;
    if (!btn) return;
    var row = btn.closest('.lat-dashlist__row');
    var list = row && row.parentNode;
    if (!list) return;
    if (btn.getAttribute('data-move') === 'up' && row.previousElementSibling) {
      list.insertBefore(row, row.previousElementSibling);
    } else if (btn.getAttribute('data-move') === 'down' && row.nextElementSibling) {
      list.insertBefore(row.nextElementSibling, row);
    }
    btn.focus();
  });
});

// The context side panel: open beside the body, folded under its label below
// the tablet width, following the viewport either way.
window.lat.widget('aside', function (root) {
  var fold = root.querySelector('.lat-aside__fold');
  if (!fold || !window.matchMedia) return;
  var small = window.matchMedia('(max-width: 992px)');
  function apply() { fold.open = !small.matches; }
  apply();
  if (small.addEventListener) small.addEventListener('change', apply);
  else if (small.addListener) small.addListener(apply);
});

// Sensitive: a sealed secret shown as a mask. Reveal fetches the stored value
// from `reveal/<field>` beside the form's own URL and shows it; typing
// replaces it, and sending the mask back leaves it as it was.
window.lat.widget('sensitive', function (root) {
  var input = root.querySelector('input');
  var btn = root.querySelector('.lat-sensitive__btn');
  if (!input || !btn) return;
  if (!root.hasAttribute('data-has-value')) { input.type = 'text'; return; }
  btn.hidden = false;
  var shown = false;
  function hide() {
    shown = false;
    input.type = 'password';
    btn.setAttribute('aria-pressed', 'false');
  }
  btn.addEventListener('click', function () {
    if (shown) { hide(); return; }
    var url = new URL('reveal/' + encodeURIComponent(root.getAttribute('data-field')), location.href.replace(/\/edit\/?(\?.*)?$/, '/'));
    fetch(url, { credentials: 'same-origin', headers: { 'X-Requested-With': 'fetch' } })
      .then(function (r) { return r.ok ? r.text() : Promise.reject(r.status); })
      .then(function (text) {
        input.value = text;
        input.type = 'text';
        shown = true;
        btn.setAttribute('aria-pressed', 'true');
        window.lat.emit(root, 'sensitive:revealed', { field: root.getAttribute('data-field') });
      })
      .catch(function () { window.lat.flash(root.getAttribute('data-failed') || 'Could not reveal the value.', 'error'); });
  });
  input.addEventListener('input', function () { if (input.type === 'password') input.type = 'text'; });
  if (input.form) input.form.addEventListener('submit', function () { if (shown) hide(); });
  return { hide: hide };
});