phlex-cmdk 0.1.0 → 0.2.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.
data/assets/js/cmdk.js CHANGED
@@ -13,7 +13,10 @@
13
13
  * import 'cmdk' // auto-starts
14
14
  *
15
15
  * Events (all bubble from within the root):
16
- * cmdk-item-select detail: { value } — item chosen via click or Enter (cancelable)
16
+ * cmdk-item-select detail: { value, metaKey, ctrlKey, shiftKey, altKey }
17
+ * — item chosen via click or Enter (cancelable); the
18
+ * modifier keys held at that moment
19
+ * (e.g. ⌘/Ctrl+Enter for an alternate action)
17
20
  * cmdk-value-change detail: { value } — selection (highlight) changed
18
21
  * cmdk-search-change detail: { search, scope, query } — search query changed
19
22
  * cmdk-scope-change detail: { scope, query } — active search scope entered/left
@@ -29,6 +32,16 @@
29
32
  * to cmdk-scope-change / cmdk-search-change to fetch scoped results from the
30
33
  * server (e.g. via Turbo). Add `data-cmdk-scope-only` to keep items hidden
31
34
  * unless their scope is active.
35
+ *
36
+ * Match highlighting (opt-in): mark the text to highlight inside an item with
37
+ * `[cmdk-item-label]` (Cmdk::ItemLabel) and the runtime wraps the matched
38
+ * characters in `<mark cmdk-match>` while searching, restoring the plain text
39
+ * when the search clears.
40
+ *
41
+ * Base styles: unless `<meta name="cmdk-base-styles" content="off">` is in the
42
+ * document, start() injects a small zero-specificity stylesheet (dialog
43
+ * placement), nonced from `<meta name="csp-nonce">` when present. The same
44
+ * rules ship as assets/css/cmdk_base.css for CSP-strict or layered hosts.
32
45
  */
33
46
 
34
47
  // ─────────────────────────────────────────────────────────────────────────────
