@cloudvoyant/helical-ui 0.22.0 → 0.23.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.cjs CHANGED
@@ -17,6 +17,7 @@ var __copyProps = (to, from, except, desc) => {
17
17
  }
18
18
  return to;
19
19
  };
20
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
20
21
  var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
22
  // If the importer is in node compatibility mode or this is not an ESM
22
23
  // file that has been converted to a CommonJS file using a Babel-
@@ -249,6 +250,7 @@ __export(index_exports, {
249
250
  navbarShrunkBase: () => navbarShrunkBase,
250
251
  navbarTriggerVariants: () => navbarTriggerVariants,
251
252
  navbarVariants: () => navbarVariants,
253
+ nodeExplicitlyIncludesMode: () => nodeExplicitlyIncludesMode,
252
254
  nodeMatchesMode: () => nodeMatchesMode,
253
255
  normalizeNodeModes: () => normalizeNodeModes,
254
256
  noticeDescriptionBase: () => noticeDescriptionBase,
@@ -346,6 +348,7 @@ __export(index_exports, {
346
348
  selectPositionerBase: () => selectPositionerBase,
347
349
  selectTriggerBase: () => selectTriggerBase,
348
350
  selectValueBase: () => selectValueBase,
351
+ serializeModalSliceText: () => serializeModalSliceText,
349
352
  shouldHandleCommandHotkey: () => shouldHandleCommandHotkey,
350
353
  sidebarMenuButtonVariants: () => sidebarMenuButtonVariants,
351
354
  sidebarStyles: () => sidebarStyles,
@@ -2506,6 +2509,57 @@ var colonCommandPrefixBase = commandMenuPrefixBase;
2506
2509
  var colonCommandInputVariants = commandMenuInputVariants;
2507
2510
  var colonCommandErrorBase = commandMenuErrorBase;
2508
2511
 
2512
+ // src/which-key/index.ts
2513
+ var which_key_exports = {};
2514
+ __export(which_key_exports, {
2515
+ DEFAULT_JUMP_ALPHABET: () => DEFAULT_JUMP_ALPHABET,
2516
+ Jumplist: () => Jumplist,
2517
+ buildWhichKeyTree: () => buildWhichKeyTree,
2518
+ createHelixPreset: () => createHelixPreset,
2519
+ createJumplist: () => createJumplist,
2520
+ createKakounePreset: () => createKakounePreset,
2521
+ createVimPreset: () => createVimPreset,
2522
+ createWhichKeyController: () => createWhichKeyController,
2523
+ eventToChordKeys: () => eventToChordKeys,
2524
+ findDirectionalPane: () => findDirectionalPane,
2525
+ flattenKeymapEntries: () => flattenKeymapEntries,
2526
+ formatWhichKeyLabel: () => formatWhichKeyLabel,
2527
+ generateJumpLabels: () => generateJumpLabels,
2528
+ getDocumentWhichKeyController: () => getDocumentWhichKeyController,
2529
+ getModalEditor: () => getModalEditor,
2530
+ getNodeChildren: () => getNodeChildren,
2531
+ getPresetKeymap: () => getPresetKeymap,
2532
+ isGroupNode: () => isGroupNode,
2533
+ jumpBadgeMatchedPrefixBase: () => jumpBadgeMatchedPrefixBase,
2534
+ jumpBadgeVariants: () => jumpBadgeVariants,
2535
+ jumpOverlayRootBase: () => jumpOverlayRootBase,
2536
+ nodeExplicitlyIncludesMode: () => nodeExplicitlyIncludesMode,
2537
+ nodeMatchesMode: () => nodeMatchesMode,
2538
+ normalizeNodeModes: () => normalizeNodeModes,
2539
+ notifyAllModalEditors: () => notifyAllModalEditors,
2540
+ paneVariants: () => paneVariants,
2541
+ registerModalEditor: () => registerModalEditor,
2542
+ resolveNode: () => resolveNode,
2543
+ subscribeDocumentWhichKeyController: () => subscribeDocumentWhichKeyController,
2544
+ whichKeyBodyVariants: () => whichKeyBodyVariants,
2545
+ whichKeyBreadcrumbBase: () => whichKeyBreadcrumbBase,
2546
+ whichKeyExplorerContentBase: () => whichKeyExplorerContentBase,
2547
+ whichKeyExplorerHeaderBase: () => whichKeyExplorerHeaderBase,
2548
+ whichKeyExplorerHighlightMarkBase: () => whichKeyExplorerHighlightMarkBase,
2549
+ whichKeyExplorerInputBase: () => whichKeyExplorerInputBase,
2550
+ whichKeyExplorerItemBase: () => whichKeyExplorerItemBase,
2551
+ whichKeyExplorerListContentBase: () => whichKeyExplorerListContentBase,
2552
+ whichKeyExplorerListboxBase: () => whichKeyExplorerListboxBase,
2553
+ whichKeyFooterBase: () => whichKeyFooterBase,
2554
+ whichKeyHeaderBase: () => whichKeyHeaderBase,
2555
+ whichKeyItemBase: () => whichKeyItemBase,
2556
+ whichKeyItemLabelBase: () => whichKeyItemLabelBase,
2557
+ whichKeyModeBadgeVariants: () => whichKeyModeBadgeVariants,
2558
+ whichKeyTitleBase: () => whichKeyTitleBase,
2559
+ whichKeyVariants: () => whichKeyVariants
2560
+ });
2561
+ __reExport(which_key_exports, require("@tanstack/hotkeys"));
2562
+
2509
2563
  // src/which-key/core.ts
2510
2564
  var DEFAULT_JUMP_ALPHABET = "asdfghjklqwertyuiopzxcvbnm";
2511
2565
  function nodeMatchesMode(node, mode) {
@@ -2515,6 +2569,13 @@ function nodeMatchesMode(node, mode) {
2515
2569
  }
2516
2570
  return node.mode === mode;
2517
2571
  }
2572
+ function nodeExplicitlyIncludesMode(node, mode) {
2573
+ if (!node.mode) return false;
2574
+ if (Array.isArray(node.mode)) {
2575
+ return node.mode.includes(mode);
2576
+ }
2577
+ return node.mode === mode;
2578
+ }
2518
2579
  function normalizeNodeModes(node) {
2519
2580
  if (!node.mode) return ["normal"];
2520
2581
  return Array.isArray(node.mode) ? node.mode : [node.mode];
@@ -2526,7 +2587,7 @@ function getNodeChildren(node, rootTrie, visitedProxies = /* @__PURE__ */ new Se
2526
2587
  if (!visitedProxies.has(proxyKey)) {
2527
2588
  const nextVisited = new Set(visitedProxies);
2528
2589
  nextVisited.add(proxyKey);
2529
- const target = resolveNodeInternal(rootTrie, node.proxy, void 0, nextVisited);
2590
+ const target = resolveNodeInternal(rootTrie, node.proxy, void 0, nextVisited, rootTrie);
2530
2591
  if (target) {
2531
2592
  proxyChildren = getNodeChildren(target, rootTrie, nextVisited);
2532
2593
  }
@@ -2539,7 +2600,7 @@ function getNodeChildren(node, rootTrie, visitedProxies = /* @__PURE__ */ new Se
2539
2600
  ...node.children ?? {}
2540
2601
  };
2541
2602
  }
2542
- function resolveNodeInternal(rootTrie, path, mode, visitedProxies) {
2603
+ function resolveNodeInternal(rootTrie, path, mode, visitedProxies, proxyRootTrie = rootTrie) {
2543
2604
  if (path.length === 0) return null;
2544
2605
  let currentMap = rootTrie;
2545
2606
  let currentNode = null;
@@ -2551,13 +2612,13 @@ function resolveNodeInternal(rootTrie, path, mode, visitedProxies) {
2551
2612
  if (mode && !nodeMatchesMode(candidate, mode)) return null;
2552
2613
  currentNode = candidate;
2553
2614
  if (i < path.length - 1) {
2554
- currentMap = getNodeChildren(candidate, rootTrie, visitedProxies);
2615
+ currentMap = getNodeChildren(candidate, proxyRootTrie, visitedProxies);
2555
2616
  }
2556
2617
  }
2557
2618
  return currentNode;
2558
2619
  }
2559
- function resolveNode(rootTrie, path, mode) {
2560
- return resolveNodeInternal(rootTrie, path, mode, /* @__PURE__ */ new Set());
2620
+ function resolveNode(rootTrie, path, mode, proxyRootTrie = rootTrie) {
2621
+ return resolveNodeInternal(rootTrie, path, mode, /* @__PURE__ */ new Set(), proxyRootTrie);
2561
2622
  }
2562
2623
  function isGroupNode(node, rootTrie) {
2563
2624
  const children = getNodeChildren(node, rootTrie);
@@ -3006,17 +3067,6 @@ function createWindowMenu() {
3006
3067
  };
3007
3068
  }
3008
3069
  function createSpaceMenu(leaderKey = "Space", viewKey = "z") {
3009
- const paneSlots = {};
3010
- for (let i = 1; i <= 9; i += 1) {
3011
- paneSlots[String(i)] = {
3012
- key: String(i),
3013
- label: `Focus Pane ${i}`,
3014
- description: `Switch focus directly to pane #${i}`,
3015
- category: "Window / Pane",
3016
- commandId: `pane.focus.${i}`,
3017
- hidden: i > 4
3018
- };
3019
- }
3020
3070
  return {
3021
3071
  key: leaderKey,
3022
3072
  label: "Leader",
@@ -3091,8 +3141,7 @@ function createSpaceMenu(leaderKey = "Space", viewKey = "z") {
3091
3141
  commandId: "preset.kakoune"
3092
3142
  }
3093
3143
  }
3094
- },
3095
- ...paneSlots
3144
+ }
3096
3145
  }
3097
3146
  };
3098
3147
  }
@@ -3963,6 +4012,93 @@ var import_dismissable = require("@zag-js/dismissable");
3963
4012
  var import_dom_query = require("@zag-js/dom-query");
3964
4013
  var import_focus_visible = require("@zag-js/focus-visible");
3965
4014
  var import_live_region2 = require("@zag-js/live-region");
4015
+ var PRIORITY_WEIGHT = {
4016
+ overlay: 60,
4017
+ widget: 50,
4018
+ extension: 40,
4019
+ editor: 30,
4020
+ pane: 20,
4021
+ global: 10
4022
+ };
4023
+ function resolveLayerEnabled(layer) {
4024
+ try {
4025
+ return typeof layer.enabled === "function" ? Boolean(layer.enabled()) : Boolean(layer.enabled);
4026
+ } catch {
4027
+ return false;
4028
+ }
4029
+ }
4030
+ function resolveLayerNodes(layer) {
4031
+ try {
4032
+ return (typeof layer.nodes === "function" ? layer.nodes() : layer.nodes) ?? {};
4033
+ } catch {
4034
+ return {};
4035
+ }
4036
+ }
4037
+ function resolveLayerElement(layer) {
4038
+ if (!layer.hasElementOption) return null;
4039
+ try {
4040
+ return (typeof layer.element === "function" ? layer.element() : layer.element) ?? null;
4041
+ } catch {
4042
+ return null;
4043
+ }
4044
+ }
4045
+ function elementContains(container, target) {
4046
+ if (!target) return false;
4047
+ if (container === target) return true;
4048
+ if (typeof container.contains === "function") {
4049
+ try {
4050
+ if (container.contains(target)) return true;
4051
+ } catch {
4052
+ }
4053
+ }
4054
+ let curr = target.parentElement;
4055
+ while (curr) {
4056
+ if (curr === container) return true;
4057
+ curr = curr.parentElement;
4058
+ }
4059
+ return false;
4060
+ }
4061
+ function getElementDepth(el) {
4062
+ let depth = 0;
4063
+ let curr = el.parentElement;
4064
+ while (curr) {
4065
+ depth += 1;
4066
+ curr = curr.parentElement;
4067
+ }
4068
+ return depth;
4069
+ }
4070
+ function compareResolvedLayers(a, b) {
4071
+ if (Boolean(a.isPreset) !== Boolean(b.isPreset)) {
4072
+ return a.isPreset ? 1 : -1;
4073
+ }
4074
+ const aIsOverlay = a.priority === "overlay";
4075
+ const bIsOverlay = b.priority === "overlay";
4076
+ if (aIsOverlay !== bIsOverlay) {
4077
+ return aIsOverlay ? -1 : 1;
4078
+ }
4079
+ if (a.matchedElement && b.matchedElement) {
4080
+ if (a.matchedElement !== b.matchedElement) {
4081
+ if (elementContains(a.matchedElement, b.matchedElement)) {
4082
+ return 1;
4083
+ }
4084
+ if (elementContains(b.matchedElement, a.matchedElement)) {
4085
+ return -1;
4086
+ }
4087
+ if (b.elementDepth !== a.elementDepth) {
4088
+ return b.elementDepth - a.elementDepth;
4089
+ }
4090
+ }
4091
+ } else if (a.matchedElement && !b.matchedElement) {
4092
+ return -1;
4093
+ } else if (!a.matchedElement && b.matchedElement) {
4094
+ return 1;
4095
+ }
4096
+ const weightDiff = PRIORITY_WEIGHT[b.priority] - PRIORITY_WEIGHT[a.priority];
4097
+ if (weightDiff !== 0) {
4098
+ return weightDiff;
4099
+ }
4100
+ return b.registrationOrder - a.registrationOrder;
4101
+ }
3966
4102
  function mergeKeymapTrees(base, overlay) {
3967
4103
  const result = { ...base };
3968
4104
  for (const [key, node] of Object.entries(overlay)) {
@@ -3993,11 +4129,18 @@ function isHTMLElementLike(value) {
3993
4129
  }
3994
4130
  function isTextEntryElement(el) {
3995
4131
  if (!el || !isHTMLElementLike(el)) return false;
3996
- if (getModalEditor(el)) return true;
4132
+ if (el.closest?.("[data-modal-ignore-pointer]")) return false;
4133
+ const tag = typeof el.tagName === "string" ? el.tagName.toLowerCase() : "";
4134
+ if (getModalEditor(el)) {
4135
+ const nonEditableIsland = el.closest?.('[contenteditable="false"]');
4136
+ if (nonEditableIsland) {
4137
+ return tag === "input" || tag === "textarea";
4138
+ }
4139
+ return true;
4140
+ }
3997
4141
  if (el.isContentEditable || el.getAttribute?.("contenteditable") === "true") {
3998
4142
  return true;
3999
4143
  }
4000
- const tag = typeof el.tagName === "string" ? el.tagName.toLowerCase() : "";
4001
4144
  if (tag === "textarea") {
4002
4145
  return !el.disabled && !el.readOnly;
4003
4146
  }
@@ -4024,6 +4167,24 @@ function isTextEntryElement(el) {
4024
4167
  return false;
4025
4168
  }
4026
4169
  }
4170
+ function expandChordCandidateAliases(candidates) {
4171
+ const result = [];
4172
+ const pushUnique = (val) => {
4173
+ if (val && !result.includes(val)) {
4174
+ result.push(val);
4175
+ }
4176
+ };
4177
+ for (const candidate of candidates) {
4178
+ pushUnique(candidate);
4179
+ if (candidate.includes("+") && candidate.length > 1) {
4180
+ pushUnique(candidate.replace(/\b(Control|Ctrl|Alt|Shift|Meta|Mod)\+/g, "$1-"));
4181
+ }
4182
+ if (candidate.includes("-") && candidate.length > 1) {
4183
+ pushUnique(candidate.replace(/\b(Control|Ctrl|Alt|Shift|Meta|Mod)-/g, "$1+"));
4184
+ }
4185
+ }
4186
+ return result;
4187
+ }
4027
4188
  function eventToChordKeys(event) {
4028
4189
  const rawKey = event.key;
4029
4190
  if (!rawKey) return [];
@@ -4048,6 +4209,21 @@ function eventToChordKeys(event) {
4048
4209
  if (baseKey.length === 1 && baseKey.toLowerCase() !== baseKey) {
4049
4210
  candidates2.push([...mods, baseKey.toLowerCase()].join("+"));
4050
4211
  }
4212
+ if (hasCtrl !== hasMeta) {
4213
+ const modAliasMods = ["Mod"];
4214
+ if (hasAlt) modAliasMods.push("Alt");
4215
+ if (hasShift) modAliasMods.push("Shift");
4216
+ const modPrimary = [...modAliasMods, primaryKey].join("+");
4217
+ if (!candidates2.includes(modPrimary)) {
4218
+ candidates2.push(modPrimary);
4219
+ }
4220
+ if (baseKey.length === 1 && baseKey.toLowerCase() !== baseKey) {
4221
+ const modLower = [...modAliasMods, baseKey.toLowerCase()].join("+");
4222
+ if (!candidates2.includes(modLower)) {
4223
+ candidates2.push(modLower);
4224
+ }
4225
+ }
4226
+ }
4051
4227
  try {
4052
4228
  const parsed = (0, import_hotkeys3.parseKeyboardEvent)(event);
4053
4229
  if (parsed?.key) {
@@ -4063,16 +4239,23 @@ function eventToChordKeys(event) {
4063
4239
  }
4064
4240
  } catch {
4065
4241
  }
4066
- return candidates2;
4242
+ return expandChordCandidateAliases(candidates2);
4067
4243
  }
4068
- const candidates = [baseKey];
4244
+ const candidates = [];
4245
+ if (hasShift && baseKey.length > 1) {
4246
+ candidates.push(`Shift+${baseKey}`);
4247
+ if (normalizedName !== baseKey) {
4248
+ candidates.push(`Shift+${normalizedName}`);
4249
+ }
4250
+ }
4251
+ candidates.push(baseKey);
4069
4252
  if (hasShift && baseKey.length === 1) {
4070
4253
  candidates.push(`Shift+${baseKey.toUpperCase()}`);
4071
4254
  candidates.push(`Shift+${baseKey}`);
4072
4255
  } else if (baseKey.length > 1 && normalizedName !== baseKey) {
4073
4256
  candidates.push(normalizedName);
4074
4257
  }
4075
- return candidates;
4258
+ return expandChordCandidateAliases(candidates);
4076
4259
  }
4077
4260
  function getTopMostModalDialog(doc) {
4078
4261
  const dialogs = Array.from(
@@ -4089,15 +4272,66 @@ function getTopMostModalDialog(doc) {
4089
4272
  }
4090
4273
  return dialogs[dialogs.length - 1] ?? null;
4091
4274
  }
4275
+ function getVisibleTreeItems(root) {
4276
+ if (typeof root.querySelectorAll !== "function") return [];
4277
+ const candidates = Array.from(
4278
+ root.querySelectorAll(
4279
+ '[data-part="branch-control"]:not([disabled]):not([data-disabled]):not([aria-disabled="true"]), [role="treeitem"]:not([disabled]):not([data-disabled]):not([aria-disabled="true"]), [data-which-key-target]:not([disabled]):not([data-disabled]):not([aria-disabled="true"])'
4280
+ )
4281
+ );
4282
+ return candidates.filter((el) => {
4283
+ if (el.getAttribute("role") === "treeitem" && el.getAttribute("data-part") === "branch" && el.querySelector('[data-part="branch-control"]')) {
4284
+ return false;
4285
+ }
4286
+ if (el.closest('[hidden], [data-part="branch-content"][data-state="closed"]')) {
4287
+ return false;
4288
+ }
4289
+ const closedBranch = el.closest('[role="treeitem"][aria-expanded="false"]');
4290
+ if (closedBranch && closedBranch !== el) {
4291
+ const isControlForClosedBranch = el.getAttribute("data-part") === "branch-control" && el.closest('[data-part="branch"]') === closedBranch;
4292
+ if (!isControlForClosedBranch) {
4293
+ return false;
4294
+ }
4295
+ }
4296
+ return true;
4297
+ });
4298
+ }
4299
+ function mergeElementsInDomOrder(lists) {
4300
+ const seen = /* @__PURE__ */ new Set();
4301
+ const combined = [];
4302
+ for (const list of lists) {
4303
+ for (const el of list) {
4304
+ if (el instanceof HTMLElement && !seen.has(el)) {
4305
+ seen.add(el);
4306
+ combined.push(el);
4307
+ }
4308
+ }
4309
+ }
4310
+ if (combined.length > 1 && typeof combined[0].compareDocumentPosition === "function") {
4311
+ combined.sort((a, b) => {
4312
+ if (a === b) return 0;
4313
+ const pos = a.compareDocumentPosition(b);
4314
+ if (pos & 4) return -1;
4315
+ if (pos & 2) return 1;
4316
+ return 0;
4317
+ });
4318
+ }
4319
+ return combined;
4320
+ }
4092
4321
  function getPaneFocusableItems(container, ownScope, ignoreEnteredExample = false) {
4093
4322
  const doc = container.ownerDocument;
4094
4323
  const activeEl = doc?.activeElement instanceof HTMLElement ? doc.activeElement : null;
4095
4324
  const enteredExample = !ignoreEnteredExample && !ownScope && activeEl && !activeEl.hasAttribute("data-example") ? activeEl.closest("[data-example]") : null;
4096
4325
  const searchRoot = enteredExample && container.contains(enteredExample) ? enteredExample.querySelector("[data-example-preview]") ?? enteredExample : container;
4097
- const raw = (0, import_dom_query.getFocusables)(searchRoot, { includeContainer: false });
4326
+ const raw = mergeElementsInDomOrder([
4327
+ (0, import_dom_query.getFocusables)(searchRoot, { includeContainer: false }),
4328
+ getVisibleTreeItems(searchRoot)
4329
+ ]);
4098
4330
  return raw.filter((el) => {
4099
4331
  if (!(el instanceof HTMLElement)) return false;
4100
- if (el.tabIndex < 0 && el.getAttribute("role") !== "tab") return false;
4332
+ if (el.tabIndex < 0 && el.getAttribute("role") !== "tab" && el.getAttribute("role") !== "treeitem" && el.getAttribute("data-part") !== "branch-control" && !el.hasAttribute("data-which-key-target")) {
4333
+ return false;
4334
+ }
4101
4335
  if (el.closest(
4102
4336
  '[data-which-key-root], [data-which-key-explorer], [data-which-key-jump-overlay], [data-scope="toast"]'
4103
4337
  )) {
@@ -4130,12 +4364,14 @@ function getJumpableItems(container, ownScope) {
4130
4364
  '[role="tab"]:not([disabled]):not([data-disabled]):not([aria-disabled="true"])'
4131
4365
  )
4132
4366
  );
4367
+ const rawTreeItems = getVisibleTreeItems(container);
4368
+ const merged = mergeElementsInDomOrder([rawFocusables, rawTabs, rawTreeItems]);
4133
4369
  const combined = [];
4134
- const seen = /* @__PURE__ */ new Set();
4135
- for (const el of [...rawFocusables, ...rawTabs]) {
4136
- if (!(el instanceof HTMLElement) || seen.has(el)) continue;
4137
- seen.add(el);
4138
- if (el.tabIndex < 0 && el.getAttribute("role") !== "tab") continue;
4370
+ for (const el of merged) {
4371
+ if (!(el instanceof HTMLElement)) continue;
4372
+ if (el.tabIndex < 0 && el.getAttribute("role") !== "tab" && el.getAttribute("role") !== "treeitem" && el.getAttribute("data-part") !== "branch-control" && !el.hasAttribute("data-which-key-target")) {
4373
+ continue;
4374
+ }
4139
4375
  if (el.closest(
4140
4376
  '[data-which-key-root], [data-which-key-explorer], [data-which-key-jump-overlay], [data-scope="toast"]'
4141
4377
  )) {
@@ -4172,7 +4408,33 @@ function notifyRootControllerListeners(doc) {
4172
4408
  function getDocumentWhichKeyController(doc) {
4173
4409
  const resolved = doc ?? (typeof document !== "undefined" ? document : void 0);
4174
4410
  if (!resolved) return null;
4175
- return rootControllerByDoc.get(resolved) ?? null;
4411
+ const root = rootControllerByDoc.get(resolved);
4412
+ if (root) return root;
4413
+ const entries = attachedEntriesByDoc.get(resolved);
4414
+ if (!entries || entries.size === 0) return null;
4415
+ const activeEl = resolved.activeElement && isElementLike(resolved.activeElement) ? resolved.activeElement : null;
4416
+ const focusedScope = activeEl ? activeEl.closest?.("[data-which-key-scope]") ?? null : null;
4417
+ if (focusedScope) {
4418
+ for (const entry of entries) {
4419
+ if (entry.getScopeElement() === focusedScope) {
4420
+ return entry.controller;
4421
+ }
4422
+ }
4423
+ }
4424
+ const remembered = lastInteractedScopeByDoc.get(resolved) ?? null;
4425
+ if (remembered) {
4426
+ for (const entry of entries) {
4427
+ if (entry.getScopeElement() === remembered) {
4428
+ return entry.controller;
4429
+ }
4430
+ }
4431
+ }
4432
+ for (const entry of entries) {
4433
+ if (isScopeElementActive(entry.getScopeElement(), resolved)) {
4434
+ return entry.controller;
4435
+ }
4436
+ }
4437
+ return Array.from(entries)[0]?.controller ?? null;
4176
4438
  }
4177
4439
  function subscribeDocumentWhichKeyController(doc, listener) {
4178
4440
  const resolved = doc ?? (typeof document !== "undefined" ? document : void 0);
@@ -4321,11 +4583,15 @@ function createWhichKeyController(options = {}) {
4321
4583
  const commandHandlers = /* @__PURE__ */ new Map();
4322
4584
  const panes = /* @__PURE__ */ new Map();
4323
4585
  const jumplist = createJumplist(50);
4586
+ let layerRegistrationCounter = 0;
4324
4587
  if (options.keymap) {
4325
4588
  keymapLayers.set("__initial__", {
4326
4589
  id: "__initial__",
4327
4590
  nodes: options.keymap,
4328
- enabled: true
4591
+ enabled: true,
4592
+ priority: "global",
4593
+ hasElementOption: false,
4594
+ registrationOrder: ++layerRegistrationCounter
4329
4595
  });
4330
4596
  }
4331
4597
  if (options.commands) {
@@ -4361,12 +4627,64 @@ function createWhichKeyController(options = {}) {
4361
4627
  } catch {
4362
4628
  }
4363
4629
  }
4364
- function buildMergedTrie() {
4365
- let trie = getPresetKeymap(preset, leaderKey);
4630
+ function getOrderedActiveLayers(event, includePreset = true, ignoreElementContainment = false) {
4631
+ const doc = resolveDoc();
4632
+ const rawEventTarget = event?.target ?? null;
4633
+ const eventTargetEl = isElementLike(rawEventTarget) ? rawEventTarget : null;
4634
+ const activeEl = doc?.activeElement && isElementLike(doc.activeElement) ? doc.activeElement : null;
4635
+ const resolved = [];
4366
4636
  for (const layer of keymapLayers.values()) {
4367
- if (!layer.enabled) continue;
4637
+ if (!resolveLayerEnabled(layer)) continue;
4368
4638
  if (layer.scope && layer.scope !== activePaneId) continue;
4369
- trie = mergeKeymapTrees(trie, layer.nodes);
4639
+ let matchedElement = null;
4640
+ let elementDepth = -1;
4641
+ if (layer.hasElementOption) {
4642
+ const el = resolveLayerElement(layer);
4643
+ if (!el) continue;
4644
+ if (!ignoreElementContainment) {
4645
+ const containsEventTarget = elementContains(el, eventTargetEl);
4646
+ const containsActiveEl = elementContains(el, activeEl);
4647
+ if (!containsEventTarget && !containsActiveEl) continue;
4648
+ }
4649
+ matchedElement = el;
4650
+ elementDepth = getElementDepth(el);
4651
+ }
4652
+ if (layer.matchesTarget && event) {
4653
+ const checkTarget = rawEventTarget ?? activeEl;
4654
+ try {
4655
+ if (!layer.matchesTarget(checkTarget, event)) continue;
4656
+ } catch {
4657
+ continue;
4658
+ }
4659
+ }
4660
+ resolved.push({
4661
+ id: layer.id,
4662
+ nodes: resolveLayerNodes(layer),
4663
+ priority: layer.priority,
4664
+ matchedElement,
4665
+ elementDepth,
4666
+ registrationOrder: layer.registrationOrder
4667
+ });
4668
+ }
4669
+ resolved.sort(compareResolvedLayers);
4670
+ if (includePreset) {
4671
+ resolved.push({
4672
+ id: "__preset__",
4673
+ nodes: getPresetKeymap(preset, leaderKey),
4674
+ priority: "global",
4675
+ matchedElement: null,
4676
+ elementDepth: -1,
4677
+ registrationOrder: -1,
4678
+ isPreset: true
4679
+ });
4680
+ }
4681
+ return resolved;
4682
+ }
4683
+ function buildMergedTrie() {
4684
+ const layers = getOrderedActiveLayers(void 0, true, true);
4685
+ let trie = {};
4686
+ for (let i = layers.length - 1; i >= 0; i -= 1) {
4687
+ trie = mergeKeymapTrees(trie, layers[i].nodes);
4370
4688
  }
4371
4689
  return trie;
4372
4690
  }
@@ -4789,8 +5107,14 @@ function createWhichKeyController(options = {}) {
4789
5107
  recordCurrentLocation();
4790
5108
  activePaneId = targetPane.id;
4791
5109
  const ownScope = options.getScopeElement?.() ?? null;
4792
- const remembered = targetPane.lastFocusedElement && targetPane.element.contains(targetPane.lastFocusedElement) && (ownScope || !targetPane.lastFocusedElement.closest("[data-which-key-scope]")) ? targetPane.lastFocusedElement : null;
4793
- const firstFocusable = remembered ?? getPaneFocusableItems(targetPane.element, ownScope)[0] ?? null;
5110
+ const hasTree = typeof targetPane.element.querySelector === "function" && Boolean(targetPane.element.querySelector('[role="tree"]'));
5111
+ const remembered = targetPane.lastFocusedElement && targetPane.element.contains(targetPane.lastFocusedElement) && (!hasTree || Boolean(targetPane.lastFocusedElement.closest('[role="tree"]'))) && (ownScope || !targetPane.lastFocusedElement.closest("[data-which-key-scope]")) ? targetPane.lastFocusedElement : null;
5112
+ const preferredTarget = !remembered && typeof targetPane.element.querySelector === "function" ? targetPane.element.querySelector(
5113
+ '[data-pane-focus-target]:not([disabled]):not([data-disabled]):not([aria-disabled="true"]), [role="treeitem"][aria-selected="true"]:not([data-part="branch"]):not([disabled]):not([data-disabled]):not([aria-disabled="true"]), [data-part="branch"][aria-selected="true"] > [data-part="branch-control"]:not([disabled]):not([data-disabled]):not([aria-disabled="true"]), [data-part="branch-control"][tabindex="0"]:not([disabled]):not([data-disabled]):not([aria-disabled="true"]), [role="treeitem"][tabindex="0"]:not([data-part="branch"]):not([disabled]):not([data-disabled]):not([aria-disabled="true"])'
5114
+ ) ?? getVisibleTreeItems(targetPane.element)[0] ?? targetPane.element.querySelector(
5115
+ '[data-modal-editor="true"], .ProseMirror[contenteditable="true"]'
5116
+ ) : null;
5117
+ const firstFocusable = remembered ?? preferredTarget ?? getPaneFocusableItems(targetPane.element, ownScope)[0] ?? null;
4794
5118
  if (firstFocusable instanceof HTMLElement) {
4795
5119
  focusElementInActivePane(firstFocusable);
4796
5120
  } else {
@@ -5281,6 +5605,71 @@ function createWhichKeyController(options = {}) {
5281
5605
  }
5282
5606
  return handled;
5283
5607
  }
5608
+ const activeTree = activeEl?.closest('[role="tree"]');
5609
+ if (activeTree && (motion === "down" || motion === "up" || motion === "left" || motion === "right" || motion === "docStart" || motion === "docEnd")) {
5610
+ const ariaKey = motion === "down" ? "ArrowDown" : motion === "up" ? "ArrowUp" : motion === "left" ? "ArrowLeft" : motion === "right" ? "ArrowRight" : motion === "docStart" ? "Home" : "End";
5611
+ const steps = motion === "docStart" || motion === "docEnd" ? 1 : Math.max(1, ctx.count);
5612
+ let movedOrHandled = false;
5613
+ runProgrammaticFocus(() => {
5614
+ for (let s = 0; s < steps; s += 1) {
5615
+ const currentTreeEl = (doc?.activeElement instanceof HTMLElement && activeTree.contains(doc.activeElement) ? doc.activeElement : activeEl) ?? null;
5616
+ if (!currentTreeEl) break;
5617
+ let prevented = false;
5618
+ if (typeof KeyboardEvent === "function" && typeof currentTreeEl.dispatchEvent === "function") {
5619
+ const synth = new KeyboardEvent("keydown", {
5620
+ key: ariaKey,
5621
+ code: ariaKey,
5622
+ bubbles: true,
5623
+ cancelable: true
5624
+ });
5625
+ currentTreeEl.dispatchEvent(synth);
5626
+ prevented = synth.defaultPrevented;
5627
+ }
5628
+ if (prevented || doc?.activeElement && doc.activeElement !== currentTreeEl) {
5629
+ movedOrHandled = true;
5630
+ continue;
5631
+ }
5632
+ const treeItems = getVisibleTreeItems(activeTree);
5633
+ if (treeItems.length === 0) break;
5634
+ const currentIdx = treeItems.findIndex((t) => t === currentTreeEl || t.contains(currentTreeEl));
5635
+ if (motion === "down" || motion === "up") {
5636
+ const delta = motion === "down" ? 1 : -1;
5637
+ const nextIdx = currentIdx === -1 ? delta > 0 ? 0 : treeItems.length - 1 : Math.max(0, Math.min(treeItems.length - 1, currentIdx + delta));
5638
+ const nextTarget = treeItems[nextIdx];
5639
+ if (nextTarget) {
5640
+ focusElementInActivePane(nextTarget);
5641
+ movedOrHandled = true;
5642
+ }
5643
+ } else if (motion === "docStart" || motion === "docEnd") {
5644
+ const nextTarget = motion === "docStart" ? treeItems[0] : treeItems[treeItems.length - 1];
5645
+ if (nextTarget) {
5646
+ focusElementInActivePane(nextTarget);
5647
+ movedOrHandled = true;
5648
+ }
5649
+ } else if (motion === "right" || motion === "left") {
5650
+ const branchEl = currentTreeEl.closest('[role="treeitem"][aria-expanded]');
5651
+ const isExpanded = branchEl?.getAttribute("aria-expanded") === "true";
5652
+ if (motion === "right" && branchEl && !isExpanded) {
5653
+ currentTreeEl.click();
5654
+ movedOrHandled = true;
5655
+ } else if (motion === "left" && branchEl && isExpanded) {
5656
+ currentTreeEl.click();
5657
+ movedOrHandled = true;
5658
+ }
5659
+ }
5660
+ }
5661
+ });
5662
+ if (movedOrHandled) {
5663
+ if (activePaneId && doc?.activeElement instanceof HTMLElement) {
5664
+ const pane = panes.get(activePaneId);
5665
+ if (pane && pane.element?.contains(doc.activeElement)) {
5666
+ pane.lastFocusedElement = doc.activeElement;
5667
+ }
5668
+ }
5669
+ emit();
5670
+ return true;
5671
+ }
5672
+ }
5284
5673
  const activeTab = activeEl?.closest('[role="tab"]');
5285
5674
  const activeTablist = activeTab?.closest('[role="tablist"]');
5286
5675
  if (activeTab && activeTablist) {
@@ -5473,29 +5862,126 @@ function createWhichKeyController(options = {}) {
5473
5862
  options.onCommand?.(commandId, ctx);
5474
5863
  return handled;
5475
5864
  }
5476
- function invokeNode(node, event) {
5865
+ function createCommandContext(event) {
5477
5866
  const count = countBuffer ? Math.max(1, Number.parseInt(countBuffer, 10)) : 1;
5478
- const ctx = {
5867
+ return {
5479
5868
  count,
5480
5869
  mode,
5481
5870
  preset,
5482
5871
  activePaneId,
5483
5872
  event
5484
5873
  };
5874
+ }
5875
+ function tryInvokeLeafNode(node, ctx) {
5876
+ if (node.when && !node.when(ctx)) {
5877
+ return false;
5878
+ }
5485
5879
  let handled = false;
5486
5880
  if (node.action) {
5487
5881
  const res = node.action(ctx);
5488
5882
  handled = res !== false;
5489
5883
  }
5490
- if (!handled && node.commandId) {
5884
+ if (!handled && !node.action && node.commandId) {
5491
5885
  handled = executeCommand(node.commandId, ctx);
5492
5886
  }
5887
+ if (!handled) {
5888
+ return false;
5889
+ }
5493
5890
  countBuffer = "";
5494
5891
  if (!sticky) {
5495
5892
  activePath = [];
5496
5893
  }
5497
5894
  emit();
5498
- return handled;
5895
+ return true;
5896
+ }
5897
+ function evaluateLayersInPrefix(chordCandidates, event) {
5898
+ const layers = getOrderedActiveLayers(event, true);
5899
+ const mergedTrie = buildMergedTrie();
5900
+ let matchedAnyNode = false;
5901
+ for (const layer of layers) {
5902
+ const parentNode = resolveNode(layer.nodes, activePath, mode, mergedTrie);
5903
+ if (!parentNode) continue;
5904
+ const children = getNodeChildren(parentNode, mergedTrie);
5905
+ for (const candidate of chordCandidates) {
5906
+ const child = children[candidate];
5907
+ if (!child || !nodeMatchesMode(child, mode)) continue;
5908
+ matchedAnyNode = true;
5909
+ const ctx = createCommandContext(event);
5910
+ if (child.when && !child.when(ctx)) continue;
5911
+ if (!child.action && !child.commandId && isGroupNode(child, mergedTrie)) {
5912
+ activePath = [...activePath, candidate];
5913
+ if (child.sticky || child.loop) {
5914
+ sticky = true;
5915
+ }
5916
+ announce(`${child.group ?? child.label} menu`);
5917
+ emit();
5918
+ if (event) {
5919
+ event.preventDefault();
5920
+ event.stopPropagation();
5921
+ }
5922
+ return { handled: true, matchedAnyNode: true };
5923
+ }
5924
+ if (tryInvokeLeafNode(child, ctx)) {
5925
+ if (event) {
5926
+ event.preventDefault();
5927
+ event.stopPropagation();
5928
+ }
5929
+ return { handled: true, matchedAnyNode: true };
5930
+ }
5931
+ }
5932
+ }
5933
+ return { handled: false, matchedAnyNode };
5934
+ }
5935
+ function evaluateLayersAtRoot(chordCandidates, event, evalOptions = {}) {
5936
+ const insertModeOnly = Boolean(evalOptions.insertModeOnly);
5937
+ const includePreset = evalOptions.includePreset ?? !insertModeOnly;
5938
+ const layers = getOrderedActiveLayers(event, includePreset);
5939
+ const expandedCandidates = expandChordCandidateAliases(chordCandidates);
5940
+ let mergedTrieCache = null;
5941
+ const getMerged = () => mergedTrieCache ??= buildMergedTrie();
5942
+ for (const layer of layers) {
5943
+ for (const candidate of expandedCandidates) {
5944
+ const node = layer.nodes[candidate];
5945
+ if (!node) continue;
5946
+ if (insertModeOnly) {
5947
+ const matchesInsert = layer.priority === "overlay" ? nodeMatchesMode(node, "insert") : nodeExplicitlyIncludesMode(node, "insert");
5948
+ if (!matchesInsert) continue;
5949
+ } else if (!nodeMatchesMode(node, mode)) {
5950
+ continue;
5951
+ }
5952
+ const ctx = createCommandContext(event);
5953
+ if (node.when && !node.when(ctx)) continue;
5954
+ if (!node.action && !node.commandId && isGroupNode(node, getMerged())) {
5955
+ activePath = [candidate];
5956
+ sticky = Boolean(node.sticky || node.loop);
5957
+ announce(`${node.group ?? node.label} menu`);
5958
+ emit();
5959
+ if (event) {
5960
+ event.preventDefault();
5961
+ event.stopPropagation();
5962
+ }
5963
+ return true;
5964
+ }
5965
+ if (tryInvokeLeafNode(node, ctx)) {
5966
+ if (event) {
5967
+ event.preventDefault();
5968
+ event.stopPropagation();
5969
+ }
5970
+ return true;
5971
+ }
5972
+ }
5973
+ }
5974
+ return false;
5975
+ }
5976
+ function hasRegisteredNodeForCandidate(candidate, event) {
5977
+ const layers = getOrderedActiveLayers(event, false);
5978
+ for (const layer of layers) {
5979
+ const node = layer.nodes[candidate];
5980
+ if (node && nodeMatchesMode(node, mode)) {
5981
+ return true;
5982
+ }
5983
+ }
5984
+ return false;
5499
5985
  }
5500
5986
  function executeExplorerEntry(entryOrId) {
5501
5987
  const state = computeState();
@@ -5575,51 +6061,29 @@ function createWhichKeyController(options = {}) {
5575
6061
  return false;
5576
6062
  }
5577
6063
  function triggerKey(key, event) {
5578
- const rootTrie = buildMergedTrie();
6064
+ if (mode === "insert") {
6065
+ return evaluateLayersAtRoot([key], event, { insertModeOnly: true, includePreset: false });
6066
+ }
5579
6067
  if (activePath.length > 0) {
5580
- const currentParent = resolveNode(rootTrie, activePath, mode);
5581
- if (!currentParent) {
6068
+ const { handled } = evaluateLayersInPrefix([key], event);
6069
+ if (!handled && !sticky) {
5582
6070
  closePrefix();
5583
- return false;
5584
6071
  }
5585
- const children = getNodeChildren(currentParent, rootTrie);
5586
- const child = children[key];
5587
- if (!child || !nodeMatchesMode(child, mode)) {
5588
- if (!sticky) {
5589
- closePrefix();
5590
- }
5591
- return false;
5592
- }
5593
- if (isGroupNode(child, rootTrie)) {
5594
- activePath = [...activePath, key];
5595
- if (child.sticky || child.loop) {
5596
- sticky = true;
5597
- }
5598
- announce(`${child.group ?? child.label} menu`);
5599
- emit();
5600
- return true;
5601
- }
5602
- return invokeNode(child, event);
6072
+ return handled;
5603
6073
  }
5604
- if (/^[0-9]$/.test(key) && (countBuffer.length > 0 || key !== "0" || !rootTrie["0"])) {
6074
+ const rootTrie = buildMergedTrie();
6075
+ if (/^[0-9]$/.test(key) && !hasRegisteredNodeForCandidate(key, event) && (countBuffer.length > 0 || key !== "0" || !rootTrie["0"])) {
5605
6076
  if (countBuffer.length > 0 || key !== "0") {
5606
6077
  countBuffer += key;
5607
6078
  emit();
6079
+ if (event) {
6080
+ event.preventDefault();
6081
+ event.stopPropagation();
6082
+ }
5608
6083
  return true;
5609
6084
  }
5610
6085
  }
5611
- const rootNode = rootTrie[key];
5612
- if (!rootNode || !nodeMatchesMode(rootNode, mode)) {
5613
- return false;
5614
- }
5615
- if (isGroupNode(rootNode, rootTrie)) {
5616
- activePath = [key];
5617
- sticky = Boolean(rootNode.sticky || rootNode.loop);
5618
- announce(`${rootNode.group ?? rootNode.label} menu`);
5619
- emit();
5620
- return true;
5621
- }
5622
- return invokeNode(rootNode, event);
6086
+ return evaluateLayersAtRoot([key], event, { insertModeOnly: false, includePreset: true });
5623
6087
  }
5624
6088
  function handleKeyDown(event) {
5625
6089
  if (!isControllerEnabled()) return false;
@@ -5645,14 +6109,41 @@ function createWhichKeyController(options = {}) {
5645
6109
  const editorTarget = getModalEditor(targetEl);
5646
6110
  const inEditable = isTextEntryElement(targetEl);
5647
6111
  if (mode === "insert") {
6112
+ const insertChordCandidates = eventToChordKeys(event);
6113
+ if (insertChordCandidates.length > 0 && evaluateLayersAtRoot(insertChordCandidates, event, {
6114
+ insertModeOnly: true,
6115
+ includePreset: false
6116
+ })) {
6117
+ return true;
6118
+ }
5648
6119
  if (event.key === "Escape") {
5649
6120
  if (editorTarget?.hasActiveSuggestion?.()) {
5650
6121
  return false;
5651
6122
  }
6123
+ const hasOpenInsertOverlay = Boolean(
6124
+ doc?.querySelector(
6125
+ '[data-editor-overlay], [data-slash-menu-surface], [data-mention-menu-surface], [data-editor-slash-menu], [data-editor-mention-menu], [data-scope="select"][data-state="open"], [data-scope="menu"][data-state="open"], [data-scope="popover"][data-state="open"], [data-scope="combobox"][data-state="open"], [role="alertdialog"]:not([data-state="closed"])'
6126
+ )
6127
+ );
6128
+ if (hasOpenInsertOverlay) {
6129
+ return false;
6130
+ }
6131
+ if (isHTMLElementLike(targetEl) && targetEl.closest?.('[data-part="node-rename-input"]')) {
6132
+ setMode("normal");
6133
+ return false;
6134
+ }
5652
6135
  event.preventDefault();
5653
6136
  event.stopPropagation();
5654
6137
  event.stopImmediatePropagation?.();
5655
6138
  setMode("normal");
6139
+ if (isHTMLElementLike(targetEl) && editorTarget && targetEl.closest?.('[contenteditable="false"]')) {
6140
+ const pmRoot = targetEl.closest?.(".ProseMirror");
6141
+ if (pmRoot) {
6142
+ runProgrammaticFocus(() => {
6143
+ pmRoot.focus({ preventScroll: true });
6144
+ });
6145
+ }
6146
+ }
5656
6147
  return true;
5657
6148
  }
5658
6149
  return false;
@@ -5677,19 +6168,52 @@ function createWhichKeyController(options = {}) {
5677
6168
  }
5678
6169
  const chordCandidates2 = eventToChordKeys(event);
5679
6170
  if (chordCandidates2.length === 0) return false;
5680
- const rootTrie2 = buildMergedTrie();
5681
- const parentNode = resolveNode(rootTrie2, activePath, mode);
5682
- const children = parentNode ? getNodeChildren(parentNode, rootTrie2) : {};
5683
- const matchedChord = chordCandidates2.find((c) => Boolean(children[c]));
5684
- event.preventDefault();
5685
- event.stopPropagation();
5686
- if (matchedChord) {
5687
- return triggerKey(matchedChord, event);
6171
+ const { handled, matchedAnyNode } = evaluateLayersInPrefix(chordCandidates2, event);
6172
+ if (handled) {
6173
+ return true;
5688
6174
  }
5689
6175
  if (!sticky) {
5690
6176
  closePrefix();
5691
6177
  }
5692
- return true;
6178
+ if (!matchedAnyNode) {
6179
+ event.preventDefault();
6180
+ event.stopPropagation();
6181
+ return true;
6182
+ }
6183
+ return false;
6184
+ }
6185
+ const chordCandidates = eventToChordKeys(event);
6186
+ if (event.key === " " && !event.ctrlKey && !event.metaKey && !event.altKey && targetEl) {
6187
+ const role = targetEl.getAttribute("role");
6188
+ const isToggleControl = targetEl instanceof HTMLInputElement && (targetEl.type === "checkbox" || targetEl.type === "radio") || role === "checkbox" || role === "switch" || role === "radio";
6189
+ if (isToggleControl) {
6190
+ return false;
6191
+ }
6192
+ const isButtonControl = targetEl.tagName === "BUTTON" || role === "button";
6193
+ if (isButtonControl) {
6194
+ const previewAncestor = targetEl.closest("[data-example-preview]");
6195
+ const ownScope = options.getScopeElement?.() ?? null;
6196
+ if (previewAncestor && (!ownScope || !previewAncestor.contains(ownScope))) {
6197
+ return false;
6198
+ }
6199
+ }
6200
+ }
6201
+ if (chordCandidates.length > 0) {
6202
+ const rootTrie = buildMergedTrie();
6203
+ for (const candidate of chordCandidates) {
6204
+ if (/^[0-9]$/.test(candidate) && !hasRegisteredNodeForCandidate(candidate, event) && (countBuffer.length > 0 || candidate !== "0" || !rootTrie["0"])) {
6205
+ if (countBuffer.length > 0 || candidate !== "0") {
6206
+ countBuffer += keyFromCandidate(candidate);
6207
+ emit();
6208
+ event.preventDefault();
6209
+ event.stopPropagation();
6210
+ return true;
6211
+ }
6212
+ }
6213
+ }
6214
+ if (evaluateLayersAtRoot(chordCandidates, event, { insertModeOnly: false, includePreset: true })) {
6215
+ return true;
6216
+ }
5693
6217
  }
5694
6218
  if (event.key === "Escape") {
5695
6219
  if (editorTarget && (mode === "select" || !editorTarget.hasActiveSuggestion?.())) {
@@ -5749,21 +6273,6 @@ function createWhichKeyController(options = {}) {
5749
6273
  setMode("insert");
5750
6274
  return true;
5751
6275
  }
5752
- if (event.key === " " && !event.ctrlKey && !event.metaKey && !event.altKey && targetEl) {
5753
- const role = targetEl.getAttribute("role");
5754
- const isToggleControl = targetEl instanceof HTMLInputElement && (targetEl.type === "checkbox" || targetEl.type === "radio") || role === "checkbox" || role === "switch" || role === "radio";
5755
- if (isToggleControl) {
5756
- return false;
5757
- }
5758
- const isButtonControl = targetEl.tagName === "BUTTON" || role === "button";
5759
- if (isButtonControl) {
5760
- const previewAncestor = targetEl.closest("[data-example-preview]");
5761
- const ownScope = options.getScopeElement?.() ?? null;
5762
- if (previewAncestor && (!ownScope || !previewAncestor.contains(ownScope))) {
5763
- return false;
5764
- }
5765
- }
5766
- }
5767
6276
  if (editorTarget && !editorTarget.hasActiveSuggestion?.() && !event.ctrlKey && !event.metaKey && !event.altKey && (event.key === "ArrowLeft" || event.key === "ArrowRight" || event.key === "ArrowUp" || event.key === "ArrowDown")) {
5768
6277
  const arrowMotion = event.key === "ArrowLeft" ? "left" : event.key === "ArrowRight" ? "right" : event.key === "ArrowUp" ? "up" : "down";
5769
6278
  if (event.shiftKey && mode === "normal") {
@@ -5778,23 +6287,6 @@ function createWhichKeyController(options = {}) {
5778
6287
  emit();
5779
6288
  return true;
5780
6289
  }
5781
- const chordCandidates = eventToChordKeys(event);
5782
- if (chordCandidates.length === 0) return false;
5783
- const rootTrie = buildMergedTrie();
5784
- for (const candidate of chordCandidates) {
5785
- if (/^[0-9]$/.test(candidate) && (countBuffer.length > 0 || candidate !== "0" || !rootTrie["0"])) {
5786
- if (countBuffer.length > 0 || candidate !== "0") {
5787
- event.preventDefault();
5788
- event.stopPropagation();
5789
- return triggerKey(candidate, event);
5790
- }
5791
- }
5792
- if (rootTrie[candidate] && nodeMatchesMode(rootTrie[candidate], mode)) {
5793
- event.preventDefault();
5794
- event.stopPropagation();
5795
- return triggerKey(candidate, event);
5796
- }
5797
- }
5798
6290
  if (inEditable && event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) {
5799
6291
  event.preventDefault();
5800
6292
  event.stopPropagation();
@@ -5802,10 +6294,13 @@ function createWhichKeyController(options = {}) {
5802
6294
  }
5803
6295
  return false;
5804
6296
  }
6297
+ function keyFromCandidate(candidate) {
6298
+ return candidate;
6299
+ }
5805
6300
  function attach(target) {
5806
6301
  detachCleanups.forEach((fn) => fn());
5807
6302
  detachCleanups = [];
5808
- const doc = target instanceof Document ? target : target?.ownerDocument ?? resolveDoc();
6303
+ const doc = typeof Document !== "undefined" && target instanceof Document ? target : target && "ownerDocument" in target && target.ownerDocument ? target.ownerDocument : target ?? resolveDoc();
5809
6304
  if (!doc) return () => {
5810
6305
  };
5811
6306
  const eventTarget = target ?? doc;
@@ -5831,6 +6326,7 @@ function createWhichKeyController(options = {}) {
5831
6326
  liveRegion = null;
5832
6327
  }
5833
6328
  const entry = {
6329
+ controller: controllerApi,
5834
6330
  getScopeElement: () => options.getScopeElement?.() ?? null,
5835
6331
  isBusy: () => activePath.length > 0 || sticky || explorerOpen || mode === "jump" || countBuffer.length > 0
5836
6332
  };
@@ -5840,8 +6336,10 @@ function createWhichKeyController(options = {}) {
5840
6336
  attachedEntriesByDoc.set(doc, docEntries);
5841
6337
  }
5842
6338
  docEntries.add(entry);
6339
+ notifyRootControllerListeners(doc);
5843
6340
  detachCleanups.push(() => {
5844
6341
  docEntries?.delete(entry);
6342
+ notifyRootControllerListeners(doc);
5845
6343
  });
5846
6344
  if (!options.getScopeElement?.()) {
5847
6345
  const storedPreset = readStoredPreset();
@@ -5967,16 +6465,26 @@ function createWhichKeyController(options = {}) {
5967
6465
  keymapLayers.clear();
5968
6466
  }
5969
6467
  function registerKeymap(id, nodes, layerOptions) {
5970
- keymapLayers.set(id, {
6468
+ const hasElementOption = layerOptions !== void 0 && Object.prototype.hasOwnProperty.call(layerOptions, "element") && layerOptions.element !== void 0;
6469
+ const defaultPriority = layerOptions?.scope ? "pane" : "global";
6470
+ const entry = {
5971
6471
  id,
5972
6472
  nodes,
5973
6473
  scope: layerOptions?.scope,
5974
- enabled: layerOptions?.enabled ?? true
5975
- });
6474
+ enabled: layerOptions?.enabled ?? true,
6475
+ priority: layerOptions?.priority ?? defaultPriority,
6476
+ hasElementOption,
6477
+ element: layerOptions?.element,
6478
+ matchesTarget: layerOptions?.matchesTarget,
6479
+ registrationOrder: ++layerRegistrationCounter
6480
+ };
6481
+ keymapLayers.set(id, entry);
5976
6482
  emit();
5977
6483
  return () => {
5978
- keymapLayers.delete(id);
5979
- emit();
6484
+ if (keymapLayers.get(id) === entry) {
6485
+ keymapLayers.delete(id);
6486
+ emit();
6487
+ }
5980
6488
  };
5981
6489
  }
5982
6490
  function registerCommand(commandId, handler) {
@@ -6156,6 +6664,9 @@ var jumpBadgeVariants = (0, import_class_variance_authority22.cva)(
6156
6664
  );
6157
6665
  var jumpBadgeMatchedPrefixBase = "opacity-50 line-through";
6158
6666
 
6667
+ // src/index.ts
6668
+ __reExport(index_exports, which_key_exports, module.exports);
6669
+
6159
6670
  // src/editor/build-extensions.ts
6160
6671
  var import_starter_kit = __toESM(require("@tiptap/starter-kit"), 1);
6161
6672
  var import_extension_placeholder = __toESM(require("@tiptap/extension-placeholder"), 1);
@@ -6273,6 +6784,23 @@ var import_history = require("@tiptap/pm/history");
6273
6784
  var import_state2 = require("@tiptap/pm/state");
6274
6785
  var import_view = require("@tiptap/pm/view");
6275
6786
  var modalKeymapPluginKey = new import_state2.PluginKey("modalKeymap");
6787
+ var NON_TEXT_MODAL_NODE_TYPES = /* @__PURE__ */ new Set([
6788
+ "notice",
6789
+ "blockquote",
6790
+ "codeBlock",
6791
+ "imageNode",
6792
+ "image",
6793
+ "linkPreview",
6794
+ "horizontalRule",
6795
+ "urlMention",
6796
+ "internalMention",
6797
+ "unparsedBlock",
6798
+ "unparsedInline",
6799
+ "mathInline",
6800
+ "mathBlock",
6801
+ "mermaidBlock",
6802
+ "manimBlock"
6803
+ ]);
6276
6804
  function collectLeafBlocks(doc) {
6277
6805
  const blocks = [];
6278
6806
  doc.descendants((node, pos) => {
@@ -6368,9 +6896,16 @@ function getCharEnd(doc, pos) {
6368
6896
  }
6369
6897
  return pos + 1;
6370
6898
  }
6899
+ if (!$pos.parent.isTextblock) {
6900
+ const after = $pos.nodeAfter;
6901
+ if (after && after.isAtom) {
6902
+ return pos + after.nodeSize;
6903
+ }
6904
+ }
6371
6905
  return pos;
6372
6906
  }
6373
6907
  function getCursorCharPos(doc, sel) {
6908
+ if (sel instanceof import_state2.NodeSelection) return sel.from;
6374
6909
  if (sel.empty) return sel.head;
6375
6910
  if (sel.head > sel.anchor) {
6376
6911
  const $head = doc.resolve(sel.head);
@@ -6381,6 +6916,7 @@ function getCursorCharPos(doc, sel) {
6381
6916
  return sel.head;
6382
6917
  }
6383
6918
  function getAnchorCharPos(doc, sel) {
6919
+ if (sel instanceof import_state2.NodeSelection) return sel.from;
6384
6920
  if (sel.empty) return sel.anchor;
6385
6921
  if (sel.head < sel.anchor) {
6386
6922
  const $anchor = doc.resolve(sel.anchor);
@@ -6390,12 +6926,175 @@ function getAnchorCharPos(doc, sel) {
6390
6926
  }
6391
6927
  return sel.anchor;
6392
6928
  }
6393
- function createExtendedSelection(doc, sel, nextCursorChar) {
6394
- const anchorChar = getAnchorCharPos(doc, sel);
6395
- if (nextCursorChar >= anchorChar) {
6396
- return import_state2.TextSelection.create(doc, anchorChar, getCharEnd(doc, nextCursorChar));
6929
+ function getContainerInnerTextBounds(node, nodePos) {
6930
+ let firstTextStart = -1;
6931
+ let lastTextEnd = -1;
6932
+ if (node.isTextblock) {
6933
+ return {
6934
+ firstTextStart: nodePos + 1,
6935
+ lastTextEnd: nodePos + 1 + node.content.size
6936
+ };
6937
+ }
6938
+ node.descendants((child, relPos) => {
6939
+ if (child.isTextblock) {
6940
+ const absStart = nodePos + 1 + relPos + 1;
6941
+ const absEnd = absStart + child.content.size;
6942
+ if (firstTextStart === -1) firstTextStart = absStart;
6943
+ lastTextEnd = absEnd;
6944
+ return false;
6945
+ }
6946
+ return true;
6947
+ });
6948
+ return { firstTextStart, lastTextEnd };
6949
+ }
6950
+ function expandWholeContainerRange(doc, from, to, expandNotices = true) {
6951
+ if (!expandNotices || from >= to) return { from, to };
6952
+ let nextFrom = from;
6953
+ let nextTo = to;
6954
+ doc.nodesBetween(from, to, (node, pos) => {
6955
+ if (node.type.name === "notice" || node.type.name === "blockquote") {
6956
+ const { firstTextStart, lastTextEnd } = getContainerInnerTextBounds(node, pos);
6957
+ if (firstTextStart !== -1 && lastTextEnd !== -1 && nextFrom <= firstTextStart && nextTo >= lastTextEnd) {
6958
+ nextFrom = Math.min(nextFrom, pos);
6959
+ nextTo = Math.max(nextTo, pos + node.nodeSize);
6960
+ }
6961
+ return false;
6962
+ }
6963
+ if (node.isAtom && !node.isText) {
6964
+ if (nextFrom <= pos && nextTo >= pos + node.nodeSize) {
6965
+ nextFrom = Math.min(nextFrom, pos);
6966
+ nextTo = Math.max(nextTo, pos + node.nodeSize);
6967
+ }
6968
+ return false;
6969
+ }
6970
+ return true;
6971
+ });
6972
+ return { from: nextFrom, to: nextTo };
6973
+ }
6974
+ function createSafeModalSelection(doc, anchorPos, headPos) {
6975
+ const from = Math.min(anchorPos, headPos);
6976
+ const to = Math.max(anchorPos, headPos);
6977
+ if (from < to) {
6978
+ const directNode = doc.nodeAt(from);
6979
+ if (directNode && from + directNode.nodeSize === to && import_state2.NodeSelection.isSelectable(directNode)) {
6980
+ return import_state2.NodeSelection.create(doc, from);
6981
+ }
6982
+ }
6983
+ const resolveInlinePos = (pos, preferDir) => {
6984
+ const clamped = Math.max(0, Math.min(doc.content.size, pos));
6985
+ const $pos = doc.resolve(clamped);
6986
+ if ($pos.parent.inlineContent) return clamped;
6987
+ const found = import_state2.Selection.findFrom($pos, preferDir, true) ?? import_state2.Selection.findFrom($pos, -preferDir, true);
6988
+ return found ? preferDir > 0 ? found.from : found.to : clamped;
6989
+ };
6990
+ const forward = headPos >= anchorPos;
6991
+ const safeAnchor = resolveInlinePos(anchorPos, forward ? 1 : -1);
6992
+ const safeHead = resolveInlinePos(headPos, forward ? -1 : 1);
6993
+ if (doc.resolve(safeAnchor).parent.inlineContent && doc.resolve(safeHead).parent.inlineContent) {
6994
+ return import_state2.TextSelection.create(doc, safeAnchor, safeHead);
6995
+ }
6996
+ return import_state2.Selection.near(doc.resolve(headPos));
6997
+ }
6998
+ function createExtendedSelection(doc, sel, nextCursorChar, targetAtomBlock) {
6999
+ const anchorStart = sel instanceof import_state2.NodeSelection ? sel.from : getAnchorCharPos(doc, sel);
7000
+ const anchorEnd = sel instanceof import_state2.NodeSelection ? sel.to : getCharEnd(doc, anchorStart);
7001
+ const targetStart = targetAtomBlock ? targetAtomBlock.start : nextCursorChar;
7002
+ const targetEnd = targetAtomBlock ? targetAtomBlock.end : getCharEnd(doc, nextCursorChar);
7003
+ if (targetStart >= anchorStart) {
7004
+ const rawFrom2 = anchorStart;
7005
+ const rawTo2 = Math.max(anchorEnd, targetEnd);
7006
+ return createSafeModalSelection(doc, rawFrom2, rawTo2);
7007
+ }
7008
+ const rawFrom = targetStart;
7009
+ const rawTo = anchorEnd;
7010
+ return createSafeModalSelection(doc, rawTo, rawFrom);
7011
+ }
7012
+ function findCurrentBlockIndex(blocks, doc, sel) {
7013
+ if (blocks.length === 0) return -1;
7014
+ if (sel instanceof import_state2.NodeSelection) {
7015
+ const nodeIdx = blocks.findIndex((b) => b.pos === sel.from);
7016
+ if (nodeIdx !== -1) return nodeIdx;
7017
+ }
7018
+ const cursorPos = getCursorCharPos(doc, sel);
7019
+ const textIdx = blocks.findIndex((b) => b.isTextblock && cursorPos >= b.start && cursorPos <= b.end);
7020
+ if (textIdx !== -1) return textIdx;
7021
+ if (!sel.empty) {
7022
+ if (sel.head > sel.anchor) {
7023
+ const forwardAtomIdx = blocks.findIndex((b) => b.isAtom && sel.head === b.end);
7024
+ if (forwardAtomIdx !== -1) return forwardAtomIdx;
7025
+ } else if (sel.head < sel.anchor) {
7026
+ const backwardAtomIdx = blocks.findIndex((b) => b.isAtom && sel.head === b.start);
7027
+ if (backwardAtomIdx !== -1) return backwardAtomIdx;
7028
+ }
7029
+ }
7030
+ const atomIdx = blocks.findIndex((b) => b.isAtom && cursorPos >= b.start && cursorPos <= b.end);
7031
+ return atomIdx !== -1 ? atomIdx : 0;
7032
+ }
7033
+ function serializeModalSliceText(doc, from, to) {
7034
+ if (from >= to) return "";
7035
+ let hasRichNode = false;
7036
+ const parts = [];
7037
+ doc.nodesBetween(from, to, (node, pos) => {
7038
+ const fullyCovered = pos >= from && pos + node.nodeSize <= to;
7039
+ if (fullyCovered) {
7040
+ if (node.type.name === "imageNode" || node.type.name === "image") {
7041
+ hasRichNode = true;
7042
+ parts.push(`![${String(node.attrs.alt ?? "")}](${String(node.attrs.src ?? "")})`);
7043
+ return false;
7044
+ }
7045
+ if (node.type.name === "linkPreview") {
7046
+ hasRichNode = true;
7047
+ const label = String(node.attrs.title || node.attrs.url || "link");
7048
+ parts.push(`[${label}](${String(node.attrs.url ?? "")})`);
7049
+ return false;
7050
+ }
7051
+ if (node.type.name === "urlMention") {
7052
+ hasRichNode = true;
7053
+ const label = String(node.attrs.title || node.attrs.url || "mention");
7054
+ parts.push(`[${label}](${String(node.attrs.url ?? "")})`);
7055
+ return false;
7056
+ }
7057
+ if (node.type.name === "internalMention") {
7058
+ hasRichNode = true;
7059
+ parts.push(`@${String(node.attrs.label || node.attrs.id || "mention")}`);
7060
+ return false;
7061
+ }
7062
+ if (node.type.name === "horizontalRule") {
7063
+ hasRichNode = true;
7064
+ parts.push("---");
7065
+ return false;
7066
+ }
7067
+ if (node.type.name === "unparsedBlock" || node.type.name === "unparsedInline") {
7068
+ hasRichNode = true;
7069
+ parts.push(String(node.attrs.raw ?? node.textContent ?? ""));
7070
+ return false;
7071
+ }
7072
+ if (node.type.name === "notice") {
7073
+ hasRichNode = true;
7074
+ const variant = String(node.attrs.variant ?? "info");
7075
+ const title = node.attrs.title ? `${String(node.attrs.title)}: ` : "";
7076
+ parts.push(`::: ${variant}
7077
+ ${title}${node.textContent}
7078
+ :::`);
7079
+ return false;
7080
+ }
7081
+ }
7082
+ if (node.isTextblock) {
7083
+ const start = Math.max(from, pos + 1);
7084
+ const end = Math.min(to, pos + 1 + node.content.size);
7085
+ if (end > start) {
7086
+ parts.push(doc.textBetween(start, end, "\n"));
7087
+ }
7088
+ return false;
7089
+ }
7090
+ return true;
7091
+ });
7092
+ if (hasRichNode && parts.length > 0) {
7093
+ return parts.join("\n");
6397
7094
  }
6398
- return import_state2.TextSelection.create(doc, getCharEnd(doc, anchorChar), nextCursorChar);
7095
+ const plain = doc.textBetween(from, to, "\n");
7096
+ if (plain) return plain;
7097
+ return parts.join("\n");
6399
7098
  }
6400
7099
  function createModalTargetForEditor(editor, options) {
6401
7100
  const getStorage = () => editor.storage.modalKeymap;
@@ -6471,26 +7170,49 @@ function createModalTargetForEditor(editor, options) {
6471
7170
  return true;
6472
7171
  }
6473
7172
  if (motion === "lineSelect") {
6474
- const blocks = collectLeafBlocks(doc).filter((b) => b.isTextblock);
7173
+ const blocks = collectLeafBlocks(doc);
6475
7174
  if (blocks.length === 0) return false;
6476
- const currentBlockIdx = blocks.findIndex((b) => sel.from >= b.start && sel.from <= b.end);
6477
- const startIdx = currentBlockIdx === -1 ? 0 : currentBlockIdx;
7175
+ const currentBlockIdx = blocks.findIndex(
7176
+ (b) => b.isTextblock ? sel.from >= b.start && sel.from <= b.end : sel.from >= b.start && sel.from < b.end
7177
+ );
7178
+ const startIdx = currentBlockIdx === -1 ? findCurrentBlockIndex(blocks, doc, sel) : currentBlockIdx;
6478
7179
  const startBlock = blocks[startIdx];
6479
- const alreadyCoversCurrent = sel.from <= startBlock.start && sel.to >= startBlock.end && !sel.empty;
7180
+ const alreadyCoversCurrent = !sel.empty && sel.from <= startBlock.start && (startBlock.isAtom ? sel.to >= startBlock.end : sel.to >= startBlock.end);
6480
7181
  let endBlockIdx = startIdx + (steps - 1);
6481
7182
  if (alreadyCoversCurrent) {
6482
- const currentEndIdx = blocks.findIndex((b) => sel.to >= b.start && sel.to <= b.end);
6483
- endBlockIdx = (currentEndIdx === -1 ? startIdx : currentEndIdx) + steps;
7183
+ let currentEndIdx = startIdx;
7184
+ for (let i = startIdx; i < blocks.length; i += 1) {
7185
+ const b = blocks[i];
7186
+ if (sel.to >= b.start && sel.to <= b.end) {
7187
+ currentEndIdx = i;
7188
+ }
7189
+ }
7190
+ endBlockIdx = currentEndIdx + steps;
6484
7191
  }
6485
7192
  const endBlock = blocks[Math.min(blocks.length - 1, endBlockIdx)];
6486
- tr = tr.setSelection(import_state2.TextSelection.create(doc, startBlock.start, endBlock.end));
6487
- tr = updateMeta(tr, { goalColumn: null });
7193
+ if (startBlock === endBlock && startBlock.isAtom && import_state2.NodeSelection.isSelectable(startBlock.node)) {
7194
+ tr = tr.setSelection(import_state2.NodeSelection.create(doc, startBlock.pos));
7195
+ } else {
7196
+ tr = tr.setSelection(createSafeModalSelection(doc, startBlock.start, endBlock.end));
7197
+ }
7198
+ if (mode === "normal") {
7199
+ getStorage().mode = "select";
7200
+ tr = updateMeta(tr, { mode: "select", goalColumn: null });
7201
+ } else {
7202
+ tr = updateMeta(tr, { goalColumn: null });
7203
+ }
6488
7204
  dispatchTransaction(editor, tr.scrollIntoView());
6489
7205
  return true;
6490
7206
  }
6491
7207
  if (motion === "lineStart" || motion === "lineEnd") {
7208
+ if (sel instanceof import_state2.NodeSelection && !isExtend) {
7209
+ return true;
7210
+ }
6492
7211
  const cursorPos = getCursorCharPos(doc, sel);
6493
7212
  const $head = doc.resolve(cursorPos);
7213
+ if (!$head.parent.isTextblock) {
7214
+ return false;
7215
+ }
6494
7216
  if (isExtend) {
6495
7217
  const dest = motion === "lineStart" ? $head.start() : Math.max($head.start(), $head.end() - 1);
6496
7218
  tr = tr.setSelection(createExtendedSelection(doc, sel, dest));
@@ -6518,20 +7240,18 @@ function createModalTargetForEditor(editor, options) {
6518
7240
  const dir = motion === "paragraphForward" ? 1 : -1;
6519
7241
  const blocks = collectLeafBlocks(doc);
6520
7242
  if (blocks.length === 0) return false;
6521
- const cursorPos = getCursorCharPos(doc, sel);
6522
- let currentIdx = blocks.findIndex(
6523
- (b) => b.isTextblock ? cursorPos >= b.start && cursorPos <= b.end : sel.from === b.pos
6524
- );
6525
- if (currentIdx === -1) {
6526
- currentIdx = 0;
6527
- }
7243
+ const currentIdx = findCurrentBlockIndex(blocks, doc, sel);
6528
7244
  const targetIdx = Math.max(0, Math.min(blocks.length - 1, currentIdx + dir * steps));
6529
7245
  const targetBlock = blocks[targetIdx];
6530
- if (targetBlock.isAtom && import_state2.NodeSelection.isSelectable(targetBlock.node)) {
7246
+ if (isExtend) {
7247
+ if (targetBlock.isAtom) {
7248
+ tr = tr.setSelection(createExtendedSelection(doc, sel, targetBlock.start, targetBlock));
7249
+ } else {
7250
+ const dest = dir > 0 ? Math.max(targetBlock.start, targetBlock.end - 1) : targetBlock.start;
7251
+ tr = tr.setSelection(createExtendedSelection(doc, sel, dest));
7252
+ }
7253
+ } else if (targetBlock.isAtom && import_state2.NodeSelection.isSelectable(targetBlock.node)) {
6531
7254
  tr = tr.setSelection(import_state2.NodeSelection.create(doc, targetBlock.pos));
6532
- } else if (isExtend) {
6533
- const dest = dir > 0 ? Math.max(targetBlock.start, targetBlock.end - 1) : targetBlock.start;
6534
- tr = tr.setSelection(createExtendedSelection(doc, sel, dest));
6535
7255
  } else if (isSelectionFirst) {
6536
7256
  tr = tr.setSelection(import_state2.TextSelection.create(doc, targetBlock.start, targetBlock.end));
6537
7257
  } else {
@@ -6553,6 +7273,10 @@ function createModalTargetForEditor(editor, options) {
6553
7273
  const childNode = dir > 0 ? $pos.nodeAfter : $pos.nodeBefore;
6554
7274
  if (childNode && childNode.isAtom && !childNode.isText && import_state2.NodeSelection.isSelectable(childNode)) {
6555
7275
  const atomPos = dir > 0 ? targetPos : targetPos - childNode.nodeSize;
7276
+ if (isExtend) {
7277
+ targetPos = atomPos;
7278
+ continue;
7279
+ }
6556
7280
  tr = tr.setSelection(import_state2.NodeSelection.create(doc, atomPos));
6557
7281
  tr = updateMeta(tr, { goalColumn: null });
6558
7282
  dispatchTransaction(editor, tr.scrollIntoView());
@@ -6582,25 +7306,25 @@ function createModalTargetForEditor(editor, options) {
6582
7306
  const blocks = collectLeafBlocks(doc);
6583
7307
  if (blocks.length === 0) return false;
6584
7308
  const cursorPos = getCursorCharPos(doc, sel);
6585
- let currentIdx = blocks.findIndex(
6586
- (b) => b.isTextblock ? cursorPos >= b.start && cursorPos <= b.end : sel.from === b.pos
6587
- );
6588
- if (currentIdx === -1) {
6589
- currentIdx = 0;
6590
- }
7309
+ const currentIdx = findCurrentBlockIndex(blocks, doc, sel);
6591
7310
  const currentBlock = blocks[currentIdx];
6592
- const currentColumn = currentBlock.isTextblock ? cursorPos - currentBlock.start : 0;
7311
+ const currentColumn = currentBlock.isTextblock ? Math.max(0, cursorPos - currentBlock.start) : 0;
6593
7312
  const goalCol = pluginState?.goalColumn ?? currentColumn;
6594
7313
  const targetIdx = Math.max(0, Math.min(blocks.length - 1, currentIdx + dir * steps));
6595
7314
  const targetBlock = blocks[targetIdx];
6596
- if (targetBlock.isAtom && import_state2.NodeSelection.isSelectable(targetBlock.node)) {
7315
+ if (isExtend) {
7316
+ if (targetBlock.isAtom) {
7317
+ tr = tr.setSelection(createExtendedSelection(doc, sel, targetBlock.start, targetBlock));
7318
+ } else {
7319
+ const maxTargetPos = targetBlock.end > targetBlock.start ? targetBlock.end - 1 : targetBlock.start;
7320
+ const nextHead = dir > 0 ? maxTargetPos : Math.min(targetBlock.start + goalCol, maxTargetPos);
7321
+ tr = tr.setSelection(createExtendedSelection(doc, sel, nextHead));
7322
+ }
7323
+ } else if (targetBlock.isAtom && import_state2.NodeSelection.isSelectable(targetBlock.node)) {
6597
7324
  tr = tr.setSelection(import_state2.NodeSelection.create(doc, targetBlock.pos));
6598
7325
  } else {
6599
- const maxTargetPos = targetBlock.end > targetBlock.start ? targetBlock.end - 1 : targetBlock.start;
6600
- const nextHead = Math.min(targetBlock.start + goalCol, isExtend ? maxTargetPos : targetBlock.end);
6601
- tr = tr.setSelection(
6602
- isExtend ? createExtendedSelection(doc, sel, nextHead) : import_state2.TextSelection.create(doc, nextHead)
6603
- );
7326
+ const nextHead = Math.min(targetBlock.start + goalCol, targetBlock.end);
7327
+ tr = tr.setSelection(import_state2.TextSelection.create(doc, nextHead));
6604
7328
  }
6605
7329
  tr = updateMeta(tr, { goalColumn: goalCol });
6606
7330
  dispatchTransaction(editor, tr.scrollIntoView());
@@ -6701,33 +7425,14 @@ function createModalTargetForEditor(editor, options) {
6701
7425
  }
6702
7426
  if (!targetNode || targetPos < 0) return false;
6703
7427
  const foundNode = targetNode;
6704
- let firstTextStart = -1;
6705
- let lastTextEnd = -1;
6706
- foundNode.descendants((child, relPos) => {
6707
- if (child.isTextblock) {
6708
- const absStart = targetPos + 1 + relPos + 1;
6709
- const absEnd = absStart + child.content.size;
6710
- if (firstTextStart === -1) firstTextStart = absStart;
6711
- lastTextEnd = absEnd;
6712
- return false;
6713
- }
6714
- return true;
6715
- });
6716
- if (foundNode.isTextblock) {
6717
- firstTextStart = targetPos + 1;
6718
- lastTextEnd = targetPos + 1 + foundNode.content.size;
6719
- }
7428
+ const { firstTextStart, lastTextEnd } = getContainerInnerTextBounds(foundNode, targetPos);
6720
7429
  if (firstTextStart === -1 || lastTextEnd === -1) return false;
6721
7430
  if (isInner) {
6722
7431
  const tr2 = state.tr.setSelection(import_state2.TextSelection.create(doc, firstTextStart, lastTextEnd));
6723
7432
  dispatchTransaction(editor, tr2.scrollIntoView());
6724
7433
  return true;
6725
7434
  }
6726
- const nodeStart = import_state2.Selection.findFrom(doc.resolve(targetPos), 1, true)?.from ?? firstTextStart;
6727
- const nodeEnd = import_state2.Selection.findFrom(doc.resolve(targetPos + foundNode.nodeSize), -1, true)?.to ?? lastTextEnd;
6728
- const tr = state.tr.setSelection(
6729
- import_state2.TextSelection.create(doc, Math.min(nodeStart, firstTextStart), Math.max(nodeEnd, lastTextEnd))
6730
- );
7435
+ const tr = state.tr.setSelection(createSafeModalSelection(doc, targetPos, targetPos + foundNode.nodeSize));
6731
7436
  dispatchTransaction(editor, tr.scrollIntoView());
6732
7437
  return true;
6733
7438
  },
@@ -6738,13 +7443,14 @@ function createModalTargetForEditor(editor, options) {
6738
7443
  const pluginState = modalKeymapPluginKey.getState(state);
6739
7444
  const currentSecondary = pluginState?.secondaryRanges ?? [];
6740
7445
  if (action === "collapse") {
6741
- let tr = state.tr.setSelection(import_state2.TextSelection.create(doc, getCursorCharPos(doc, sel)));
7446
+ const nextSelection = sel instanceof import_state2.NodeSelection ? sel : import_state2.TextSelection.create(doc, getCursorCharPos(doc, sel));
7447
+ let tr = state.tr.setSelection(nextSelection);
6742
7448
  tr = updateMeta(tr, { secondaryRanges: [] });
6743
7449
  dispatchTransaction(editor, tr);
6744
7450
  return true;
6745
7451
  }
6746
7452
  if (action === "flip") {
6747
- if (sel.empty) return false;
7453
+ if (sel.empty || sel instanceof import_state2.NodeSelection) return false;
6748
7454
  const tr = state.tr.setSelection(import_state2.TextSelection.create(doc, sel.head, sel.anchor));
6749
7455
  dispatchTransaction(editor, tr);
6750
7456
  return true;
@@ -6782,7 +7488,7 @@ function createModalTargetForEditor(editor, options) {
6782
7488
  }
6783
7489
  return false;
6784
7490
  },
6785
- execOperator(op, { count }) {
7491
+ execOperator(op, { mode, count }) {
6786
7492
  const state = editor.state;
6787
7493
  const doc = state.doc;
6788
7494
  const sel = state.selection;
@@ -6804,14 +7510,14 @@ function createModalTargetForEditor(editor, options) {
6804
7510
  return (0, import_history.redo)(state, (tr) => dispatchTransaction(editor, tr));
6805
7511
  }
6806
7512
  if (op === "insertStart") {
6807
- let tr = state.tr.setSelection(import_state2.TextSelection.create(doc, sel.from));
7513
+ let tr = state.tr.setSelection(sel instanceof import_state2.NodeSelection ? sel : import_state2.TextSelection.create(doc, sel.from));
6808
7514
  tr = updateMeta(tr, { mode: "insert", secondaryRanges: [] });
6809
7515
  storage.mode = "insert";
6810
7516
  dispatchTransaction(editor, tr);
6811
7517
  return { enterInsert: true };
6812
7518
  }
6813
7519
  if (op === "appendEnd") {
6814
- const dest = sel.empty ? Math.min(sel.$head.end(), sel.to + 1) : sel.to;
7520
+ const dest = sel instanceof import_state2.NodeSelection ? sel.to : sel.empty ? Math.min(sel.$head.end(), sel.to + 1) : sel.to;
6815
7521
  let tr = state.tr.setSelection(import_state2.TextSelection.create(doc, dest));
6816
7522
  tr = updateMeta(tr, { mode: "insert", secondaryRanges: [] });
6817
7523
  storage.mode = "insert";
@@ -6819,10 +7525,21 @@ function createModalTargetForEditor(editor, options) {
6819
7525
  return { enterInsert: true };
6820
7526
  }
6821
7527
  if (op === "openBelow" || op === "openAbove") {
6822
- const $pos = sel.$head;
6823
- const blockDepth = Math.max(1, $pos.depth);
6824
- const beforeBlock = $pos.before(blockDepth);
6825
- const afterBlock = $pos.after(blockDepth);
7528
+ let beforeBlock;
7529
+ let afterBlock;
7530
+ if (sel instanceof import_state2.NodeSelection && sel.node.isBlock) {
7531
+ beforeBlock = sel.from;
7532
+ afterBlock = sel.to;
7533
+ } else {
7534
+ const $pos = sel.$head;
7535
+ if ($pos.depth >= 1) {
7536
+ beforeBlock = $pos.before(1);
7537
+ afterBlock = $pos.after(1);
7538
+ } else {
7539
+ beforeBlock = sel.from;
7540
+ afterBlock = sel.to;
7541
+ }
7542
+ }
6826
7543
  const enforceH1 = options.enforceTitle !== false;
6827
7544
  const isFirstTitle = enforceH1 && beforeBlock === 0 && doc.firstChild?.type.name === "heading" && doc.firstChild.attrs.level === 1;
6828
7545
  const insertPos = op === "openBelow" || isFirstTitle ? afterBlock : beforeBlock;
@@ -6848,17 +7565,26 @@ function createModalTargetForEditor(editor, options) {
6848
7565
  primaryTo = Math.min($head.end(), primaryFrom + Math.max(1, count));
6849
7566
  }
6850
7567
  }
7568
+ } else if (mode === "select") {
7569
+ const expanded = expandWholeContainerRange(doc, primaryFrom, primaryTo, true);
7570
+ primaryFrom = expanded.from;
7571
+ primaryTo = expanded.to;
6851
7572
  }
6852
7573
  if (op === "yank") {
6853
7574
  const slice = doc.slice(primaryFrom, primaryTo);
6854
7575
  storage.registerSlice = slice;
6855
7576
  sharedRegisterSlice = slice;
6856
- const yankedText = doc.textBetween(primaryFrom, primaryTo, "\n");
7577
+ const yankedText = serializeModalSliceText(doc, primaryFrom, primaryTo);
6857
7578
  if (yankedText && typeof navigator !== "undefined" && navigator.clipboard?.writeText) {
6858
7579
  void navigator.clipboard.writeText(yankedText).catch(() => {
6859
7580
  });
6860
7581
  }
6861
- const tr = state.tr.setSelection(import_state2.TextSelection.create(doc, primaryFrom));
7582
+ const collapsedSelection = sel instanceof import_state2.NodeSelection ? import_state2.NodeSelection.create(doc, sel.from) : import_state2.Selection.near(doc.resolve(primaryFrom), 1);
7583
+ let tr = state.tr.setSelection(collapsedSelection);
7584
+ if (mode === "select") {
7585
+ storage.mode = "normal";
7586
+ tr = updateMeta(tr, { mode: "normal", secondaryRanges: [] });
7587
+ }
6862
7588
  dispatchTransaction(editor, tr);
6863
7589
  return { enterInsert: false, yankedText };
6864
7590
  }
@@ -6891,10 +7617,13 @@ function createModalTargetForEditor(editor, options) {
6891
7617
  tr = tr.delete(r.from, r.to);
6892
7618
  }
6893
7619
  }
7620
+ if (tr.doc.childCount === 0 && state.schema.nodes.paragraph) {
7621
+ tr = tr.insert(0, state.schema.nodes.paragraph.create());
7622
+ }
6894
7623
  const nextPos = Math.min(tr.doc.content.size, primaryClamped.from);
6895
7624
  const resolved = import_state2.Selection.near(tr.doc.resolve(nextPos));
6896
7625
  tr = tr.setSelection(resolved);
6897
- const nextMode = op === "change" ? "insert" : storage.mode;
7626
+ const nextMode = op === "change" ? "insert" : "normal";
6898
7627
  storage.mode = nextMode;
6899
7628
  tr = updateMeta(tr, { mode: nextMode, secondaryRanges: [] });
6900
7629
  dispatchTransaction(editor, tr.scrollIntoView());
@@ -6903,6 +7632,42 @@ function createModalTargetForEditor(editor, options) {
6903
7632
  if (op === "pasteAfter" || op === "pasteBefore") {
6904
7633
  const slice = storage.registerSlice ?? sharedRegisterSlice;
6905
7634
  if (!slice || slice.size === 0) return false;
7635
+ const isClosedBlockSlice = slice.openStart === 0 && slice.openEnd === 0 && Boolean(slice.content.firstChild?.isBlock);
7636
+ if (isClosedBlockSlice) {
7637
+ let insertPos2;
7638
+ if (sel instanceof import_state2.NodeSelection && sel.node.isBlock) {
7639
+ insertPos2 = op === "pasteAfter" ? sel.to : sel.from;
7640
+ } else {
7641
+ const $ref = op === "pasteAfter" ? sel.$to : sel.$from;
7642
+ if ($ref.depth >= 1) {
7643
+ insertPos2 = op === "pasteAfter" ? $ref.after(1) : $ref.before(1);
7644
+ } else {
7645
+ insertPos2 = op === "pasteAfter" ? sel.to : sel.from;
7646
+ }
7647
+ }
7648
+ const enforceH1 = options.enforceTitle !== false;
7649
+ if (enforceH1 && insertPos2 === 0 && doc.firstChild?.type.name === "heading" && doc.firstChild.attrs.level === 1) {
7650
+ insertPos2 = doc.firstChild.nodeSize;
7651
+ }
7652
+ let tr2 = state.tr;
7653
+ let currentInsertPos = insertPos2;
7654
+ for (let i = 0; i < Math.max(1, count); i += 1) {
7655
+ tr2 = tr2.insert(currentInsertPos, slice.content);
7656
+ currentInsertPos += slice.content.size;
7657
+ }
7658
+ const firstInserted = slice.content.firstChild;
7659
+ if (firstInserted && firstInserted.isAtom && import_state2.NodeSelection.isSelectable(firstInserted)) {
7660
+ tr2 = tr2.setSelection(import_state2.NodeSelection.create(tr2.doc, insertPos2));
7661
+ } else {
7662
+ tr2 = tr2.setSelection(import_state2.Selection.near(tr2.doc.resolve(Math.min(tr2.doc.content.size, insertPos2 + 1)), 1));
7663
+ }
7664
+ if (mode === "select") {
7665
+ storage.mode = "normal";
7666
+ tr2 = updateMeta(tr2, { mode: "normal", secondaryRanges: [] });
7667
+ }
7668
+ dispatchTransaction(editor, tr2.scrollIntoView());
7669
+ return true;
7670
+ }
6906
7671
  let insertPos = op === "pasteAfter" ? sel.to : sel.from;
6907
7672
  if (op === "pasteAfter" && sel.empty && sel.$head.parent.isTextblock && insertPos < sel.$head.end()) {
6908
7673
  insertPos += 1;
@@ -6911,6 +7676,10 @@ function createModalTargetForEditor(editor, options) {
6911
7676
  for (let i = 0; i < Math.max(1, count); i += 1) {
6912
7677
  tr = tr.replaceRange(insertPos, insertPos, slice);
6913
7678
  }
7679
+ if (mode === "select") {
7680
+ storage.mode = "normal";
7681
+ tr = updateMeta(tr, { mode: "normal", secondaryRanges: [] });
7682
+ }
6914
7683
  dispatchTransaction(editor, tr.scrollIntoView());
6915
7684
  return true;
6916
7685
  }
@@ -6941,7 +7710,7 @@ function createModalTargetForEditor(editor, options) {
6941
7710
  const doc = typeof document !== "undefined" ? document : null;
6942
7711
  if (!doc) return false;
6943
7712
  const activePopup = doc.querySelector(
6944
- '[data-slash-menu-surface], [data-mention-menu-surface], [data-editor-slash-menu], [data-editor-mention-menu], .tippy-box[data-state="visible"]'
7713
+ '[data-slash-menu-surface], [data-mention-menu-surface], [data-editor-slash-menu], [data-editor-mention-menu], [data-editor-overlay], .tippy-box[data-state="visible"]'
6945
7714
  );
6946
7715
  if (activePopup) return true;
6947
7716
  let root = doc;
@@ -7047,7 +7816,20 @@ var ModalKeymap = import_core6.Extension.create({
7047
7816
  },
7048
7817
  props: {
7049
7818
  handleDOMEvents: {
7050
- mousedown(view) {
7819
+ mousedown(view, event) {
7820
+ const targetNode = event?.target instanceof Element ? event.target : null;
7821
+ if (targetNode) {
7822
+ if (targetNode.closest("[data-modal-ignore-pointer]")) {
7823
+ return false;
7824
+ }
7825
+ const nonEditable = targetNode.closest('[contenteditable="false"]');
7826
+ if (nonEditable && view.dom.contains(nonEditable)) {
7827
+ const tag = targetNode.tagName.toLowerCase();
7828
+ if (tag !== "input" && tag !== "textarea" && !targetNode.closest("input, textarea")) {
7829
+ return false;
7830
+ }
7831
+ }
7832
+ }
7051
7833
  if (storage.mode !== "insert") {
7052
7834
  storage.mode = "insert";
7053
7835
  try {
@@ -7084,6 +7866,29 @@ var ModalKeymap = import_core6.Extension.create({
7084
7866
  const decos = [];
7085
7867
  const { doc, selection } = state;
7086
7868
  const head = selection.head;
7869
+ const pushNodeDecorationsInRange = (from, to, isPrimary) => {
7870
+ if (from >= to) return;
7871
+ doc.nodesBetween(from, to, (node, pos) => {
7872
+ const isRichModalNode = NON_TEXT_MODAL_NODE_TYPES.has(node.type.name) || node.isAtom && !node.isText;
7873
+ if (!isRichModalNode) return true;
7874
+ const fullyCovered = pos >= from && pos + node.nodeSize <= to;
7875
+ let innerCovered = false;
7876
+ if (!fullyCovered && (node.type.name === "notice" || node.type.name === "blockquote")) {
7877
+ const { firstTextStart, lastTextEnd } = getContainerInnerTextBounds(node, pos);
7878
+ innerCovered = pluginState.mode === "select" && firstTextStart !== -1 && lastTextEnd !== -1 && from <= firstTextStart && to >= lastTextEnd;
7879
+ }
7880
+ if (fullyCovered || innerCovered) {
7881
+ decos.push(
7882
+ import_view.Decoration.node(pos, pos + node.nodeSize, {
7883
+ class: isPrimary ? selection instanceof import_state2.NodeSelection && pos === selection.from ? "pm-modal-node-selection pm-modal-cursor" : "pm-modal-node-selection" : "pm-modal-node-selection pm-multi-selection",
7884
+ "data-pm-modal-node-selection": pluginState.mode,
7885
+ ...isPrimary && selection instanceof import_state2.NodeSelection && pos === selection.from ? { "data-pm-modal-cursor": pluginState.mode } : {}
7886
+ })
7887
+ );
7888
+ }
7889
+ return true;
7890
+ });
7891
+ };
7087
7892
  const pushCursorDecoration = (pos, isMulti = false) => {
7088
7893
  if (pos < 0 || pos > doc.content.size) return;
7089
7894
  const $pos = doc.resolve(pos);
@@ -7098,6 +7903,16 @@ var ModalKeymap = import_core6.Extension.create({
7098
7903
  );
7099
7904
  return;
7100
7905
  }
7906
+ if (nodeAfter && nodeAfter.isAtom && !nodeAfter.isText) {
7907
+ decos.push(
7908
+ import_view.Decoration.node(pos, pos + nodeAfter.nodeSize, {
7909
+ class: "pm-modal-node-selection pm-modal-cursor",
7910
+ "data-pm-modal-node-selection": pluginState.mode,
7911
+ "data-pm-modal-cursor": pluginState.mode
7912
+ })
7913
+ );
7914
+ return;
7915
+ }
7101
7916
  if (typeof document !== "undefined") {
7102
7917
  decos.push(
7103
7918
  import_view.Decoration.widget(
@@ -7121,9 +7936,12 @@ var ModalKeymap = import_core6.Extension.create({
7121
7936
  );
7122
7937
  }
7123
7938
  };
7124
- if (selection.empty) {
7939
+ if (selection instanceof import_state2.NodeSelection) {
7940
+ pushNodeDecorationsInRange(selection.from, selection.to, true);
7941
+ } else if (selection.empty) {
7125
7942
  pushCursorDecoration(head, false);
7126
7943
  } else if (selection.from < selection.to) {
7944
+ pushNodeDecorationsInRange(selection.from, selection.to, true);
7127
7945
  decos.push(
7128
7946
  import_view.Decoration.inline(selection.from, selection.to, {
7129
7947
  class: "pm-modal-selection",
@@ -7131,11 +7949,14 @@ var ModalKeymap = import_core6.Extension.create({
7131
7949
  })
7132
7950
  );
7133
7951
  const $head = doc.resolve(head);
7134
- const cursorPos = selection.head > selection.anchor ? $head.nodeBefore?.isText && head - 1 >= selection.from ? head - 1 : head : head;
7135
- pushCursorDecoration(cursorPos, false);
7952
+ if ($head.parent.isTextblock) {
7953
+ const cursorPos = selection.head > selection.anchor ? $head.nodeBefore?.isText && head - 1 >= selection.from ? head - 1 : head : head;
7954
+ pushCursorDecoration(cursorPos, false);
7955
+ }
7136
7956
  }
7137
7957
  for (const range of pluginState.secondaryRanges) {
7138
7958
  if (range.from >= 0 && range.to <= doc.content.size && range.from < range.to) {
7959
+ pushNodeDecorationsInRange(range.from, range.to, false);
7139
7960
  decos.push(
7140
7961
  import_view.Decoration.inline(range.from, range.to, {
7141
7962
  class: "pm-multi-selection",
@@ -7438,11 +8259,16 @@ var createImageNode = (nodeView) => import_core8.Node.create({
7438
8259
  };
7439
8260
  },
7440
8261
  addProseMirrorPlugins() {
8262
+ const editor = this.editor;
7441
8263
  let arrowKeyPressed = false;
7442
8264
  const captionFocusPlugin = new import_state4.Plugin({
7443
8265
  key: new import_state4.PluginKey("imageNodeCaptionFocus"),
7444
8266
  props: {
7445
8267
  handleKeyDown(_view, event) {
8268
+ if (!isEditorInInsertMode(editor)) {
8269
+ arrowKeyPressed = false;
8270
+ return false;
8271
+ }
7446
8272
  if (event.key === "ArrowDown" || event.key === "ArrowUp") {
7447
8273
  arrowKeyPressed = true;
7448
8274
  }
@@ -7452,6 +8278,10 @@ var createImageNode = (nodeView) => import_core8.Node.create({
7452
8278
  view() {
7453
8279
  return {
7454
8280
  update(view, prevState) {
8281
+ if (!isEditorInInsertMode(editor)) {
8282
+ arrowKeyPressed = false;
8283
+ return;
8284
+ }
7455
8285
  const { selection } = view.state;
7456
8286
  const { selection: prevSelection } = prevState;
7457
8287
  const movedOntoImage = arrowKeyPressed && selection instanceof import_state4.NodeSelection && selection.node.type.name === "imageNode" && !(prevSelection instanceof import_state4.NodeSelection && prevSelection.from === selection.from);
@@ -8303,6 +9133,7 @@ function lockEditorOverlayScroll(editorElement, overlayElement) {
8303
9133
  navbarShrunkBase,
8304
9134
  navbarTriggerVariants,
8305
9135
  navbarVariants,
9136
+ nodeExplicitlyIncludesMode,
8306
9137
  nodeMatchesMode,
8307
9138
  normalizeNodeModes,
8308
9139
  noticeDescriptionBase,
@@ -8400,6 +9231,7 @@ function lockEditorOverlayScroll(editorElement, overlayElement) {
8400
9231
  selectPositionerBase,
8401
9232
  selectTriggerBase,
8402
9233
  selectValueBase,
9234
+ serializeModalSliceText,
8403
9235
  shouldHandleCommandHotkey,
8404
9236
  sidebarMenuButtonVariants,
8405
9237
  sidebarStyles,