@cloudvoyant/helical-ui 0.20.1 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -414,7 +414,7 @@ var navbarMenuRootBase = "group/nav-menu relative flex max-w-max flex-1 items-ce
414
414
  var navbarMenuListBase = "group flex flex-1 list-none items-center justify-center gap-1";
415
415
  var navbarMenuItemBase = "relative";
416
416
  var navbarMenuTriggerStyle = cva8(
417
- "group inline-flex h-9 w-max items-center justify-center rounded-md bg-background px-3 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=open]:bg-accent/50 data-[state=open]:text-accent-foreground data-[state=open]:hover:bg-accent data-[state=open]:focus:bg-accent",
417
+ "group inline-flex h-9 w-max items-center justify-center rounded-md bg-background px-3 text-sm font-medium outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=open]:bg-accent/50 data-[state=open]:text-accent-foreground data-[state=open]:hover:bg-accent data-[state=open]:focus:bg-accent",
418
418
  {
419
419
  variants: {
420
420
  density: {
@@ -1207,6 +1207,3613 @@ var listboxItemIndicatorBase = "absolute inset-y-0 end-2 flex items-center justi
1207
1207
  var listboxInputBase = "w-full border-b border-input bg-transparent px-2.5 py-1.5 text-sm outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/30";
1208
1208
  var listboxEmptyBase = "px-2 py-6 text-center text-sm text-muted-foreground";
1209
1209
  var listboxLabelBase = "px-2 py-1.5 text-xs font-semibold text-muted-foreground";
1210
+ var listboxItemGroupBase = "flex flex-col py-1 first:pt-0 last:pb-0";
1211
+ var listboxItemGroupLabelBase = "px-2 py-1 text-[11px] font-semibold tracking-wider text-muted-foreground uppercase select-none";
1212
+
1213
+ // src/kbd.ts
1214
+ import { cva as cva19 } from "class-variance-authority";
1215
+ import { formatForDisplay } from "@tanstack/hotkeys";
1216
+ var kbdVariants = cva19(
1217
+ "inline-flex shrink-0 items-center justify-center gap-0.5 rounded border font-mono font-medium leading-none tracking-tight select-none",
1218
+ {
1219
+ variants: {
1220
+ variant: {
1221
+ outline: "border-border border-b-2 bg-muted/70 text-foreground shadow-2xs",
1222
+ subtle: "border-transparent bg-muted text-muted-foreground",
1223
+ solid: "border-transparent bg-primary text-primary-foreground shadow-2xs"
1224
+ },
1225
+ size: {
1226
+ sm: "min-h-4 min-w-4 px-1 py-0.5 text-[10px]",
1227
+ md: "min-h-5 min-w-5 px-1.5 py-0.5 text-xs",
1228
+ lg: "min-h-6 min-w-6 px-2 py-1 text-sm"
1229
+ }
1230
+ },
1231
+ defaultVariants: {
1232
+ variant: "outline",
1233
+ size: "md"
1234
+ }
1235
+ }
1236
+ );
1237
+ var kbdGroupBase = "inline-flex items-center gap-1";
1238
+ var KEY_LABEL_OVERRIDES = {
1239
+ Space: "Space",
1240
+ " ": "Space",
1241
+ Escape: "Esc",
1242
+ Backspace: "\u232B",
1243
+ Enter: "\u21B5",
1244
+ ArrowUp: "\u2191",
1245
+ ArrowDown: "\u2193",
1246
+ ArrowLeft: "\u2190",
1247
+ ArrowRight: "\u2192"
1248
+ };
1249
+ function formatKeyChord(chord, options) {
1250
+ const trimmed = chord.trim();
1251
+ if (!trimmed) return "";
1252
+ if (KEY_LABEL_OVERRIDES[trimmed]) {
1253
+ return KEY_LABEL_OVERRIDES[trimmed];
1254
+ }
1255
+ if (trimmed.length === 1) {
1256
+ return trimmed;
1257
+ }
1258
+ if (/^Shift\+([a-zA-Z])$/.test(trimmed)) {
1259
+ return trimmed.slice(-1).toUpperCase();
1260
+ }
1261
+ try {
1262
+ const formatted = formatForDisplay(trimmed, {
1263
+ platform: options?.platform,
1264
+ useSymbols: options?.useSymbols ?? true
1265
+ });
1266
+ return formatted || trimmed;
1267
+ } catch {
1268
+ return trimmed;
1269
+ }
1270
+ }
1271
+ function formatKeySequence(hotkey, options) {
1272
+ const steps = Array.isArray(hotkey) ? hotkey : hotkey.trim().split(/\s+/).filter(Boolean);
1273
+ return steps.map((step) => formatKeyChord(step, options));
1274
+ }
1275
+
1276
+ // src/which-key/core.ts
1277
+ var DEFAULT_JUMP_ALPHABET = "asdfghjklqwertyuiopzxcvbnm";
1278
+ function nodeMatchesMode(node, mode) {
1279
+ if (!mode || !node.mode) return true;
1280
+ if (Array.isArray(node.mode)) {
1281
+ return node.mode.includes(mode);
1282
+ }
1283
+ return node.mode === mode;
1284
+ }
1285
+ function normalizeNodeModes(node) {
1286
+ if (!node.mode) return ["normal"];
1287
+ return Array.isArray(node.mode) ? node.mode : [node.mode];
1288
+ }
1289
+ function getNodeChildren(node, rootTrie, visitedProxies = /* @__PURE__ */ new Set()) {
1290
+ let proxyChildren = {};
1291
+ if (node.proxy && node.proxy.length > 0) {
1292
+ const proxyKey = node.proxy.join(">");
1293
+ if (!visitedProxies.has(proxyKey)) {
1294
+ const nextVisited = new Set(visitedProxies);
1295
+ nextVisited.add(proxyKey);
1296
+ const target = resolveNodeInternal(rootTrie, node.proxy, void 0, nextVisited);
1297
+ if (target) {
1298
+ proxyChildren = getNodeChildren(target, rootTrie, nextVisited);
1299
+ }
1300
+ }
1301
+ }
1302
+ const expandedChildren = node.expand ? node.expand() : {};
1303
+ return {
1304
+ ...proxyChildren,
1305
+ ...expandedChildren,
1306
+ ...node.children ?? {}
1307
+ };
1308
+ }
1309
+ function resolveNodeInternal(rootTrie, path, mode, visitedProxies) {
1310
+ if (path.length === 0) return null;
1311
+ let currentMap = rootTrie;
1312
+ let currentNode = null;
1313
+ for (let i = 0; i < path.length; i += 1) {
1314
+ const step = path[i];
1315
+ if (!step) return null;
1316
+ const candidate = currentMap[step];
1317
+ if (!candidate) return null;
1318
+ if (mode && !nodeMatchesMode(candidate, mode)) return null;
1319
+ currentNode = candidate;
1320
+ if (i < path.length - 1) {
1321
+ currentMap = getNodeChildren(candidate, rootTrie, visitedProxies);
1322
+ }
1323
+ }
1324
+ return currentNode;
1325
+ }
1326
+ function resolveNode(rootTrie, path, mode) {
1327
+ return resolveNodeInternal(rootTrie, path, mode, /* @__PURE__ */ new Set());
1328
+ }
1329
+ function isGroupNode(node, rootTrie) {
1330
+ const children = getNodeChildren(node, rootTrie);
1331
+ return Object.keys(children).length > 0;
1332
+ }
1333
+ function buildWhichKeyTree(rootTrie, activePath, mode) {
1334
+ if (activePath.length === 0) {
1335
+ const items2 = Object.values(rootTrie).filter((item) => !item.hidden && nodeMatchesMode(item, mode));
1336
+ return {
1337
+ node: null,
1338
+ items: items2,
1339
+ title: "Commands",
1340
+ breadcrumb: [],
1341
+ sticky: false
1342
+ };
1343
+ }
1344
+ const node = resolveNode(rootTrie, activePath, mode);
1345
+ if (!node) {
1346
+ return {
1347
+ node: null,
1348
+ items: [],
1349
+ title: "",
1350
+ breadcrumb: activePath,
1351
+ sticky: false
1352
+ };
1353
+ }
1354
+ const childrenMap = getNodeChildren(node, rootTrie);
1355
+ const items = Object.values(childrenMap).filter((item) => !item.hidden && nodeMatchesMode(item, mode));
1356
+ let sticky = Boolean(node.sticky || node.loop);
1357
+ if (!sticky && node.proxy && node.proxy.length > 0) {
1358
+ const target = resolveNode(rootTrie, node.proxy, mode);
1359
+ if (target) {
1360
+ sticky = Boolean(target.sticky || target.loop);
1361
+ }
1362
+ }
1363
+ return {
1364
+ node,
1365
+ items,
1366
+ title: node.group ?? node.label,
1367
+ breadcrumb: [...activePath],
1368
+ sticky
1369
+ };
1370
+ }
1371
+ function flattenKeymapEntries(rootTrie, mode) {
1372
+ const entries = [];
1373
+ const seenIds = /* @__PURE__ */ new Set();
1374
+ function walk(map, chords, groupPath, visitedProxies) {
1375
+ for (const [key, node] of Object.entries(map)) {
1376
+ if (node.hidden) continue;
1377
+ if (mode && !nodeMatchesMode(node, mode)) continue;
1378
+ const nextChords = [...chords, node.key || key];
1379
+ const children = getNodeChildren(node, rootTrie, visitedProxies);
1380
+ const childKeys = Object.keys(children);
1381
+ if (childKeys.length > 0) {
1382
+ const groupTitle = node.group ?? node.label.replace(/^\+/, "");
1383
+ const nextGroupPath = [...groupPath, groupTitle];
1384
+ const nextVisited = new Set(visitedProxies);
1385
+ if (node.proxy && node.proxy.length > 0) {
1386
+ nextVisited.add(node.proxy.join(">"));
1387
+ }
1388
+ walk(children, nextChords, nextGroupPath, nextVisited);
1389
+ }
1390
+ if (node.commandId || node.action || childKeys.length === 0) {
1391
+ if (childKeys.length > 0 && !node.commandId && !node.action) {
1392
+ continue;
1393
+ }
1394
+ const sequenceText = nextChords.join(" ");
1395
+ const category = node.category ?? (groupPath.length > 0 ? groupPath[0] : "General");
1396
+ const group = groupPath.length > 0 ? groupPath.join(" / ") : category;
1397
+ const id = `${sequenceText}::${node.commandId ?? node.label}`;
1398
+ if (seenIds.has(id)) continue;
1399
+ seenIds.add(id);
1400
+ entries.push({
1401
+ id,
1402
+ chords: nextChords,
1403
+ sequenceText,
1404
+ label: node.label,
1405
+ description: node.description ?? node.label,
1406
+ group,
1407
+ category,
1408
+ mode: normalizeNodeModes(node),
1409
+ commandId: node.commandId,
1410
+ action: node.action
1411
+ });
1412
+ }
1413
+ }
1414
+ }
1415
+ walk(rootTrie, [], [], /* @__PURE__ */ new Set());
1416
+ return entries;
1417
+ }
1418
+ function findDirectionalPane(origin, candidates, direction) {
1419
+ const originCenterX = origin.x + origin.width / 2;
1420
+ const originCenterY = origin.y + origin.height / 2;
1421
+ let bestCandidate = null;
1422
+ let bestScore = Number.POSITIVE_INFINITY;
1423
+ for (const candidate of candidates) {
1424
+ if (candidate.disabled || candidate.id === origin.id) continue;
1425
+ if (candidate.width <= 0 || candidate.height <= 0) continue;
1426
+ const centerX = candidate.x + candidate.width / 2;
1427
+ const centerY = candidate.y + candidate.height / 2;
1428
+ const dx = centerX - originCenterX;
1429
+ const dy = centerY - originCenterY;
1430
+ const gapX = Math.max(
1431
+ 0,
1432
+ Math.max(origin.x, candidate.x) - Math.min(origin.x + origin.width, candidate.x + candidate.width)
1433
+ );
1434
+ const gapY = Math.max(
1435
+ 0,
1436
+ Math.max(origin.y, candidate.y) - Math.min(origin.y + origin.height, candidate.y + candidate.height)
1437
+ );
1438
+ let primaryDist = 0;
1439
+ let orthogonalDist = 0;
1440
+ switch (direction) {
1441
+ case "left":
1442
+ if (dx >= -1) continue;
1443
+ primaryDist = -dx;
1444
+ orthogonalDist = gapY;
1445
+ break;
1446
+ case "right":
1447
+ if (dx <= 1) continue;
1448
+ primaryDist = dx;
1449
+ orthogonalDist = gapY;
1450
+ break;
1451
+ case "up":
1452
+ if (dy >= -1) continue;
1453
+ primaryDist = -dy;
1454
+ orthogonalDist = gapX;
1455
+ break;
1456
+ case "down":
1457
+ if (dy <= 1) continue;
1458
+ primaryDist = dy;
1459
+ orthogonalDist = gapX;
1460
+ break;
1461
+ }
1462
+ const euclidean = Math.hypot(dx, dy);
1463
+ const score = primaryDist + orthogonalDist * 2 + euclidean * 0.01;
1464
+ if (score < bestScore) {
1465
+ bestScore = score;
1466
+ bestCandidate = candidate;
1467
+ }
1468
+ }
1469
+ return bestCandidate;
1470
+ }
1471
+ function generateJumpLabels(count, alphabet = DEFAULT_JUMP_ALPHABET) {
1472
+ if (count <= 0) return [];
1473
+ const chars = Array.from(new Set(alphabet.split("").filter(Boolean)));
1474
+ const n = chars.length;
1475
+ if (n === 0) return [];
1476
+ if (n === 1) {
1477
+ return Array.from({ length: count }, (_, idx) => chars[0].repeat(idx + 1));
1478
+ }
1479
+ if (count <= n) {
1480
+ return chars.slice(0, count);
1481
+ }
1482
+ const queue = [...chars];
1483
+ while (queue.length < count) {
1484
+ const prefix = queue.shift();
1485
+ for (const ch of chars) {
1486
+ queue.push(prefix + ch);
1487
+ if (queue.length + (chars.length - 1) >= count && queue.length >= count) {
1488
+ break;
1489
+ }
1490
+ }
1491
+ }
1492
+ return queue.slice(0, count);
1493
+ }
1494
+ var Jumplist = class {
1495
+ stack = [];
1496
+ index = -1;
1497
+ maxSize;
1498
+ constructor(maxSize = 50) {
1499
+ this.maxSize = Math.max(2, maxSize);
1500
+ }
1501
+ push(entry) {
1502
+ const current = this.stack[this.index];
1503
+ if (current && current.paneId === entry.paneId && current.element === entry.element && current.elementSelector === entry.elementSelector) {
1504
+ return;
1505
+ }
1506
+ if (this.index < this.stack.length - 1) {
1507
+ this.stack = this.stack.slice(0, this.index + 1);
1508
+ }
1509
+ this.stack.push({
1510
+ ...entry,
1511
+ timestamp: entry.timestamp ?? Date.now()
1512
+ });
1513
+ if (this.stack.length > this.maxSize) {
1514
+ this.stack.shift();
1515
+ }
1516
+ this.index = this.stack.length - 1;
1517
+ }
1518
+ back(current) {
1519
+ if (this.stack.length === 0) return null;
1520
+ if (current && this.index === this.stack.length - 1) {
1521
+ const tip = this.stack[this.index];
1522
+ if (!tip || tip.paneId !== current.paneId || tip.element !== current.element || tip.elementSelector !== current.elementSelector) {
1523
+ this.push(current);
1524
+ }
1525
+ }
1526
+ if (this.index <= 0) {
1527
+ return null;
1528
+ }
1529
+ this.index -= 1;
1530
+ return this.stack[this.index] ?? null;
1531
+ }
1532
+ forward() {
1533
+ if (this.index < 0 || this.index >= this.stack.length - 1) {
1534
+ return null;
1535
+ }
1536
+ this.index += 1;
1537
+ return this.stack[this.index] ?? null;
1538
+ }
1539
+ entries() {
1540
+ return this.stack;
1541
+ }
1542
+ currentIndex() {
1543
+ return this.index;
1544
+ }
1545
+ clear() {
1546
+ this.stack = [];
1547
+ this.index = -1;
1548
+ }
1549
+ };
1550
+ function createJumplist(maxSize = 50) {
1551
+ return new Jumplist(maxSize);
1552
+ }
1553
+
1554
+ // src/which-key/types.ts
1555
+ var globalModalState = globalThis;
1556
+ var modalEditorRegistry = globalModalState.__helicalModalEditorRegistry__ ??= /* @__PURE__ */ new WeakMap();
1557
+ var activeModalEditors = globalModalState.__helicalActiveModalEditors__ ??= /* @__PURE__ */ new Set();
1558
+ function registerModalEditor(element, target) {
1559
+ modalEditorRegistry.set(element, target);
1560
+ activeModalEditors.add(target);
1561
+ return () => {
1562
+ if (modalEditorRegistry.get(element) === target) {
1563
+ modalEditorRegistry.delete(element);
1564
+ }
1565
+ activeModalEditors.delete(target);
1566
+ };
1567
+ }
1568
+ function getModalEditor(element) {
1569
+ let curr = element;
1570
+ while (curr) {
1571
+ const found = modalEditorRegistry.get(curr);
1572
+ if (found) return found;
1573
+ curr = curr.parentElement;
1574
+ }
1575
+ return void 0;
1576
+ }
1577
+ function notifyAllModalEditors(state) {
1578
+ for (const target of activeModalEditors) {
1579
+ target.setModalState(state);
1580
+ }
1581
+ }
1582
+
1583
+ // src/which-key/presets.ts
1584
+ function createTextObjectChildren() {
1585
+ return {
1586
+ i: {
1587
+ key: "i",
1588
+ label: "+inner",
1589
+ group: "Inner Text Object",
1590
+ category: "Match / Text Objects",
1591
+ mode: ["normal", "select"],
1592
+ children: {
1593
+ w: {
1594
+ key: "w",
1595
+ label: "Inner Word",
1596
+ description: "Select inner word (iw)",
1597
+ category: "Match / Text Objects",
1598
+ commandId: "textObject.iw"
1599
+ },
1600
+ p: {
1601
+ key: "p",
1602
+ label: "Inner Paragraph",
1603
+ description: "Select inner paragraph (ip)",
1604
+ category: "Match / Text Objects",
1605
+ commandId: "textObject.ip"
1606
+ },
1607
+ c: {
1608
+ key: "c",
1609
+ label: "Inner Code Block",
1610
+ description: "Select inner code block (ic)",
1611
+ category: "Match / Text Objects",
1612
+ commandId: "textObject.ic"
1613
+ },
1614
+ n: {
1615
+ key: "n",
1616
+ label: "Inner Notice / Callout",
1617
+ description: "Select inner notice or blockquote (in)",
1618
+ category: "Match / Text Objects",
1619
+ commandId: "textObject.in"
1620
+ },
1621
+ l: {
1622
+ key: "l",
1623
+ label: "Inner List Item",
1624
+ description: "Select inner list item (il)",
1625
+ category: "Match / Text Objects",
1626
+ commandId: "textObject.il"
1627
+ }
1628
+ }
1629
+ },
1630
+ a: {
1631
+ key: "a",
1632
+ label: "+around",
1633
+ group: "Around Text Object",
1634
+ category: "Match / Text Objects",
1635
+ mode: ["normal", "select"],
1636
+ children: {
1637
+ w: {
1638
+ key: "w",
1639
+ label: "Around Word",
1640
+ description: "Select word and surrounding whitespace (aw)",
1641
+ category: "Match / Text Objects",
1642
+ commandId: "textObject.aw"
1643
+ },
1644
+ p: {
1645
+ key: "p",
1646
+ label: "Around Paragraph",
1647
+ description: "Select entire paragraph block (ap)",
1648
+ category: "Match / Text Objects",
1649
+ commandId: "textObject.ap"
1650
+ },
1651
+ c: {
1652
+ key: "c",
1653
+ label: "Around Code Block",
1654
+ description: "Select entire code block (ac)",
1655
+ category: "Match / Text Objects",
1656
+ commandId: "textObject.ac"
1657
+ },
1658
+ n: {
1659
+ key: "n",
1660
+ label: "Around Notice / Callout",
1661
+ description: "Select entire notice or blockquote (an)",
1662
+ category: "Match / Text Objects",
1663
+ commandId: "textObject.an"
1664
+ },
1665
+ l: {
1666
+ key: "l",
1667
+ label: "Around List Item",
1668
+ description: "Select entire list item (al)",
1669
+ category: "Match / Text Objects",
1670
+ commandId: "textObject.al"
1671
+ }
1672
+ }
1673
+ }
1674
+ };
1675
+ }
1676
+ function createWindowMenu() {
1677
+ return {
1678
+ key: "Control+w",
1679
+ label: "+window",
1680
+ group: "Window / Pane",
1681
+ category: "Window / Pane",
1682
+ mode: ["normal", "select"],
1683
+ children: {
1684
+ h: {
1685
+ key: "h",
1686
+ label: "Focus Pane Left",
1687
+ description: "Move focus to the pane on the left",
1688
+ category: "Window / Pane",
1689
+ commandId: "pane.left"
1690
+ },
1691
+ j: {
1692
+ key: "j",
1693
+ label: "Focus Pane Down",
1694
+ description: "Move focus to the pane below",
1695
+ category: "Window / Pane",
1696
+ commandId: "pane.down"
1697
+ },
1698
+ k: {
1699
+ key: "k",
1700
+ label: "Focus Pane Up",
1701
+ description: "Move focus to the pane above",
1702
+ category: "Window / Pane",
1703
+ commandId: "pane.up"
1704
+ },
1705
+ l: {
1706
+ key: "l",
1707
+ label: "Focus Pane Right",
1708
+ description: "Move focus to the pane on the right",
1709
+ category: "Window / Pane",
1710
+ commandId: "pane.right"
1711
+ },
1712
+ ArrowLeft: {
1713
+ key: "ArrowLeft",
1714
+ label: "Focus Pane Left",
1715
+ category: "Window / Pane",
1716
+ commandId: "pane.left",
1717
+ hidden: true
1718
+ },
1719
+ ArrowDown: {
1720
+ key: "ArrowDown",
1721
+ label: "Focus Pane Down",
1722
+ category: "Window / Pane",
1723
+ commandId: "pane.down",
1724
+ hidden: true
1725
+ },
1726
+ ArrowUp: {
1727
+ key: "ArrowUp",
1728
+ label: "Focus Pane Up",
1729
+ category: "Window / Pane",
1730
+ commandId: "pane.up",
1731
+ hidden: true
1732
+ },
1733
+ ArrowRight: {
1734
+ key: "ArrowRight",
1735
+ label: "Focus Pane Right",
1736
+ category: "Window / Pane",
1737
+ commandId: "pane.right",
1738
+ hidden: true
1739
+ },
1740
+ w: {
1741
+ key: "w",
1742
+ label: "Cycle Next Pane",
1743
+ description: "Cycle focus to the next registered pane",
1744
+ category: "Window / Pane",
1745
+ commandId: "pane.next"
1746
+ },
1747
+ W: {
1748
+ key: "W",
1749
+ label: "Cycle Previous Pane",
1750
+ description: "Cycle focus to the previous registered pane",
1751
+ category: "Window / Pane",
1752
+ commandId: "pane.prev"
1753
+ },
1754
+ s: {
1755
+ key: "s",
1756
+ label: "+sticky window",
1757
+ group: "Sticky Window Mode",
1758
+ description: "Keep Window menu open until Escape",
1759
+ category: "Window / Pane",
1760
+ sticky: true,
1761
+ loop: true,
1762
+ proxy: ["Control+w"]
1763
+ }
1764
+ }
1765
+ };
1766
+ }
1767
+ function createSpaceMenu(leaderKey = "Space", viewKey = "z") {
1768
+ const paneSlots = {};
1769
+ for (let i = 1; i <= 9; i += 1) {
1770
+ paneSlots[String(i)] = {
1771
+ key: String(i),
1772
+ label: `Focus Pane ${i}`,
1773
+ description: `Switch focus directly to pane #${i}`,
1774
+ category: "Window / Pane",
1775
+ commandId: `pane.focus.${i}`,
1776
+ hidden: i > 4
1777
+ };
1778
+ }
1779
+ return {
1780
+ key: leaderKey,
1781
+ label: "+leader",
1782
+ group: "Leader",
1783
+ category: "Leader",
1784
+ mode: ["normal", "select"],
1785
+ children: {
1786
+ "?": {
1787
+ key: "?",
1788
+ label: "Explore Keybindings",
1789
+ description: "Open searchable keybinding exploration menu (<leader>?)",
1790
+ category: "Space",
1791
+ commandId: "whichKey.openExplorer"
1792
+ },
1793
+ w: {
1794
+ key: "w",
1795
+ label: "+window",
1796
+ group: "Window / Pane",
1797
+ description: "Spatial and indexed pane navigation",
1798
+ category: "Window / Pane",
1799
+ proxy: ["Control+w"]
1800
+ },
1801
+ j: {
1802
+ key: "j",
1803
+ label: "Jump to Element",
1804
+ description: "Show 2D home-row jump labels over visible controls",
1805
+ category: "Navigation",
1806
+ commandId: "jump.start"
1807
+ },
1808
+ g: {
1809
+ key: "g",
1810
+ label: "+goto",
1811
+ group: "Goto",
1812
+ description: "Go to locations and boundaries",
1813
+ category: "Goto",
1814
+ proxy: ["g"]
1815
+ },
1816
+ v: {
1817
+ key: "v",
1818
+ label: "+view",
1819
+ group: "View / Scroll",
1820
+ description: "Scroll and align viewport",
1821
+ category: "View",
1822
+ proxy: [viewKey]
1823
+ },
1824
+ k: {
1825
+ key: "k",
1826
+ label: "+preset",
1827
+ group: "Keybinding Preset",
1828
+ description: "Switch modal grammar (Helix / Vim / Kakoune)",
1829
+ category: "Space",
1830
+ children: {
1831
+ h: {
1832
+ key: "h",
1833
+ label: "Helix Preset",
1834
+ description: "Switch to Helix selection-first grammar (default)",
1835
+ category: "Preset",
1836
+ commandId: "preset.helix"
1837
+ },
1838
+ v: {
1839
+ key: "v",
1840
+ label: "Vim Preset",
1841
+ description: "Switch to Vim operator-motion grammar",
1842
+ category: "Preset",
1843
+ commandId: "preset.vim"
1844
+ },
1845
+ k: {
1846
+ key: "k",
1847
+ label: "Kakoune Preset",
1848
+ description: "Switch to Kakoune object-verb grammar",
1849
+ category: "Preset",
1850
+ commandId: "preset.kakoune"
1851
+ }
1852
+ }
1853
+ },
1854
+ ...paneSlots
1855
+ }
1856
+ };
1857
+ }
1858
+ function createViewMenu(key, centerKey) {
1859
+ return {
1860
+ key,
1861
+ label: "+view",
1862
+ group: "View",
1863
+ category: "View",
1864
+ mode: ["normal", "select"],
1865
+ children: {
1866
+ [centerKey]: {
1867
+ key: centerKey,
1868
+ label: "Center Viewport",
1869
+ description: "Center the focused item in the viewport",
1870
+ category: "View",
1871
+ commandId: "view.center"
1872
+ },
1873
+ c: {
1874
+ key: "c",
1875
+ label: "Center Viewport",
1876
+ description: "Center the focused item in the viewport",
1877
+ category: "View",
1878
+ commandId: "view.center"
1879
+ },
1880
+ t: {
1881
+ key: "t",
1882
+ label: "Align Top",
1883
+ description: "Align focused item to top of viewport",
1884
+ category: "View",
1885
+ commandId: "view.top"
1886
+ },
1887
+ b: {
1888
+ key: "b",
1889
+ label: "Align Bottom",
1890
+ description: "Align focused item to bottom of viewport",
1891
+ category: "View",
1892
+ commandId: "view.bottom"
1893
+ },
1894
+ j: {
1895
+ key: "j",
1896
+ label: "Scroll Down",
1897
+ description: "Scroll active pane down",
1898
+ category: "View",
1899
+ commandId: "view.scrollDown"
1900
+ },
1901
+ k: {
1902
+ key: "k",
1903
+ label: "Scroll Up",
1904
+ description: "Scroll active pane up",
1905
+ category: "View",
1906
+ commandId: "view.scrollUp"
1907
+ }
1908
+ }
1909
+ };
1910
+ }
1911
+ function createUnimpairedMenus() {
1912
+ return {
1913
+ "[": {
1914
+ key: "[",
1915
+ label: "+prev",
1916
+ group: "Previous (Unimpaired)",
1917
+ category: "Unimpaired",
1918
+ mode: ["normal", "select"],
1919
+ children: {
1920
+ s: {
1921
+ key: "s",
1922
+ label: "Previous Section",
1923
+ description: "Jump to previous heading or PageSection",
1924
+ category: "Unimpaired",
1925
+ commandId: "section.prev"
1926
+ },
1927
+ t: {
1928
+ key: "t",
1929
+ label: "Previous Tab",
1930
+ description: "Switch to previous tab in active tablist ([t)",
1931
+ category: "Unimpaired",
1932
+ commandId: "tab.prev"
1933
+ },
1934
+ p: {
1935
+ key: "p",
1936
+ label: "Previous Paragraph / Section",
1937
+ description: "Jump to previous paragraph or section",
1938
+ category: "Unimpaired",
1939
+ commandId: "motion.paragraphBackward"
1940
+ },
1941
+ f: {
1942
+ key: "f",
1943
+ label: "Previous Focusable Block",
1944
+ description: "Move focus to previous interactive control",
1945
+ category: "Unimpaired",
1946
+ commandId: "focus.prevBlock"
1947
+ },
1948
+ Space: {
1949
+ key: "Space",
1950
+ label: "Blank Line Above",
1951
+ description: "Insert blank line above current block",
1952
+ category: "Unimpaired",
1953
+ commandId: "operator.openAbove"
1954
+ }
1955
+ }
1956
+ },
1957
+ "]": {
1958
+ key: "]",
1959
+ label: "+next",
1960
+ group: "Next (Unimpaired)",
1961
+ category: "Unimpaired",
1962
+ mode: ["normal", "select"],
1963
+ children: {
1964
+ s: {
1965
+ key: "s",
1966
+ label: "Next Section",
1967
+ description: "Jump to next heading or PageSection",
1968
+ category: "Unimpaired",
1969
+ commandId: "section.next"
1970
+ },
1971
+ t: {
1972
+ key: "t",
1973
+ label: "Next Tab",
1974
+ description: "Switch to next tab in active tablist (]t)",
1975
+ category: "Unimpaired",
1976
+ commandId: "tab.next"
1977
+ },
1978
+ p: {
1979
+ key: "p",
1980
+ label: "Next Paragraph / Section",
1981
+ description: "Jump to next paragraph or section",
1982
+ category: "Unimpaired",
1983
+ commandId: "motion.paragraphForward"
1984
+ },
1985
+ f: {
1986
+ key: "f",
1987
+ label: "Next Focusable Block",
1988
+ description: "Move focus to next interactive control",
1989
+ category: "Unimpaired",
1990
+ commandId: "focus.nextBlock"
1991
+ },
1992
+ Space: {
1993
+ key: "Space",
1994
+ label: "Blank Line Below",
1995
+ description: "Insert blank line below current block",
1996
+ category: "Unimpaired",
1997
+ commandId: "operator.openBelow"
1998
+ }
1999
+ }
2000
+ }
2001
+ };
2002
+ }
2003
+ function createSharedMotionsAndOperators() {
2004
+ return {
2005
+ h: {
2006
+ key: "h",
2007
+ label: "Move Left",
2008
+ description: "Move cursor or focus left",
2009
+ category: "Motion",
2010
+ mode: ["normal", "select"],
2011
+ commandId: "motion.left",
2012
+ hidden: true
2013
+ },
2014
+ j: {
2015
+ key: "j",
2016
+ label: "Move Down / Next Item",
2017
+ description: "Step focus to next item or line down",
2018
+ category: "Motion",
2019
+ mode: ["normal", "select"],
2020
+ commandId: "motion.down",
2021
+ hidden: true
2022
+ },
2023
+ k: {
2024
+ key: "k",
2025
+ label: "Move Up / Previous Item",
2026
+ description: "Step focus to previous item or line up",
2027
+ category: "Motion",
2028
+ mode: ["normal", "select"],
2029
+ commandId: "motion.up",
2030
+ hidden: true
2031
+ },
2032
+ l: {
2033
+ key: "l",
2034
+ label: "Move Right",
2035
+ description: "Move cursor or focus right",
2036
+ category: "Motion",
2037
+ mode: ["normal", "select"],
2038
+ commandId: "motion.right",
2039
+ hidden: true
2040
+ },
2041
+ w: {
2042
+ key: "w",
2043
+ label: "Next Word",
2044
+ description: "Select or move to next word (w)",
2045
+ category: "Motion",
2046
+ mode: ["normal", "select"],
2047
+ commandId: "motion.wordForward"
2048
+ },
2049
+ b: {
2050
+ key: "b",
2051
+ label: "Previous Word",
2052
+ description: "Select or move to previous word (b)",
2053
+ category: "Motion",
2054
+ mode: ["normal", "select"],
2055
+ commandId: "motion.wordBackward"
2056
+ },
2057
+ e: {
2058
+ key: "e",
2059
+ label: "Word End",
2060
+ description: "Select or move to end of word (e)",
2061
+ category: "Motion",
2062
+ mode: ["normal", "select"],
2063
+ commandId: "motion.wordEnd"
2064
+ },
2065
+ "{": {
2066
+ key: "{",
2067
+ label: "Previous Paragraph / Section",
2068
+ description: "Jump to previous paragraph or section ({)",
2069
+ category: "Motion",
2070
+ mode: ["normal", "select"],
2071
+ commandId: "motion.paragraphBackward"
2072
+ },
2073
+ "}": {
2074
+ key: "}",
2075
+ label: "Next Paragraph / Section",
2076
+ description: "Jump to next paragraph or section (})",
2077
+ category: "Motion",
2078
+ mode: ["normal", "select"],
2079
+ commandId: "motion.paragraphForward"
2080
+ },
2081
+ "0": {
2082
+ key: "0",
2083
+ label: "Start of Line / Group",
2084
+ description: "Move to beginning of line or group (0)",
2085
+ category: "Motion",
2086
+ mode: ["normal", "select"],
2087
+ commandId: "motion.lineStart"
2088
+ },
2089
+ $: {
2090
+ key: "$",
2091
+ label: "End of Line / Group",
2092
+ description: "Move to end of line or group ($)",
2093
+ category: "Motion",
2094
+ mode: ["normal", "select"],
2095
+ commandId: "motion.lineEnd"
2096
+ },
2097
+ i: {
2098
+ key: "i",
2099
+ label: "Insert Mode",
2100
+ description: "Enter insert mode at start of selection or control",
2101
+ category: "Mode / Operator",
2102
+ mode: ["normal", "select"],
2103
+ commandId: "operator.insertStart"
2104
+ },
2105
+ a: {
2106
+ key: "a",
2107
+ label: "Append / Insert After",
2108
+ description: "Enter insert mode at end of selection or control",
2109
+ category: "Mode / Operator",
2110
+ mode: ["normal"],
2111
+ commandId: "operator.appendEnd"
2112
+ },
2113
+ o: {
2114
+ key: "o",
2115
+ label: "Open Line Below",
2116
+ description: "Open new paragraph below and enter insert mode",
2117
+ category: "Mode / Operator",
2118
+ mode: ["normal", "select"],
2119
+ commandId: "operator.openBelow"
2120
+ },
2121
+ O: {
2122
+ key: "O",
2123
+ label: "Open Line Above",
2124
+ description: "Open new paragraph above and enter insert mode",
2125
+ category: "Mode / Operator",
2126
+ mode: ["normal", "select"],
2127
+ commandId: "operator.openAbove"
2128
+ },
2129
+ d: {
2130
+ key: "d",
2131
+ label: "Delete Selection",
2132
+ description: "Delete active selection and store in register",
2133
+ category: "Operator",
2134
+ mode: ["normal", "select"],
2135
+ commandId: "operator.delete"
2136
+ },
2137
+ c: {
2138
+ key: "c",
2139
+ label: "Change Selection",
2140
+ description: "Delete selection and enter insert mode",
2141
+ category: "Operator",
2142
+ mode: ["normal", "select"],
2143
+ commandId: "operator.change"
2144
+ },
2145
+ y: {
2146
+ key: "y",
2147
+ label: "Yank Selection",
2148
+ description: "Copy selection slice into register",
2149
+ category: "Operator",
2150
+ mode: ["normal", "select"],
2151
+ commandId: "operator.yank"
2152
+ },
2153
+ p: {
2154
+ key: "p",
2155
+ label: "Paste After",
2156
+ description: "Paste yanked slice after selection",
2157
+ category: "Operator",
2158
+ mode: ["normal", "select"],
2159
+ commandId: "operator.pasteAfter"
2160
+ },
2161
+ P: {
2162
+ key: "P",
2163
+ label: "Paste Before",
2164
+ description: "Paste yanked slice before selection",
2165
+ category: "Operator",
2166
+ mode: ["normal", "select"],
2167
+ commandId: "operator.pasteBefore"
2168
+ },
2169
+ u: {
2170
+ key: "u",
2171
+ label: "Undo",
2172
+ description: "Undo last editor transaction",
2173
+ category: "Operator",
2174
+ mode: ["normal", "select"],
2175
+ commandId: "operator.undo"
2176
+ },
2177
+ "Control+o": {
2178
+ key: "Control+o",
2179
+ label: "Jump Back",
2180
+ description: "Navigate backward in Jumplist history",
2181
+ category: "Navigation",
2182
+ mode: ["normal", "select"],
2183
+ commandId: "jumplist.back"
2184
+ },
2185
+ "Control+i": {
2186
+ key: "Control+i",
2187
+ label: "Jump Forward",
2188
+ description: "Navigate forward in Jumplist history",
2189
+ category: "Navigation",
2190
+ mode: ["normal", "select"],
2191
+ commandId: "jumplist.forward"
2192
+ },
2193
+ "?": {
2194
+ key: "?",
2195
+ label: "Explore Keybindings",
2196
+ description: "Open searchable keybinding exploration menu (?)",
2197
+ category: "Navigation",
2198
+ mode: ["normal", "select"],
2199
+ commandId: "whichKey.openExplorer"
2200
+ }
2201
+ };
2202
+ }
2203
+ function createHelixPreset(leaderKey = "Space") {
2204
+ const textObjects = createTextObjectChildren();
2205
+ const unimpaired = createUnimpairedMenus();
2206
+ return {
2207
+ ...createSharedMotionsAndOperators(),
2208
+ [leaderKey]: createSpaceMenu(leaderKey, "z"),
2209
+ "Control+w": createWindowMenu(),
2210
+ g: {
2211
+ key: "g",
2212
+ label: "+goto",
2213
+ group: "Goto",
2214
+ category: "Goto",
2215
+ mode: ["normal", "select"],
2216
+ children: {
2217
+ g: {
2218
+ key: "g",
2219
+ label: "Go to Top",
2220
+ description: "Jump to first item or top of document (gg)",
2221
+ category: "Goto",
2222
+ commandId: "motion.docStart"
2223
+ },
2224
+ e: {
2225
+ key: "e",
2226
+ label: "Go to End",
2227
+ description: "Jump to last item or bottom of document (ge)",
2228
+ category: "Goto",
2229
+ commandId: "motion.docEnd"
2230
+ },
2231
+ h: {
2232
+ key: "h",
2233
+ label: "Line / Group Start",
2234
+ description: "Move to start of line or control group (gh)",
2235
+ category: "Goto",
2236
+ commandId: "motion.lineStart"
2237
+ },
2238
+ l: {
2239
+ key: "l",
2240
+ label: "Line / Group End",
2241
+ description: "Move to end of line or control group (gl)",
2242
+ category: "Goto",
2243
+ commandId: "motion.lineEnd"
2244
+ },
2245
+ c: {
2246
+ key: "c",
2247
+ label: "Window Center",
2248
+ description: "Jump to center of visible viewport (gc)",
2249
+ category: "Goto",
2250
+ commandId: "view.center"
2251
+ },
2252
+ b: {
2253
+ key: "b",
2254
+ label: "Window Bottom",
2255
+ description: "Jump to bottom of visible viewport (gb)",
2256
+ category: "Goto",
2257
+ commandId: "view.bottom"
2258
+ },
2259
+ n: {
2260
+ key: "n",
2261
+ label: "Next Tab / Section",
2262
+ description: "Switch to next tab or section (gn)",
2263
+ category: "Goto",
2264
+ commandId: "tab.next"
2265
+ },
2266
+ p: {
2267
+ key: "p",
2268
+ label: "Previous Tab / Section",
2269
+ description: "Switch to previous tab or section (gp)",
2270
+ category: "Goto",
2271
+ commandId: "tab.prev"
2272
+ },
2273
+ t: {
2274
+ key: "t",
2275
+ label: "Next Tab",
2276
+ description: "Switch to next tab or section (gt)",
2277
+ category: "Goto",
2278
+ commandId: "tab.next"
2279
+ },
2280
+ T: {
2281
+ key: "T",
2282
+ label: "Previous Tab",
2283
+ description: "Switch to previous tab or section (gT)",
2284
+ category: "Goto",
2285
+ commandId: "tab.prev"
2286
+ },
2287
+ w: {
2288
+ key: "w",
2289
+ label: "Jump Label (2D)",
2290
+ description: "Overlay 2D home-row jump labels (gw)",
2291
+ category: "Goto",
2292
+ commandId: "jump.start"
2293
+ }
2294
+ }
2295
+ },
2296
+ z: createViewMenu("z", "z"),
2297
+ Z: {
2298
+ key: "Z",
2299
+ label: "+sticky view",
2300
+ group: "View (Sticky)",
2301
+ description: "Lock View menu open until Escape",
2302
+ category: "View",
2303
+ mode: ["normal", "select"],
2304
+ sticky: true,
2305
+ loop: true,
2306
+ proxy: ["z"]
2307
+ },
2308
+ m: {
2309
+ key: "m",
2310
+ label: "+match",
2311
+ group: "Match / Text Objects",
2312
+ category: "Match / Text Objects",
2313
+ mode: ["normal", "select"],
2314
+ children: {
2315
+ m: {
2316
+ key: "m",
2317
+ label: "Goto Matching Bracket / Flip",
2318
+ description: "Flip selection anchor and head (mm)",
2319
+ category: "Match / Text Objects",
2320
+ commandId: "selection.flip"
2321
+ },
2322
+ ...textObjects
2323
+ }
2324
+ },
2325
+ v: {
2326
+ key: "v",
2327
+ label: "Select / Extend Mode",
2328
+ description: "Toggle Helix select/extend mode (v)",
2329
+ category: "Selection",
2330
+ mode: ["normal", "select"],
2331
+ commandId: "mode.toggleSelect"
2332
+ },
2333
+ x: {
2334
+ key: "x",
2335
+ label: "Select Line",
2336
+ description: "Select current line or extend to next line (x)",
2337
+ category: "Selection",
2338
+ mode: ["normal", "select"],
2339
+ commandId: "motion.lineSelect"
2340
+ },
2341
+ ";": {
2342
+ key: ";",
2343
+ label: "Collapse Selection",
2344
+ description: "Collapse selection to cursor head (;)",
2345
+ category: "Selection",
2346
+ mode: ["normal", "select"],
2347
+ commandId: "selection.collapse"
2348
+ },
2349
+ "Alt+;": {
2350
+ key: "Alt+;",
2351
+ label: "Flip Selection Direction",
2352
+ description: "Swap selection anchor and head (Alt-;)",
2353
+ category: "Selection",
2354
+ mode: ["normal", "select"],
2355
+ commandId: "selection.flip"
2356
+ },
2357
+ C: {
2358
+ key: "C",
2359
+ label: "Copy Selection Below",
2360
+ description: "Add secondary cursor on next line/block (C)",
2361
+ category: "Selection",
2362
+ mode: ["normal", "select"],
2363
+ commandId: "selection.addCursorBelow"
2364
+ },
2365
+ ",": {
2366
+ key: ",",
2367
+ label: "Keep Primary Selection",
2368
+ description: "Clear secondary cursors and keep primary selection (,)",
2369
+ category: "Selection",
2370
+ mode: ["normal", "select"],
2371
+ commandId: "selection.keepPrimary"
2372
+ },
2373
+ U: {
2374
+ key: "U",
2375
+ label: "Redo",
2376
+ description: "Redo last undone editor transaction (U)",
2377
+ category: "Operator",
2378
+ mode: ["normal", "select"],
2379
+ commandId: "operator.redo"
2380
+ },
2381
+ ...unimpaired
2382
+ };
2383
+ }
2384
+ function createVimPreset(leaderKey = "Space") {
2385
+ const textObjects = createTextObjectChildren();
2386
+ const unimpaired = createUnimpairedMenus();
2387
+ return {
2388
+ ...createSharedMotionsAndOperators(),
2389
+ [leaderKey]: createSpaceMenu(leaderKey, "z"),
2390
+ "Control+w": createWindowMenu(),
2391
+ g: {
2392
+ key: "g",
2393
+ label: "+goto",
2394
+ group: "Goto",
2395
+ category: "Goto",
2396
+ mode: ["normal", "select"],
2397
+ children: {
2398
+ g: {
2399
+ key: "g",
2400
+ label: "First Line / Top",
2401
+ description: "Jump to first item or top of document (gg)",
2402
+ category: "Goto",
2403
+ commandId: "motion.docStart"
2404
+ },
2405
+ e: {
2406
+ key: "e",
2407
+ label: "Backward Word End / Bottom",
2408
+ description: "Jump to bottom of pane or document (ge)",
2409
+ category: "Goto",
2410
+ commandId: "motion.docEnd"
2411
+ },
2412
+ h: {
2413
+ key: "h",
2414
+ label: "Start of Line",
2415
+ description: "Move to start of line or group (gh)",
2416
+ category: "Goto",
2417
+ commandId: "motion.lineStart"
2418
+ },
2419
+ l: {
2420
+ key: "l",
2421
+ label: "End of Line",
2422
+ description: "Move to end of line or group (gl)",
2423
+ category: "Goto",
2424
+ commandId: "motion.lineEnd"
2425
+ },
2426
+ t: {
2427
+ key: "t",
2428
+ label: "Next Tab / Section",
2429
+ description: "Go to next tab or section (gt)",
2430
+ category: "Goto",
2431
+ commandId: "tab.next"
2432
+ },
2433
+ T: {
2434
+ key: "T",
2435
+ label: "Previous Tab / Section",
2436
+ description: "Go to previous tab or section (gT)",
2437
+ category: "Goto",
2438
+ commandId: "tab.prev"
2439
+ },
2440
+ n: {
2441
+ key: "n",
2442
+ label: "Next Tab / Section",
2443
+ description: "Go to next tab or section (gn)",
2444
+ category: "Goto",
2445
+ commandId: "tab.next"
2446
+ },
2447
+ p: {
2448
+ key: "p",
2449
+ label: "Previous Tab / Section",
2450
+ description: "Go to previous tab or section (gp)",
2451
+ category: "Goto",
2452
+ commandId: "tab.prev"
2453
+ },
2454
+ w: {
2455
+ key: "w",
2456
+ label: "Jump Label (2D)",
2457
+ description: "Overlay 2D home-row jump labels (gw)",
2458
+ category: "Goto",
2459
+ commandId: "jump.start"
2460
+ }
2461
+ }
2462
+ },
2463
+ G: {
2464
+ key: "G",
2465
+ label: "Last Line / Bottom",
2466
+ description: "Jump immediately to bottom of pane or document (G)",
2467
+ category: "Motion",
2468
+ mode: ["normal", "select"],
2469
+ commandId: "motion.docEnd"
2470
+ },
2471
+ s: {
2472
+ key: "s",
2473
+ label: "Flash / Sneak Jump",
2474
+ description: "Trigger 2D forward jump labels (s)",
2475
+ category: "Navigation",
2476
+ mode: ["normal", "select"],
2477
+ commandId: "jump.start"
2478
+ },
2479
+ v: {
2480
+ key: "v",
2481
+ label: "Visual Mode",
2482
+ description: "Toggle characterwise Visual selection mode (v)",
2483
+ category: "Mode",
2484
+ mode: ["normal", "select"],
2485
+ commandId: "mode.toggleSelect"
2486
+ },
2487
+ V: {
2488
+ key: "V",
2489
+ label: "Visual Line Mode",
2490
+ description: "Select entire line in Visual Line mode (V)",
2491
+ category: "Mode",
2492
+ mode: ["normal", "select"],
2493
+ commandId: "motion.lineSelect"
2494
+ },
2495
+ z: createViewMenu("z", "z"),
2496
+ m: {
2497
+ key: "m",
2498
+ label: "+text-objects",
2499
+ group: "Text Objects",
2500
+ category: "Match / Text Objects",
2501
+ mode: ["normal", "select"],
2502
+ children: textObjects
2503
+ },
2504
+ "Control+r": {
2505
+ key: "Control+r",
2506
+ label: "Redo",
2507
+ description: "Redo last undone editor transaction (Ctrl-r)",
2508
+ category: "Operator",
2509
+ mode: ["normal", "select"],
2510
+ commandId: "operator.redo"
2511
+ },
2512
+ ...unimpaired
2513
+ };
2514
+ }
2515
+ function createKakounePreset(leaderKey = "Space") {
2516
+ const textObjects = createTextObjectChildren();
2517
+ const unimpaired = createUnimpairedMenus();
2518
+ return {
2519
+ ...createSharedMotionsAndOperators(),
2520
+ [leaderKey]: createSpaceMenu(leaderKey, "v"),
2521
+ "Control+w": createWindowMenu(),
2522
+ g: {
2523
+ key: "g",
2524
+ label: "+goto",
2525
+ group: "Goto",
2526
+ category: "Goto",
2527
+ mode: ["normal", "select"],
2528
+ children: {
2529
+ g: {
2530
+ key: "g",
2531
+ label: "Buffer Top",
2532
+ description: "Go to top of buffer or first item (gg)",
2533
+ category: "Goto",
2534
+ commandId: "motion.docStart"
2535
+ },
2536
+ k: {
2537
+ key: "k",
2538
+ label: "Buffer Top",
2539
+ description: "Go to top of buffer (gk)",
2540
+ category: "Goto",
2541
+ commandId: "motion.docStart"
2542
+ },
2543
+ j: {
2544
+ key: "j",
2545
+ label: "Buffer Bottom",
2546
+ description: "Go to bottom of buffer (gj)",
2547
+ category: "Goto",
2548
+ commandId: "motion.docEnd"
2549
+ },
2550
+ e: {
2551
+ key: "e",
2552
+ label: "Buffer End",
2553
+ description: "Go to end of buffer (ge)",
2554
+ category: "Goto",
2555
+ commandId: "motion.docEnd"
2556
+ },
2557
+ h: {
2558
+ key: "h",
2559
+ label: "Line Start",
2560
+ description: "Go to start of line or group (gh)",
2561
+ category: "Goto",
2562
+ commandId: "motion.lineStart"
2563
+ },
2564
+ l: {
2565
+ key: "l",
2566
+ label: "Line End",
2567
+ description: "Go to end of line or group (gl)",
2568
+ category: "Goto",
2569
+ commandId: "motion.lineEnd"
2570
+ },
2571
+ c: {
2572
+ key: "c",
2573
+ label: "Window Center",
2574
+ description: "Go to center of visible window (gc)",
2575
+ category: "Goto",
2576
+ commandId: "view.center"
2577
+ },
2578
+ b: {
2579
+ key: "b",
2580
+ label: "Window Bottom",
2581
+ description: "Go to bottom of visible window (gb)",
2582
+ category: "Goto",
2583
+ commandId: "view.bottom"
2584
+ },
2585
+ a: {
2586
+ key: "a",
2587
+ label: "Previous Location",
2588
+ description: "Jump to alternate / previous location (ga)",
2589
+ category: "Goto",
2590
+ commandId: "jumplist.back"
2591
+ },
2592
+ n: {
2593
+ key: "n",
2594
+ label: "Next Tab / Section",
2595
+ description: "Switch to next tab or section (gn)",
2596
+ category: "Goto",
2597
+ commandId: "tab.next"
2598
+ },
2599
+ p: {
2600
+ key: "p",
2601
+ label: "Previous Tab / Section",
2602
+ description: "Switch to previous tab or section (gp)",
2603
+ category: "Goto",
2604
+ commandId: "tab.prev"
2605
+ },
2606
+ t: {
2607
+ key: "t",
2608
+ label: "Next Tab",
2609
+ description: "Switch to next tab or section (gt)",
2610
+ category: "Goto",
2611
+ commandId: "tab.next"
2612
+ },
2613
+ T: {
2614
+ key: "T",
2615
+ label: "Previous Tab",
2616
+ description: "Switch to previous tab or section (gT)",
2617
+ category: "Goto",
2618
+ commandId: "tab.prev"
2619
+ },
2620
+ w: {
2621
+ key: "w",
2622
+ label: "Jump Label (2D)",
2623
+ description: "Overlay 2D home-row jump labels (gw)",
2624
+ category: "Goto",
2625
+ commandId: "jump.start"
2626
+ }
2627
+ }
2628
+ },
2629
+ v: createViewMenu("v", "v"),
2630
+ V: {
2631
+ key: "V",
2632
+ label: "+lock view",
2633
+ group: "View (Lock)",
2634
+ description: "Lock Kakoune View mode open until Escape (V)",
2635
+ category: "View",
2636
+ mode: ["normal", "select"],
2637
+ sticky: true,
2638
+ loop: true,
2639
+ proxy: ["v"]
2640
+ },
2641
+ m: {
2642
+ key: "m",
2643
+ label: "+object",
2644
+ group: "Object / Match",
2645
+ category: "Match / Text Objects",
2646
+ mode: ["normal", "select"],
2647
+ children: textObjects
2648
+ },
2649
+ x: {
2650
+ key: "x",
2651
+ label: "Select Line",
2652
+ description: "Select current line (x)",
2653
+ category: "Selection",
2654
+ mode: ["normal", "select"],
2655
+ commandId: "motion.lineSelect"
2656
+ },
2657
+ ";": {
2658
+ key: ";",
2659
+ label: "Reduce Selection to Cursor",
2660
+ description: "Collapse selection to single cursor (;)",
2661
+ category: "Selection",
2662
+ mode: ["normal", "select"],
2663
+ commandId: "selection.collapse"
2664
+ },
2665
+ "Alt+;": {
2666
+ key: "Alt+;",
2667
+ label: "Flip Selection Direction",
2668
+ description: "Swap anchor and cursor (Alt-;)",
2669
+ category: "Selection",
2670
+ mode: ["normal", "select"],
2671
+ commandId: "selection.flip"
2672
+ },
2673
+ C: {
2674
+ key: "C",
2675
+ label: "Copy Selection on Next Line",
2676
+ description: "Add secondary selection on next line (C)",
2677
+ category: "Selection",
2678
+ mode: ["normal", "select"],
2679
+ commandId: "selection.addCursorBelow"
2680
+ },
2681
+ ",": {
2682
+ key: ",",
2683
+ label: "Keep Main Selection",
2684
+ description: "Clear secondary selections (,)",
2685
+ category: "Selection",
2686
+ mode: ["normal", "select"],
2687
+ commandId: "selection.keepPrimary"
2688
+ },
2689
+ U: {
2690
+ key: "U",
2691
+ label: "Redo",
2692
+ description: "Redo last undone change (U)",
2693
+ category: "Operator",
2694
+ mode: ["normal", "select"],
2695
+ commandId: "operator.redo"
2696
+ },
2697
+ ...unimpaired
2698
+ };
2699
+ }
2700
+ function getPresetKeymap(preset, leaderKey = "Space") {
2701
+ switch (preset) {
2702
+ case "vim":
2703
+ return createVimPreset(leaderKey);
2704
+ case "kakoune":
2705
+ return createKakounePreset(leaderKey);
2706
+ case "helix":
2707
+ default:
2708
+ return createHelixPreset(leaderKey);
2709
+ }
2710
+ }
2711
+
2712
+ // src/which-key/controller.ts
2713
+ import { isModifierKey, normalizeKeyName, parseKeyboardEvent } from "@tanstack/hotkeys";
2714
+ import { trackDismissableBranch } from "@zag-js/dismissable";
2715
+ import { getFirstFocusable, getFocusables, isEditableElement, isInView } from "@zag-js/dom-query";
2716
+ import { setInteractionModality, trackInteractionModality } from "@zag-js/focus-visible";
2717
+ import { createLiveRegion } from "@zag-js/live-region";
2718
+ function mergeKeymapTrees(base, overlay) {
2719
+ const result = { ...base };
2720
+ for (const [key, node] of Object.entries(overlay)) {
2721
+ const existing = result[key];
2722
+ if (existing && existing.children && node.children) {
2723
+ result[key] = {
2724
+ ...existing,
2725
+ ...node,
2726
+ children: mergeKeymapTrees(existing.children, node.children)
2727
+ };
2728
+ } else {
2729
+ result[key] = node;
2730
+ }
2731
+ }
2732
+ return result;
2733
+ }
2734
+ function isElementLike(value) {
2735
+ if (!value || typeof value !== "object") return false;
2736
+ if (typeof Element !== "undefined" && value instanceof Element) return true;
2737
+ return "parentElement" in value || "tagName" in value;
2738
+ }
2739
+ function isHTMLElementLike(value) {
2740
+ if (!value || typeof value !== "object") return false;
2741
+ if (typeof HTMLElement !== "undefined" && value instanceof HTMLElement) {
2742
+ return true;
2743
+ }
2744
+ return "parentElement" in value || "tagName" in value;
2745
+ }
2746
+ function isTextEntryElement(el) {
2747
+ if (!el || !isHTMLElementLike(el)) return false;
2748
+ if (getModalEditor(el)) return true;
2749
+ if (el.isContentEditable || el.getAttribute?.("contenteditable") === "true") {
2750
+ return true;
2751
+ }
2752
+ const tag = typeof el.tagName === "string" ? el.tagName.toLowerCase() : "";
2753
+ if (tag === "textarea") {
2754
+ return !el.disabled && !el.readOnly;
2755
+ }
2756
+ if (tag === "input") {
2757
+ const input = el;
2758
+ if (input.disabled || input.readOnly) return false;
2759
+ const nonTextTypes = /* @__PURE__ */ new Set([
2760
+ "button",
2761
+ "checkbox",
2762
+ "color",
2763
+ "file",
2764
+ "hidden",
2765
+ "image",
2766
+ "radio",
2767
+ "range",
2768
+ "reset",
2769
+ "submit"
2770
+ ]);
2771
+ return !nonTextTypes.has((input.type || "text").toLowerCase());
2772
+ }
2773
+ try {
2774
+ return isEditableElement(el);
2775
+ } catch {
2776
+ return false;
2777
+ }
2778
+ }
2779
+ function eventToChordKeys(event) {
2780
+ const rawKey = event.key;
2781
+ if (!rawKey) return [];
2782
+ const normalizedName = normalizeKeyName(rawKey);
2783
+ if (isModifierKey(normalizedName) || rawKey === "Shift" || rawKey === "Control" || rawKey === "Alt" || rawKey === "Meta") {
2784
+ return [];
2785
+ }
2786
+ const hasCtrl = event.ctrlKey;
2787
+ const hasAlt = event.altKey;
2788
+ const hasMeta = event.metaKey;
2789
+ const hasShift = event.shiftKey;
2790
+ const baseKey = rawKey === " " || event.code === "Space" ? "Space" : rawKey;
2791
+ if (hasCtrl || hasAlt || hasMeta) {
2792
+ const mods = [];
2793
+ if (hasCtrl) mods.push("Control");
2794
+ if (hasAlt) mods.push("Alt");
2795
+ if (hasShift && baseKey.length > 1) mods.push("Shift");
2796
+ if (hasMeta) mods.push("Meta");
2797
+ const candidates2 = [];
2798
+ const primaryKey = baseKey.length === 1 ? baseKey : normalizedName;
2799
+ candidates2.push([...mods, primaryKey].join("+"));
2800
+ if (baseKey.length === 1 && baseKey.toLowerCase() !== baseKey) {
2801
+ candidates2.push([...mods, baseKey.toLowerCase()].join("+"));
2802
+ }
2803
+ try {
2804
+ const parsed = parseKeyboardEvent(event);
2805
+ if (parsed?.key) {
2806
+ const parsedMods = [];
2807
+ if (parsed.ctrl) parsedMods.push("Control");
2808
+ if (parsed.alt) parsedMods.push("Alt");
2809
+ if (parsed.shift) parsedMods.push("Shift");
2810
+ if (parsed.meta) parsedMods.push("Meta");
2811
+ const fromTanstack = [...parsedMods, parsed.key].join("+");
2812
+ if (!candidates2.includes(fromTanstack)) {
2813
+ candidates2.push(fromTanstack);
2814
+ }
2815
+ }
2816
+ } catch {
2817
+ }
2818
+ return candidates2;
2819
+ }
2820
+ const candidates = [baseKey];
2821
+ if (hasShift && baseKey.length === 1) {
2822
+ candidates.push(`Shift+${baseKey.toUpperCase()}`);
2823
+ candidates.push(`Shift+${baseKey}`);
2824
+ } else if (baseKey.length > 1 && normalizedName !== baseKey) {
2825
+ candidates.push(normalizedName);
2826
+ }
2827
+ return candidates;
2828
+ }
2829
+ function getTopMostModalDialog(doc) {
2830
+ const dialogs = Array.from(
2831
+ doc.querySelectorAll(
2832
+ '[data-scope="dialog"][data-part="content"][data-state="open"], [role="dialog"][aria-modal="true"]:not([data-state="closed"]), [role="alertdialog"][aria-modal="true"]:not([data-state="closed"])'
2833
+ )
2834
+ ).filter((el) => !el.hasAttribute("data-which-key-explorer"));
2835
+ if (dialogs.length === 0) return null;
2836
+ for (let i = dialogs.length - 1; i >= 0; i -= 1) {
2837
+ const candidate = dialogs[i];
2838
+ if (candidate.style.pointerEvents !== "none") {
2839
+ return candidate;
2840
+ }
2841
+ }
2842
+ return dialogs[dialogs.length - 1] ?? null;
2843
+ }
2844
+ function getPaneFocusableItems(container, ownScope) {
2845
+ const doc = container.ownerDocument;
2846
+ const activeEl = doc?.activeElement instanceof HTMLElement ? doc.activeElement : null;
2847
+ const enteredExample = !ownScope && activeEl && !activeEl.hasAttribute("data-example") ? activeEl.closest("[data-example]") : null;
2848
+ const searchRoot = enteredExample && container.contains(enteredExample) ? enteredExample.querySelector("[data-example-preview]") ?? enteredExample : container;
2849
+ const raw = getFocusables(searchRoot, { includeContainer: false });
2850
+ return raw.filter((el) => {
2851
+ if (!(el instanceof HTMLElement)) return false;
2852
+ if (el.closest("[data-which-key-root], [data-which-key-explorer], [data-which-key-jump-overlay]")) {
2853
+ return false;
2854
+ }
2855
+ const fwEl = el.closest("[data-fw]");
2856
+ const activeFw = doc?.documentElement?.getAttribute("data-framework");
2857
+ if (fwEl && activeFw && fwEl.getAttribute("data-fw") !== activeFw) {
2858
+ return false;
2859
+ }
2860
+ if (!ownScope) {
2861
+ if (!enteredExample) {
2862
+ const parentExample = el.parentElement?.closest("[data-example]");
2863
+ if (parentExample) return false;
2864
+ }
2865
+ const nestedScope = el.closest("[data-which-key-scope]");
2866
+ if (nestedScope) return false;
2867
+ }
2868
+ if (el.getAttribute("aria-hidden") === "true" || el.hasAttribute("inert")) {
2869
+ return false;
2870
+ }
2871
+ return true;
2872
+ });
2873
+ }
2874
+ function getJumpableItems(container, ownScope) {
2875
+ const doc = container.ownerDocument;
2876
+ const rawFocusables = getFocusables(container, { includeContainer: false });
2877
+ const rawTabs = Array.from(
2878
+ container.querySelectorAll(
2879
+ '[role="tab"]:not([disabled]):not([data-disabled]):not([aria-disabled="true"])'
2880
+ )
2881
+ );
2882
+ const combined = [];
2883
+ const seen = /* @__PURE__ */ new Set();
2884
+ for (const el of [...rawFocusables, ...rawTabs]) {
2885
+ if (!(el instanceof HTMLElement) || seen.has(el)) continue;
2886
+ seen.add(el);
2887
+ if (el.closest("[data-which-key-root], [data-which-key-explorer], [data-which-key-jump-overlay]")) {
2888
+ continue;
2889
+ }
2890
+ const fwEl = el.closest("[data-fw]");
2891
+ const activeFw = doc?.documentElement?.getAttribute("data-framework");
2892
+ if (fwEl && activeFw && fwEl.getAttribute("data-fw") !== activeFw) {
2893
+ continue;
2894
+ }
2895
+ if (!ownScope) {
2896
+ const nestedScope = el.closest("[data-which-key-scope]");
2897
+ if (nestedScope) continue;
2898
+ }
2899
+ if (el.getAttribute("aria-hidden") === "true" || el.hasAttribute("inert")) {
2900
+ continue;
2901
+ }
2902
+ combined.push(el);
2903
+ }
2904
+ return combined;
2905
+ }
2906
+ var globalWhichKeyState = globalThis;
2907
+ var attachedEntriesByDoc = globalWhichKeyState.__helicalAttachedEntriesByDoc__ ??= /* @__PURE__ */ new WeakMap();
2908
+ var lastInteractedScopeByDoc = globalWhichKeyState.__helicalLastInteractedScopeByDoc__ ??= /* @__PURE__ */ new WeakMap();
2909
+ var rootControllerByDoc = globalWhichKeyState.__helicalRootControllerByDoc__ ??= /* @__PURE__ */ new WeakMap();
2910
+ var rootControllerListenersByDoc = globalWhichKeyState.__helicalRootControllerListenersByDoc__ ??= /* @__PURE__ */ new WeakMap();
2911
+ function notifyRootControllerListeners(doc) {
2912
+ const set = rootControllerListenersByDoc.get(doc);
2913
+ if (!set) return;
2914
+ for (const fn of set) {
2915
+ fn();
2916
+ }
2917
+ }
2918
+ function getDocumentWhichKeyController(doc) {
2919
+ const resolved = doc ?? (typeof document !== "undefined" ? document : void 0);
2920
+ if (!resolved) return null;
2921
+ return rootControllerByDoc.get(resolved) ?? null;
2922
+ }
2923
+ function subscribeDocumentWhichKeyController(doc, listener) {
2924
+ const resolved = doc ?? (typeof document !== "undefined" ? document : void 0);
2925
+ if (!resolved) return () => {
2926
+ };
2927
+ let set = rootControllerListenersByDoc.get(resolved);
2928
+ if (!set) {
2929
+ set = /* @__PURE__ */ new Set();
2930
+ rootControllerListenersByDoc.set(resolved, set);
2931
+ }
2932
+ set.add(listener);
2933
+ return () => {
2934
+ set?.delete(listener);
2935
+ };
2936
+ }
2937
+ function isScopeElementActive(scopeEl, doc) {
2938
+ if (!scopeEl) return true;
2939
+ if (!scopeEl.isConnected) return false;
2940
+ const fwEl = scopeEl.closest?.("[data-fw]");
2941
+ const activeFw = doc.documentElement?.getAttribute("data-framework");
2942
+ if (fwEl && activeFw && fwEl.getAttribute("data-fw") !== activeFw) {
2943
+ return false;
2944
+ }
2945
+ return true;
2946
+ }
2947
+ function shouldEntryHandleEvent(entry, doc) {
2948
+ const ownScope = entry.getScopeElement();
2949
+ if (!isScopeElementActive(ownScope, doc)) {
2950
+ return false;
2951
+ }
2952
+ const allEntries = attachedEntriesByDoc.get(doc);
2953
+ if (!allEntries || allEntries.size <= 1) {
2954
+ return true;
2955
+ }
2956
+ const visibleEntries = Array.from(allEntries).filter((e) => isScopeElementActive(e.getScopeElement(), doc));
2957
+ if (visibleEntries.length <= 1) {
2958
+ return visibleEntries[0] === entry;
2959
+ }
2960
+ const busyEntry = visibleEntries.find((e) => e.isBusy());
2961
+ if (busyEntry) {
2962
+ return busyEntry === entry;
2963
+ }
2964
+ const activeEl = doc.activeElement && doc.activeElement !== doc.body && doc.activeElement !== doc.documentElement && isElementLike(doc.activeElement) ? doc.activeElement : null;
2965
+ const focusedScope = activeEl ? activeEl.closest?.("[data-which-key-scope]") ?? null : null;
2966
+ const rememberedScope = lastInteractedScopeByDoc.get(doc) ?? null;
2967
+ const targetScope = focusedScope && isScopeElementActive(focusedScope, doc) ? focusedScope : rememberedScope && isScopeElementActive(rememberedScope, doc) ? rememberedScope : null;
2968
+ if (targetScope) {
2969
+ const scopedMatch = visibleEntries.find((e) => e.getScopeElement() === targetScope);
2970
+ if (scopedMatch) {
2971
+ return scopedMatch === entry;
2972
+ }
2973
+ }
2974
+ const rootEntry = visibleEntries.find((e) => e.getScopeElement() === null);
2975
+ if (rootEntry) {
2976
+ return rootEntry === entry;
2977
+ }
2978
+ return visibleEntries[0] === entry;
2979
+ }
2980
+ function createWhichKeyController(options = {}) {
2981
+ const storageKey = options.storageKey;
2982
+ function isMobileViewport() {
2983
+ if (options.disableOnMobile === false) return false;
2984
+ const doc = resolveDoc();
2985
+ const win = doc?.defaultView ?? (typeof window !== "undefined" ? window : null);
2986
+ if (!win || typeof win.matchMedia !== "function") return false;
2987
+ try {
2988
+ return win.matchMedia("(pointer: coarse) and (hover: none)").matches || win.matchMedia("(max-width: 767px) and (pointer: coarse)").matches;
2989
+ } catch {
2990
+ return false;
2991
+ }
2992
+ }
2993
+ function isControllerEnabled() {
2994
+ if (options.enabled === false) return false;
2995
+ if (isMobileViewport()) return false;
2996
+ return true;
2997
+ }
2998
+ function readStoredPreset() {
2999
+ if (!storageKey || typeof window === "undefined") return null;
3000
+ try {
3001
+ const raw = window.localStorage.getItem(`${storageKey}:keymap-preset`);
3002
+ if (raw === "helix" || raw === "vim" || raw === "kakoune") return raw;
3003
+ } catch {
3004
+ }
3005
+ return null;
3006
+ }
3007
+ function writeStoredPreset(next) {
3008
+ const doc = resolveDoc();
3009
+ if (doc?.documentElement && !options.getScopeElement?.()) {
3010
+ doc.documentElement.dataset.keymapPreset = next;
3011
+ }
3012
+ if (!storageKey || typeof window === "undefined") return;
3013
+ try {
3014
+ window.localStorage.setItem(`${storageKey}:keymap-preset`, next);
3015
+ } catch {
3016
+ }
3017
+ }
3018
+ function readStoredJumpAction() {
3019
+ if (!storageKey || typeof window === "undefined") return null;
3020
+ try {
3021
+ const raw = window.localStorage.getItem(`${storageKey}:jump-action`);
3022
+ if (raw === "activate" || raw === "focus") return raw;
3023
+ } catch {
3024
+ }
3025
+ return null;
3026
+ }
3027
+ function writeStoredJumpAction(next) {
3028
+ const doc = resolveDoc();
3029
+ if (doc?.documentElement && !options.getScopeElement?.()) {
3030
+ doc.documentElement.dataset.jumpAction = next;
3031
+ }
3032
+ if (!storageKey || typeof window === "undefined") return;
3033
+ try {
3034
+ window.localStorage.setItem(`${storageKey}:jump-action`, next);
3035
+ } catch {
3036
+ }
3037
+ }
3038
+ let preset = options.preset ?? readStoredPreset() ?? "helix";
3039
+ let mode = options.defaultMode ?? "normal";
3040
+ const leaderKey = options.leaderKey ?? "Space";
3041
+ let jumpAction = options.jumpAction ?? readStoredJumpAction() ?? "activate";
3042
+ const jumpAlphabet = options.jumpAlphabet ?? DEFAULT_JUMP_ALPHABET;
3043
+ const listeners = /* @__PURE__ */ new Set();
3044
+ const keymapLayers = /* @__PURE__ */ new Map();
3045
+ const commandHandlers = /* @__PURE__ */ new Map();
3046
+ const panes = /* @__PURE__ */ new Map();
3047
+ const jumplist = createJumplist(50);
3048
+ if (options.keymap) {
3049
+ keymapLayers.set("__initial__", {
3050
+ id: "__initial__",
3051
+ nodes: options.keymap,
3052
+ enabled: true
3053
+ });
3054
+ }
3055
+ if (options.commands) {
3056
+ for (const [cmdId, handler] of Object.entries(options.commands)) {
3057
+ commandHandlers.set(cmdId, handler);
3058
+ }
3059
+ }
3060
+ let activePath = [];
3061
+ let sticky = false;
3062
+ let countBuffer = "";
3063
+ let explorerOpen = false;
3064
+ let explorerQuery = "";
3065
+ let activePaneId = null;
3066
+ let jumpQuery = "";
3067
+ let rawJumpTargets = [];
3068
+ let statusMessage = "";
3069
+ let programmaticFocusDepth = 0;
3070
+ let liveRegion = null;
3071
+ let detachCleanups = [];
3072
+ function resolveDoc() {
3073
+ if (options.getDocument) {
3074
+ try {
3075
+ return options.getDocument();
3076
+ } catch {
3077
+ }
3078
+ }
3079
+ return typeof document !== "undefined" ? document : null;
3080
+ }
3081
+ function announce(message) {
3082
+ statusMessage = message;
3083
+ try {
3084
+ liveRegion?.announce(message);
3085
+ } catch {
3086
+ }
3087
+ }
3088
+ function buildMergedTrie() {
3089
+ let trie = getPresetKeymap(preset, leaderKey);
3090
+ for (const layer of keymapLayers.values()) {
3091
+ if (!layer.enabled) continue;
3092
+ if (layer.scope && layer.scope !== activePaneId) continue;
3093
+ trie = mergeKeymapTrees(trie, layer.nodes);
3094
+ }
3095
+ return trie;
3096
+ }
3097
+ function syncPaneActiveAttributes() {
3098
+ for (const pane of panes.values()) {
3099
+ if (pane.element && typeof pane.element.setAttribute === "function") {
3100
+ pane.element.setAttribute("data-pane-active", pane.id === activePaneId ? "true" : "false");
3101
+ }
3102
+ }
3103
+ }
3104
+ function syncDomPanes(docOverride) {
3105
+ const doc = docOverride ?? resolveDoc();
3106
+ if (!doc || typeof doc.querySelectorAll !== "function") return;
3107
+ const ownScope = options.getScopeElement?.() ?? null;
3108
+ const root = ownScope ?? doc.body;
3109
+ if (!root || typeof root.querySelectorAll !== "function") return;
3110
+ const elements = Array.from(root.querySelectorAll("[data-pane-id]"));
3111
+ for (const el of elements) {
3112
+ if (!ownScope && el.closest("[data-which-key-scope]")) continue;
3113
+ const id = el.getAttribute("data-pane-id");
3114
+ if (!id) continue;
3115
+ const existing = panes.get(id);
3116
+ if (existing && existing.element === el) continue;
3117
+ const title = el.getAttribute("data-pane-title") || existing?.title || id;
3118
+ const orderAttr = el.getAttribute("data-pane-order");
3119
+ const parsedOrder = orderAttr ? Number.parseInt(orderAttr, 10) : Number.NaN;
3120
+ const order = !Number.isNaN(parsedOrder) ? parsedOrder : existing?.order ?? panes.size + 1;
3121
+ const disabled = el.getAttribute("data-pane-disabled") === "true";
3122
+ panes.set(id, {
3123
+ id,
3124
+ title,
3125
+ element: el,
3126
+ disabled,
3127
+ order,
3128
+ lastFocusedElement: existing?.lastFocusedElement ?? null
3129
+ });
3130
+ if (!activePaneId && !disabled) {
3131
+ activePaneId = id;
3132
+ }
3133
+ }
3134
+ syncPaneActiveAttributes();
3135
+ }
3136
+ function getOrderedPanes() {
3137
+ return Array.from(panes.values()).filter((p) => !p.disabled).sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
3138
+ }
3139
+ function computeFilteredJumpTargets() {
3140
+ if (mode !== "jump") return [];
3141
+ return rawJumpTargets.filter((t) => t.label.startsWith(jumpQuery)).map((t) => ({
3142
+ ...t,
3143
+ matchedPrefix: jumpQuery,
3144
+ remainingLabel: t.label.slice(jumpQuery.length)
3145
+ }));
3146
+ }
3147
+ function computeState() {
3148
+ const rootTrie = buildMergedTrie();
3149
+ const effectiveMode = mode === "jump" ? "normal" : mode;
3150
+ const tree = buildWhichKeyTree(rootTrie, activePath, effectiveMode);
3151
+ const allEntries = flattenKeymapEntries(rootTrie);
3152
+ const q = explorerQuery.trim().toLowerCase();
3153
+ const filteredEntries = q ? allEntries.filter(
3154
+ (entry) => entry.label.toLowerCase().includes(q) || (entry.description?.toLowerCase().includes(q) ?? false) || entry.group.toLowerCase().includes(q) || entry.sequenceText.toLowerCase().includes(q)
3155
+ ) : allEntries;
3156
+ return {
3157
+ preset,
3158
+ mode,
3159
+ leaderKey,
3160
+ activePath: [...activePath],
3161
+ breadcrumb: tree.breadcrumb,
3162
+ title: tree.title,
3163
+ items: tree.items,
3164
+ isOpen: activePath.length > 0 && tree.items.length > 0,
3165
+ sticky: sticky || tree.sticky,
3166
+ countBuffer,
3167
+ explorerOpen,
3168
+ explorerQuery,
3169
+ explorerEntries: filteredEntries,
3170
+ activePaneId,
3171
+ panes: getOrderedPanes(),
3172
+ jumpQuery,
3173
+ jumpAction,
3174
+ jumpTargets: computeFilteredJumpTargets(),
3175
+ statusMessage
3176
+ };
3177
+ }
3178
+ let cachedState = computeState();
3179
+ function emit() {
3180
+ syncPaneActiveAttributes();
3181
+ cachedState = computeState();
3182
+ for (const listener of listeners) {
3183
+ listener(cachedState);
3184
+ }
3185
+ }
3186
+ function runProgrammaticFocus(fn) {
3187
+ programmaticFocusDepth += 1;
3188
+ try {
3189
+ setInteractionModality("keyboard");
3190
+ } catch {
3191
+ }
3192
+ try {
3193
+ fn();
3194
+ } finally {
3195
+ programmaticFocusDepth = Math.max(0, programmaticFocusDepth - 1);
3196
+ }
3197
+ }
3198
+ function getActiveContainer() {
3199
+ const doc = resolveDoc();
3200
+ if (!doc) return null;
3201
+ const topModal = getTopMostModalDialog(doc);
3202
+ if (topModal) return topModal;
3203
+ if (activePaneId) {
3204
+ const activePane = panes.get(activePaneId);
3205
+ if (activePane?.element) return activePane.element;
3206
+ }
3207
+ const firstPane = getOrderedPanes().find((p) => p.element);
3208
+ if (firstPane?.element) {
3209
+ activePaneId = firstPane.id;
3210
+ return firstPane.element;
3211
+ }
3212
+ return options.getScopeElement?.() ?? doc.body;
3213
+ }
3214
+ function recordCurrentLocation() {
3215
+ const doc = resolveDoc();
3216
+ const activeEl = doc?.activeElement ?? null;
3217
+ const paneId = activePaneId ?? getOrderedPanes()[0]?.id ?? "root";
3218
+ jumplist.push({
3219
+ paneId,
3220
+ element: activeEl,
3221
+ scrollTop: getActiveContainer()?.scrollTop ?? 0
3222
+ });
3223
+ }
3224
+ function setMode(nextMode) {
3225
+ if (mode === nextMode) return;
3226
+ mode = nextMode;
3227
+ if (nextMode !== "jump") {
3228
+ jumpQuery = "";
3229
+ rawJumpTargets = [];
3230
+ }
3231
+ if (nextMode === "insert") {
3232
+ activePath = [];
3233
+ sticky = false;
3234
+ countBuffer = "";
3235
+ }
3236
+ notifyAllModalEditors({ mode: nextMode, preset });
3237
+ options.onModeChange?.(nextMode);
3238
+ announce(`${nextMode.charAt(0).toUpperCase()}${nextMode.slice(1)} mode`);
3239
+ emit();
3240
+ }
3241
+ function setPreset(nextPreset) {
3242
+ if (preset === nextPreset) return;
3243
+ preset = nextPreset;
3244
+ activePath = [];
3245
+ sticky = false;
3246
+ countBuffer = "";
3247
+ writeStoredPreset(nextPreset);
3248
+ notifyAllModalEditors({ mode, preset: nextPreset });
3249
+ options.onPresetChange?.(nextPreset);
3250
+ announce(`Switched to ${nextPreset} preset`);
3251
+ emit();
3252
+ }
3253
+ function setJumpAction(action) {
3254
+ if (jumpAction === action) return;
3255
+ jumpAction = action;
3256
+ writeStoredJumpAction(action);
3257
+ options.onJumpActionChange?.(action);
3258
+ emit();
3259
+ }
3260
+ function openPrefix(path, opts) {
3261
+ activePath = [...path];
3262
+ sticky = Boolean(opts?.sticky);
3263
+ emit();
3264
+ }
3265
+ function closePrefix() {
3266
+ if (activePath.length === 0 && !sticky && !countBuffer) return;
3267
+ activePath = [];
3268
+ sticky = false;
3269
+ countBuffer = "";
3270
+ emit();
3271
+ }
3272
+ function stepBackPrefix() {
3273
+ if (activePath.length === 0) return false;
3274
+ activePath = activePath.slice(0, -1);
3275
+ if (activePath.length === 0) {
3276
+ sticky = false;
3277
+ }
3278
+ emit();
3279
+ return true;
3280
+ }
3281
+ function openExplorer() {
3282
+ activePath = [];
3283
+ sticky = false;
3284
+ countBuffer = "";
3285
+ explorerQuery = "";
3286
+ explorerOpen = true;
3287
+ announce("Keybinding explorer opened");
3288
+ emit();
3289
+ }
3290
+ function closeExplorer() {
3291
+ if (!explorerOpen) return;
3292
+ explorerOpen = false;
3293
+ explorerQuery = "";
3294
+ emit();
3295
+ }
3296
+ function setExplorerQuery(query) {
3297
+ explorerQuery = query;
3298
+ emit();
3299
+ }
3300
+ function enterExampleContainer(exampleEl) {
3301
+ const doc = resolveDoc();
3302
+ const activeFw = doc?.documentElement?.getAttribute("data-framework");
3303
+ const preview = exampleEl.querySelector("[data-example-preview]") ?? exampleEl;
3304
+ const scopes = Array.from(preview.querySelectorAll("[data-which-key-scope]"));
3305
+ const activeScope = doc ? scopes.find((s) => isScopeElementActive(s, doc)) ?? null : null;
3306
+ if (activeScope && doc) {
3307
+ lastInteractedScopeByDoc.set(doc, activeScope);
3308
+ const scopeFocusables = getPaneFocusableItems(activeScope, activeScope);
3309
+ const target = scopeFocusables[0] ?? preview;
3310
+ recordCurrentLocation();
3311
+ focusElementInActivePane(target);
3312
+ announce("Entered example preview");
3313
+ emit();
3314
+ return true;
3315
+ }
3316
+ const rawFocusables = getFocusables(preview, { includeContainer: false }).filter((el) => {
3317
+ if (!(el instanceof HTMLElement)) return false;
3318
+ const fwEl = el.closest("[data-fw]");
3319
+ if (fwEl && activeFw && fwEl.getAttribute("data-fw") !== activeFw) return false;
3320
+ if (el.getAttribute("aria-hidden") === "true" || el.hasAttribute("inert")) return false;
3321
+ return true;
3322
+ });
3323
+ if (rawFocusables.length > 0) {
3324
+ recordCurrentLocation();
3325
+ focusElementInActivePane(rawFocusables[0]);
3326
+ announce("Entered example preview");
3327
+ emit();
3328
+ return true;
3329
+ }
3330
+ const codeToggle = exampleEl.querySelector("[data-example-toggle]");
3331
+ if (codeToggle) {
3332
+ codeToggle.click();
3333
+ announce("Toggled example code");
3334
+ return true;
3335
+ }
3336
+ return false;
3337
+ }
3338
+ function focusElementInActivePane(target) {
3339
+ runProgrammaticFocus(() => {
3340
+ target.focus({ preventScroll: true });
3341
+ if (typeof target.scrollIntoView === "function") {
3342
+ try {
3343
+ target.scrollIntoView({
3344
+ block: "nearest",
3345
+ inline: "nearest",
3346
+ behavior: "instant"
3347
+ });
3348
+ } catch {
3349
+ }
3350
+ }
3351
+ });
3352
+ if (activePaneId) {
3353
+ const pane = panes.get(activePaneId);
3354
+ if (pane) {
3355
+ pane.lastFocusedElement = target;
3356
+ }
3357
+ }
3358
+ }
3359
+ function stepFocusInPane(delta) {
3360
+ const container = getActiveContainer();
3361
+ if (!container) return false;
3362
+ const items = getPaneFocusableItems(container, options.getScopeElement?.());
3363
+ if (items.length === 0) return false;
3364
+ const doc = resolveDoc();
3365
+ const activeEl = doc?.activeElement;
3366
+ const currentIndex = activeEl ? items.indexOf(activeEl) : -1;
3367
+ let nextIndex = 0;
3368
+ if (currentIndex === -1) {
3369
+ const activePane = activePaneId ? panes.get(activePaneId) : void 0;
3370
+ if (activePane?.lastFocusedElement) {
3371
+ const rememberedIdx = items.indexOf(activePane.lastFocusedElement);
3372
+ if (rememberedIdx !== -1) {
3373
+ nextIndex = delta > 0 ? Math.min(items.length - 1, rememberedIdx + delta) : Math.max(0, rememberedIdx + delta);
3374
+ } else {
3375
+ nextIndex = delta >= 0 ? 0 : items.length - 1;
3376
+ }
3377
+ } else {
3378
+ nextIndex = delta >= 0 ? 0 : items.length - 1;
3379
+ }
3380
+ } else {
3381
+ nextIndex = Math.max(0, Math.min(items.length - 1, currentIndex + delta));
3382
+ }
3383
+ const target = items[nextIndex];
3384
+ if (!target) return false;
3385
+ focusElementInActivePane(target);
3386
+ emit();
3387
+ return true;
3388
+ }
3389
+ function jumpToBoundary(boundary) {
3390
+ const container = getActiveContainer();
3391
+ if (!container) return false;
3392
+ const items = getPaneFocusableItems(container, options.getScopeElement?.());
3393
+ if (items.length === 0) return false;
3394
+ recordCurrentLocation();
3395
+ if (boundary === "start" || boundary === "first-in-group") {
3396
+ const target2 = items[0];
3397
+ focusElementInActivePane(target2);
3398
+ if (boundary === "start") {
3399
+ container.scrollTop = 0;
3400
+ }
3401
+ recordCurrentLocation();
3402
+ emit();
3403
+ return true;
3404
+ }
3405
+ const target = items[items.length - 1];
3406
+ focusElementInActivePane(target);
3407
+ if (boundary === "end") {
3408
+ container.scrollTop = container.scrollHeight;
3409
+ }
3410
+ recordCurrentLocation();
3411
+ emit();
3412
+ return true;
3413
+ }
3414
+ function scrollActivePane(action, count = 1) {
3415
+ const container = getActiveContainer();
3416
+ if (!container) return false;
3417
+ const doc = resolveDoc();
3418
+ const activeEl = doc?.activeElement;
3419
+ if (action === "center" && activeEl && typeof activeEl.scrollIntoView === "function") {
3420
+ try {
3421
+ activeEl.scrollIntoView({ block: "center", behavior: "instant" });
3422
+ } catch {
3423
+ }
3424
+ return true;
3425
+ }
3426
+ if (action === "top" && activeEl && typeof activeEl.scrollIntoView === "function") {
3427
+ try {
3428
+ activeEl.scrollIntoView({ block: "start", behavior: "instant" });
3429
+ } catch {
3430
+ }
3431
+ return true;
3432
+ }
3433
+ if (action === "bottom" && activeEl && typeof activeEl.scrollIntoView === "function") {
3434
+ try {
3435
+ activeEl.scrollIntoView({ block: "end", behavior: "instant" });
3436
+ } catch {
3437
+ }
3438
+ return true;
3439
+ }
3440
+ const stepPx = 120 * Math.max(1, count);
3441
+ const deltaY = action === "down" ? stepPx : action === "up" ? -stepPx : 0;
3442
+ if (deltaY !== 0) {
3443
+ if (typeof container.scrollBy === "function") {
3444
+ container.scrollBy({ top: deltaY, behavior: "instant" });
3445
+ } else {
3446
+ container.scrollTop += deltaY;
3447
+ }
3448
+ return true;
3449
+ }
3450
+ return false;
3451
+ }
3452
+ function focusPane(paneIdOrIndex) {
3453
+ const ordered = getOrderedPanes();
3454
+ if (ordered.length === 0) return false;
3455
+ let targetPane;
3456
+ if (typeof paneIdOrIndex === "number") {
3457
+ targetPane = ordered[paneIdOrIndex - 1];
3458
+ } else {
3459
+ targetPane = panes.get(paneIdOrIndex);
3460
+ if (!targetPane || targetPane.disabled) {
3461
+ const numeric = Number.parseInt(paneIdOrIndex, 10);
3462
+ if (!Number.isNaN(numeric) && numeric >= 1) {
3463
+ targetPane = ordered[numeric - 1];
3464
+ }
3465
+ }
3466
+ }
3467
+ if (!targetPane || !targetPane.element) return false;
3468
+ recordCurrentLocation();
3469
+ activePaneId = targetPane.id;
3470
+ const ownScope = options.getScopeElement?.() ?? null;
3471
+ const remembered = targetPane.lastFocusedElement && targetPane.element.contains(targetPane.lastFocusedElement) && (ownScope || !targetPane.lastFocusedElement.closest("[data-which-key-scope]")) ? targetPane.lastFocusedElement : null;
3472
+ const firstFocusable = remembered ?? getPaneFocusableItems(targetPane.element, ownScope)[0] ?? null;
3473
+ if (firstFocusable instanceof HTMLElement) {
3474
+ focusElementInActivePane(firstFocusable);
3475
+ } else {
3476
+ runProgrammaticFocus(() => {
3477
+ if (targetPane.element.tabIndex < 0) {
3478
+ targetPane.element.tabIndex = -1;
3479
+ }
3480
+ targetPane.element.focus({ preventScroll: false });
3481
+ });
3482
+ }
3483
+ if (mode === "insert") {
3484
+ mode = "normal";
3485
+ notifyAllModalEditors({ mode: "normal", preset });
3486
+ }
3487
+ recordCurrentLocation();
3488
+ announce(`Focused pane ${targetPane.title}`);
3489
+ emit();
3490
+ return true;
3491
+ }
3492
+ function focusPaneDirection(direction) {
3493
+ const ordered = getOrderedPanes().filter((p) => p.element);
3494
+ if (ordered.length === 0) return false;
3495
+ const currentPane = (activePaneId ? panes.get(activePaneId) : void 0) ?? ordered[0];
3496
+ if (!currentPane?.element) return false;
3497
+ const toRect = (p) => {
3498
+ const r = p.element.getBoundingClientRect();
3499
+ return {
3500
+ id: p.id,
3501
+ x: r.left,
3502
+ y: r.top,
3503
+ width: r.width || p.element.offsetWidth || 100,
3504
+ height: r.height || p.element.offsetHeight || 100,
3505
+ disabled: p.disabled,
3506
+ order: p.order
3507
+ };
3508
+ };
3509
+ const originRect = toRect(currentPane);
3510
+ const candidateRects = ordered.map(toRect);
3511
+ const matched = findDirectionalPane(originRect, candidateRects, direction);
3512
+ if (matched) {
3513
+ return focusPane(matched.id);
3514
+ }
3515
+ if (originRect.x === 0 && originRect.y === 0 && ordered.length > 1) {
3516
+ return cyclePane(direction === "left" || direction === "up");
3517
+ }
3518
+ return false;
3519
+ }
3520
+ function cyclePane(reverse = false) {
3521
+ const ordered = getOrderedPanes().filter((p) => p.element);
3522
+ if (ordered.length === 0) return false;
3523
+ const currentIndex = ordered.findIndex((p) => p.id === activePaneId);
3524
+ const nextIndex = currentIndex === -1 ? 0 : (currentIndex + (reverse ? -1 : 1) + ordered.length) % ordered.length;
3525
+ const target = ordered[nextIndex];
3526
+ return target ? focusPane(target.id) : false;
3527
+ }
3528
+ function startJumpMode(customAction) {
3529
+ const doc = resolveDoc();
3530
+ if (!doc) return;
3531
+ if (customAction) {
3532
+ jumpAction = customAction;
3533
+ }
3534
+ const ownScope = options.getScopeElement?.() ?? null;
3535
+ const scopeRoot = getTopMostModalDialog(doc) ?? ownScope ?? doc.body;
3536
+ const allFocusable = getJumpableItems(scopeRoot, ownScope);
3537
+ const visible = allFocusable.filter((el) => {
3538
+ const rect = el.getBoundingClientRect();
3539
+ if (rect.width <= 0 || rect.height <= 0) return false;
3540
+ if (ownScope) {
3541
+ return true;
3542
+ }
3543
+ const intersectsViewport = rect.bottom > 0 && rect.right > 0 && rect.top < (doc.defaultView?.innerHeight ?? 1080) && rect.left < (doc.defaultView?.innerWidth ?? 1920);
3544
+ try {
3545
+ return isInView(el, doc.defaultView ?? scopeRoot) || intersectsViewport;
3546
+ } catch {
3547
+ return intersectsViewport;
3548
+ }
3549
+ });
3550
+ if (visible.length === 0) return;
3551
+ const labels = generateJumpLabels(visible.length, jumpAlphabet);
3552
+ rawJumpTargets = visible.map((el, idx) => {
3553
+ const r = el.getBoundingClientRect();
3554
+ return {
3555
+ id: `jump-${idx}-${labels[idx]}`,
3556
+ label: labels[idx],
3557
+ element: el,
3558
+ rect: {
3559
+ top: r.top,
3560
+ left: r.left,
3561
+ width: r.width,
3562
+ height: r.height
3563
+ }
3564
+ };
3565
+ });
3566
+ jumpQuery = "";
3567
+ activePath = [];
3568
+ sticky = false;
3569
+ countBuffer = "";
3570
+ mode = "jump";
3571
+ announce(`Jump mode (${rawJumpTargets.length} targets)`);
3572
+ emit();
3573
+ }
3574
+ function cancelJumpMode() {
3575
+ if (mode !== "jump") return;
3576
+ jumpQuery = "";
3577
+ rawJumpTargets = [];
3578
+ mode = "normal";
3579
+ emit();
3580
+ }
3581
+ function jumpBack() {
3582
+ const doc = resolveDoc();
3583
+ const activeEl = doc?.activeElement ?? null;
3584
+ const currentPaneId = activePaneId ?? getOrderedPanes()[0]?.id ?? "root";
3585
+ const target = jumplist.back({
3586
+ paneId: currentPaneId,
3587
+ element: activeEl
3588
+ });
3589
+ if (!target) return false;
3590
+ if (target.paneId && panes.has(target.paneId)) {
3591
+ activePaneId = target.paneId;
3592
+ }
3593
+ if (target.element && target.element.isConnected) {
3594
+ focusElementInActivePane(target.element);
3595
+ } else if (target.paneId) {
3596
+ focusPane(target.paneId);
3597
+ }
3598
+ emit();
3599
+ return true;
3600
+ }
3601
+ function jumpForward() {
3602
+ const target = jumplist.forward();
3603
+ if (!target) return false;
3604
+ if (target.paneId && panes.has(target.paneId)) {
3605
+ activePaneId = target.paneId;
3606
+ }
3607
+ if (target.element && target.element.isConnected) {
3608
+ focusElementInActivePane(target.element);
3609
+ } else if (target.paneId) {
3610
+ focusPane(target.paneId);
3611
+ }
3612
+ emit();
3613
+ return true;
3614
+ }
3615
+ function stepFocusVerticalInPane(delta) {
3616
+ const container = getActiveContainer();
3617
+ if (!container) return false;
3618
+ const items = getPaneFocusableItems(container, options.getScopeElement?.());
3619
+ if (items.length === 0) return false;
3620
+ const doc = resolveDoc();
3621
+ const activeEl = doc?.activeElement;
3622
+ const currentIndex = activeEl ? items.indexOf(activeEl) : -1;
3623
+ if (currentIndex === -1) {
3624
+ return stepFocusInPane(delta);
3625
+ }
3626
+ const initialRect = items[currentIndex].getBoundingClientRect();
3627
+ if (initialRect.width <= 0 || initialRect.height <= 0) {
3628
+ return stepFocusInPane(delta);
3629
+ }
3630
+ const initialCenterX = initialRect.left + initialRect.width / 2;
3631
+ const initialCenterY = initialRect.top + initialRect.height / 2;
3632
+ const rowTolerance = Math.max(8, initialRect.height * 0.5);
3633
+ const hasSiblingInSameRow = items.some((el, idx) => {
3634
+ if (idx === currentIndex) return false;
3635
+ const r = el.getBoundingClientRect();
3636
+ if (r.width <= 0 || r.height <= 0) return false;
3637
+ const cy = r.top + r.height / 2;
3638
+ const cx = r.left + r.width / 2;
3639
+ return Math.abs(cy - initialCenterY) <= rowTolerance && Math.abs(cx - initialCenterX) > 8;
3640
+ });
3641
+ if (!hasSiblingInSameRow) {
3642
+ return stepFocusInPane(delta);
3643
+ }
3644
+ const dir = delta >= 0 ? 1 : -1;
3645
+ const steps = Math.max(1, Math.abs(delta));
3646
+ let currentEl = items[currentIndex];
3647
+ for (let s = 0; s < steps; s += 1) {
3648
+ const curRect = currentEl.getBoundingClientRect();
3649
+ const curCenterY = curRect.top + curRect.height / 2;
3650
+ const curTol = Math.max(8, curRect.height * 0.5);
3651
+ const candidates = items.map((el) => {
3652
+ const r = el.getBoundingClientRect();
3653
+ return {
3654
+ el,
3655
+ cx: r.left + r.width / 2,
3656
+ cy: r.top + r.height / 2,
3657
+ h: r.height,
3658
+ w: r.width
3659
+ };
3660
+ }).filter((c) => {
3661
+ if (c.w <= 0 || c.h <= 0) return false;
3662
+ return dir > 0 ? c.cy > curCenterY + curTol : c.cy < curCenterY - curTol;
3663
+ });
3664
+ if (candidates.length === 0) {
3665
+ if (s === 0) {
3666
+ return stepFocusInPane(delta);
3667
+ }
3668
+ break;
3669
+ }
3670
+ let closestRowY = candidates[0].cy;
3671
+ for (const c of candidates) {
3672
+ if (Math.abs(c.cy - curCenterY) < Math.abs(closestRowY - curCenterY)) {
3673
+ closestRowY = c.cy;
3674
+ }
3675
+ }
3676
+ const rowCandidates = candidates.filter((c) => Math.abs(c.cy - closestRowY) <= curTol);
3677
+ let best = rowCandidates[0];
3678
+ for (const c of rowCandidates) {
3679
+ if (Math.abs(c.cx - initialCenterX) < Math.abs(best.cx - initialCenterX)) {
3680
+ best = c;
3681
+ }
3682
+ }
3683
+ currentEl = best.el;
3684
+ }
3685
+ focusElementInActivePane(currentEl);
3686
+ emit();
3687
+ return true;
3688
+ }
3689
+ function isElementInActiveFramework(el, doc) {
3690
+ const fwEl = el.closest("[data-fw]");
3691
+ const activeFw = doc?.documentElement?.getAttribute("data-framework");
3692
+ if (fwEl && activeFw && fwEl.getAttribute("data-fw") !== activeFw) {
3693
+ return false;
3694
+ }
3695
+ if (el.getAttribute("aria-hidden") === "true" || el.hasAttribute("inert")) {
3696
+ return false;
3697
+ }
3698
+ return true;
3699
+ }
3700
+ function findActiveTablist(activeEl, container) {
3701
+ const doc = resolveDoc();
3702
+ if (activeEl) {
3703
+ const directTablist = activeEl.closest('[role="tablist"]');
3704
+ if (directTablist && isElementInActiveFramework(directTablist, doc)) {
3705
+ return directTablist;
3706
+ }
3707
+ const tabsScope = activeEl.closest('[data-scope="tabs"]');
3708
+ if (tabsScope) {
3709
+ const list = Array.from(tabsScope.querySelectorAll('[role="tablist"]')).find(
3710
+ (el) => isElementInActiveFramework(el, doc)
3711
+ );
3712
+ if (list) return list;
3713
+ }
3714
+ const tabPanel = activeEl.closest('[role="tabpanel"]');
3715
+ if (tabPanel?.parentElement) {
3716
+ const list = Array.from(tabPanel.parentElement.querySelectorAll('[role="tablist"]')).find(
3717
+ (el) => isElementInActiveFramework(el, doc)
3718
+ );
3719
+ if (list) return list;
3720
+ }
3721
+ const exampleContainer = activeEl.hasAttribute("data-example") ? activeEl : activeEl.closest("[data-example]");
3722
+ if (exampleContainer) {
3723
+ const list = Array.from(exampleContainer.querySelectorAll('[role="tablist"]')).find(
3724
+ (el) => isElementInActiveFramework(el, doc)
3725
+ );
3726
+ if (list) return list;
3727
+ }
3728
+ }
3729
+ const searchRoot = container ?? doc?.body ?? null;
3730
+ if (!searchRoot) return null;
3731
+ const allLists = Array.from(searchRoot.querySelectorAll('[role="tablist"]')).filter(
3732
+ (el) => isElementInActiveFramework(el, doc)
3733
+ );
3734
+ return allLists[0] ?? null;
3735
+ }
3736
+ function stepTab(delta, boundary) {
3737
+ const doc = resolveDoc();
3738
+ const activeEl = doc?.activeElement ?? null;
3739
+ const container = getActiveContainer();
3740
+ const tablist = findActiveTablist(activeEl, container);
3741
+ if (!tablist) return false;
3742
+ const tabs = Array.from(
3743
+ tablist.querySelectorAll(
3744
+ '[role="tab"]:not([disabled]):not([data-disabled]):not([aria-disabled="true"])'
3745
+ )
3746
+ ).filter((el) => isElementInActiveFramework(el, doc));
3747
+ if (tabs.length === 0) return false;
3748
+ let currentIdx = activeEl ? tabs.findIndex((t) => t === activeEl || t.contains(activeEl)) : -1;
3749
+ if (currentIdx === -1) {
3750
+ currentIdx = tabs.findIndex(
3751
+ (t) => t.getAttribute("aria-selected") === "true" || t.hasAttribute("data-selected") || t.getAttribute("data-state") === "active"
3752
+ );
3753
+ }
3754
+ if (currentIdx === -1) {
3755
+ currentIdx = 0;
3756
+ }
3757
+ let targetIdx;
3758
+ if (boundary === "first") {
3759
+ targetIdx = 0;
3760
+ } else if (boundary === "last") {
3761
+ targetIdx = tabs.length - 1;
3762
+ } else {
3763
+ targetIdx = ((currentIdx + delta) % tabs.length + tabs.length) % tabs.length;
3764
+ }
3765
+ const targetTab = tabs[targetIdx];
3766
+ if (!targetTab) return false;
3767
+ recordCurrentLocation();
3768
+ focusElementInActivePane(targetTab);
3769
+ targetTab.click();
3770
+ recordCurrentLocation();
3771
+ announce(`Tab ${targetTab.textContent?.trim() || targetIdx + 1}`);
3772
+ emit();
3773
+ return true;
3774
+ }
3775
+ function stepSection(delta) {
3776
+ const container = getActiveContainer();
3777
+ if (!container) return false;
3778
+ const sections = Array.from(
3779
+ container.querySelectorAll(
3780
+ '[data-page-section], [data-slot="page-section"], section[id], .docs-prose :is(h2, h3)'
3781
+ )
3782
+ );
3783
+ if (sections.length === 0) {
3784
+ return stepFocusInPane(delta);
3785
+ }
3786
+ const doc = resolveDoc();
3787
+ const activeEl = doc?.activeElement;
3788
+ const currentIdx = activeEl ? sections.findIndex((s) => s === activeEl || s.contains(activeEl)) : -1;
3789
+ const nextIdx = currentIdx === -1 ? delta >= 0 ? 0 : sections.length - 1 : Math.max(0, Math.min(sections.length - 1, currentIdx + delta));
3790
+ const targetSection = sections[nextIdx];
3791
+ if (!targetSection) return false;
3792
+ recordCurrentLocation();
3793
+ if (typeof targetSection.scrollIntoView === "function") {
3794
+ try {
3795
+ targetSection.scrollIntoView({ block: "start", behavior: "instant" });
3796
+ } catch {
3797
+ }
3798
+ }
3799
+ const innerFocusable = getPaneFocusableItems(targetSection, options.getScopeElement?.())[0] ?? getFirstFocusable(targetSection, { includeContainer: false });
3800
+ if (innerFocusable instanceof HTMLElement) {
3801
+ focusElementInActivePane(innerFocusable);
3802
+ } else {
3803
+ runProgrammaticFocus(() => {
3804
+ if (targetSection.tabIndex < 0) {
3805
+ targetSection.tabIndex = -1;
3806
+ }
3807
+ targetSection.style.outline = "none";
3808
+ targetSection.focus({ preventScroll: true });
3809
+ });
3810
+ }
3811
+ recordCurrentLocation();
3812
+ emit();
3813
+ return true;
3814
+ }
3815
+ function handleGenericContentEditableMotion(el, motion, count) {
3816
+ const win = el.ownerDocument?.defaultView;
3817
+ const sel = win?.getSelection?.();
3818
+ if (!sel || typeof sel.modify !== "function") return false;
3819
+ const alter = mode === "select" || (preset === "helix" || preset === "kakoune") && (motion === "wordForward" || motion === "wordBackward" || motion === "wordEnd" || motion === "lineSelect") ? "extend" : "move";
3820
+ for (let i = 0; i < Math.max(1, count); i += 1) {
3821
+ switch (motion) {
3822
+ case "left":
3823
+ sel.modify(alter, "backward", "character");
3824
+ break;
3825
+ case "right":
3826
+ sel.modify(alter, "forward", "character");
3827
+ break;
3828
+ case "up":
3829
+ sel.modify(alter, "backward", "line");
3830
+ break;
3831
+ case "down":
3832
+ sel.modify(alter, "forward", "line");
3833
+ break;
3834
+ case "wordForward":
3835
+ case "wordEnd":
3836
+ sel.modify(alter, "forward", "word");
3837
+ break;
3838
+ case "wordBackward":
3839
+ sel.modify(alter, "backward", "word");
3840
+ break;
3841
+ case "paragraphForward":
3842
+ sel.modify(alter, "forward", "paragraphboundary");
3843
+ break;
3844
+ case "paragraphBackward":
3845
+ sel.modify(alter, "backward", "paragraphboundary");
3846
+ break;
3847
+ case "lineStart":
3848
+ sel.modify(alter, "backward", "lineboundary");
3849
+ break;
3850
+ case "lineEnd":
3851
+ sel.modify(alter, "forward", "lineboundary");
3852
+ break;
3853
+ case "lineSelect":
3854
+ sel.modify("move", "backward", "lineboundary");
3855
+ sel.modify("extend", "forward", "lineboundary");
3856
+ break;
3857
+ case "docStart":
3858
+ sel.modify(alter, "backward", "documentboundary");
3859
+ break;
3860
+ case "docEnd":
3861
+ sel.modify(alter, "forward", "documentboundary");
3862
+ break;
3863
+ }
3864
+ }
3865
+ return true;
3866
+ }
3867
+ function executeBuiltInCommand(commandId, ctx) {
3868
+ const doc = resolveDoc();
3869
+ const eventTarget = isElementLike(ctx.event?.target) ? ctx.event.target : null;
3870
+ const activeEl = eventTarget ?? doc?.activeElement ?? null;
3871
+ const editorTarget = getModalEditor(activeEl);
3872
+ if (commandId === "whichKey.openExplorer") {
3873
+ openExplorer();
3874
+ return true;
3875
+ }
3876
+ if (commandId === "preset.helix") {
3877
+ setPreset("helix");
3878
+ return true;
3879
+ }
3880
+ if (commandId === "preset.vim") {
3881
+ setPreset("vim");
3882
+ return true;
3883
+ }
3884
+ if (commandId === "preset.kakoune") {
3885
+ setPreset("kakoune");
3886
+ return true;
3887
+ }
3888
+ if (commandId === "mode.toggleSelect") {
3889
+ const nextMode = mode === "select" ? "normal" : "select";
3890
+ if (nextMode === "normal" && editorTarget) {
3891
+ editorTarget.transformSelection("collapse");
3892
+ }
3893
+ setMode(nextMode);
3894
+ return true;
3895
+ }
3896
+ if (commandId === "jump.start") {
3897
+ startJumpMode();
3898
+ return true;
3899
+ }
3900
+ if (commandId === "jump.activate") {
3901
+ startJumpMode("activate");
3902
+ return true;
3903
+ }
3904
+ if (commandId === "jump.focus") {
3905
+ startJumpMode("focus");
3906
+ return true;
3907
+ }
3908
+ if (commandId === "jump.action.activate") {
3909
+ setJumpAction("activate");
3910
+ return true;
3911
+ }
3912
+ if (commandId === "jump.action.focus") {
3913
+ setJumpAction("focus");
3914
+ return true;
3915
+ }
3916
+ if (commandId === "jumplist.back") {
3917
+ return jumpBack();
3918
+ }
3919
+ if (commandId === "jumplist.forward") {
3920
+ return jumpForward();
3921
+ }
3922
+ if (commandId.startsWith("pane.focus.")) {
3923
+ const idx = Number.parseInt(commandId.slice("pane.focus.".length), 10);
3924
+ return focusPane(idx);
3925
+ }
3926
+ if (commandId === "pane.left") return focusPaneDirection("left");
3927
+ if (commandId === "pane.down") return focusPaneDirection("down");
3928
+ if (commandId === "pane.up") return focusPaneDirection("up");
3929
+ if (commandId === "pane.right") return focusPaneDirection("right");
3930
+ if (commandId === "pane.next") return cyclePane(false);
3931
+ if (commandId === "pane.prev") return cyclePane(true);
3932
+ if (commandId === "view.center") return scrollActivePane("center", ctx.count);
3933
+ if (commandId === "view.top") return scrollActivePane("top", ctx.count);
3934
+ if (commandId === "view.bottom") return scrollActivePane("bottom", ctx.count);
3935
+ if (commandId === "view.scrollDown") return scrollActivePane("down", ctx.count);
3936
+ if (commandId === "view.scrollUp") return scrollActivePane("up", ctx.count);
3937
+ if (commandId === "tab.next") return stepTab(ctx.count) || stepSection(ctx.count);
3938
+ if (commandId === "tab.prev") return stepTab(-ctx.count) || stepSection(-ctx.count);
3939
+ if (commandId === "section.next") return stepSection(ctx.count);
3940
+ if (commandId === "section.prev") return stepSection(-ctx.count);
3941
+ if (commandId === "focus.nextBlock") return stepFocusInPane(ctx.count);
3942
+ if (commandId === "focus.prevBlock") return stepFocusInPane(-ctx.count);
3943
+ if (commandId.startsWith("motion.")) {
3944
+ const motion = commandId.slice("motion.".length);
3945
+ if (editorTarget) {
3946
+ const handled = editorTarget.move(motion, {
3947
+ preset,
3948
+ mode,
3949
+ count: ctx.count
3950
+ });
3951
+ if (motion === "lineSelect" && mode === "normal") {
3952
+ setMode("select");
3953
+ }
3954
+ return handled;
3955
+ }
3956
+ if (activeEl && (activeEl.isContentEditable || activeEl.getAttribute("contenteditable") === "true")) {
3957
+ const handled = handleGenericContentEditableMotion(activeEl, motion, ctx.count);
3958
+ if (handled && motion === "lineSelect" && mode === "normal") {
3959
+ setMode("select");
3960
+ }
3961
+ return handled;
3962
+ }
3963
+ const activeTab = activeEl?.closest('[role="tab"]');
3964
+ const activeTablist = activeTab?.closest('[role="tablist"]');
3965
+ if (activeTab && activeTablist) {
3966
+ const isVertical = activeTablist.getAttribute("aria-orientation") === "vertical" || activeTablist.getAttribute("data-orientation") === "vertical";
3967
+ if (!isVertical) {
3968
+ if (motion === "right" || motion === "wordForward" || motion === "wordEnd") {
3969
+ return stepTab(ctx.count);
3970
+ }
3971
+ if (motion === "left" || motion === "wordBackward") {
3972
+ return stepTab(-ctx.count);
3973
+ }
3974
+ if (motion === "lineStart") {
3975
+ return stepTab(0, "first");
3976
+ }
3977
+ if (motion === "lineEnd") {
3978
+ return stepTab(0, "last");
3979
+ }
3980
+ } else {
3981
+ if (motion === "down") {
3982
+ return stepTab(ctx.count);
3983
+ }
3984
+ if (motion === "up") {
3985
+ return stepTab(-ctx.count);
3986
+ }
3987
+ if (motion === "lineStart") {
3988
+ return stepTab(0, "first");
3989
+ }
3990
+ if (motion === "lineEnd") {
3991
+ return stepTab(0, "last");
3992
+ }
3993
+ }
3994
+ }
3995
+ switch (motion) {
3996
+ case "down":
3997
+ return stepFocusVerticalInPane(ctx.count);
3998
+ case "up":
3999
+ return stepFocusVerticalInPane(-ctx.count);
4000
+ case "wordForward":
4001
+ case "wordEnd":
4002
+ case "right":
4003
+ return stepFocusInPane(ctx.count);
4004
+ case "wordBackward":
4005
+ case "left":
4006
+ return stepFocusInPane(-ctx.count);
4007
+ case "paragraphForward":
4008
+ return stepSection(ctx.count);
4009
+ case "paragraphBackward":
4010
+ return stepSection(-ctx.count);
4011
+ case "docStart":
4012
+ return jumpToBoundary("start");
4013
+ case "docEnd":
4014
+ return jumpToBoundary("end");
4015
+ case "lineStart":
4016
+ return jumpToBoundary("first-in-group");
4017
+ case "lineEnd":
4018
+ return jumpToBoundary("last-in-group");
4019
+ case "lineSelect":
4020
+ setMode(mode === "select" ? "normal" : "select");
4021
+ return true;
4022
+ }
4023
+ }
4024
+ if (commandId.startsWith("textObject.")) {
4025
+ const spec = commandId.slice("textObject.".length);
4026
+ if (editorTarget) {
4027
+ return editorTarget.selectTextObject(spec, { preset, mode });
4028
+ }
4029
+ return false;
4030
+ }
4031
+ if (commandId.startsWith("selection.")) {
4032
+ const transform = commandId.slice("selection.".length);
4033
+ if (editorTarget) {
4034
+ const handled = editorTarget.transformSelection(transform);
4035
+ if (transform === "collapse" && mode === "select") {
4036
+ setMode("normal");
4037
+ }
4038
+ return handled;
4039
+ }
4040
+ if (transform === "collapse" && mode === "select") {
4041
+ setMode("normal");
4042
+ return true;
4043
+ }
4044
+ return false;
4045
+ }
4046
+ if (commandId.startsWith("operator.")) {
4047
+ const op = commandId.slice("operator.".length);
4048
+ const emitYankNotification = (yankedText) => {
4049
+ if (!yankedText) return;
4050
+ options.onYank?.(yankedText, ctx);
4051
+ if (typeof CustomEvent === "function") {
4052
+ const dispatchTarget = activeEl ?? doc ?? null;
4053
+ dispatchTarget?.dispatchEvent?.(
4054
+ new CustomEvent("helical:yank", {
4055
+ bubbles: true,
4056
+ detail: {
4057
+ text: yankedText,
4058
+ preset: ctx.preset,
4059
+ mode: ctx.mode,
4060
+ count: ctx.count
4061
+ }
4062
+ })
4063
+ );
4064
+ }
4065
+ };
4066
+ if (editorTarget) {
4067
+ const res = editorTarget.execOperator(op, {
4068
+ preset,
4069
+ mode,
4070
+ count: ctx.count
4071
+ });
4072
+ if (op === "yank" && typeof res === "object" && res !== null && typeof res.yankedText === "string") {
4073
+ emitYankNotification(res.yankedText);
4074
+ }
4075
+ const shouldEnterInsert = typeof res === "object" && res !== null && res.enterInsert || op === "change" || op === "insertStart" || op === "appendEnd" || op === "openBelow" || op === "openAbove";
4076
+ if (shouldEnterInsert) {
4077
+ setMode("insert");
4078
+ } else if ((op === "delete" || op === "yank") && mode === "select") {
4079
+ setMode("normal");
4080
+ }
4081
+ return Boolean(res);
4082
+ }
4083
+ if (op === "yank") {
4084
+ let selectedText = "";
4085
+ if (activeEl instanceof HTMLInputElement || activeEl instanceof HTMLTextAreaElement) {
4086
+ const start = activeEl.selectionStart ?? 0;
4087
+ const end = activeEl.selectionEnd ?? 0;
4088
+ selectedText = activeEl.value.slice(start, end);
4089
+ } else {
4090
+ selectedText = doc?.defaultView?.getSelection?.()?.toString() ?? "";
4091
+ }
4092
+ if (selectedText && typeof navigator !== "undefined" && navigator.clipboard?.writeText) {
4093
+ void navigator.clipboard.writeText(selectedText).catch(() => {
4094
+ });
4095
+ }
4096
+ emitYankNotification(selectedText);
4097
+ if (mode === "select") {
4098
+ setMode("normal");
4099
+ }
4100
+ return Boolean(selectedText);
4101
+ }
4102
+ if (op === "insertStart" && activeEl?.hasAttribute("data-example")) {
4103
+ return enterExampleContainer(activeEl);
4104
+ }
4105
+ if (op === "change" && activeEl && !isTextEntryElement(activeEl)) {
4106
+ const exampleCard = activeEl.closest("[data-example]");
4107
+ if (exampleCard) {
4108
+ const toggle = exampleCard.querySelector("[data-example-toggle]");
4109
+ if (toggle) {
4110
+ toggle.click();
4111
+ announce("Toggled example code");
4112
+ return true;
4113
+ }
4114
+ }
4115
+ }
4116
+ if (op === "insertStart" || op === "appendEnd" || op === "change") {
4117
+ if (isTextEntryElement(activeEl)) {
4118
+ if (activeEl instanceof HTMLInputElement || activeEl instanceof HTMLTextAreaElement) {
4119
+ try {
4120
+ const pos = op === "insertStart" ? 0 : activeEl.value.length;
4121
+ activeEl.setSelectionRange(pos, pos);
4122
+ } catch {
4123
+ }
4124
+ }
4125
+ setMode("insert");
4126
+ return true;
4127
+ }
4128
+ setMode("insert");
4129
+ return true;
4130
+ }
4131
+ }
4132
+ return false;
4133
+ }
4134
+ function executeCommand(commandId, partialCtx) {
4135
+ const count = partialCtx?.count ?? (countBuffer ? Math.max(1, Number.parseInt(countBuffer, 10)) : 1);
4136
+ const ctx = {
4137
+ count,
4138
+ mode: partialCtx?.mode ?? mode,
4139
+ preset: partialCtx?.preset ?? preset,
4140
+ activePaneId: partialCtx?.activePaneId ?? activePaneId,
4141
+ event: partialCtx?.event
4142
+ };
4143
+ const customHandler = commandHandlers.get(commandId);
4144
+ let handled = false;
4145
+ if (customHandler) {
4146
+ const res = customHandler(ctx);
4147
+ handled = res !== false;
4148
+ }
4149
+ if (!handled) {
4150
+ handled = executeBuiltInCommand(commandId, ctx);
4151
+ }
4152
+ options.onCommand?.(commandId, ctx);
4153
+ return handled;
4154
+ }
4155
+ function invokeNode(node, event) {
4156
+ const count = countBuffer ? Math.max(1, Number.parseInt(countBuffer, 10)) : 1;
4157
+ const ctx = {
4158
+ count,
4159
+ mode,
4160
+ preset,
4161
+ activePaneId,
4162
+ event
4163
+ };
4164
+ let handled = false;
4165
+ if (node.action) {
4166
+ const res = node.action(ctx);
4167
+ handled = res !== false;
4168
+ }
4169
+ if (!handled && node.commandId) {
4170
+ handled = executeCommand(node.commandId, ctx);
4171
+ }
4172
+ countBuffer = "";
4173
+ if (!sticky) {
4174
+ activePath = [];
4175
+ }
4176
+ emit();
4177
+ return handled;
4178
+ }
4179
+ function executeExplorerEntry(entryOrId) {
4180
+ const state = computeState();
4181
+ const entry = typeof entryOrId === "string" ? state.explorerEntries.find((item) => item.id === entryOrId) : entryOrId;
4182
+ if (!entry) return false;
4183
+ closeExplorer();
4184
+ const ctx = {
4185
+ count: 1,
4186
+ mode,
4187
+ preset,
4188
+ activePaneId
4189
+ };
4190
+ let handled = false;
4191
+ if (entry.action) {
4192
+ const res = entry.action(ctx);
4193
+ handled = res !== false;
4194
+ }
4195
+ if (!handled && entry.commandId) {
4196
+ handled = executeCommand(entry.commandId, ctx);
4197
+ }
4198
+ emit();
4199
+ return handled;
4200
+ }
4201
+ function handleJumpKeyDown(event) {
4202
+ if (event.key === "Escape") {
4203
+ event.preventDefault();
4204
+ event.stopPropagation();
4205
+ event.stopImmediatePropagation?.();
4206
+ cancelJumpMode();
4207
+ return true;
4208
+ }
4209
+ if (event.key === "Backspace") {
4210
+ event.preventDefault();
4211
+ event.stopPropagation();
4212
+ if (jumpQuery.length > 0) {
4213
+ jumpQuery = jumpQuery.slice(0, -1);
4214
+ emit();
4215
+ } else {
4216
+ cancelJumpMode();
4217
+ }
4218
+ return true;
4219
+ }
4220
+ if (event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) {
4221
+ const nextQuery = jumpQuery + event.key.toLowerCase();
4222
+ const matching = rawJumpTargets.filter((t) => t.label.startsWith(nextQuery));
4223
+ event.preventDefault();
4224
+ event.stopPropagation();
4225
+ if (matching.length === 0) {
4226
+ return true;
4227
+ }
4228
+ const exact = matching.find((t) => t.label === nextQuery);
4229
+ if (exact && matching.length === 1) {
4230
+ recordCurrentLocation();
4231
+ const targetEl = exact.element;
4232
+ const actionToRun = jumpAction;
4233
+ jumpQuery = "";
4234
+ rawJumpTargets = [];
4235
+ mode = "normal";
4236
+ for (const pane of panes.values()) {
4237
+ if (pane.element && pane.element.contains(targetEl)) {
4238
+ activePaneId = pane.id;
4239
+ break;
4240
+ }
4241
+ }
4242
+ focusElementInActivePane(targetEl);
4243
+ if (actionToRun === "activate") {
4244
+ targetEl.click();
4245
+ }
4246
+ recordCurrentLocation();
4247
+ emit();
4248
+ return true;
4249
+ }
4250
+ jumpQuery = nextQuery;
4251
+ emit();
4252
+ return true;
4253
+ }
4254
+ return false;
4255
+ }
4256
+ function triggerKey(key, event) {
4257
+ const rootTrie = buildMergedTrie();
4258
+ if (activePath.length > 0) {
4259
+ const currentParent = resolveNode(rootTrie, activePath, mode);
4260
+ if (!currentParent) {
4261
+ closePrefix();
4262
+ return false;
4263
+ }
4264
+ const children = getNodeChildren(currentParent, rootTrie);
4265
+ const child = children[key];
4266
+ if (!child || !nodeMatchesMode(child, mode)) {
4267
+ if (!sticky) {
4268
+ closePrefix();
4269
+ }
4270
+ return false;
4271
+ }
4272
+ if (isGroupNode(child, rootTrie)) {
4273
+ activePath = [...activePath, key];
4274
+ if (child.sticky || child.loop) {
4275
+ sticky = true;
4276
+ }
4277
+ announce(`${child.group ?? child.label} menu`);
4278
+ emit();
4279
+ return true;
4280
+ }
4281
+ return invokeNode(child, event);
4282
+ }
4283
+ if (/^[0-9]$/.test(key) && (countBuffer.length > 0 || key !== "0" || !rootTrie["0"])) {
4284
+ if (countBuffer.length > 0 || key !== "0") {
4285
+ countBuffer += key;
4286
+ emit();
4287
+ return true;
4288
+ }
4289
+ }
4290
+ const rootNode = rootTrie[key];
4291
+ if (!rootNode || !nodeMatchesMode(rootNode, mode)) {
4292
+ return false;
4293
+ }
4294
+ if (isGroupNode(rootNode, rootTrie)) {
4295
+ activePath = [key];
4296
+ sticky = Boolean(rootNode.sticky || rootNode.loop);
4297
+ announce(`${rootNode.group ?? rootNode.label} menu`);
4298
+ emit();
4299
+ return true;
4300
+ }
4301
+ return invokeNode(rootNode, event);
4302
+ }
4303
+ function handleKeyDown(event) {
4304
+ if (!isControllerEnabled()) return false;
4305
+ if (event.defaultPrevented && activePath.length === 0 && mode !== "jump") {
4306
+ return false;
4307
+ }
4308
+ if (explorerOpen) {
4309
+ if (event.key === "Escape") {
4310
+ event.preventDefault();
4311
+ event.stopPropagation();
4312
+ closeExplorer();
4313
+ return true;
4314
+ }
4315
+ return false;
4316
+ }
4317
+ const doc = resolveDoc();
4318
+ const targetEl = (isElementLike(event.target) ? event.target : null) ?? doc?.activeElement ?? null;
4319
+ const editorTarget = getModalEditor(targetEl);
4320
+ const inEditable = isTextEntryElement(targetEl);
4321
+ if (mode === "insert") {
4322
+ if (event.key === "Escape") {
4323
+ if (editorTarget?.hasActiveSuggestion?.()) {
4324
+ return false;
4325
+ }
4326
+ event.preventDefault();
4327
+ event.stopPropagation();
4328
+ event.stopImmediatePropagation?.();
4329
+ setMode("normal");
4330
+ return true;
4331
+ }
4332
+ return false;
4333
+ }
4334
+ if (mode === "jump") {
4335
+ return handleJumpKeyDown(event);
4336
+ }
4337
+ if (activePath.length > 0) {
4338
+ if (event.key === "Escape") {
4339
+ event.preventDefault();
4340
+ event.stopPropagation();
4341
+ event.stopImmediatePropagation?.();
4342
+ closePrefix();
4343
+ return true;
4344
+ }
4345
+ if (event.key === "Backspace") {
4346
+ event.preventDefault();
4347
+ event.stopPropagation();
4348
+ event.stopImmediatePropagation?.();
4349
+ stepBackPrefix();
4350
+ return true;
4351
+ }
4352
+ const chordCandidates2 = eventToChordKeys(event);
4353
+ if (chordCandidates2.length === 0) return false;
4354
+ const rootTrie2 = buildMergedTrie();
4355
+ const parentNode = resolveNode(rootTrie2, activePath, mode);
4356
+ const children = parentNode ? getNodeChildren(parentNode, rootTrie2) : {};
4357
+ const matchedChord = chordCandidates2.find((c) => Boolean(children[c]));
4358
+ event.preventDefault();
4359
+ event.stopPropagation();
4360
+ if (matchedChord) {
4361
+ return triggerKey(matchedChord, event);
4362
+ }
4363
+ if (!sticky) {
4364
+ closePrefix();
4365
+ }
4366
+ return true;
4367
+ }
4368
+ if (event.key === "Escape") {
4369
+ if (editorTarget && (mode === "select" || !editorTarget.hasActiveSuggestion?.())) {
4370
+ event.preventDefault();
4371
+ event.stopPropagation();
4372
+ countBuffer = "";
4373
+ editorTarget.setModalState({ mode: "normal", preset });
4374
+ if (mode === "select") {
4375
+ editorTarget.transformSelection("collapse");
4376
+ setMode("normal");
4377
+ } else {
4378
+ emit();
4379
+ }
4380
+ return true;
4381
+ }
4382
+ if (countBuffer.length > 0 || mode === "select") {
4383
+ event.preventDefault();
4384
+ event.stopPropagation();
4385
+ countBuffer = "";
4386
+ if (editorTarget) {
4387
+ editorTarget.transformSelection("collapse");
4388
+ }
4389
+ if (mode === "select") {
4390
+ setMode("normal");
4391
+ } else {
4392
+ emit();
4393
+ }
4394
+ return true;
4395
+ }
4396
+ const parentExample = targetEl instanceof HTMLElement && !targetEl.hasAttribute("data-example") ? targetEl.closest("[data-example]") : null;
4397
+ const hasOpenFloatingSurface = Boolean(
4398
+ doc?.querySelector(
4399
+ '[data-scope="popover"][data-state="open"], [data-scope="menu"][data-state="open"], [data-scope="select"][data-state="open"], [data-scope="combobox"][data-state="open"], [role="dialog"]:not([hidden]):not([data-state="closed"]), [role="listbox"]:not([hidden]):not([data-state="closed"]), [aria-expanded="true"]'
4400
+ )
4401
+ );
4402
+ if (parentExample && (!doc || !getTopMostModalDialog(doc) && !hasOpenFloatingSurface)) {
4403
+ event.preventDefault();
4404
+ event.stopPropagation();
4405
+ if (doc) {
4406
+ lastInteractedScopeByDoc.set(doc, null);
4407
+ }
4408
+ focusElementInActivePane(parentExample);
4409
+ announce("Exited example preview");
4410
+ emit();
4411
+ return true;
4412
+ }
4413
+ return false;
4414
+ }
4415
+ if (event.key === "Enter" && !event.ctrlKey && !event.metaKey && !event.altKey && targetEl instanceof HTMLElement && targetEl.hasAttribute("data-example")) {
4416
+ event.preventDefault();
4417
+ event.stopPropagation();
4418
+ return enterExampleContainer(targetEl);
4419
+ }
4420
+ if (event.key === "Enter" && !event.ctrlKey && !event.metaKey && !event.altKey && inEditable && !editorTarget) {
4421
+ event.preventDefault();
4422
+ event.stopPropagation();
4423
+ setMode("insert");
4424
+ return true;
4425
+ }
4426
+ if (event.key === " " && !event.ctrlKey && !event.metaKey && !event.altKey && targetEl) {
4427
+ const role = targetEl.getAttribute("role");
4428
+ const isToggleControl = targetEl instanceof HTMLInputElement && (targetEl.type === "checkbox" || targetEl.type === "radio") || role === "checkbox" || role === "switch" || role === "radio";
4429
+ if (isToggleControl) {
4430
+ return false;
4431
+ }
4432
+ const isButtonControl = targetEl.tagName === "BUTTON" || role === "button";
4433
+ if (isButtonControl) {
4434
+ const previewAncestor = targetEl.closest("[data-example-preview]");
4435
+ const ownScope = options.getScopeElement?.() ?? null;
4436
+ if (previewAncestor && (!ownScope || !previewAncestor.contains(ownScope))) {
4437
+ return false;
4438
+ }
4439
+ }
4440
+ }
4441
+ if (editorTarget && !editorTarget.hasActiveSuggestion?.() && !event.ctrlKey && !event.metaKey && !event.altKey && (event.key === "ArrowLeft" || event.key === "ArrowRight" || event.key === "ArrowUp" || event.key === "ArrowDown")) {
4442
+ const arrowMotion = event.key === "ArrowLeft" ? "left" : event.key === "ArrowRight" ? "right" : event.key === "ArrowUp" ? "up" : "down";
4443
+ if (event.shiftKey && mode === "normal") {
4444
+ setMode("select");
4445
+ }
4446
+ const effectiveMode = event.shiftKey ? "select" : mode;
4447
+ const count = countBuffer.length > 0 ? Math.max(1, Number.parseInt(countBuffer, 10)) : 1;
4448
+ countBuffer = "";
4449
+ event.preventDefault();
4450
+ event.stopPropagation();
4451
+ editorTarget.move(arrowMotion, { preset, mode: effectiveMode, count });
4452
+ emit();
4453
+ return true;
4454
+ }
4455
+ const chordCandidates = eventToChordKeys(event);
4456
+ if (chordCandidates.length === 0) return false;
4457
+ const rootTrie = buildMergedTrie();
4458
+ for (const candidate of chordCandidates) {
4459
+ if (/^[0-9]$/.test(candidate) && (countBuffer.length > 0 || candidate !== "0" || !rootTrie["0"])) {
4460
+ if (countBuffer.length > 0 || candidate !== "0") {
4461
+ event.preventDefault();
4462
+ event.stopPropagation();
4463
+ return triggerKey(candidate, event);
4464
+ }
4465
+ }
4466
+ if (rootTrie[candidate] && nodeMatchesMode(rootTrie[candidate], mode)) {
4467
+ event.preventDefault();
4468
+ event.stopPropagation();
4469
+ return triggerKey(candidate, event);
4470
+ }
4471
+ }
4472
+ if (inEditable && event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) {
4473
+ event.preventDefault();
4474
+ event.stopPropagation();
4475
+ return true;
4476
+ }
4477
+ return false;
4478
+ }
4479
+ function attach(target) {
4480
+ detachCleanups.forEach((fn) => fn());
4481
+ detachCleanups = [];
4482
+ const doc = target instanceof Document ? target : target?.ownerDocument ?? resolveDoc();
4483
+ if (!doc) return () => {
4484
+ };
4485
+ const eventTarget = target ?? doc;
4486
+ try {
4487
+ const cleanupModality = trackInteractionModality({
4488
+ root: doc,
4489
+ onChange: () => {
4490
+ }
4491
+ });
4492
+ detachCleanups.push(cleanupModality);
4493
+ } catch {
4494
+ }
4495
+ try {
4496
+ liveRegion = createLiveRegion({
4497
+ level: "polite",
4498
+ document: doc
4499
+ });
4500
+ detachCleanups.push(() => {
4501
+ liveRegion?.destroy();
4502
+ liveRegion = null;
4503
+ });
4504
+ } catch {
4505
+ liveRegion = null;
4506
+ }
4507
+ const entry = {
4508
+ getScopeElement: () => options.getScopeElement?.() ?? null,
4509
+ isBusy: () => activePath.length > 0 || sticky || explorerOpen || mode === "jump" || countBuffer.length > 0
4510
+ };
4511
+ let docEntries = attachedEntriesByDoc.get(doc);
4512
+ if (!docEntries) {
4513
+ docEntries = /* @__PURE__ */ new Set();
4514
+ attachedEntriesByDoc.set(doc, docEntries);
4515
+ }
4516
+ docEntries.add(entry);
4517
+ detachCleanups.push(() => {
4518
+ docEntries?.delete(entry);
4519
+ });
4520
+ if (!options.getScopeElement?.()) {
4521
+ const storedPreset = readStoredPreset();
4522
+ if (storedPreset && !options.preset) {
4523
+ preset = storedPreset;
4524
+ }
4525
+ const storedJump = readStoredJumpAction();
4526
+ if (storedJump && !options.jumpAction) {
4527
+ jumpAction = storedJump;
4528
+ }
4529
+ if (doc.documentElement) {
4530
+ doc.documentElement.dataset.keymapPreset = preset;
4531
+ doc.documentElement.dataset.jumpAction = jumpAction;
4532
+ }
4533
+ rootControllerByDoc.set(doc, controllerApi);
4534
+ notifyRootControllerListeners(doc);
4535
+ detachCleanups.push(() => {
4536
+ if (rootControllerByDoc.get(doc) === controllerApi) {
4537
+ rootControllerByDoc.delete(doc);
4538
+ notifyRootControllerListeners(doc);
4539
+ }
4540
+ });
4541
+ }
4542
+ syncDomPanes(doc);
4543
+ emit();
4544
+ const onPointerDown = (e) => {
4545
+ if (!isControllerEnabled()) return;
4546
+ const targetNode = e.target instanceof Element ? e.target : null;
4547
+ if (!targetNode) return;
4548
+ if (!targetNode.closest(
4549
+ '[data-which-key-root], [data-which-key-explorer], [data-which-key-jump-overlay], [data-scope="dialog"]'
4550
+ )) {
4551
+ const clickedScope = targetNode.closest("[data-which-key-scope]") ?? null;
4552
+ if (!clickedScope || isScopeElementActive(clickedScope, doc)) {
4553
+ lastInteractedScopeByDoc.set(doc, clickedScope);
4554
+ }
4555
+ }
4556
+ if (!shouldEntryHandleEvent(entry, doc)) return;
4557
+ for (const pane of panes.values()) {
4558
+ if (pane.element && pane.element.contains(targetNode)) {
4559
+ if (activePaneId !== pane.id) {
4560
+ activePaneId = pane.id;
4561
+ emit();
4562
+ }
4563
+ break;
4564
+ }
4565
+ }
4566
+ if (isTextEntryElement(targetNode) && (mode === "normal" || mode === "select")) {
4567
+ setMode("insert");
4568
+ }
4569
+ };
4570
+ const onFocusIn = (e) => {
4571
+ if (!isControllerEnabled()) return;
4572
+ const targetNode = e.target instanceof HTMLElement ? e.target : null;
4573
+ if (!targetNode) return;
4574
+ if (programmaticFocusDepth === 0 && !targetNode.closest(
4575
+ '[data-which-key-root], [data-which-key-explorer], [data-which-key-jump-overlay], [data-scope="dialog"]'
4576
+ )) {
4577
+ const focusedScope = targetNode.closest("[data-which-key-scope]") ?? null;
4578
+ if (!focusedScope || isScopeElementActive(focusedScope, doc)) {
4579
+ lastInteractedScopeByDoc.set(doc, focusedScope);
4580
+ }
4581
+ }
4582
+ if (!shouldEntryHandleEvent(entry, doc)) return;
4583
+ for (const pane of panes.values()) {
4584
+ if (pane.element && pane.element.contains(targetNode)) {
4585
+ const prevPaneId = activePaneId;
4586
+ activePaneId = pane.id;
4587
+ pane.lastFocusedElement = targetNode;
4588
+ if (prevPaneId !== pane.id) {
4589
+ emit();
4590
+ }
4591
+ break;
4592
+ }
4593
+ }
4594
+ if (programmaticFocusDepth > 0) {
4595
+ return;
4596
+ }
4597
+ if (isTextEntryElement(targetNode) && !getModalEditor(targetNode)) {
4598
+ if (mode === "normal" || mode === "select") {
4599
+ setMode("insert");
4600
+ }
4601
+ }
4602
+ };
4603
+ const onKeyDown = (e) => {
4604
+ if (!shouldEntryHandleEvent(entry, doc)) return;
4605
+ if (e instanceof KeyboardEvent || e && typeof e.key === "string") {
4606
+ handleKeyDown(e);
4607
+ }
4608
+ };
4609
+ eventTarget.addEventListener("pointerdown", onPointerDown, true);
4610
+ eventTarget.addEventListener("focusin", onFocusIn, true);
4611
+ eventTarget.addEventListener("keydown", onKeyDown, true);
4612
+ detachCleanups.push(() => {
4613
+ eventTarget.removeEventListener("pointerdown", onPointerDown, true);
4614
+ eventTarget.removeEventListener("focusin", onFocusIn, true);
4615
+ eventTarget.removeEventListener("keydown", onKeyDown, true);
4616
+ });
4617
+ return () => {
4618
+ detachCleanups.forEach((fn) => fn());
4619
+ detachCleanups = [];
4620
+ };
4621
+ }
4622
+ function destroy() {
4623
+ detachCleanups.forEach((fn) => fn());
4624
+ detachCleanups = [];
4625
+ listeners.clear();
4626
+ panes.clear();
4627
+ keymapLayers.clear();
4628
+ }
4629
+ function registerKeymap(id, nodes, layerOptions) {
4630
+ keymapLayers.set(id, {
4631
+ id,
4632
+ nodes,
4633
+ scope: layerOptions?.scope,
4634
+ enabled: layerOptions?.enabled ?? true
4635
+ });
4636
+ emit();
4637
+ return () => {
4638
+ keymapLayers.delete(id);
4639
+ emit();
4640
+ };
4641
+ }
4642
+ function registerCommand(commandId, handler) {
4643
+ commandHandlers.set(commandId, handler);
4644
+ return () => {
4645
+ if (commandHandlers.get(commandId) === handler) {
4646
+ commandHandlers.delete(commandId);
4647
+ }
4648
+ };
4649
+ }
4650
+ function registerPane(pane) {
4651
+ const existing = panes.get(pane.id);
4652
+ const registration = {
4653
+ id: pane.id,
4654
+ title: pane.title,
4655
+ element: pane.element,
4656
+ disabled: pane.disabled,
4657
+ order: pane.order ?? existing?.order ?? panes.size + 1,
4658
+ lastFocusedElement: existing?.lastFocusedElement ?? null
4659
+ };
4660
+ panes.set(pane.id, registration);
4661
+ if (!activePaneId && !pane.disabled && pane.element) {
4662
+ activePaneId = pane.id;
4663
+ }
4664
+ emit();
4665
+ return () => {
4666
+ panes.delete(pane.id);
4667
+ if (activePaneId === pane.id) {
4668
+ const remaining = getOrderedPanes();
4669
+ activePaneId = remaining[0]?.id ?? null;
4670
+ }
4671
+ emit();
4672
+ };
4673
+ }
4674
+ function trackBranchElement(nodeOrFn) {
4675
+ try {
4676
+ return trackDismissableBranch(nodeOrFn, { defer: true });
4677
+ } catch {
4678
+ return () => {
4679
+ };
4680
+ }
4681
+ }
4682
+ const controllerApi = {
4683
+ getState: () => cachedState,
4684
+ subscribe: (listener) => {
4685
+ listeners.add(listener);
4686
+ return () => {
4687
+ listeners.delete(listener);
4688
+ };
4689
+ },
4690
+ attach,
4691
+ destroy,
4692
+ handleKeyDown,
4693
+ setPreset,
4694
+ setMode,
4695
+ setJumpAction,
4696
+ openPrefix,
4697
+ closePrefix,
4698
+ stepBackPrefix,
4699
+ triggerKey: (key) => triggerKey(key),
4700
+ openExplorer,
4701
+ closeExplorer,
4702
+ setExplorerQuery,
4703
+ executeExplorerEntry,
4704
+ registerKeymap,
4705
+ registerCommand,
4706
+ executeCommand,
4707
+ registerPane,
4708
+ focusPane,
4709
+ focusPaneDirection,
4710
+ cyclePane,
4711
+ stepFocusInPane,
4712
+ jumpToBoundary,
4713
+ scrollActivePane,
4714
+ startJumpMode,
4715
+ cancelJumpMode,
4716
+ jumpBack,
4717
+ jumpForward,
4718
+ trackBranchElement
4719
+ };
4720
+ return controllerApi;
4721
+ }
4722
+
4723
+ // src/which-key/styles.ts
4724
+ import { cva as cva20 } from "class-variance-authority";
4725
+ var whichKeyVariants = cva20(
4726
+ "fixed z-50 flex flex-col overflow-hidden border bg-popover/95 text-popover-foreground shadow-xl backdrop-blur-md transition-all duration-150 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
4727
+ {
4728
+ variants: {
4729
+ variant: {
4730
+ helix: "right-4 bottom-4 w-80 max-w-[calc(100vw-2rem)] rounded-lg data-[state=closed]:slide-out-to-bottom-2 data-[state=open]:slide-in-from-bottom-2",
4731
+ modern: "bottom-4 left-1/2 w-[min(36rem,calc(100vw-2rem))] -translate-x-1/2 rounded-xl data-[state=closed]:slide-out-to-bottom-2 data-[state=open]:slide-in-from-bottom-2",
4732
+ classic: "inset-x-0 bottom-0 w-full rounded-none border-x-0 border-b-0 px-4 py-2"
4733
+ }
4734
+ },
4735
+ defaultVariants: {
4736
+ variant: "helix"
4737
+ }
4738
+ }
4739
+ );
4740
+ var whichKeyHeaderBase = "flex items-center justify-between gap-2 px-3 pt-2.5 pb-1 text-xs font-medium";
4741
+ var whichKeyTitleBase = "flex items-center gap-1.5 font-semibold text-foreground";
4742
+ var whichKeyBreadcrumbBase = "flex items-center gap-1 text-[11px] text-muted-foreground";
4743
+ var whichKeyBodyVariants = cva20("p-1.5", {
4744
+ variants: {
4745
+ variant: {
4746
+ helix: "flex flex-col gap-0.5",
4747
+ modern: "grid grid-cols-1 gap-1 sm:grid-cols-2",
4748
+ classic: "grid grid-cols-2 gap-x-4 gap-y-1 sm:grid-cols-3 md:grid-cols-4"
4749
+ }
4750
+ },
4751
+ defaultVariants: {
4752
+ variant: "helix"
4753
+ }
4754
+ });
4755
+ var whichKeyItemBase = "group flex w-full cursor-pointer items-center justify-between gap-3 rounded-md px-2 py-1 text-left text-xs transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:bg-accent focus-visible:text-accent-foreground focus-visible:outline-none";
4756
+ var whichKeyItemLabelBase = "truncate text-foreground group-hover:text-accent-foreground data-[group=true]:font-medium data-[group=true]:text-primary";
4757
+ var whichKeyFooterBase = "flex items-center justify-between gap-2 px-3 pt-1 pb-2 text-[10px] text-muted-foreground";
4758
+ var whichKeyModeBadgeVariants = cva20(
4759
+ "inline-flex items-center gap-1 rounded font-mono font-semibold tracking-wider uppercase select-none",
4760
+ {
4761
+ variants: {
4762
+ mode: {
4763
+ normal: "bg-primary/15 text-primary",
4764
+ select: "bg-warn/20 text-warn",
4765
+ insert: "bg-success/20 text-success",
4766
+ jump: "bg-info/20 text-info"
4767
+ },
4768
+ size: {
4769
+ sm: "px-1.5 py-0.5 text-[10px]",
4770
+ md: "px-2 py-0.5 text-xs",
4771
+ lg: "px-2.5 py-1 text-sm"
4772
+ }
4773
+ },
4774
+ defaultVariants: {
4775
+ mode: "normal",
4776
+ size: "sm"
4777
+ }
4778
+ }
4779
+ );
4780
+ var whichKeyExplorerContentBase = "flex max-h-[min(34rem,85vh)] w-full max-w-xl flex-col gap-0 overflow-hidden bg-popover p-0 text-popover-foreground";
4781
+ var whichKeyExplorerHeaderBase = "flex flex-row items-center justify-between gap-2 px-4 pt-3.5 pb-2.5";
4782
+ var whichKeyExplorerListboxBase = "flex min-h-0 flex-1 flex-col rounded-none border-0 bg-transparent shadow-none";
4783
+ var whichKeyExplorerInputBase = "mx-4 mb-2 w-[calc(100%-2rem)] rounded-md border-0 border-b-2 border-transparent bg-muted/60 px-3 py-2 text-sm text-foreground outline-none transition-colors placeholder:text-muted-foreground focus:border-primary focus-visible:border-primary focus-visible:ring-0";
4784
+ var whichKeyExplorerListContentBase = "max-h-none flex-1 overflow-visible px-2.5 pt-1 pb-3 outline-none";
4785
+ var whichKeyExplorerItemBase = "flex w-full cursor-pointer items-center justify-between gap-3 rounded-md px-2.5 py-1.5 text-sm outline-none data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground";
4786
+ var whichKeyExplorerHighlightMarkBase = "rounded-xs bg-primary/20 px-0.5 font-semibold text-foreground";
4787
+ var paneVariants = cva20(
4788
+ "relative transition-shadow duration-150 data-[pane-active=true]:ring-1 data-[pane-active=true]:ring-primary/40",
4789
+ {
4790
+ variants: {
4791
+ active: {
4792
+ true: "ring-1 ring-primary/40",
4793
+ false: ""
4794
+ }
4795
+ },
4796
+ defaultVariants: {
4797
+ active: false
4798
+ }
4799
+ }
4800
+ );
4801
+ var jumpOverlayRootBase = "pointer-events-none fixed inset-0 z-[60] overflow-hidden";
4802
+ var jumpBadgeVariants = cva20(
4803
+ "pointer-events-auto fixed z-[61] inline-flex items-center justify-center rounded border px-1 py-0.5 font-mono text-[11px] leading-none font-bold shadow-md transition-transform select-none",
4804
+ {
4805
+ variants: {
4806
+ action: {
4807
+ focus: "border-primary bg-primary text-primary-foreground",
4808
+ activate: "border-warn bg-warn text-warn-foreground"
4809
+ }
4810
+ },
4811
+ defaultVariants: {
4812
+ action: "focus"
4813
+ }
4814
+ }
4815
+ );
4816
+ var jumpBadgeMatchedPrefixBase = "opacity-50 line-through";
1210
4817
 
1211
4818
  // src/editor/build-extensions.ts
1212
4819
  import StarterKit from "@tiptap/starter-kit";
@@ -1315,9 +4922,898 @@ var EditorHeading = Heading2.extend({
1315
4922
  });
1316
4923
 
1317
4924
  // src/editor/extensions/slash-commands.ts
1318
- import { Extension as Extension3 } from "@tiptap/core";
1319
- import { PluginKey as PluginKey2 } from "@tiptap/pm/state";
4925
+ import { Extension as Extension4 } from "@tiptap/core";
4926
+ import { PluginKey as PluginKey3 } from "@tiptap/pm/state";
1320
4927
  import Suggestion from "@tiptap/suggestion";
4928
+
4929
+ // src/editor/extensions/modal-keymap.ts
4930
+ import { Extension as Extension3 } from "@tiptap/core";
4931
+ import { undo, redo } from "@tiptap/pm/history";
4932
+ import { NodeSelection, Plugin as Plugin2, PluginKey as PluginKey2, Selection, TextSelection } from "@tiptap/pm/state";
4933
+ import { Decoration, DecorationSet } from "@tiptap/pm/view";
4934
+ var modalKeymapPluginKey = new PluginKey2("modalKeymap");
4935
+ function collectLeafBlocks(doc) {
4936
+ const blocks = [];
4937
+ doc.descendants((node, pos) => {
4938
+ if (node.isTextblock) {
4939
+ blocks.push({
4940
+ node,
4941
+ pos,
4942
+ start: pos + 1,
4943
+ end: pos + 1 + node.content.size,
4944
+ isTextblock: true,
4945
+ isAtom: false
4946
+ });
4947
+ return false;
4948
+ }
4949
+ if (node.isAtom && !node.isText) {
4950
+ blocks.push({
4951
+ node,
4952
+ pos,
4953
+ start: pos,
4954
+ end: pos + node.nodeSize,
4955
+ isTextblock: false,
4956
+ isAtom: true
4957
+ });
4958
+ return false;
4959
+ }
4960
+ return true;
4961
+ });
4962
+ return blocks;
4963
+ }
4964
+ function collectWords(doc) {
4965
+ const tokens = [];
4966
+ doc.descendants((node, pos) => {
4967
+ if (!node.isTextblock) return true;
4968
+ const blockStart = pos + 1;
4969
+ const blockEnd = pos + 1 + node.content.size;
4970
+ let offset = 0;
4971
+ node.forEach((child) => {
4972
+ if (child.isText && child.text) {
4973
+ const regex = /\w+|[^\w\s]+/g;
4974
+ let match = regex.exec(child.text);
4975
+ while (match !== null) {
4976
+ tokens.push({
4977
+ start: blockStart + offset + match.index,
4978
+ end: blockStart + offset + match.index + match[0].length,
4979
+ text: match[0],
4980
+ blockStart,
4981
+ blockEnd
4982
+ });
4983
+ match = regex.exec(child.text);
4984
+ }
4985
+ } else if (child.isAtom) {
4986
+ tokens.push({
4987
+ start: blockStart + offset,
4988
+ end: blockStart + offset + child.nodeSize,
4989
+ text: "\uFFFC",
4990
+ blockStart,
4991
+ blockEnd
4992
+ });
4993
+ }
4994
+ offset += child.nodeSize;
4995
+ });
4996
+ return false;
4997
+ });
4998
+ return tokens;
4999
+ }
5000
+ function dispatchTransaction(editor, tr) {
5001
+ editor.view.dispatch(tr);
5002
+ }
5003
+ function isEditorInInsertMode(editor) {
5004
+ const storage = editor.storage.modalKeymap;
5005
+ if (!storage) return true;
5006
+ return storage.mode === "insert";
5007
+ }
5008
+ function getEditorModalTarget(editor) {
5009
+ const storage = editor.storage.modalKeymap;
5010
+ if (!storage) return void 0;
5011
+ if (editor.state.plugins.length === 0 && editor.extensionManager?.plugins?.length) {
5012
+ editor.view.updateState(editor.state.reconfigure({ plugins: editor.extensionManager.plugins }));
5013
+ }
5014
+ if (!storage.target) {
5015
+ storage.target = createModalTargetForEditor(editor, { enforceTitle: true });
5016
+ }
5017
+ return storage.target;
5018
+ }
5019
+ var sharedRegisterSlice = null;
5020
+ function getCharEnd(doc, pos) {
5021
+ if (pos < 0 || pos >= doc.content.size) return pos;
5022
+ const $pos = doc.resolve(pos);
5023
+ if ($pos.parent.isTextblock && pos < $pos.end()) {
5024
+ const after = $pos.nodeAfter;
5025
+ if (after && after.isAtom && !after.isText) {
5026
+ return pos + after.nodeSize;
5027
+ }
5028
+ return pos + 1;
5029
+ }
5030
+ return pos;
5031
+ }
5032
+ function getCursorCharPos(doc, sel) {
5033
+ if (sel.empty) return sel.head;
5034
+ if (sel.head > sel.anchor) {
5035
+ const $head = doc.resolve(sel.head);
5036
+ if ($head.parent.isTextblock && sel.head > $head.start() && sel.head - 1 >= sel.from) {
5037
+ return sel.head - 1;
5038
+ }
5039
+ }
5040
+ return sel.head;
5041
+ }
5042
+ function getAnchorCharPos(doc, sel) {
5043
+ if (sel.empty) return sel.anchor;
5044
+ if (sel.head < sel.anchor) {
5045
+ const $anchor = doc.resolve(sel.anchor);
5046
+ if ($anchor.parent.isTextblock && sel.anchor > $anchor.start() && sel.anchor - 1 >= sel.from) {
5047
+ return sel.anchor - 1;
5048
+ }
5049
+ }
5050
+ return sel.anchor;
5051
+ }
5052
+ function createExtendedSelection(doc, sel, nextCursorChar) {
5053
+ const anchorChar = getAnchorCharPos(doc, sel);
5054
+ if (nextCursorChar >= anchorChar) {
5055
+ return TextSelection.create(doc, anchorChar, getCharEnd(doc, nextCursorChar));
5056
+ }
5057
+ return TextSelection.create(doc, getCharEnd(doc, anchorChar), nextCursorChar);
5058
+ }
5059
+ function createModalTargetForEditor(editor, options) {
5060
+ const getStorage = () => editor.storage.modalKeymap;
5061
+ const updateMeta = (tr, patch) => {
5062
+ const prev = modalKeymapPluginKey.getState(editor.state) ?? {
5063
+ mode: getStorage().mode,
5064
+ preset: getStorage().preset,
5065
+ secondaryRanges: [],
5066
+ goalColumn: null
5067
+ };
5068
+ return tr.setMeta(modalKeymapPluginKey, {
5069
+ ...prev,
5070
+ ...patch
5071
+ });
5072
+ };
5073
+ return {
5074
+ move(motion, { preset, mode, count }) {
5075
+ const state = editor.state;
5076
+ const doc = state.doc;
5077
+ const sel = state.selection;
5078
+ const steps = Math.max(1, count);
5079
+ const isSelectionFirst = (preset === "helix" || preset === "kakoune") && mode === "normal";
5080
+ const isExtend = mode === "select";
5081
+ let tr = state.tr;
5082
+ const pluginState = modalKeymapPluginKey.getState(state);
5083
+ if (motion === "wordForward" || motion === "wordBackward" || motion === "wordEnd") {
5084
+ const words = collectWords(doc);
5085
+ if (words.length === 0) return false;
5086
+ const cursor = sel.head;
5087
+ let targetWord;
5088
+ if (motion === "wordForward") {
5089
+ const idx = words.findIndex((w) => w.start > cursor);
5090
+ if (idx === -1) {
5091
+ targetWord = words[words.length - 1];
5092
+ } else {
5093
+ const currentWord = words.find((w) => cursor >= w.start && cursor < w.end);
5094
+ if (isSelectionFirst && currentWord && sel.empty) {
5095
+ targetWord = words[Math.min(words.length - 1, words.indexOf(currentWord) + (steps - 1))];
5096
+ } else {
5097
+ targetWord = words[Math.min(words.length - 1, idx + steps - 1)];
5098
+ }
5099
+ }
5100
+ } else if (motion === "wordEnd") {
5101
+ const idx = words.findIndex((w) => w.end > cursor);
5102
+ targetWord = idx === -1 ? words[words.length - 1] : words[Math.min(words.length - 1, idx + steps - 1)];
5103
+ } else {
5104
+ const backRef = sel.empty ? cursor : sel.from;
5105
+ let idx = -1;
5106
+ for (let i = words.length - 1; i >= 0; i -= 1) {
5107
+ if (words[i].start < backRef) {
5108
+ idx = i;
5109
+ break;
5110
+ }
5111
+ }
5112
+ targetWord = idx === -1 ? words[0] : words[Math.max(0, idx - (steps - 1))];
5113
+ }
5114
+ if (!targetWord) return false;
5115
+ if (isExtend) {
5116
+ const nextCursor = motion === "wordBackward" ? targetWord.start : Math.max(targetWord.start, targetWord.end - 1);
5117
+ tr = tr.setSelection(createExtendedSelection(doc, sel, nextCursor));
5118
+ } else if (isSelectionFirst) {
5119
+ if (motion === "wordBackward") {
5120
+ tr = tr.setSelection(TextSelection.create(doc, targetWord.end, targetWord.start));
5121
+ } else {
5122
+ tr = tr.setSelection(TextSelection.create(doc, targetWord.start, targetWord.end));
5123
+ }
5124
+ } else {
5125
+ const destPos = motion === "wordEnd" ? Math.max(targetWord.start, targetWord.end - 1) : targetWord.start;
5126
+ tr = tr.setSelection(TextSelection.create(doc, destPos));
5127
+ }
5128
+ tr = updateMeta(tr, { goalColumn: null });
5129
+ dispatchTransaction(editor, tr.scrollIntoView());
5130
+ return true;
5131
+ }
5132
+ if (motion === "lineSelect") {
5133
+ const blocks = collectLeafBlocks(doc).filter((b) => b.isTextblock);
5134
+ if (blocks.length === 0) return false;
5135
+ const currentBlockIdx = blocks.findIndex((b) => sel.from >= b.start && sel.from <= b.end);
5136
+ const startIdx = currentBlockIdx === -1 ? 0 : currentBlockIdx;
5137
+ const startBlock = blocks[startIdx];
5138
+ const alreadyCoversCurrent = sel.from <= startBlock.start && sel.to >= startBlock.end && !sel.empty;
5139
+ let endBlockIdx = startIdx + (steps - 1);
5140
+ if (alreadyCoversCurrent) {
5141
+ const currentEndIdx = blocks.findIndex((b) => sel.to >= b.start && sel.to <= b.end);
5142
+ endBlockIdx = (currentEndIdx === -1 ? startIdx : currentEndIdx) + steps;
5143
+ }
5144
+ const endBlock = blocks[Math.min(blocks.length - 1, endBlockIdx)];
5145
+ tr = tr.setSelection(TextSelection.create(doc, startBlock.start, endBlock.end));
5146
+ tr = updateMeta(tr, { goalColumn: null });
5147
+ dispatchTransaction(editor, tr.scrollIntoView());
5148
+ return true;
5149
+ }
5150
+ if (motion === "lineStart" || motion === "lineEnd") {
5151
+ const cursorPos = getCursorCharPos(doc, sel);
5152
+ const $head = doc.resolve(cursorPos);
5153
+ if (isExtend) {
5154
+ const dest = motion === "lineStart" ? $head.start() : Math.max($head.start(), $head.end() - 1);
5155
+ tr = tr.setSelection(createExtendedSelection(doc, sel, dest));
5156
+ } else {
5157
+ const dest = motion === "lineStart" ? $head.start() : $head.end();
5158
+ tr = tr.setSelection(TextSelection.create(doc, dest));
5159
+ }
5160
+ tr = updateMeta(tr, { goalColumn: null });
5161
+ dispatchTransaction(editor, tr.scrollIntoView());
5162
+ return true;
5163
+ }
5164
+ if (motion === "docStart" || motion === "docEnd") {
5165
+ const edgeSel = motion === "docStart" ? Selection.atStart(doc) : Selection.atEnd(doc);
5166
+ if (isExtend) {
5167
+ const dest = motion === "docStart" ? edgeSel.head : Math.max(edgeSel.$head.start(), edgeSel.head - 1);
5168
+ tr = tr.setSelection(createExtendedSelection(doc, sel, dest));
5169
+ } else {
5170
+ tr = tr.setSelection(edgeSel);
5171
+ }
5172
+ tr = updateMeta(tr, { goalColumn: null });
5173
+ dispatchTransaction(editor, tr.scrollIntoView());
5174
+ return true;
5175
+ }
5176
+ if (motion === "paragraphForward" || motion === "paragraphBackward") {
5177
+ const dir = motion === "paragraphForward" ? 1 : -1;
5178
+ const blocks = collectLeafBlocks(doc);
5179
+ if (blocks.length === 0) return false;
5180
+ const cursorPos = getCursorCharPos(doc, sel);
5181
+ let currentIdx = blocks.findIndex(
5182
+ (b) => b.isTextblock ? cursorPos >= b.start && cursorPos <= b.end : sel.from === b.pos
5183
+ );
5184
+ if (currentIdx === -1) {
5185
+ currentIdx = 0;
5186
+ }
5187
+ const targetIdx = Math.max(0, Math.min(blocks.length - 1, currentIdx + dir * steps));
5188
+ const targetBlock = blocks[targetIdx];
5189
+ if (targetBlock.isAtom && NodeSelection.isSelectable(targetBlock.node)) {
5190
+ tr = tr.setSelection(NodeSelection.create(doc, targetBlock.pos));
5191
+ } else if (isExtend) {
5192
+ const dest = dir > 0 ? Math.max(targetBlock.start, targetBlock.end - 1) : targetBlock.start;
5193
+ tr = tr.setSelection(createExtendedSelection(doc, sel, dest));
5194
+ } else if (isSelectionFirst) {
5195
+ tr = tr.setSelection(TextSelection.create(doc, targetBlock.start, targetBlock.end));
5196
+ } else {
5197
+ tr = tr.setSelection(TextSelection.create(doc, targetBlock.start));
5198
+ }
5199
+ tr = updateMeta(tr, { goalColumn: null });
5200
+ dispatchTransaction(editor, tr.scrollIntoView());
5201
+ return true;
5202
+ }
5203
+ if (motion === "left" || motion === "right") {
5204
+ const dir = motion === "left" ? -1 : 1;
5205
+ const blocks = collectLeafBlocks(doc);
5206
+ if (blocks.length === 0) return false;
5207
+ let targetPos = getCursorCharPos(doc, sel);
5208
+ for (let i = 0; i < steps; i += 1) {
5209
+ const $pos = doc.resolve(targetPos);
5210
+ const nextInBlock = targetPos + dir;
5211
+ if ($pos.parent.isTextblock && nextInBlock >= $pos.start() && nextInBlock <= $pos.end()) {
5212
+ const childNode = dir > 0 ? $pos.nodeAfter : $pos.nodeBefore;
5213
+ if (childNode && childNode.isAtom && !childNode.isText && NodeSelection.isSelectable(childNode)) {
5214
+ const atomPos = dir > 0 ? targetPos : targetPos - childNode.nodeSize;
5215
+ tr = tr.setSelection(NodeSelection.create(doc, atomPos));
5216
+ tr = updateMeta(tr, { goalColumn: null });
5217
+ dispatchTransaction(editor, tr.scrollIntoView());
5218
+ return true;
5219
+ }
5220
+ targetPos = nextInBlock;
5221
+ } else {
5222
+ const found = Selection.findFrom(
5223
+ doc.resolve(Math.max(0, Math.min(doc.content.size, targetPos + dir))),
5224
+ dir,
5225
+ true
5226
+ );
5227
+ if (found) {
5228
+ targetPos = found.head;
5229
+ }
5230
+ }
5231
+ }
5232
+ tr = tr.setSelection(
5233
+ isExtend ? createExtendedSelection(doc, sel, targetPos) : TextSelection.create(doc, targetPos)
5234
+ );
5235
+ tr = updateMeta(tr, { goalColumn: null });
5236
+ dispatchTransaction(editor, tr.scrollIntoView());
5237
+ return true;
5238
+ }
5239
+ if (motion === "down" || motion === "up") {
5240
+ const dir = motion === "down" ? 1 : -1;
5241
+ const blocks = collectLeafBlocks(doc);
5242
+ if (blocks.length === 0) return false;
5243
+ const cursorPos = getCursorCharPos(doc, sel);
5244
+ let currentIdx = blocks.findIndex(
5245
+ (b) => b.isTextblock ? cursorPos >= b.start && cursorPos <= b.end : sel.from === b.pos
5246
+ );
5247
+ if (currentIdx === -1) {
5248
+ currentIdx = 0;
5249
+ }
5250
+ const currentBlock = blocks[currentIdx];
5251
+ const currentColumn = currentBlock.isTextblock ? cursorPos - currentBlock.start : 0;
5252
+ const goalCol = pluginState?.goalColumn ?? currentColumn;
5253
+ const targetIdx = Math.max(0, Math.min(blocks.length - 1, currentIdx + dir * steps));
5254
+ const targetBlock = blocks[targetIdx];
5255
+ if (targetBlock.isAtom && NodeSelection.isSelectable(targetBlock.node)) {
5256
+ tr = tr.setSelection(NodeSelection.create(doc, targetBlock.pos));
5257
+ } else {
5258
+ const maxTargetPos = targetBlock.end > targetBlock.start ? targetBlock.end - 1 : targetBlock.start;
5259
+ const nextHead = Math.min(targetBlock.start + goalCol, isExtend ? maxTargetPos : targetBlock.end);
5260
+ tr = tr.setSelection(
5261
+ isExtend ? createExtendedSelection(doc, sel, nextHead) : TextSelection.create(doc, nextHead)
5262
+ );
5263
+ }
5264
+ tr = updateMeta(tr, { goalColumn: goalCol });
5265
+ dispatchTransaction(editor, tr.scrollIntoView());
5266
+ return true;
5267
+ }
5268
+ return false;
5269
+ },
5270
+ selectTextObject(spec) {
5271
+ const state = editor.state;
5272
+ const doc = state.doc;
5273
+ const sel = state.selection;
5274
+ const isInner = spec.startsWith("i");
5275
+ const kind = spec.slice(1);
5276
+ if (kind === "w") {
5277
+ const words = collectWords(doc);
5278
+ if (words.length === 0) return false;
5279
+ const cursor = sel.head;
5280
+ const matched = words.find((w) => cursor >= w.start && cursor <= w.end) ?? words.find((w) => w.start >= cursor) ?? words[words.length - 1];
5281
+ let from = matched.start;
5282
+ let to = matched.end;
5283
+ if (!isInner) {
5284
+ const $end = doc.resolve(to);
5285
+ const afterText = doc.textBetween(to, $end.end(), "");
5286
+ const trailingWs = /^\s+/.exec(afterText);
5287
+ if (trailingWs) {
5288
+ to += trailingWs[0].length;
5289
+ } else {
5290
+ const $start = doc.resolve(from);
5291
+ const beforeText = doc.textBetween($start.start(), from, "");
5292
+ const leadingWs = /\s+$/.exec(beforeText);
5293
+ if (leadingWs) {
5294
+ from -= leadingWs[0].length;
5295
+ }
5296
+ }
5297
+ }
5298
+ const tr2 = state.tr.setSelection(TextSelection.create(doc, from, to));
5299
+ dispatchTransaction(editor, tr2.scrollIntoView());
5300
+ return true;
5301
+ }
5302
+ const matchesNodeType = (typeName) => {
5303
+ switch (kind) {
5304
+ case "p":
5305
+ return typeName === "paragraph" || typeName === "heading";
5306
+ case "c":
5307
+ return typeName === "codeBlock";
5308
+ case "n":
5309
+ return typeName === "notice" || typeName === "blockquote";
5310
+ case "l":
5311
+ return typeName === "listItem" || typeName === "taskItem";
5312
+ default:
5313
+ return false;
5314
+ }
5315
+ };
5316
+ const $head = sel.$head;
5317
+ let targetNode = null;
5318
+ let targetPos = -1;
5319
+ if (kind === "p") {
5320
+ for (let d = $head.depth; d >= 1; d -= 1) {
5321
+ const ancestor = $head.node(d);
5322
+ if (ancestor.type.name === "paragraph") {
5323
+ targetNode = ancestor;
5324
+ targetPos = $head.before(d);
5325
+ break;
5326
+ }
5327
+ }
5328
+ if (!targetNode) {
5329
+ doc.descendants((node, pos) => {
5330
+ if (targetNode) return false;
5331
+ if (node.type.name === "paragraph") {
5332
+ targetNode = node;
5333
+ targetPos = pos;
5334
+ return false;
5335
+ }
5336
+ return true;
5337
+ });
5338
+ }
5339
+ }
5340
+ if (!targetNode) {
5341
+ for (let d = $head.depth; d >= 1; d -= 1) {
5342
+ const ancestor = $head.node(d);
5343
+ if (matchesNodeType(ancestor.type.name)) {
5344
+ targetNode = ancestor;
5345
+ targetPos = $head.before(d);
5346
+ break;
5347
+ }
5348
+ }
5349
+ }
5350
+ if (!targetNode) {
5351
+ doc.descendants((node, pos) => {
5352
+ if (targetNode) return false;
5353
+ if (matchesNodeType(node.type.name)) {
5354
+ targetNode = node;
5355
+ targetPos = pos;
5356
+ return false;
5357
+ }
5358
+ return true;
5359
+ });
5360
+ }
5361
+ if (!targetNode || targetPos < 0) return false;
5362
+ const foundNode = targetNode;
5363
+ let firstTextStart = -1;
5364
+ let lastTextEnd = -1;
5365
+ foundNode.descendants((child, relPos) => {
5366
+ if (child.isTextblock) {
5367
+ const absStart = targetPos + 1 + relPos + 1;
5368
+ const absEnd = absStart + child.content.size;
5369
+ if (firstTextStart === -1) firstTextStart = absStart;
5370
+ lastTextEnd = absEnd;
5371
+ return false;
5372
+ }
5373
+ return true;
5374
+ });
5375
+ if (foundNode.isTextblock) {
5376
+ firstTextStart = targetPos + 1;
5377
+ lastTextEnd = targetPos + 1 + foundNode.content.size;
5378
+ }
5379
+ if (firstTextStart === -1 || lastTextEnd === -1) return false;
5380
+ if (isInner) {
5381
+ const tr2 = state.tr.setSelection(TextSelection.create(doc, firstTextStart, lastTextEnd));
5382
+ dispatchTransaction(editor, tr2.scrollIntoView());
5383
+ return true;
5384
+ }
5385
+ const nodeStart = Selection.findFrom(doc.resolve(targetPos), 1, true)?.from ?? firstTextStart;
5386
+ const nodeEnd = Selection.findFrom(doc.resolve(targetPos + foundNode.nodeSize), -1, true)?.to ?? lastTextEnd;
5387
+ const tr = state.tr.setSelection(
5388
+ TextSelection.create(doc, Math.min(nodeStart, firstTextStart), Math.max(nodeEnd, lastTextEnd))
5389
+ );
5390
+ dispatchTransaction(editor, tr.scrollIntoView());
5391
+ return true;
5392
+ },
5393
+ transformSelection(action) {
5394
+ const state = editor.state;
5395
+ const doc = state.doc;
5396
+ const sel = state.selection;
5397
+ const pluginState = modalKeymapPluginKey.getState(state);
5398
+ const currentSecondary = pluginState?.secondaryRanges ?? [];
5399
+ if (action === "collapse") {
5400
+ let tr = state.tr.setSelection(TextSelection.create(doc, getCursorCharPos(doc, sel)));
5401
+ tr = updateMeta(tr, { secondaryRanges: [] });
5402
+ dispatchTransaction(editor, tr);
5403
+ return true;
5404
+ }
5405
+ if (action === "flip") {
5406
+ if (sel.empty) return false;
5407
+ const tr = state.tr.setSelection(TextSelection.create(doc, sel.head, sel.anchor));
5408
+ dispatchTransaction(editor, tr);
5409
+ return true;
5410
+ }
5411
+ if (action === "keepPrimary") {
5412
+ const tr = updateMeta(state.tr, { secondaryRanges: [] });
5413
+ dispatchTransaction(editor, tr);
5414
+ return true;
5415
+ }
5416
+ if (action === "addCursorBelow" || action === "addCursorAbove") {
5417
+ const dir = action === "addCursorBelow" ? 1 : -1;
5418
+ const blocks = collectLeafBlocks(doc).filter((b) => b.isTextblock);
5419
+ if (blocks.length < 2) return false;
5420
+ const referenceHead = currentSecondary.length > 0 ? currentSecondary[currentSecondary.length - 1].head : sel.head;
5421
+ const currentIdx = blocks.findIndex((b) => referenceHead >= b.start && referenceHead <= b.end);
5422
+ if (currentIdx === -1) return false;
5423
+ const nextIdx = currentIdx + dir;
5424
+ if (nextIdx < 0 || nextIdx >= blocks.length) return false;
5425
+ const currBlock = blocks[currentIdx];
5426
+ const nextBlock = blocks[nextIdx];
5427
+ const colOffset = referenceHead - currBlock.start;
5428
+ const selLength = Math.max(0, sel.to - sel.from);
5429
+ const nextFrom = Math.min(nextBlock.start + colOffset, nextBlock.end);
5430
+ const nextTo = Math.min(nextFrom + selLength, nextBlock.end);
5431
+ const nextRange = {
5432
+ from: nextFrom,
5433
+ to: nextTo,
5434
+ head: nextTo
5435
+ };
5436
+ const tr = updateMeta(state.tr, {
5437
+ secondaryRanges: [...currentSecondary, nextRange]
5438
+ });
5439
+ dispatchTransaction(editor, tr);
5440
+ return true;
5441
+ }
5442
+ return false;
5443
+ },
5444
+ execOperator(op, { count }) {
5445
+ const state = editor.state;
5446
+ const doc = state.doc;
5447
+ const sel = state.selection;
5448
+ const storage = getStorage();
5449
+ const pluginState = modalKeymapPluginKey.getState(state);
5450
+ const secondaryRanges = pluginState?.secondaryRanges ?? [];
5451
+ if (op === "undo") {
5452
+ if (typeof editor.commands?.undo === "function") {
5453
+ const ok = editor.commands.undo();
5454
+ if (ok) return true;
5455
+ }
5456
+ return undo(state, (tr) => dispatchTransaction(editor, tr));
5457
+ }
5458
+ if (op === "redo") {
5459
+ if (typeof editor.commands?.redo === "function") {
5460
+ const ok = editor.commands.redo();
5461
+ if (ok) return true;
5462
+ }
5463
+ return redo(state, (tr) => dispatchTransaction(editor, tr));
5464
+ }
5465
+ if (op === "insertStart") {
5466
+ let tr = state.tr.setSelection(TextSelection.create(doc, sel.from));
5467
+ tr = updateMeta(tr, { mode: "insert", secondaryRanges: [] });
5468
+ storage.mode = "insert";
5469
+ dispatchTransaction(editor, tr);
5470
+ return { enterInsert: true };
5471
+ }
5472
+ if (op === "appendEnd") {
5473
+ const dest = sel.empty ? Math.min(sel.$head.end(), sel.to + 1) : sel.to;
5474
+ let tr = state.tr.setSelection(TextSelection.create(doc, dest));
5475
+ tr = updateMeta(tr, { mode: "insert", secondaryRanges: [] });
5476
+ storage.mode = "insert";
5477
+ dispatchTransaction(editor, tr);
5478
+ return { enterInsert: true };
5479
+ }
5480
+ if (op === "openBelow" || op === "openAbove") {
5481
+ const $pos = sel.$head;
5482
+ const blockDepth = Math.max(1, $pos.depth);
5483
+ const beforeBlock = $pos.before(blockDepth);
5484
+ const afterBlock = $pos.after(blockDepth);
5485
+ const enforceH1 = options.enforceTitle !== false;
5486
+ const isFirstTitle = enforceH1 && beforeBlock === 0 && doc.firstChild?.type.name === "heading" && doc.firstChild.attrs.level === 1;
5487
+ const insertPos = op === "openBelow" || isFirstTitle ? afterBlock : beforeBlock;
5488
+ const paragraphType = state.schema.nodes.paragraph;
5489
+ if (!paragraphType) return false;
5490
+ const newParagraph = paragraphType.create();
5491
+ let tr = state.tr.insert(insertPos, newParagraph);
5492
+ tr = tr.setSelection(TextSelection.create(tr.doc, insertPos + 1));
5493
+ tr = updateMeta(tr, { mode: "insert", secondaryRanges: [] });
5494
+ storage.mode = "insert";
5495
+ dispatchTransaction(editor, tr.scrollIntoView());
5496
+ return { enterInsert: true };
5497
+ }
5498
+ let primaryFrom = sel.from;
5499
+ let primaryTo = sel.to;
5500
+ if (primaryFrom === primaryTo) {
5501
+ const $head = sel.$head;
5502
+ if ($head.parent.isTextblock) {
5503
+ if (op === "yank") {
5504
+ primaryFrom = $head.start();
5505
+ primaryTo = $head.end();
5506
+ } else {
5507
+ primaryTo = Math.min($head.end(), primaryFrom + Math.max(1, count));
5508
+ }
5509
+ }
5510
+ }
5511
+ if (op === "yank") {
5512
+ const slice = doc.slice(primaryFrom, primaryTo);
5513
+ storage.registerSlice = slice;
5514
+ sharedRegisterSlice = slice;
5515
+ const yankedText = doc.textBetween(primaryFrom, primaryTo, "\n");
5516
+ if (yankedText && typeof navigator !== "undefined" && navigator.clipboard?.writeText) {
5517
+ void navigator.clipboard.writeText(yankedText).catch(() => {
5518
+ });
5519
+ }
5520
+ const tr = state.tr.setSelection(TextSelection.create(doc, primaryFrom));
5521
+ dispatchTransaction(editor, tr);
5522
+ return { enterInsert: false, yankedText };
5523
+ }
5524
+ if (op === "delete" || op === "change") {
5525
+ const enforceH1 = options.enforceTitle !== false;
5526
+ const firstChild = doc.firstChild;
5527
+ const hasTitleH1 = enforceH1 && firstChild?.type.name === "heading" && firstChild.attrs.level === 1;
5528
+ const titleEnd = hasTitleH1 ? 1 + firstChild.content.size : -1;
5529
+ const clampRange = (from, to) => {
5530
+ if (hasTitleH1 && from <= titleEnd) {
5531
+ const clampedFrom = Math.max(1, from);
5532
+ const clampedTo = to <= titleEnd + 1 ? Math.min(titleEnd, to) : to;
5533
+ return { from: clampedFrom, to: Math.max(clampedFrom, clampedTo) };
5534
+ }
5535
+ return { from, to };
5536
+ };
5537
+ const primaryClamped = clampRange(primaryFrom, primaryTo);
5538
+ const slice = doc.slice(primaryClamped.from, primaryClamped.to);
5539
+ storage.registerSlice = slice;
5540
+ sharedRegisterSlice = slice;
5541
+ const allRanges = [
5542
+ primaryClamped,
5543
+ ...secondaryRanges.map(
5544
+ (r) => clampRange(r.from, r.to > r.from ? r.to : Math.min(doc.content.size, r.from + 1))
5545
+ )
5546
+ ].sort((a, b) => b.from - a.from);
5547
+ let tr = state.tr;
5548
+ for (const r of allRanges) {
5549
+ if (r.to > r.from) {
5550
+ tr = tr.delete(r.from, r.to);
5551
+ }
5552
+ }
5553
+ const nextPos = Math.min(tr.doc.content.size, primaryClamped.from);
5554
+ const resolved = Selection.near(tr.doc.resolve(nextPos));
5555
+ tr = tr.setSelection(resolved);
5556
+ const nextMode = op === "change" ? "insert" : storage.mode;
5557
+ storage.mode = nextMode;
5558
+ tr = updateMeta(tr, { mode: nextMode, secondaryRanges: [] });
5559
+ dispatchTransaction(editor, tr.scrollIntoView());
5560
+ return { enterInsert: op === "change" };
5561
+ }
5562
+ if (op === "pasteAfter" || op === "pasteBefore") {
5563
+ const slice = storage.registerSlice ?? sharedRegisterSlice;
5564
+ if (!slice || slice.size === 0) return false;
5565
+ let insertPos = op === "pasteAfter" ? sel.to : sel.from;
5566
+ if (op === "pasteAfter" && sel.empty && sel.$head.parent.isTextblock && insertPos < sel.$head.end()) {
5567
+ insertPos += 1;
5568
+ }
5569
+ let tr = state.tr;
5570
+ for (let i = 0; i < Math.max(1, count); i += 1) {
5571
+ tr = tr.replaceRange(insertPos, insertPos, slice);
5572
+ }
5573
+ dispatchTransaction(editor, tr.scrollIntoView());
5574
+ return true;
5575
+ }
5576
+ return false;
5577
+ },
5578
+ setModalState({ mode: nextMode, preset: nextPreset }) {
5579
+ const storage = getStorage();
5580
+ const prev = modalKeymapPluginKey.getState(editor.state);
5581
+ if (storage.mode === nextMode && storage.preset === nextPreset && prev?.mode === nextMode && prev?.preset === nextPreset) {
5582
+ return;
5583
+ }
5584
+ storage.mode = nextMode;
5585
+ storage.preset = nextPreset;
5586
+ if (prev && prev.mode === nextMode && prev.preset === nextPreset && prev.secondaryRanges.length === 0) {
5587
+ return;
5588
+ }
5589
+ try {
5590
+ const tr = updateMeta(editor.state.tr, {
5591
+ mode: nextMode,
5592
+ preset: nextPreset,
5593
+ ...nextMode === "insert" ? { secondaryRanges: [] } : {}
5594
+ });
5595
+ dispatchTransaction(editor, tr);
5596
+ } catch {
5597
+ }
5598
+ },
5599
+ hasActiveSuggestion() {
5600
+ const doc = typeof document !== "undefined" ? document : null;
5601
+ if (!doc) return false;
5602
+ const activePopup = doc.querySelector(
5603
+ '[data-slash-menu-surface], [data-mention-menu-surface], [data-editor-slash-menu], [data-editor-mention-menu], .tippy-box[data-state="visible"]'
5604
+ );
5605
+ if (activePopup) return true;
5606
+ let root = doc;
5607
+ try {
5608
+ root = editor.view.dom.parentElement ?? doc;
5609
+ } catch {
5610
+ root = doc;
5611
+ }
5612
+ if (root.querySelector('[role="dialog"]')) return true;
5613
+ const toolbars = Array.from(root.querySelectorAll('[role="toolbar"]'));
5614
+ for (const tb of toolbars) {
5615
+ const style = doc.defaultView?.getComputedStyle(tb);
5616
+ if (style && style.display !== "none" && style.visibility !== "hidden" && style.opacity !== "0") {
5617
+ return true;
5618
+ }
5619
+ }
5620
+ return false;
5621
+ }
5622
+ };
5623
+ }
5624
+ var ModalKeymap = Extension3.create({
5625
+ name: "modalKeymap",
5626
+ addOptions() {
5627
+ return {
5628
+ enforceTitle: true
5629
+ };
5630
+ },
5631
+ addStorage() {
5632
+ return {
5633
+ target: null,
5634
+ mode: "insert",
5635
+ preset: "helix",
5636
+ registerSlice: null,
5637
+ cleanupDomRegistration: void 0
5638
+ };
5639
+ },
5640
+ onCreate() {
5641
+ const target = this.storage.target ?? createModalTargetForEditor(this.editor, this.options);
5642
+ this.storage.target = target;
5643
+ try {
5644
+ const dom = this.editor.view.dom;
5645
+ if (typeof HTMLElement !== "undefined" && dom instanceof HTMLElement) {
5646
+ this.storage.cleanupDomRegistration = registerModalEditor(dom, target);
5647
+ }
5648
+ } catch {
5649
+ }
5650
+ },
5651
+ onDestroy() {
5652
+ this.storage.cleanupDomRegistration?.();
5653
+ this.storage.cleanupDomRegistration = void 0;
5654
+ this.storage.target = null;
5655
+ },
5656
+ addProseMirrorPlugins() {
5657
+ const { storage, editor, options } = this;
5658
+ if (!storage.target) {
5659
+ storage.target = createModalTargetForEditor(editor, options);
5660
+ }
5661
+ return [
5662
+ new Plugin2({
5663
+ key: modalKeymapPluginKey,
5664
+ state: {
5665
+ init() {
5666
+ return {
5667
+ mode: storage.mode,
5668
+ preset: storage.preset,
5669
+ secondaryRanges: [],
5670
+ goalColumn: null
5671
+ };
5672
+ },
5673
+ apply(tr, prev) {
5674
+ const meta = tr.getMeta(modalKeymapPluginKey);
5675
+ if (meta) {
5676
+ return {
5677
+ mode: meta.mode ?? prev.mode,
5678
+ preset: meta.preset ?? prev.preset,
5679
+ secondaryRanges: meta.secondaryRanges ?? prev.secondaryRanges,
5680
+ goalColumn: meta.goalColumn !== void 0 ? meta.goalColumn : prev.goalColumn
5681
+ };
5682
+ }
5683
+ if (tr.docChanged && prev.secondaryRanges.length > 0) {
5684
+ return {
5685
+ ...prev,
5686
+ secondaryRanges: prev.secondaryRanges.map((r) => ({
5687
+ from: tr.mapping.map(r.from),
5688
+ to: tr.mapping.map(r.to),
5689
+ head: tr.mapping.map(r.head)
5690
+ }))
5691
+ };
5692
+ }
5693
+ return prev;
5694
+ }
5695
+ },
5696
+ view(editorView) {
5697
+ if (typeof HTMLElement !== "undefined" && editorView.dom instanceof HTMLElement && storage.target && !storage.cleanupDomRegistration) {
5698
+ storage.cleanupDomRegistration = registerModalEditor(editorView.dom, storage.target);
5699
+ }
5700
+ return {
5701
+ destroy() {
5702
+ storage.cleanupDomRegistration?.();
5703
+ storage.cleanupDomRegistration = void 0;
5704
+ }
5705
+ };
5706
+ },
5707
+ props: {
5708
+ handleDOMEvents: {
5709
+ mousedown(view) {
5710
+ if (storage.mode !== "insert") {
5711
+ storage.mode = "insert";
5712
+ try {
5713
+ const prev = modalKeymapPluginKey.getState(view.state);
5714
+ if (prev && prev.mode !== "insert") {
5715
+ view.dispatch(
5716
+ view.state.tr.setMeta(modalKeymapPluginKey, {
5717
+ ...prev,
5718
+ mode: "insert",
5719
+ secondaryRanges: []
5720
+ })
5721
+ );
5722
+ }
5723
+ } catch {
5724
+ }
5725
+ }
5726
+ return false;
5727
+ }
5728
+ },
5729
+ attributes(state) {
5730
+ const pluginState = modalKeymapPluginKey.getState(state);
5731
+ const currentMode = pluginState?.mode ?? "insert";
5732
+ const currentPreset = pluginState?.preset ?? "helix";
5733
+ return {
5734
+ "data-modal-mode": currentMode,
5735
+ "data-modal-preset": currentPreset
5736
+ };
5737
+ },
5738
+ decorations(state) {
5739
+ const pluginState = modalKeymapPluginKey.getState(state);
5740
+ if (!pluginState || pluginState.mode === "insert") {
5741
+ return DecorationSet.empty;
5742
+ }
5743
+ const decos = [];
5744
+ const { doc, selection } = state;
5745
+ const head = selection.head;
5746
+ const pushCursorDecoration = (pos, isMulti = false) => {
5747
+ if (pos < 0 || pos > doc.content.size) return;
5748
+ const $pos = doc.resolve(pos);
5749
+ const nodeAfter = $pos.nodeAfter;
5750
+ if (nodeAfter?.isText && nodeAfter.text && nodeAfter.text.length > 0 && pos + 1 <= doc.content.size) {
5751
+ decos.push(
5752
+ Decoration.inline(
5753
+ pos,
5754
+ pos + 1,
5755
+ isMulti ? { class: "pm-multi-cursor", "data-pm-multi-cursor": "true" } : { class: "pm-modal-cursor", "data-pm-modal-cursor": pluginState.mode }
5756
+ )
5757
+ );
5758
+ return;
5759
+ }
5760
+ if (typeof document !== "undefined") {
5761
+ decos.push(
5762
+ Decoration.widget(
5763
+ pos,
5764
+ () => {
5765
+ const span = document.createElement("span");
5766
+ span.className = isMulti ? "pm-multi-cursor pm-modal-cursor-eol" : "pm-modal-cursor pm-modal-cursor-eol";
5767
+ span.setAttribute(
5768
+ isMulti ? "data-pm-multi-cursor" : "data-pm-modal-cursor",
5769
+ isMulti ? "true" : pluginState.mode
5770
+ );
5771
+ span.setAttribute("aria-hidden", "true");
5772
+ span.textContent = "\xA0";
5773
+ return span;
5774
+ },
5775
+ {
5776
+ side: 1,
5777
+ key: isMulti ? `multi-cursor-${pos}` : `modal-cursor-${pos}-${pluginState.mode}`
5778
+ }
5779
+ )
5780
+ );
5781
+ }
5782
+ };
5783
+ if (selection.empty) {
5784
+ pushCursorDecoration(head, false);
5785
+ } else if (selection.from < selection.to) {
5786
+ decos.push(
5787
+ Decoration.inline(selection.from, selection.to, {
5788
+ class: "pm-modal-selection",
5789
+ "data-pm-modal-selection": pluginState.mode
5790
+ })
5791
+ );
5792
+ const $head = doc.resolve(head);
5793
+ const cursorPos = selection.head > selection.anchor ? $head.nodeBefore?.isText && head - 1 >= selection.from ? head - 1 : head : head;
5794
+ pushCursorDecoration(cursorPos, false);
5795
+ }
5796
+ for (const range of pluginState.secondaryRanges) {
5797
+ if (range.from >= 0 && range.to <= doc.content.size && range.from < range.to) {
5798
+ decos.push(
5799
+ Decoration.inline(range.from, range.to, {
5800
+ class: "pm-multi-selection",
5801
+ "data-pm-multi-selection": "true"
5802
+ })
5803
+ );
5804
+ } else {
5805
+ pushCursorDecoration(range.head, true);
5806
+ }
5807
+ }
5808
+ return DecorationSet.create(doc, decos);
5809
+ }
5810
+ }
5811
+ })
5812
+ ];
5813
+ }
5814
+ });
5815
+
5816
+ // src/editor/extensions/slash-commands.ts
1321
5817
  function registerImageInsertCallback(editor, cb) {
1322
5818
  editor.storage.slashCommands.onInsertImage = cb;
1323
5819
  }
@@ -1330,13 +5826,14 @@ function registerYouTubeInsertCallback(editor, cb) {
1330
5826
  function unregisterYouTubeInsertCallback(editor) {
1331
5827
  editor.storage.slashCommands.onInsertYouTube = void 0;
1332
5828
  }
1333
- var slashCommands = Extension3.create({
5829
+ var slashCommands = Extension4.create({
1334
5830
  name: "slashCommands",
1335
5831
  addOptions() {
1336
5832
  return {
1337
5833
  suggestion: {
1338
5834
  char: "/",
1339
- pluginKey: new PluginKey2("slashCommands"),
5835
+ pluginKey: new PluginKey3("slashCommands"),
5836
+ allow: ({ editor }) => isEditorInInsertMode(editor),
1340
5837
  command: ({
1341
5838
  editor,
1342
5839
  range,
@@ -1549,9 +6046,9 @@ var createCodeBlockCustom = (lowlight, nodeView) => CodeBlockLowlight.extend({
1549
6046
 
1550
6047
  // src/editor/extensions/image-node.ts
1551
6048
  import { Node as Node2 } from "@tiptap/core";
1552
- import { Plugin as Plugin2, PluginKey as PluginKey3, NodeSelection, TextSelection } from "@tiptap/pm/state";
1553
- import { DecorationSet, Decoration } from "@tiptap/pm/view";
1554
- var imageBackspaceKey = new PluginKey3("imageBackspace");
6049
+ import { Plugin as Plugin3, PluginKey as PluginKey4, NodeSelection as NodeSelection2, TextSelection as TextSelection2 } from "@tiptap/pm/state";
6050
+ import { DecorationSet as DecorationSet2, Decoration as Decoration2 } from "@tiptap/pm/view";
6051
+ var imageBackspaceKey = new PluginKey4("imageBackspace");
1555
6052
  var createImageNode = (nodeView) => Node2.create({
1556
6053
  name: "imageNode",
1557
6054
  group: "block",
@@ -1601,8 +6098,8 @@ var createImageNode = (nodeView) => Node2.create({
1601
6098
  },
1602
6099
  addProseMirrorPlugins() {
1603
6100
  let arrowKeyPressed = false;
1604
- const captionFocusPlugin = new Plugin2({
1605
- key: new PluginKey3("imageNodeCaptionFocus"),
6101
+ const captionFocusPlugin = new Plugin3({
6102
+ key: new PluginKey4("imageNodeCaptionFocus"),
1606
6103
  props: {
1607
6104
  handleKeyDown(_view, event) {
1608
6105
  if (event.key === "ArrowDown" || event.key === "ArrowUp") {
@@ -1616,7 +6113,7 @@ var createImageNode = (nodeView) => Node2.create({
1616
6113
  update(view, prevState) {
1617
6114
  const { selection } = view.state;
1618
6115
  const { selection: prevSelection } = prevState;
1619
- const movedOntoImage = arrowKeyPressed && selection instanceof NodeSelection && selection.node.type.name === "imageNode" && !(prevSelection instanceof NodeSelection && prevSelection.from === selection.from);
6116
+ const movedOntoImage = arrowKeyPressed && selection instanceof NodeSelection2 && selection.node.type.name === "imageNode" && !(prevSelection instanceof NodeSelection2 && prevSelection.from === selection.from);
1620
6117
  arrowKeyPressed = false;
1621
6118
  if (movedOntoImage) {
1622
6119
  const pos = selection.from;
@@ -1626,7 +6123,7 @@ var createImageNode = (nodeView) => Node2.create({
1626
6123
  if (input) {
1627
6124
  const { tr, doc } = view.state;
1628
6125
  const $after = doc.resolve(Math.min(pos + nodeSize, doc.content.size));
1629
- view.dispatch(tr.setSelection(TextSelection.near($after)));
6126
+ view.dispatch(tr.setSelection(TextSelection2.near($after)));
1630
6127
  input.focus({ preventScroll: true });
1631
6128
  setTimeout(() => {
1632
6129
  const rect = input.getBoundingClientRect();
@@ -1640,7 +6137,7 @@ var createImageNode = (nodeView) => Node2.create({
1640
6137
  };
1641
6138
  }
1642
6139
  });
1643
- const backspacePlugin = new Plugin2({
6140
+ const backspacePlugin = new Plugin3({
1644
6141
  key: imageBackspaceKey,
1645
6142
  state: {
1646
6143
  init: () => null,
@@ -1685,8 +6182,8 @@ var createImageNode = (nodeView) => Node2.create({
1685
6182
  if (pendingPos == null) return null;
1686
6183
  const node = state.doc.nodeAt(pendingPos);
1687
6184
  if (!node) return null;
1688
- return DecorationSet.create(state.doc, [
1689
- Decoration.node(pendingPos, pendingPos + node.nodeSize, {
6185
+ return DecorationSet2.create(state.doc, [
6186
+ Decoration2.node(pendingPos, pendingPos + node.nodeSize, {
1690
6187
  class: "image-node-pending-delete"
1691
6188
  })
1692
6189
  ]);
@@ -2002,6 +6499,7 @@ var createInternalMention = ({ mentionSource, hrefBuilder, render }) => Mention.
2002
6499
  suggestion: {
2003
6500
  char: "@",
2004
6501
  allowSpaces: true,
6502
+ allow: ({ editor }) => isEditorInInsertMode(editor),
2005
6503
  command: ({ editor, range, props }) => {
2006
6504
  editor.chain().focus().insertContentAt(range, [
2007
6505
  {
@@ -2024,7 +6522,7 @@ var createInternalMention = ({ mentionSource, hrefBuilder, render }) => Mention.
2024
6522
 
2025
6523
  // src/editor/extensions/notice-node.ts
2026
6524
  import { Node as Node5, mergeAttributes as mergeAttributes4 } from "@tiptap/core";
2027
- import { Plugin as Plugin3 } from "@tiptap/pm/state";
6525
+ import { Plugin as Plugin4 } from "@tiptap/pm/state";
2028
6526
  var createNoticeNode = (nodeView) => Node5.create({
2029
6527
  name: "notice",
2030
6528
  group: "block",
@@ -2061,7 +6559,7 @@ var createNoticeNode = (nodeView) => Node5.create({
2061
6559
  },
2062
6560
  addProseMirrorPlugins() {
2063
6561
  return [
2064
- new Plugin3({
6562
+ new Plugin4({
2065
6563
  props: {
2066
6564
  handleKeyDown: (view, event) => {
2067
6565
  if (event.key !== "ArrowUp") return false;
@@ -2102,23 +6600,23 @@ var createNoticeNode = (nodeView) => Node5.create({
2102
6600
  });
2103
6601
 
2104
6602
  // src/editor/extensions/current-empty-block.ts
2105
- import { Extension as Extension4 } from "@tiptap/core";
2106
- import { Plugin as Plugin4, PluginKey as PluginKey4 } from "@tiptap/pm/state";
2107
- import { Decoration as Decoration2, DecorationSet as DecorationSet2 } from "@tiptap/pm/view";
2108
- var currentEmptyBlockKey = new PluginKey4("currentEmptyBlock");
2109
- var CurrentEmptyBlock = Extension4.create({
6603
+ import { Extension as Extension5 } from "@tiptap/core";
6604
+ import { Plugin as Plugin5, PluginKey as PluginKey5 } from "@tiptap/pm/state";
6605
+ import { Decoration as Decoration3, DecorationSet as DecorationSet3 } from "@tiptap/pm/view";
6606
+ var currentEmptyBlockKey = new PluginKey5("currentEmptyBlock");
6607
+ var CurrentEmptyBlock = Extension5.create({
2110
6608
  name: "currentEmptyBlock",
2111
6609
  addProseMirrorPlugins() {
2112
6610
  return [
2113
- new Plugin4({
6611
+ new Plugin5({
2114
6612
  key: currentEmptyBlockKey,
2115
6613
  props: {
2116
6614
  decorations(state) {
2117
6615
  const { selection } = state;
2118
6616
  const { $from } = selection;
2119
6617
  if (!selection.empty || $from.depth === 0 || $from.parent.content.size > 0) return null;
2120
- return DecorationSet2.create(state.doc, [
2121
- Decoration2.node($from.before($from.depth), $from.after($from.depth), {
6618
+ return DecorationSet3.create(state.doc, [
6619
+ Decoration3.node($from.before($from.depth), $from.after($from.depth), {
2122
6620
  class: "is-current-empty"
2123
6621
  })
2124
6622
  ]);
@@ -2185,7 +6683,8 @@ function buildExtensions(options) {
2185
6683
  createLinkPreview(nodeViews.linkPreview),
2186
6684
  createImageNode(nodeViews.image),
2187
6685
  createUrlMention(nodeViews.urlMention),
2188
- slashCommands.configure({ suggestion: { render: slashRender ?? (() => ({})) } })
6686
+ slashCommands.configure({ suggestion: { render: slashRender ?? (() => ({})) } }),
6687
+ ModalKeymap.configure({ enforceTitle })
2189
6688
  ];
2190
6689
  }
2191
6690
 
@@ -2243,9 +6742,12 @@ function lockEditorOverlayScroll(editorElement, overlayElement) {
2243
6742
  return () => container.removeEventListener("wheel", preventWheel);
2244
6743
  }
2245
6744
  export {
6745
+ DEFAULT_JUMP_ALPHABET,
2246
6746
  EditorHeading,
2247
6747
  ExitHeading,
2248
6748
  HeadingWithId,
6749
+ Jumplist,
6750
+ ModalKeymap,
2249
6751
  SIDEBAR_KEYBOARD_SHORTCUT,
2250
6752
  SIDEBAR_WIDGET_DEFAULT_SNAP_POINT,
2251
6753
  SIDEBAR_WIDGET_SNAP_POINTS,
@@ -2258,6 +6760,7 @@ export {
2258
6760
  badgeVariants,
2259
6761
  buildChartDefinition,
2260
6762
  buildExtensions,
6763
+ buildWhichKeyTree,
2261
6764
  buttonVariants,
2262
6765
  cardBodyBase,
2263
6766
  cardCoverVariants,
@@ -2302,11 +6805,16 @@ export {
2302
6805
  comboboxTriggerBase,
2303
6806
  containerBase,
2304
6807
  createCodeBlockCustom,
6808
+ createHelixPreset,
2305
6809
  createImageNode,
2306
6810
  createInternalMention,
6811
+ createJumplist,
6812
+ createKakounePreset,
2307
6813
  createLinkPreview,
2308
6814
  createNoticeNode,
2309
6815
  createUrlMention,
6816
+ createVimPreset,
6817
+ createWhichKeyController,
2310
6818
  defaultChartColor,
2311
6819
  defaultListboxFilter,
2312
6820
  dialogBackdropBase,
@@ -2320,6 +6828,7 @@ export {
2320
6828
  dialogHeaderStickyBase,
2321
6829
  dialogPositionerBase,
2322
6830
  dialogTitleBase,
6831
+ eventToChordKeys,
2323
6832
  extractYouTubeId,
2324
6833
  feedbackCorrectBase,
2325
6834
  feedbackExplanationBase,
@@ -2337,13 +6846,30 @@ export {
2337
6846
  figureCaptionBase,
2338
6847
  figureImageBase,
2339
6848
  figureRootBase,
6849
+ findDirectionalPane,
2340
6850
  findEditorScrollContainer,
6851
+ flattenKeymapEntries,
6852
+ formatKeyChord,
6853
+ formatKeySequence,
2341
6854
  formatTime,
6855
+ generateJumpLabels,
6856
+ getDocumentWhichKeyController,
6857
+ getEditorModalTarget,
6858
+ getModalEditor,
6859
+ getNodeChildren,
6860
+ getPresetKeymap,
2342
6861
  hstackBase,
2343
6862
  injectCodeBlockStyles,
2344
6863
  inputVariants,
2345
6864
  insertPastedUrlAsLink,
6865
+ isEditorInInsertMode,
6866
+ isGroupNode,
2346
6867
  itemVariants,
6868
+ jumpBadgeMatchedPrefixBase,
6869
+ jumpBadgeVariants,
6870
+ jumpOverlayRootBase,
6871
+ kbdGroupBase,
6872
+ kbdVariants,
2347
6873
  latexDisplayBase,
2348
6874
  latexErrorBase,
2349
6875
  latexInlineBase,
@@ -2352,6 +6878,8 @@ export {
2352
6878
  listboxEmptyBase,
2353
6879
  listboxInputBase,
2354
6880
  listboxItemBase,
6881
+ listboxItemGroupBase,
6882
+ listboxItemGroupLabelBase,
2355
6883
  listboxItemIndicatorBase,
2356
6884
  listboxItemTextBase,
2357
6885
  listboxLabelBase,
@@ -2368,6 +6896,7 @@ export {
2368
6896
  mermaidSourceBase,
2369
6897
  mermaidSvgAspectRatio,
2370
6898
  mermaidSvgBase,
6899
+ modalKeymapPluginKey,
2371
6900
  nativeSelectIconBase,
2372
6901
  nativeSelectVariants,
2373
6902
  nativeSelectWrapperBase,
@@ -2397,9 +6926,12 @@ export {
2397
6926
  navbarShrunkBase,
2398
6927
  navbarTriggerVariants,
2399
6928
  navbarVariants,
6929
+ nodeMatchesMode,
6930
+ normalizeNodeModes,
2400
6931
  noticeDescriptionBase,
2401
6932
  noticeTitleBase,
2402
6933
  noticeVariants,
6934
+ notifyAllModalEditors,
2403
6935
  numberInputControlBase,
2404
6936
  numberInputInputBase,
2405
6937
  numberInputRootBase,
@@ -2415,6 +6947,7 @@ export {
2415
6947
  paginationItemBase,
2416
6948
  paginationRootBase,
2417
6949
  paginationTriggerBase,
6950
+ paneVariants,
2418
6951
  parseYouTubeChapters,
2419
6952
  placeEditorOverlay,
2420
6953
  placeEditorOverlayAt,
@@ -2454,11 +6987,13 @@ export {
2454
6987
  radioGroupItemTextBase,
2455
6988
  radioGroupRootBase,
2456
6989
  registerImageInsertCallback,
6990
+ registerModalEditor,
2457
6991
  registerYouTubeInsertCallback,
2458
6992
  renderChartSvgString,
2459
6993
  renderCodeToHtml,
2460
6994
  renderMermaidSource,
2461
6995
  resolveMermaidThemeVariables,
6996
+ resolveNode,
2462
6997
  revealChevronBase,
2463
6998
  revealContentBase,
2464
6999
  revealRootBase,
@@ -2489,6 +7024,7 @@ export {
2489
7024
  splitterResizeTriggerSeparatorBase,
2490
7025
  splitterRootBase,
2491
7026
  stackBase,
7027
+ subscribeDocumentWhichKeyController,
2492
7028
  switchControlBase,
2493
7029
  switchLabelBase,
2494
7030
  switchThumbBase,
@@ -2518,6 +7054,22 @@ export {
2518
7054
  unregisterImageInsertCallback,
2519
7055
  unregisterYouTubeInsertCallback,
2520
7056
  vstackBase,
7057
+ whichKeyBodyVariants,
7058
+ whichKeyBreadcrumbBase,
7059
+ whichKeyExplorerContentBase,
7060
+ whichKeyExplorerHeaderBase,
7061
+ whichKeyExplorerHighlightMarkBase,
7062
+ whichKeyExplorerInputBase,
7063
+ whichKeyExplorerItemBase,
7064
+ whichKeyExplorerListContentBase,
7065
+ whichKeyExplorerListboxBase,
7066
+ whichKeyFooterBase,
7067
+ whichKeyHeaderBase,
7068
+ whichKeyItemBase,
7069
+ whichKeyItemLabelBase,
7070
+ whichKeyModeBadgeVariants,
7071
+ whichKeyTitleBase,
7072
+ whichKeyVariants,
2521
7073
  windowBodyBase,
2522
7074
  windowCloseTriggerBase,
2523
7075
  windowContentBase,