@@ -49,7 +62,11 @@ const IS_GAP_REGEXP = /[\\/_+.#"@[({&]/,
49
62
  IS_SPACE_REGEXP = /[\s-]/,
50
63
  COUNT_SPACE_REGEXP = /[\s-]/g
51
64
 
52
- function commandScoreInner(string, abbreviation, lowerString, lowerAbbreviation, stringIndex, abbreviationIndex, memoizedResults) {
65
+ // The scoring arithmetic below is unchanged from the port; the memo is a typed
66
+ // array instead of string keys (no allocation per call), and `choices`, when
67
+ // given, records which index won at each step so the match path can be read
68
+ // back for highlighting.
69
+ function commandScoreInner(string, abbreviation, lowerString, lowerAbbreviation, stringIndex, abbreviationIndex, memo, stride, choices) {
53
70
  if (abbreviationIndex === abbreviation.length) {
54
71
  if (stringIndex === string.length) {
55
72
  return SCORE_CONTINUE_MATCH
@@ -57,19 +74,22 @@ function commandScoreInner(string, abbreviation, lowerString, lowerAbbreviation,
57
74
  return PENALTY_NOT_COMPLETE
58
75
  }
59
76
 
60
- const memoizeKey = `${stringIndex},${abbreviationIndex}`
61
- if (memoizedResults[memoizeKey] !== undefined) {
62
- return memoizedResults[memoizeKey]
77
+ const memoizeKey = stringIndex * stride + abbreviationIndex
78
+ const memoized = memo[memoizeKey]
79
+ if (memoized >= 0) {
80
+ return memoized
63
81
  }
64
82
 
65
83
  const abbreviationChar = lowerAbbreviation.charAt(abbreviationIndex)
66
84
  let index = lowerString.indexOf(abbreviationChar, stringIndex)
67
85
  let highScore = 0
86
+ let choice = -1
68
87
 
69
- let score, transposedScore, wordBreaks, spaceBreaks
88
+ let score, transposedScore, wordBreaks, spaceBreaks, transposed
70
89
 
71
90
  while (index >= 0) {
72
- score = commandScoreInner(string, abbreviation, lowerString, lowerAbbreviation, index + 1, abbreviationIndex + 1, memoizedResults)
91
+ transposed = false
92
+ score = commandScoreInner(string, abbreviation, lowerString, lowerAbbreviation, index + 1, abbreviationIndex + 1, memo, stride, choices)
73
93
  if (score > highScore) {
74
94
  if (index === stringIndex) {
75
95
  score *= SCORE_CONTINUE_MATCH
@@ -102,31 +122,105 @@ function commandScoreInner(string, abbreviation, lowerString, lowerAbbreviation,
102
122
  (lowerAbbreviation.charAt(abbreviationIndex + 1) === lowerAbbreviation.charAt(abbreviationIndex) &&
103
123
  lowerString.charAt(index - 1) !== lowerAbbreviation.charAt(abbreviationIndex))
104
124
  ) {
105
- transposedScore = commandScoreInner(string, abbreviation, lowerString, lowerAbbreviation, index + 1, abbreviationIndex + 2, memoizedResults)
125
+ transposedScore = commandScoreInner(string, abbreviation, lowerString, lowerAbbreviation, index + 1, abbreviationIndex + 2, memo, stride, choices)
106
126
 
107
127
  if (transposedScore * SCORE_TRANSPOSITION > score) {
108
128
  score = transposedScore * SCORE_TRANSPOSITION
129
+ transposed = true
109
130
  }
110
131
  }
111
132
 
112
133
  if (score > highScore) {
113
134
  highScore = score
135
+ choice = index * 2 + (transposed ? 1 : 0)
114
136
  }
115
137
 
116
138
  index = lowerString.indexOf(abbreviationChar, index + 1)
117
139
  }
118
140
 
119
- memoizedResults[memoizeKey] = highScore
141
+ memo[memoizeKey] = highScore
142
+ if (choices) choices[memoizeKey] = choice
120
143
  return highScore
121
144
  }
122
145
 
146
+ // Lowercased/space-normalised strings are cached: item values repeat on every
147
+ // keystroke, so this saves re-normalising each one per query.
148
+ const formatted = new Map()
149
+
123
150
  function formatInput(string) {
124
- return string.toLowerCase().replace(COUNT_SPACE_REGEXP, ' ')
151
+ let result = formatted.get(string)
152
+ if (result === undefined) {
153
+ result = string.toLowerCase().replace(COUNT_SPACE_REGEXP, ' ')
154
+ if (formatted.size >= 20000) formatted.clear()
155
+ formatted.set(string, result)
156
+ }
157
+ return result
158
+ }
159
+
160
+ // Scratch buffers reused across calls (scoring is synchronous, never re-entered).
161
+ let memoBuffer = new Float64Array(4096)
162
+ let choiceBuffer = new Int32Array(4096)
163
+
164
+ function scoreString(string, abbreviation, choices) {
165
+ // +3 keeps a key unique for any abbreviation index the recursion can reach.
166
+ const stride = abbreviation.length + 3
167
+ const size = (string.length + 1) * stride
168
+ if (memoBuffer.length < size) {
169
+ memoBuffer = new Float64Array(size * 2)
170
+ choiceBuffer = new Int32Array(size * 2)
171
+ }
172
+ memoBuffer.fill(-1, 0, size)
173
+ if (choices) {
174
+ choiceBuffer.fill(-1, 0, size)
175
+ choices.array = choiceBuffer
176
+ choices.stride = stride
177
+ }
178
+ return commandScoreInner(string, abbreviation, formatInput(string), formatInput(abbreviation), 0, 0, memoBuffer, stride, choices ? choiceBuffer : null)
179
+ }
180
+
181
+ function joinAliases(string, aliases) {
182
+ return aliases && aliases.length > 0 ? `${string + ' ' + aliases.join(' ')}` : string
125
183
  }
126
184
 
127
185
  export function commandScore(string, abbreviation, aliases) {
128
- string = aliases && aliases.length > 0 ? `${string + ' ' + aliases.join(' ')}` : string
129
- return commandScoreInner(string, abbreviation, formatInput(string), formatInput(abbreviation), 0, 0, {})
186
+ return scoreString(joinAliases(string, aliases), abbreviation)
187
+ }
188
+
189
+ /**
190
+ * commandScore plus the positions it matched: `{ score, matches }`, where
191
+ * `matches` are ascending indices into `string` (then into the aliases, joined
192
+ * after it with single spaces). The score is identical to commandScore's;
193
+ * matches is empty when the score is 0. Used for match highlighting.
194
+ */
195
+ export function commandScoreWithMatches(string, abbreviation, aliases) {
196
+ const full = joinAliases(string, aliases)
197
+ const choices = {}
198
+ const score = scoreString(full, abbreviation, choices)
199
+ const matches = []
200
+ if (score > 0) {
201
+ const lowerString = formatInput(full)
202
+ const lowerAbbreviation = formatInput(abbreviation)
203
+ let stringIndex = 0
204
+ let abbreviationIndex = 0
205
+ while (abbreviationIndex < abbreviation.length) {
206
+ const choice = choices.array[stringIndex * choices.stride + abbreviationIndex]
207
+ if (choice === undefined || choice < 0) break
208
+ const index = choice >> 1
209
+ if (choice & 1) {
210
+ // A transposition ("ab" typed as "ba") consumed two characters of the
211
+ // abbreviation; a doubled letter ("hhello") consumed only one match.
212
+ if (index > 0 && lowerString.charAt(index - 1) === lowerAbbreviation.charAt(abbreviationIndex + 1)) {
213
+ matches.push(index - 1)
214
+ }
215
+ abbreviationIndex += 2
216
+ } else {
217
+ abbreviationIndex += 1
218
+ }
219
+ matches.push(index)
220
+ stringIndex = index + 1
221
+ }
222
+ }
223
+ return { score, matches: [...new Set(matches)].sort((a, b) => a - b).filter((i) => i < full.length) }
130
224
  }
131
225
 
132
226
  // ─────────────────────────────────────────────────────────────────────────────
@@ -143,6 +237,8 @@ const GROUP_HEADING_SELECTOR = '[cmdk-group-heading]'
143
237
  const ITEM_SELECTOR = '[cmdk-item]'
144
238
  const VALID_ITEM_SELECTOR = `${ITEM_SELECTOR}:not([aria-disabled="true"])`
145
239
  const DIALOG_SELECTOR = 'dialog[cmdk-dialog]'
240
+ const ITEM_LABEL_SELECTOR = '[cmdk-item-label]'
241
+ const MATCH_ATTR = 'cmdk-match'
146
242
  const VALUE_ATTR = 'data-value'
147
243
 
148
244
  const SELECT_EVENT = 'cmdk-item-select'
@@ -259,6 +355,7 @@ function config(root) {
259
355
  loop: root.hasAttribute('data-cmdk-loop'),
260
356
  vimBindings: root.getAttribute('data-cmdk-vim-bindings') !== 'false',
261
357
  disablePointerSelection: root.hasAttribute('data-cmdk-disable-pointer-selection'),
358
+ nativeHomeEnd: root.hasAttribute('data-cmdk-native-home-end'),
262
359
  }
263
360
  }
264
361
 
@@ -291,11 +388,14 @@ function createInstance(root) {
291
388
  order: new Map(), // element → original index, to restore server order when search clears
292
389
  orderUid: 0,
293
390
  itemUid: 0,
391
+ highlighted: new Set(), // [cmdk-item-label] elements currently holding <mark cmdk-match>
392
+ disconnect: [], // teardown callbacks, run by destroy()
294
393
  }
295
394
  instances.set(root, inst)
296
395
 
297
396
  wireIds(inst)
298
397
  registerNodes(inst)
398
+ adoptHighlights(inst)
299
399
  // A server-rendered input value is the initial search (React: <Command.Input value>).
300
400
  inst.search = root.querySelector(INPUT_SELECTOR)?.value || ''
301
401
  // Server-rendered scope state: data-cmdk-active-scope pins the pill at init.
@@ -312,7 +412,9 @@ function createInstance(root) {
312
412
  observeListHeight(inst)
313
413
 
314
414
  // Item mount/unmount lifecycle (Turbo streams, morphing, manual DOM changes).
315
- new MutationObserver(() => onItemsChanged(inst)).observe(root, { childList: true, subtree: true })
415
+ const observer = new MutationObserver(() => onItemsChanged(inst))
416
+ observer.observe(root, { childList: true, subtree: true })
417
+ inst.disconnect.push(() => observer.disconnect())
316
418
 
317
419
  return inst
318
420
  }
@@ -402,40 +504,55 @@ function score(inst, value, keywords, item) {
402
504
  return value ? filter(value, inst.query, keywords, item) : 0
403
505
  }
404
506
 
507
+ /** Set an inline display only when it changes (unchanged writes still cost style work). */
508
+ function setDisplay(el, shown) {
509
+ const display = shown ? '' : 'none'
510
+ if (el.style.display !== display) el.style.display = display
511
+ }
512
+
405
513
  /** Port of filterItems(): score items, toggle item/group/separator/empty visibility. */
406
514
  function filterItems(inst) {
407
515
  const { root, search, scope, picker } = inst
408
516
  const filtering = Boolean(search) && config(root).shouldFilter
517
+ // Match highlighting is opt-in markup; skip all of it when no item uses it.
518
+ const highlight = inst.highlighted.size > 0 || root.querySelector(ITEM_LABEL_SELECTOR) !== null
409
519
  let count = 0
410
520
 
521
+ // Skip per-item ancestor lookups for features the menu doesn't use.
522
+ const anyForceMount = root.querySelector('[data-cmdk-force-mount]') !== null
523
+ const anyScopeOnly = root.querySelector('[data-cmdk-scope-only]') !== null
524
+ const anyServerFiltered = root.querySelector('[data-cmdk-server-filtered]') !== null
525
+
411
526
  for (const item of root.querySelectorAll(ITEM_SELECTOR)) {
412
- const fm = forceMounted(item)
527
+ const fm = anyForceMount && forceMounted(item)
413
528
  // Scope-only items require deliberate entry: hidden (even from global
414
529
  // search and force mount) unless their scope is the active one.
415
- const scopeHidden = isScopeOnly(item) && itemScope(item) !== scope
530
+ const scopeHidden = anyScopeOnly && isScopeOnly(item) && itemScope(item) !== scope
416
531
  let rank
532
+ let scored = false // matched against the query (so its label can be highlighted)
417
533
  if (scopeHidden) {
418
534
  rank = 0
419
535
  } else if (picker) {
420
536
  // Scope-picker mode ("/..."): only scope-entry items are suggested.
421
- rank = item.hasAttribute('data-cmdk-enters-scope')
422
- ? score(inst, itemValue(item), itemKeywords(item), item)
423
- : 0
537
+ scored = item.hasAttribute('data-cmdk-enters-scope')
538
+ rank = scored ? score(inst, itemValue(item), itemKeywords(item), item) : 0
424
539
  } else if (scope && itemScope(item) !== scope) {
425
540
  rank = 0
426
- } else if (item.closest('[data-cmdk-server-filtered]')) {
541
+ } else if (anyServerFiltered && item.closest('[data-cmdk-server-filtered]')) {
427
542
  // The server already filtered these (e.g. a Turbo-framed scope search);
428
543
  // don't fuzzy-match them against the query again.
429
544
  rank = 1
430
545
  } else {
546
+ scored = filtering
431
547
  rank = filtering ? score(inst, itemValue(item), itemKeywords(item), item) : 1
432
548
  }
433
549
  inst.scores.set(item, rank)
434
550
  const shown = !scopeHidden && (fm || rank > 0)
435
551
  // React removes filtered items from the DOM; we hide them with an inline
436
552
  // style so theme CSS (e.g. `[cmdk-item] { display: flex }`) cannot win.
437
- item.style.display = shown ? '' : 'none'
553
+ setDisplay(item, shown)
438
554
  if (!fm && shown) count++
555
+ if (highlight) highlightItem(inst, item, shown && scored && (filtering || picker) ? inst.query : '')
439
556
  }
440
557
  inst.count = count
441
558
 
@@ -445,7 +562,7 @@ function filterItems(inst) {
445
562
  shown =
446
563
  (!picker && group.hasAttribute('data-cmdk-force-mount')) ||
447
564
  Array.from(group.querySelectorAll(ITEM_SELECTOR)).some(
448
- (item) => !forceMounted(item) && inst.scores.get(item) > 0,
565
+ (item) => !(anyForceMount && forceMounted(item)) && inst.scores.get(item) > 0,
449
566
  )
450
567
  } else if (shown) {
451
568
  // Hide groups whose items are all scope-hidden; keep itemless groups
@@ -453,16 +570,77 @@ function filterItems(inst) {
453
570
  const items = Array.from(group.querySelectorAll(ITEM_SELECTOR))
454
571
  shown = items.length === 0 || items.some((item) => item.style.display !== 'none')
455
572
  }
456
- group.hidden = !shown
573
+ if (group.hidden !== !shown) group.hidden = !shown
457
574
  }
458
575
 
459
576
  for (const separator of root.querySelectorAll('[cmdk-separator]')) {
460
577
  const shown = (!search && !scope) || separator.hasAttribute('data-cmdk-always-render')
461
- separator.style.display = shown ? '' : 'none'
578
+ setDisplay(separator, shown)
462
579
  }
463
580
 
464
581
  for (const empty of root.querySelectorAll('[cmdk-empty]')) {
465
- empty.style.display = count === 0 ? '' : 'none'
582
+ // Server-rendered with the `hidden` attribute (no inline style, so a
583
+ // strict CSP allows it); from here on the inline display decides, as
584
+ // before, so theme CSS cannot show it while there are results.
585
+ if (empty.hidden !== (count !== 0)) empty.hidden = count !== 0
586
+ setDisplay(empty, count === 0)
587
+ }
588
+ }
589
+
590
+ // ── Match highlighting ([cmdk-item-label] → <mark cmdk-match>) ──
591
+
592
+ const labelMarks = new WeakMap() // label element → the matches currently rendered ("1,2,5")
593
+
594
+ /** Highlight `query`'s matches in the item's [cmdk-item-label]s ('' restores the text). */
595
+ function highlightItem(inst, item, query) {
596
+ const labels = item.querySelectorAll(ITEM_LABEL_SELECTOR)
597
+ for (const label of labels) {
598
+ const marked = inst.highlighted.has(label)
599
+ if (!query && !marked) continue
600
+ // Marks only wrap runs of the label's text, so its textContent is always
601
+ // the plain text, highlighted or not.
602
+ const text = label.textContent
603
+ const matches = query ? commandScoreWithMatches(text, query).matches : []
604
+ const key = matches.join(',')
605
+ // Unchanged since the last pass (and not re-rendered by a morph meanwhile).
606
+ if (marked && labelMarks.get(label) === key && label.childElementCount > 0) continue
607
+ if (!matches.length) {
608
+ if (marked) label.textContent = text
609
+ inst.highlighted.delete(label)
610
+ labelMarks.delete(label)
611
+ continue
612
+ }
613
+ renderMarks(label, text, matches)
614
+ inst.highlighted.add(label)
615
+ labelMarks.set(label, key)
616
+ }
617
+ }
618
+
619
+ /** Rebuild a label as text nodes and <mark cmdk-match> runs (never innerHTML). */
620
+ function renderMarks(label, text, matches) {
621
+ const fragment = document.createDocumentFragment()
622
+ let position = 0
623
+ for (let i = 0; i < matches.length; ) {
624
+ let end = i
625
+ while (end + 1 < matches.length && matches[end + 1] === matches[end] + 1) end++
626
+ const from = matches[i]
627
+ const to = matches[end] + 1
628
+ if (from > position) fragment.appendChild(document.createTextNode(text.slice(position, from)))
629
+ const mark = document.createElement('mark')
630
+ mark.setAttribute(MATCH_ATTR, '')
631
+ mark.textContent = text.slice(from, to)
632
+ fragment.appendChild(mark)
633
+ position = to
634
+ i = end + 1
635
+ }
636
+ if (position < text.length) fragment.appendChild(document.createTextNode(text.slice(position)))
637
+ label.replaceChildren(fragment)
638
+ }
639
+
640
+ /** Labels that already hold marks (a page restored from Turbo's cache, a re-init after destroy). */
641
+ function adoptHighlights(inst) {
642
+ for (const mark of inst.root.querySelectorAll(`${ITEM_LABEL_SELECTOR} mark[${MATCH_ATTR}]`)) {
643
+ inst.highlighted.add(mark.closest(ITEM_LABEL_SELECTOR))
466
644
  }
467
645
  }
468
646
 
@@ -485,14 +663,27 @@ function sortItems(inst) {
485
663
  return
486
664
  }
487
665
 
488
- getValidItems(inst)
489
- .sort((a, b) => (scores.get(b) ?? 0) - (scores.get(a) ?? 0))
490
- .forEach((item) => {
491
- const container = item.closest(GROUP_ITEMS_SELECTOR) || sizer
492
- container.appendChild(directChild(container, item))
493
- })
666
+ // The result is what appending every visible item (in score order) and then
667
+ // every visible group (by best item) to the end of its container produces;
668
+ // planned per container first, so nodes already in place are not moved.
669
+ const plan = new Map() // container → Map(child → sequence; the last append wins)
670
+ let seq = 0
671
+ let direct = true
672
+ const append = (container, child) => {
673
+ if (child.parentElement !== container) direct = false
674
+ let moves = plan.get(container)
675
+ if (!moves) plan.set(container, (moves = new Map()))
676
+ moves.delete(child)
677
+ moves.set(child, seq++)
678
+ }
679
+
680
+ const items = getValidItems(inst).sort((a, b) => (scores.get(b) ?? 0) - (scores.get(a) ?? 0))
681
+ for (const item of items) {
682
+ const container = item.closest(GROUP_ITEMS_SELECTOR) || sizer
683
+ append(container, directChild(container, item))
684
+ }
494
685
 
495
- Array.from(root.querySelectorAll(GROUP_SELECTOR))
686
+ const groups = Array.from(root.querySelectorAll(GROUP_SELECTOR))
496
687
  .filter((group) => !group.hidden)
497
688
  .map((group) => {
498
689
  let max = 0
@@ -502,15 +693,40 @@ function sortItems(inst) {
502
693
  return [group, max]
503
694
  })
504
695
  .sort((a, b) => b[1] - a[1])
505
- .forEach(([group]) => group.parentElement?.appendChild(group))
696
+ for (const [group] of groups) {
697
+ if (group.parentElement) append(group.parentElement, group)
698
+ }
699
+
700
+ if (!direct) {
701
+ // Unusual markup (an item outside its container): replay the appends.
702
+ for (const [container, moves] of plan) for (const child of moves.keys()) container.appendChild(child)
703
+ return
704
+ }
705
+ for (const [container, moves] of plan) {
706
+ const stay = Array.from(container.children).filter((child) => !moves.has(child))
707
+ reorder(container, stay.concat(Array.from(moves.keys())))
708
+ }
709
+ }
710
+
711
+ /** Make `container`'s element children follow `desired`, moving only misplaced nodes. */
712
+ function reorder(container, desired) {
713
+ let current = container.firstElementChild
714
+ for (const el of desired) {
715
+ if (current === el) {
716
+ current = current.nextElementSibling
717
+ continue
718
+ }
719
+ container.insertBefore(el, current)
720
+ }
506
721
  }
507
722
 
508
723
  function restoreOrder(inst) {
509
724
  for (const container of containersOf(inst)) {
510
- Array.from(container.children)
725
+ const children = Array.from(container.children)
726
+ const known = children
511
727
  .filter((child) => inst.order.has(child))
512
728
  .sort((a, b) => inst.order.get(a) - inst.order.get(b))
513
- .forEach((child) => container.appendChild(child))
729
+ reorder(container, children.filter((child) => !inst.order.has(child)).concat(known))
514
730
  }
515
731
  }
516
732
 
@@ -519,14 +735,16 @@ function applySelection(inst) {
519
735
  for (const item of inst.root.querySelectorAll(ITEM_SELECTOR)) {
520
736
  const isSelected = Boolean(inst.value) && itemValue(item) === inst.value
521
737
  if (isSelected && !selected) selected = item
522
- item.setAttribute('aria-selected', String(isSelected))
523
- item.setAttribute('data-selected', String(isSelected))
738
+ const state = String(isSelected)
739
+ if (item.getAttribute('aria-selected') !== state) item.setAttribute('aria-selected', state)
740
+ if (item.getAttribute('data-selected') !== state) item.setAttribute('data-selected', state)
524
741
  }
525
742
 
526
743
  for (const el of [inst.root.querySelector(INPUT_SELECTOR), inst.root.querySelector(LIST_SELECTOR)]) {
527
744
  if (!el) continue
528
- if (selected) el.setAttribute('aria-activedescendant', selected.id)
529
- else el.removeAttribute('aria-activedescendant')
745
+ if (selected) {
746
+ if (el.getAttribute('aria-activedescendant') !== selected.id) el.setAttribute('aria-activedescendant', selected.id)
747
+ } else el.removeAttribute('aria-activedescendant')
530
748
  }
531
749
 
532
750
  updateFooterHint(inst, selected)
@@ -602,11 +820,20 @@ function selectFirstItem(inst, opts) {
602
820
  }
603
821
 
604
822
  /** Item chosen via click or Enter. Dispatches cmdk-item-select; honors data-href. */
605
- function triggerSelect(inst, item) {
823
+ function triggerSelect(inst, item, source) {
606
824
  if (item.getAttribute('aria-disabled') === 'true') return
607
825
  const value = itemValue(item)
608
826
  setValueState(inst, value, { scroll: false })
609
- const event = new CustomEvent(SELECT_EVENT, { bubbles: true, cancelable: true, detail: { value } })
827
+ // The modifier keys held during the click or Enter, so listeners can offer
828
+ // an alternate action (e.g. ⌘/Ctrl+Enter opens a "create" URL instead).
829
+ const detail = {
830
+ value,
831
+ metaKey: Boolean(source?.metaKey),
832
+ ctrlKey: Boolean(source?.ctrlKey),
833
+ shiftKey: Boolean(source?.shiftKey),
834
+ altKey: Boolean(source?.altKey),
835
+ }
836
+ const event = new CustomEvent(SELECT_EVENT, { bubbles: true, cancelable: true, detail })
610
837
  const proceed = item.dispatchEvent(event)
611
838
  if (!proceed) return
612
839
  const enters = item.getAttribute('data-cmdk-enters-scope')
@@ -712,10 +939,15 @@ function observeListHeight(inst) {
712
939
  const update = () => list.style.setProperty('--cmdk-list-height', sizer.offsetHeight.toFixed(1) + 'px')
713
940
  update()
714
941
  let frame
715
- new ResizeObserver(() => {
942
+ const observer = new ResizeObserver(() => {
716
943
  cancelAnimationFrame(frame)
717
944
  frame = requestAnimationFrame(update)
718
- }).observe(sizer)
945
+ })
946
+ observer.observe(sizer)
947
+ inst.disconnect.push(() => {
948
+ observer.disconnect()
949
+ cancelAnimationFrame(frame)
950
+ })
719
951
  }
720
952
 
721
953
  // ── Dialog (native <dialog> port of Command.Dialog) ──
@@ -750,15 +982,31 @@ function setupDialog(dialog) {
750
982
  }
751
983
  }
752
984
 
985
+ /**
986
+ * The physical letter for hotkey matching on non-Latin layouts: there ⌘/Ctrl+K
987
+ * reports e.key "л" (Cyrillic) or "κ" (Greek), so when e.key is a letter but
988
+ * not a Latin one, fall back to e.code ("KeyK" → "k"). Null otherwise, so Latin
989
+ * layouts (QWERTY, Dvorak, AZERTY, …) keep matching by e.key alone.
990
+ */
991
+ function physicalLetter(e) {
992
+ const key = e.key || ''
993
+ if (key.length !== 1 || /^[a-z]$/i.test(key) || !/\p{L}/u.test(key)) return null
994
+ const physical = /^Key([A-Z])$/.exec(e.code || '')
995
+ return physical ? physical[1].toLowerCase() : null
996
+ }
997
+
753
998
  function handleDialogHotkey(e) {
754
999
  if (!(e.metaKey || e.ctrlKey) || e.repeat) return
1000
+ const key = (e.key || '').toLowerCase()
1001
+ const physical = physicalLetter(e)
755
1002
  // ctrl+n/j/p/k inside a menu with vim bindings is navigation, not a hotkey.
756
- if (e.ctrlKey && !e.metaKey && ['n', 'j', 'p', 'k'].includes(e.key)) {
1003
+ if (e.ctrlKey && !e.metaKey && ['n', 'j', 'p', 'k'].some((k) => k === key || k === physical)) {
757
1004
  const root = e.target instanceof Element ? e.target.closest(ROOT_SELECTOR) : null
758
1005
  if (root && config(root).vimBindings) return
759
1006
  }
760
1007
  for (const dialog of document.querySelectorAll(`${DIALOG_SELECTOR}[data-cmdk-dialog-hotkey]`)) {
761
- if (e.key.toLowerCase() === dialog.getAttribute('data-cmdk-dialog-hotkey').toLowerCase()) {
1008
+ const hotkey = dialog.getAttribute('data-cmdk-dialog-hotkey').toLowerCase()
1009
+ if (key === hotkey || physical === hotkey) {
762
1010
  e.preventDefault()
763
1011
  dialog.open ? closeDialog(dialog) : openDialog(dialog)
764
1012
  }
@@ -776,7 +1024,7 @@ function onKeydown(e) {
776
1024
 
777
1025
  // IME composition guard (keyCode 229 covers legacy CJK IMEs).
778
1026
  if (e.defaultPrevented || e.isComposing || e.keyCode === 229) return
779
- const { vimBindings } = config(root)
1027
+ const { vimBindings, nativeHomeEnd } = config(root)
780
1028
 
781
1029
  switch (e.key) {
782
1030
  case 'n':
@@ -806,11 +1054,14 @@ function onKeydown(e) {
806
1054
  break
807
1055
  }
808
1056
  case 'Home': {
1057
+ // data-cmdk-native-home-end: Home/End move the caret inside the input.
1058
+ if (nativeHomeEnd && e.target.matches?.(INPUT_SELECTOR)) break
809
1059
  e.preventDefault()
810
1060
  updateSelectedToIndex(inst, 0)
811
1061
  break
812
1062
  }
813
1063
  case 'End': {
1064
+ if (nativeHomeEnd && e.target.matches?.(INPUT_SELECTOR)) break
814
1065
  e.preventDefault()
815
1066
  updateSelectedToIndex(inst, getValidItems(inst).length - 1)
816
1067
  break
@@ -818,7 +1069,7 @@ function onKeydown(e) {
818
1069
  case 'Enter': {
819
1070
  e.preventDefault()
820
1071
  const item = getSelectedItem(inst)
821
- if (item) triggerSelect(inst, item)
1072
+ if (item) triggerSelect(inst, item, e)
822
1073
  break
823
1074
  }
824
1075
  }
@@ -851,7 +1102,7 @@ function onClick(e) {
851
1102
 
852
1103
  const item = e.target.closest(ITEM_SELECTOR)
853
1104
  const root = item?.closest(ROOT_SELECTOR)
854
- if (item && root) triggerSelect(getInstance(root), item)
1105
+ if (item && root) triggerSelect(getInstance(root), item, e)
855
1106
  }
856
1107
 
857
1108
  function onPointerMove(e) {
@@ -876,6 +1127,21 @@ export function scan(node = document) {
876
1127
  node.querySelectorAll?.(DIALOG_SELECTOR).forEach(setupDialog)
877
1128
  }
878
1129
 
1130
+ /**
1131
+ * Tear down a menu's instance: disconnect its MutationObserver and
1132
+ * ResizeObserver, cancel pending frames and forget its state. The DOM is left
1133
+ * as it is. Call it when a menu leaves the page (e.g. from a Stimulus
1134
+ * controller's disconnect()); a later scan() or interaction with the same
1135
+ * element initialises it afresh.
1136
+ */
1137
+ export function destroy(target) {
1138
+ const root = resolveRoot(target)
1139
+ const inst = root && instances.get(root)
1140
+ if (!inst) return
1141
+ for (const teardown of inst.disconnect.splice(0)) teardown()
1142
+ instances.delete(root)
1143
+ }
1144
+
879
1145
  /** Programmatically set the search query (the React `<Command.Input value>` controlled mode). */
880
1146
  export function setSearch(target, search) {
881
1147
  const inst = getInstance(target)
@@ -931,12 +1197,10 @@ export function setFilter(target, fn) {
931
1197
  * destroy the native <dialog> centering, so the runtime re-asserts it here.
932
1198
  * `:where()` keeps specificity at zero — any consumer rule on
933
1199
  * `dialog[cmdk-dialog]` or a class overrides these.
1200
+ *
1201
+ * Identical to assets/css/cmdk_base.css (a test keeps the two in sync).
934
1202
  */
935
- function injectBaseStyles() {
936
- if (document.getElementById('cmdk-base-styles')) return
937
- const style = document.createElement('style')
938
- style.id = 'cmdk-base-styles'
939
- style.textContent = `
1203
+ const BASE_STYLES = `
940
1204
  :where(dialog[cmdk-dialog]) {
941
1205
  position: fixed;
942
1206
  inset: 0;
@@ -955,6 +1219,11 @@ function injectBaseStyles() {
955
1219
  :where([cmdk-list-sizer]) {
956
1220
  display: flow-root; /* child margins must count into --cmdk-list-height */
957
1221
  }
1222
+ /* Server-rendered hidden parts stay hidden even when theme CSS sets display. */
1223
+ [cmdk-label][hidden],
1224
+ [cmdk-empty][hidden] {
1225
+ display: none !important;
1226
+ }
958
1227
  @media (max-width: 640px) {
959
1228
  :where(dialog[cmdk-dialog]) {
960
1229
  margin: 0.5rem auto auto;
@@ -962,10 +1231,39 @@ function injectBaseStyles() {
962
1231
  max-width: calc(100vw - 1rem);
963
1232
  max-height: calc(100dvh - 1rem);
964
1233
  }
965
- }`
1234
+ }
1235
+ `
1236
+
1237
+ /**
1238
+ * Inject BASE_STYLES once, as a <style id="cmdk-base-styles"> in <head>.
1239
+ * `<meta name="cmdk-base-styles" content="…">` controls it:
1240
+ * off (or false/none) — inject nothing; include cmdk_base.css yourself
1241
+ * layer — wrap the rules in `@layer cmdk`
1242
+ * layer:<name> — wrap them in `@layer <name>`
1243
+ * The <style> gets the nonce from `<meta name="csp-nonce">` (Rails'
1244
+ * csp_meta_tag) when present, so a nonce-based style-src CSP accepts it.
1245
+ */
1246
+ function injectBaseStyles() {
1247
+ if (document.getElementById('cmdk-base-styles')) return
1248
+ const setting = (document.querySelector('meta[name="cmdk-base-styles"]')?.getAttribute('content') || '').trim()
1249
+ if (/^(off|false|none)$/i.test(setting)) return
1250
+ const layer = /^layer(?::\s*([\w-]+))?$/i.exec(setting)
1251
+ const style = document.createElement('style')
1252
+ style.id = 'cmdk-base-styles'
1253
+ const nonce = document.querySelector('meta[name="csp-nonce"]')?.getAttribute('content')
1254
+ if (nonce) style.nonce = nonce
1255
+ style.textContent = layer ? `@layer ${layer[1] || 'cmdk'} {${BASE_STYLES}}\n` : BASE_STYLES
966
1256
  document.head.appendChild(style)
967
1257
  }
968
1258
 
1259
+ /**
1260
+ * Turbo snapshots the page before leaving it; an open modal would come back
1261
+ * from the cache as a non-modal `<dialog open>`. Close cmdk dialogs first.
1262
+ */
1263
+ function onBeforeCache() {
1264
+ for (const dialog of document.querySelectorAll(`${DIALOG_SELECTOR}[open]`)) dialog.close()
1265
+ }
1266
+
969
1267
  let started = false
970
1268
 
971
1269
  export function start() {
@@ -977,6 +1275,7 @@ export function start() {
977
1275
  document.addEventListener('input', onInput)
978
1276
  document.addEventListener('click', onClick)
979
1277
  document.addEventListener('pointermove', onPointerMove)
1278
+ document.addEventListener('turbo:before-cache', onBeforeCache)
980
1279
 
981
1280
  const init = () => scan()
982
1281
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init)
@@ -986,7 +1285,8 @@ export function start() {
986
1285
  new MutationObserver((records) => {
987
1286
  for (const record of records) {
988
1287
  for (const node of record.addedNodes) {
989
- if (node.nodeType === Node.ELEMENT_NODE) scan(node)
1288
+ // Highlight marks are the runtime's own nodes, never roots or dialogs.
1289
+ if (node.nodeType === Node.ELEMENT_NODE && !node.hasAttribute(MATCH_ATTR)) scan(node)
990
1290
  }
991
1291
  }
992
1292
  }).observe(document.documentElement, { childList: true, subtree: true })
@@ -995,7 +1295,9 @@ export function start() {
995
1295
  const Cmdk = {
996
1296
  start,
997
1297
  scan,
1298
+ destroy,
998
1299
  commandScore,
1300
+ commandScoreWithMatches,
999
1301
  defaultFilter,
1000
1302
  setFilter,
1001
1303
  setSearch,