phlex-cmdk 0.1.1 → 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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 9c7f8212512b7ffc57adcf7d2428fb10994947b10cc82e920ff8b08d034255eb
4
- data.tar.gz: 2ec4b781453015d628ff1976b0047a85195980b3584c7eaddc9e2672051e3586
3
+ metadata.gz: 53c2c910049c17feb1a78ba920fd8854a553c3bbbdfd217731a176241f346ff0
4
+ data.tar.gz: 283d5a36d930e1de4bbf6a64d4340f88b4b1b15de6ded10ec1d40494553d3de3
5
5
  SHA512:
6
- metadata.gz: f2bba3534f26915215bb0fea83fc2e5c5126d4ad34510997d932125693921c2374749d921043a6a65de8f0a9d3ef6082d8053224ca2fc6fc090d71010bb92db6
7
- data.tar.gz: 6e1623684909b42f34634bd5bc037aa14266544b88b2ede7733d4899e878e843b415a1dd1a1d31ffb407f43bd925787f77e5839cf12551ac71952823fbfe840f
6
+ metadata.gz: b822531b91de17df484e48cbd2df4c2f6351d04860b1dbbd205bdd9a95389504c67fe71d53ec457105ac17ee1959fd4c3f599ea097910b2eb8007fcf5db303ba
7
+ data.tar.gz: c68a0799b1d0af19513c36bf7ccd1f1111e6cb96c0de21fe6986789395ba62897533c774444ffbb5e91efcbb62ea58754ec8e13f88b734d1d234c87bbefb7948
data/CHANGELOG.md CHANGED
@@ -1,5 +1,56 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.0 — 2026-10-29
4
+
5
+ Backward compatible: every 0.1.x option, export, event, markup attribute and
6
+ default keeps working; the new behaviour is opt-in or invisible to existing
7
+ menus.
8
+
9
+ - feat: match highlighting, opt-in with the new `Cmdk::ItemLabel` component —
10
+ matched characters are wrapped in `<mark cmdk-match>` while searching and
11
+ the plain text is restored when the search clears (built from text nodes,
12
+ never `innerHTML`); new export `commandScoreWithMatches(value, query,
13
+ keywords)` returns `{ score, matches }` with the same score as
14
+ `commandScore`
15
+ - feat: CSP support — the markup has no inline `style` attributes any more
16
+ (the accessible label and `Cmdk::Empty` use the `hidden` attribute); the
17
+ injected base styles take the nonce from `<meta name="csp-nonce">`, can be
18
+ turned off with `<meta name="cmdk-base-styles" content="off">` or put into a
19
+ cascade layer (`content="layer"` / `"layer:<name>"`), and ship as a static
20
+ stylesheet (`Cmdk.base_stylesheet_path`, `assets/css/cmdk_base.css`)
21
+ - feat: `destroy(target)` export tears a menu down (observers disconnected,
22
+ state forgotten; a later scan re-initialises it); the Stimulus base
23
+ controller calls it when its menu leaves the page
24
+ - feat: `cmdk-item-select` detail also carries `metaKey`, `ctrlKey`,
25
+ `shiftKey` and `altKey`, for alternate actions such as ⌘/Ctrl+Enter
26
+ - feat: `Cmdk::Group(heading_attributes:, items_attributes:)` and
27
+ `Cmdk::Root(label_attributes:)` pass extra attributes (class, data-*, …) to
28
+ the heading, the items wrapper and the label
29
+ - feat: `Cmdk::Root(native_home_end: true)` lets Home/End move the caret in
30
+ the input instead of selecting the first/last item
31
+ - fix: the dialog hotkey also matches the physical key (`event.code`) on
32
+ non-Latin keyboard layouts, where ⌘K reports e.g. `л`
33
+ - fix: open cmdk dialogs are closed on `turbo:before-cache`, so a page
34
+ restored from Turbo's cache no longer shows a stale, non-modal palette
35
+ - perf: filtering is 2–3× faster per keystroke (median in headless Chrome:
36
+ 1,000 items 6.6 → 3.0 ms, 5,000 items 36 → 13 ms) — nodes already in place
37
+ are no longer moved, unchanged attributes and styles are not rewritten, and
38
+ scoring reuses its buffers and caches normalised strings; the resulting DOM
39
+ is identical
40
+ - themes: keep `[cmdk-empty][hidden]` hidden and style highlight marks
41
+ - tests: Node tests for the scoring functions (`rake test:js`, checked
42
+ against the 0.1.1 implementation), headless-Chrome tests for the runtime
43
+ (`rake test:browser`, Ferrum as a development dependency) and a benchmark
44
+ (`rake bench`); the site gains a Changelog page
45
+
46
+ Note for custom themes: if your CSS sets `display` on `[cmdk-empty]`, add
47
+ `[cmdk-empty][hidden] { display: none }` so the empty state stays hidden
48
+ before the runtime starts (once it runs, it controls the display as before).
49
+ Passing `style: 'display:none'` to `Cmdk::Empty` restores the 0.1 markup.
50
+ If you copied `cmdk.js` into your app instead of serving it from the gem,
51
+ update the copy together with the gem: a 0.1 runtime does not remove the
52
+ `hidden` attribute that 0.2 renders on `Cmdk::Empty`.
53
+
3
54
  ## 0.1.1 — 2026-06-15
4
55
 
5
56
  - docs: correct the Stimulus base controller import (the bare `cmdk`
data/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # ⌘K for Phlex <img src="https://img.shields.io/badge/port%20of-cmdk-blue" align="right">
1
+ # [⌘K for Phlex](https://leongieser.github.io/phlex-cmdk/) <img src="https://img.shields.io/badge/port%20of-cmdk-blue" align="right">
2
2
 
3
3
  A feature-parity port of the [cmdk](https://cmdk.paco.me) React command menu, built for
4
4
  [Phlex](https://www.phlex.fun). Two pieces, and that is the whole dependency surface:
@@ -25,6 +25,9 @@ The runtime uses event delegation and MutationObservers rather than mounting, so
25
25
  Turbo navigation and morphing with no per-page setup, and items appended later (Turbo Streams,
26
26
  your own DOM writes) are registered, filtered and sorted automatically.
27
27
 
28
+ The rendered markup carries no inline `style` attributes, so it works under a strict
29
+ Content Security Policy (see [Content Security Policy](#content-security-policy)).
30
+
28
31
  ## Install
29
32
 
30
33
  ```ruby
@@ -102,6 +105,42 @@ where you would reach for cn(). (Heads-up: Tailwind's preflight resets break
102
105
  native `<dialog>` centering; the runtime ships zero-specificity defaults that
103
106
  handle this - see [Dialog](#dialog).)
104
107
 
108
+ ### Content Security Policy
109
+
110
+ The components render no inline `style` attributes (the accessible label and
111
+ `Cmdk::Empty` use the `hidden` attribute), and the runtime only sets styles
112
+ through the CSSOM (`element.style`), which a CSP allows. The one thing a
113
+ strict `style-src` can block is the small `<style id="cmdk-base-styles">` the
114
+ runtime injects at start (dialog placement, see [Dialog](#dialog)). Two ways
115
+ to handle it:
116
+
117
+ **Nonce it.** When the page has a `<meta name="csp-nonce">` (Rails'
118
+ `csp_meta_tag`), the runtime copies its nonce onto the injected `<style>`:
119
+
120
+ ```erb
121
+ <%= csp_meta_tag %> <%# <meta name="csp-nonce" content="…"> %>
122
+ ```
123
+
124
+ **Or include the rules yourself.** Turn the injection off and serve the same
125
+ rules as a static stylesheet (`Cmdk.base_stylesheet_path`, i.e.
126
+ [assets/css/cmdk_base.css](assets/css/cmdk_base.css)):
127
+
128
+ ```html
129
+ <meta name="cmdk-base-styles" content="off">
130
+ <link rel="stylesheet" href="/cmdk_base.css">
131
+ ```
132
+
133
+ The file has no `@layer` of its own, so a host that uses cascade layers puts
134
+ it in the layer it wants (`@import url('cmdk_base.css') layer(cmdk);`, or
135
+ inside its own build). For an injected copy in a layer, use
136
+ `<meta name="cmdk-base-styles" content="layer">` (`@layer cmdk`) or
137
+ `content="layer:vendor"` (`@layer vendor`). The meta tag must be in the
138
+ document before the runtime starts (put it in `<head>`).
139
+
140
+ With Rails and Propshaft, add the stylesheet directory to the asset paths as
141
+ shown above (`File.dirname(Cmdk.base_stylesheet_path)` is the same directory
142
+ as the themes).
143
+
105
144
  ## Use
106
145
 
107
146
  ```ruby
@@ -134,6 +173,73 @@ root.addEventListener('cmdk-value-change', (e) => preview(e.detail.value))
134
173
  root.addEventListener('cmdk-search-change', (e) => e.detail.search)
135
174
  ```
136
175
 
176
+ `cmdk-item-select` is dispatched on the chosen item and also reports the
177
+ modifier keys held during the click or Enter (`metaKey`, `ctrlKey`,
178
+ `shiftKey`, `altKey`), so an item can offer an alternate action - here
179
+ ⌘/Ctrl+Enter opens a "create" URL instead of the item's `href:`:
180
+
181
+ ```ruby
182
+ Cmdk::Item(href: '/posts', data: { create_url: '/posts/new' }) { 'Posts' }
183
+ ```
184
+
185
+ ```js
186
+ root.addEventListener('cmdk-item-select', (e) => {
187
+ const { metaKey, ctrlKey } = e.detail
188
+ const createUrl = e.target.dataset.createUrl
189
+ if ((metaKey || ctrlKey) && createUrl) {
190
+ e.preventDefault() // skip the default href visit
191
+ Turbo.visit(createUrl)
192
+ }
193
+ })
194
+ ```
195
+
196
+ Extra keyword arguments become HTML attributes on every component. For the
197
+ parts a component renders around your content, use the dedicated hashes:
198
+ `Cmdk::Root(label_attributes: {...})` for the accessible label,
199
+ `Cmdk::Group(heading_attributes: {...}, items_attributes: {...})` for the
200
+ heading and the `[cmdk-group-items]` wrapper:
201
+
202
+ ```ruby
203
+ Cmdk::Group(heading: 'Collections', class: 'palette__group',
204
+ heading_attributes: { class: 'palette__heading' },
205
+ items_attributes: { class: 'palette__items' }) { ... }
206
+ ```
207
+
208
+ The label is rendered `hidden` and named onto the input with
209
+ `aria-labelledby`; `label_attributes: { hidden: false }` shows it.
210
+
211
+ Home and End select the first and last item, as in cmdk. Pass
212
+ `Cmdk::Root(native_home_end: true)` to let them move the caret inside the input
213
+ instead (⌘↑/⌘↓ still jump to the first/last item).
214
+
215
+ ### Match highlighting
216
+
217
+ Wrap an item's text in `Cmdk::ItemLabel` and the runtime highlights the
218
+ characters the query matched, wrapping each run in `<mark cmdk-match>`, and
219
+ restores the plain text when the search clears. Items without an `ItemLabel`
220
+ render and behave exactly as before.
221
+
222
+ ```ruby
223
+ Cmdk::Item(value: 'Go to Field Notes', href: '/field_notes') do
224
+ span(class: 'icon') { '📒' }
225
+ Cmdk::ItemLabel() { 'Field Notes' }
226
+ end
227
+ ```
228
+
229
+ ```css
230
+ [cmdk-item-label] mark[cmdk-match] { background: none; color: inherit; font-weight: 600; }
231
+ ```
232
+
233
+ Matches are computed against the label's own text with the default
234
+ command-score algorithm (so an item found through its `value:` or `keywords:`
235
+ alone shows no highlight). Keep the label to plain text: while highlighted its
236
+ children are rebuilt from text nodes and `<mark>` elements (never `innerHTML`).
237
+ The shipped themes style the marks; the same positions are available in JS:
238
+
239
+ ```js
240
+ Cmdk.commandScoreWithMatches('Field Notes', 'fn') // => { score: 0.89…, matches: [0, 6] }
241
+ ```
242
+
137
243
  ### Dialog
138
244
 
139
245
  ```ruby
@@ -147,6 +253,11 @@ Renders a native `<dialog cmdk-dialog>`: Escape and backdrop clicks close it, an
147
253
  `Cmdk.openDialog(el)` / `Cmdk.closeDialog(el)` toggle it programmatically. Style the
148
254
  backdrop with `dialog[cmdk-dialog]::backdrop` (replaces Radix's `[cmdk-overlay]`).
149
255
 
256
+ The hotkey matches `event.key`; on a non-Latin keyboard layout (Cyrillic, Greek, …),
257
+ where ⌘K reports a letter like `л`, it falls back to the physical key (`event.code`
258
+ `KeyK`). Before Turbo caches a page, open cmdk dialogs are closed, so a restored page
259
+ never shows a stale, non-modal palette.
260
+
150
261
  Extra attributes on `Cmdk::Dialog(...)` go to the inner `Cmdk::Root`; to set
151
262
  attributes on the `<dialog>` element itself, pass `dialog_attributes:`. The
152
263
  shipped themes style the dialog frame (transparent border, entry animation)
@@ -167,7 +278,8 @@ pattern - the software keyboard owns the bottom of the screen, so the input
167
278
  belongs at the top), sized with `dvh` units so dynamic viewports behave. CSS
168
279
  resets (e.g. Tailwind preflight's universal `margin: 0`) break native `<dialog>`
169
280
  centering, so the runtime injects these defaults with zero specificity (`:where()`)
170
- - any rule of yours wins, even a bare element selector:
281
+ - any rule of yours wins, even a bare element selector (under a strict CSP, see
282
+ [Content Security Policy](#content-security-policy)):
171
283
 
172
284
  ```css
173
285
  dialog[cmdk-dialog] { margin-top: 30vh; } /* overrides the default placement */
@@ -309,7 +421,29 @@ export default class extends CmdkController {
309
421
  Hooks: `itemSelected`, `valueChanged`, `searchChanged`, `scopeChanged`. API and
310
422
  actions: `open`/`close`/`toggle` (dialog), `setSearch`, `setValue`, `enterScope`
311
423
  (param-friendly: `data-action="cmdk#enterScope" data-cmdk-scope-param="fruits"`),
312
- `exitScope`, and a `state` getter.
424
+ `exitScope`, and a `state` getter. When the controller disconnects because the
425
+ menu left the page (a Turbo visit, a frame reload), it calls `Cmdk.destroy` to
426
+ free the runtime's observers; a menu that is only moved (`data-turbo-permanent`)
427
+ keeps its state.
428
+
429
+ ### JavaScript API
430
+
431
+ The module's exports (also on `window.Cmdk` and the default export). `target`
432
+ is a root element, an element containing one, or a selector.
433
+
434
+ | Export | Does |
435
+ |---|---|
436
+ | `start()` | Wire the document (runs on import; idempotent) |
437
+ | `scan(node = document)` | Initialise roots and dialogs in `node` |
438
+ | `destroy(target)` | Tear down a menu: disconnect its observers, forget its state (the DOM stays); a later `scan` or interaction re-initialises it |
439
+ | `setSearch(target, query)` / `setValue(target, value)` | Controlled search / selection |
440
+ | `getState(target)` | `{ search, scope, picker, query, value, filtered: { count } }` |
441
+ | `setFilter(fn)` / `setFilter(target, fn)` | Replace the filter globally / per menu (`null` resets) |
442
+ | `enterScope(target, scope)` / `exitScope(target)` | Scoped search |
443
+ | `openDialog(target)` / `closeDialog(target)` | The `<dialog>` palette |
444
+ | `commandScore(value, query, keywords)` / `defaultFilter` | The cmdk scoring function |
445
+ | `commandScoreWithMatches(value, query, keywords)` | `{ score, matches }`: the same score plus the matched indices |
446
+ | `getInstance(target)` | The internal instance (advanced) |
313
447
 
314
448
  ### Styling
315
449
 
@@ -385,7 +519,7 @@ per color. The Lookbook previews expose this as a Theme dropdown in the preview
385
519
  | `filter={fn}` | `Cmdk.setFilter(fn)` or `Cmdk.setFilter(root, fn)` - same `(value, search, keywords) → 0..1` signature |
386
520
  | `<Command.Input value onValueChange>` | `Cmdk::Input(value:)`; `Cmdk.setSearch(root, q)`; `cmdk-search-change` |
387
521
  | `<Command.List label>` | `Cmdk::List(label:)` |
388
- | `<Command.Item value keywords disabled forceMount onSelect>` | `Cmdk::Item(value:, keywords:, disabled:, force_mount:)`; `cmdk-item-select` event; value inferred from text content when omitted |
522
+ | `<Command.Item value keywords disabled forceMount onSelect>` | `Cmdk::Item(value:, keywords:, disabled:, force_mount:)`; `cmdk-item-select` event (with the modifier keys); value inferred from text content when omitted |
389
523
  | `<Command.Group heading value forceMount>` | `Cmdk::Group(heading:, value:, force_mount:)` |
390
524
  | `<Command.Separator alwaysRender>` | `Cmdk::Separator(always_render:)` |
391
525
  | `<Command.Empty>` / `<Command.Loading progress label>` | `Cmdk::Empty()` / `Cmdk::Loading(progress:, label:)` |
@@ -394,18 +528,25 @@ per color. The Lookbook previews expose this as a Theme dropdown in the preview
394
528
  | vim bindings, Home/End, alt/meta arrows, IME guard | identical, ported from the same keydown logic |
395
529
 
396
530
  Extensions beyond the React API: `Cmdk::Item(href:)` visits a URL on select (via Turbo when
397
- present), and clearing the search restores the server-rendered order (React leaves the
398
- sorted order in place).
531
+ present), `Cmdk::ItemLabel` highlights matched characters, and clearing the search restores
532
+ the server-rendered order (React leaves the sorted order in place).
399
533
 
400
534
  ## Demo, previews & tests
401
535
 
402
536
  ```sh
403
537
  bundle install
404
- bundle exec rake test # component markup contract tests
405
- bundle exec rake demo # builds Tailwind CSS, serves http://localhost:9292
406
- bundle exec rake lookbook # Lookbook component previews on http://localhost:9293
538
+ bundle exec rake test # component markup contract tests
539
+ bundle exec rake test:js # runtime pure functions (node --test, no dependencies)
540
+ bundle exec rake test:browser # runtime DOM behaviour in headless Chrome (Ferrum)
541
+ bundle exec rake test:all # all three
542
+ bundle exec rake bench # per-keystroke filtering latency at 200/1,000/5,000 items
543
+ bundle exec rake demo # builds Tailwind CSS, serves http://localhost:9292
544
+ bundle exec rake lookbook # Lookbook component previews on http://localhost:9293
407
545
  ```
408
546
 
547
+ The browser tests and the benchmark need Chrome or Chromium installed; the
548
+ `ferrum` gem that drives it is a development dependency only.
549
+
409
550
  The [Lookbook](https://lookbook.build) previews live in [lookbook/](lookbook/) - Lookbook is a
410
551
  Rails engine, so a minimal single-file Rails host ([lookbook/app.rb](lookbook/app.rb)) boots it;
411
552
  the gem itself stays Rails-free. Scenarios cover the default menu (with live params for
@@ -0,0 +1,47 @@
1
+ /*
2
+ * phlex-cmdk base styles — the rules the runtime injects at start() as
3
+ * <style id="cmdk-base-styles">: native <dialog> placement (top-third palette,
4
+ * top-anchored sheet under 640px) and keeping server-rendered hidden parts
5
+ * hidden. Everything except the [hidden] guard is zero-specificity
6
+ * (`:where()`), so any rule of yours wins.
7
+ *
8
+ * For CSP-strict or cascade-layered hosts: turn the injection off with
9
+ *
10
+ * <meta name="cmdk-base-styles" content="off">
11
+ *
12
+ * and include this file yourself (path in Ruby: Cmdk.base_stylesheet_path),
13
+ * e.g. in a layer of your choice:
14
+ *
15
+ * @import url('cmdk_base.css') layer(cmdk);
16
+ */
17
+ :where(dialog[cmdk-dialog]) {
18
+ position: fixed;
19
+ inset: 0;
20
+ margin: 16dvh auto auto;
21
+ width: fit-content;
22
+ height: fit-content;
23
+ max-width: calc(100vw - 2rem);
24
+ max-height: calc(84dvh - 2rem);
25
+ /* The list scrolls internally; keep the dialog itself unclipped so a themed
26
+ root's border-radius and drop-shadow are not squared off at the corners. */
27
+ overflow: visible;
28
+ }
29
+ :where(dialog[cmdk-dialog])::backdrop {
30
+ background: transparent;
31
+ }
32
+ :where([cmdk-list-sizer]) {
33
+ display: flow-root; /* child margins must count into --cmdk-list-height */
34
+ }
35
+ /* Server-rendered hidden parts stay hidden even when theme CSS sets display. */
36
+ [cmdk-label][hidden],
37
+ [cmdk-empty][hidden] {
38
+ display: none !important;
39
+ }
40
+ @media (max-width: 640px) {
41
+ :where(dialog[cmdk-dialog]) {
42
+ margin: 0.5rem auto auto;
43
+ width: calc(100vw - 1rem);
44
+ max-width: calc(100vw - 1rem);
45
+ max-height: calc(100dvh - 1rem);
46
+ }
47
+ }
@@ -186,6 +186,13 @@
186
186
  color: var(--cmdk-accent-fg);
187
187
  }
188
188
 
189
+ /* Match highlighting (opt-in via Cmdk::ItemLabel). */
190
+ & [cmdk-item-label] mark[cmdk-match] {
191
+ background: none;
192
+ color: inherit;
193
+ font-weight: 600;
194
+ }
195
+
189
196
  & [cmdk-item][data-disabled='true'] {
190
197
  cursor: not-allowed;
191
198
  color: var(--cmdk-muted);
@@ -217,6 +224,12 @@
217
224
  color: var(--cmdk-muted);
218
225
  }
219
226
 
227
+ /* Rendered `hidden` until the runtime decides; keep it so despite the
228
+ display above (matters only before the runtime has started). */
229
+ & [cmdk-empty][hidden] {
230
+ display: none;
231
+ }
232
+
220
233
  & [cmdk-footer] {
221
234
  display: flex;
222
235
  align-items: center;
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,
@@ -41,6 +41,11 @@ export default class CmdkController extends Controller {
41
41
  disconnect() {
42
42
  for (const [type, listener] of this.#listeners) this.element.removeEventListener(type, listener)
43
43
  this.#listeners = []
44
+ // Free the runtime's observers once the menu has left the document (a
45
+ // Turbo visit, frame reload or morph). A menu that is only moved — e.g.
46
+ // `data-turbo-permanent` — is still connected and keeps its state.
47
+ const root = this.root
48
+ if (root && !root.isConnected) Cmdk.destroy(root)
44
49
  }
45
50
 
46
51
  /** The [cmdk-root] this controller manages. */
data/lib/cmdk/base.rb CHANGED
@@ -1,7 +1,9 @@
1
1
  module Cmdk
2
2
  # Shared base for all cmdk components.
3
3
  class Base < ::Phlex::HTML
4
- # Inline equivalent of cmdk's srOnlyStyles, used for the accessible label.
4
+ # Inline equivalent of cmdk's srOnlyStyles. No longer rendered (since
5
+ # 0.2.0 the accessible label uses the `hidden` attribute, so the markup
6
+ # needs no inline style under a strict CSP); kept for code referencing it.
5
7
  SR_ONLY_STYLE = 'position:absolute;width:1px;height:1px;padding:0;margin:-1px;' \
6
8
  'overflow:hidden;clip:rect(0, 0, 0, 0);white-space:nowrap;border-width:0'.freeze
7
9
 
data/lib/cmdk/empty.rb CHANGED
@@ -1,14 +1,18 @@
1
1
  module Cmdk
2
2
  # Shown automatically when there are no results. Port of `<Command.Empty>`.
3
- # Rendered hidden (inline display:none, so theme CSS cannot override it);
4
- # the runtime toggles it based on the filtered result count.
3
+ # Rendered with the `hidden` attribute (no inline style, so it works under a
4
+ # strict CSP); the runtime toggles it based on the filtered result count,
5
+ # with an inline display so theme CSS cannot override it. If your own CSS
6
+ # sets `display` on `[cmdk-empty]`, add `[cmdk-empty][hidden] { display:
7
+ # none }` so it stays hidden before the runtime starts (the shipped themes
8
+ # and base styles do this).
5
9
  class Empty < Base
6
10
  def initialize(**attributes)
7
11
  @attributes = attributes
8
12
  end
9
13
 
10
14
  def view_template(&block)
11
- defaults = { 'cmdk-empty' => '', role: 'presentation', style: 'display:none' }
15
+ defaults = { 'cmdk-empty' => '', role: 'presentation', hidden: true }
12
16
  div(**merged(defaults, @attributes), &block)
13
17
  end
14
18
  end
data/lib/cmdk/group.rb CHANGED
@@ -2,6 +2,10 @@ module Cmdk
2
2
  # Groups items together with an optional heading. Port of `<Command.Group>`.
3
3
  # Provide `value:` when there is no heading (it is used for sorting groups);
4
4
  # with a string heading the value is inferred from it, matching React cmdk.
5
+ #
6
+ # `heading_attributes:` and `items_attributes:` add attributes (class,
7
+ # data-*, …) to the heading and to the `[cmdk-group-items]` wrapper; extra
8
+ # keyword attributes go to the group element itself.
5
9
  class Group < Base
6
10
  # Monotonic id source for `aria-labelledby` (the analog of React's useId,
7
11
  # which this port mirrors). Deterministic and collision-free, unlike a
@@ -14,24 +18,29 @@ module Cmdk
14
18
  end
15
19
 
16
20
  def initialize(heading: nil, value: nil, force_mount: false, scope: nil, scope_only: false,
17
- server_filtered: false, **attributes)
21
+ server_filtered: false, heading_attributes: {}, items_attributes: {}, **attributes)
18
22
  @heading = heading
19
23
  @value = value
20
24
  @force_mount = force_mount
21
25
  @scope = scope
22
26
  @scope_only = scope_only
23
27
  @server_filtered = server_filtered
28
+ @heading_attributes = heading_attributes
29
+ @items_attributes = items_attributes
24
30
  @attributes = attributes
25
31
  end
26
32
 
27
33
  def view_template(&block)
28
- heading_id = @heading ? Group.next_heading_id : nil
34
+ heading_id = @heading ? (@heading_attributes[:id] || Group.next_heading_id) : nil
29
35
 
30
36
  div(**merged(group_attributes, @attributes)) do
31
37
  if @heading
32
- div('cmdk-group-heading' => '', aria_hidden: 'true', id: heading_id) { @heading }
38
+ div(**merged({ 'cmdk-group-heading' => '', aria_hidden: 'true', id: heading_id }, @heading_attributes)) do
39
+ @heading
40
+ end
33
41
  end
34
- div('cmdk-group-items' => '', role: 'group', aria_labelledby: heading_id, &block)
42
+ items = { 'cmdk-group-items' => '', role: 'group', aria_labelledby: heading_id }
43
+ div(**merged(items, @items_attributes), &block)
35
44
  end
36
45
  end
37
46
 
@@ -0,0 +1,25 @@
1
+ module Cmdk
2
+ # The part of an item whose matched characters the runtime highlights while
3
+ # searching (opt-in; an extension over the React API). Put the item's text
4
+ # in it; the runtime wraps each matched run in `<mark cmdk-match>` and
5
+ # restores the plain text when the search clears:
6
+ #
7
+ # Cmdk::Item(value: 'posts', href: '/posts') do
8
+ # icon
9
+ # Cmdk::ItemLabel() { 'Posts' }
10
+ # end
11
+ #
12
+ # Matches are computed against the label's own text with the default
13
+ # command-score algorithm. Keep the label to plain text: its children are
14
+ # replaced by text nodes and marks while highlighted. Style matches with
15
+ # `[cmdk-item-label] mark[cmdk-match]`.
16
+ class ItemLabel < Base
17
+ def initialize(**attributes)
18
+ @attributes = attributes
19
+ end
20
+
21
+ def view_template(&block)
22
+ span(**merged({ 'cmdk-item-label' => '' }, @attributes), &block)
23
+ end
24
+ end
25
+ end
data/lib/cmdk/root.rb CHANGED
@@ -14,10 +14,19 @@ module Cmdk
14
14
  # pill before the input. The rest of the input is then matched only against
15
15
  # items/groups tagged with the same `scope:`. Pass `active_scope:` to
16
16
  # server-render an already-pinned scope.
17
+ #
18
+ # The accessible `label:` renders as a `hidden` <label cmdk-label> that the
19
+ # runtime wires to the input via `aria-labelledby` (no inline style, so it
20
+ # works under a strict CSP). `label_attributes:` adds attributes to it
21
+ # (`label_attributes: { hidden: false, class: 'my-label' }` shows it).
22
+ #
23
+ # `native_home_end: true` lets Home/End move the caret inside the input
24
+ # instead of jumping to the first/last item (⌘↑/⌘↓ still do that).
17
25
  class Root < Base
18
26
  def initialize(label: nil, default_value: nil, should_filter: true, loop: false,
19
27
  vim_bindings: true, disable_pointer_selection: false, scopes: nil,
20
- scope_picker: nil, active_scope: nil, **attributes)
28
+ scope_picker: nil, active_scope: nil, label_attributes: {},
29
+ native_home_end: false, **attributes)
21
30
  @label = label
22
31
  @default_value = default_value
23
32
  @should_filter = should_filter
@@ -27,12 +36,14 @@ module Cmdk
27
36
  @scopes = scopes
28
37
  @scope_picker = scope_picker
29
38
  @active_scope = active_scope
39
+ @label_attributes = label_attributes
40
+ @native_home_end = native_home_end
30
41
  @attributes = attributes
31
42
  end
32
43
 
33
44
  def view_template(&block)
34
45
  div(**merged(root_attributes, @attributes)) do
35
- label('cmdk-label' => '', style: SR_ONLY_STYLE) { @label }
46
+ label(**merged({ 'cmdk-label' => '', hidden: true }, @label_attributes)) { @label }
36
47
  block&.call
37
48
  end
38
49
  end
@@ -48,6 +59,7 @@ module Cmdk
48
59
  data[:cmdk_default_value] = @default_value if @default_value
49
60
  data[:cmdk_scopes] = Array(@scopes).join(' ') if @scopes
50
61
  data[:cmdk_active_scope] = @active_scope if @active_scope
62
+ data[:cmdk_native_home_end] = '' if @native_home_end
51
63
  unless @scope_picker.nil?
52
64
  data[:cmdk_scope_picker] = @scope_picker == false ? 'false' : @scope_picker
53
65
  end
data/lib/cmdk/version.rb CHANGED
@@ -1,3 +1,3 @@
1
1
  module Cmdk
2
- VERSION = '0.1.1'
2
+ VERSION = '0.2.0'
3
3
  end
data/lib/cmdk.rb CHANGED
@@ -19,6 +19,14 @@ module Cmdk
19
19
  File.expand_path('../assets/css/cmdk_themes.css', __dir__)
20
20
  end
21
21
 
22
+ # Absolute path to the runtime's base styles as a static stylesheet (the
23
+ # same rules the runtime injects at start, all zero-specificity `:where()`).
24
+ # For CSP-strict or cascade-layered hosts that turn the injection off with
25
+ # `<meta name="cmdk-base-styles" content="off">` and include it themselves.
26
+ def self.base_stylesheet_path
27
+ File.expand_path('../assets/css/cmdk_base.css', __dir__)
28
+ end
29
+
22
30
  # Absolute path to the optional Stimulus base controller (requires
23
31
  # @hotwired/stimulus and the runtime pinned/aliased as `cmdk`).
24
32
  def self.stimulus_controller_path
@@ -32,6 +40,7 @@ require_relative 'cmdk/root'
32
40
  require_relative 'cmdk/input'
33
41
  require_relative 'cmdk/list'
34
42
  require_relative 'cmdk/item'
43
+ require_relative 'cmdk/item_label'
35
44
  require_relative 'cmdk/group'
36
45
  require_relative 'cmdk/separator'
37
46
  require_relative 'cmdk/empty'
metadata CHANGED
@@ -1,14 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: phlex-cmdk
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.1
4
+ version: 0.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Leon Gieser
8
- autorequire:
9
8
  bindir: bin
10
9
  cert_chain: []
11
- date: 2026-06-15 00:00:00.000000000 Z
10
+ date: 1980-01-02 00:00:00.000000000 Z
12
11
  dependencies:
13
12
  - !ruby/object:Gem::Dependency
14
13
  name: phlex
@@ -43,6 +42,7 @@ files:
43
42
  - CHANGELOG.md
44
43
  - LICENSE.md
45
44
  - README.md
45
+ - assets/css/cmdk_base.css
46
46
  - assets/css/cmdk_themes.css
47
47
  - assets/js/cmdk.js
48
48
  - assets/js/cmdk_controller.js
@@ -54,6 +54,7 @@ files:
54
54
  - lib/cmdk/group.rb
55
55
  - lib/cmdk/input.rb
56
56
  - lib/cmdk/item.rb
57
+ - lib/cmdk/item_label.rb
57
58
  - lib/cmdk/list.rb
58
59
  - lib/cmdk/loading.rb
59
60
  - lib/cmdk/root.rb
@@ -68,7 +69,6 @@ metadata:
68
69
  source_code_uri: https://github.com/leongieser/phlex-cmdk
69
70
  changelog_uri: https://github.com/leongieser/phlex-cmdk/blob/main/CHANGELOG.md
70
71
  rubygems_mfa_required: 'true'
71
- post_install_message:
72
72
  rdoc_options: []
73
73
  require_paths:
74
74
  - lib
@@ -83,8 +83,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
83
83
  - !ruby/object:Gem::Version
84
84
  version: '0'
85
85
  requirements: []
86
- rubygems_version: 3.0.3.1
87
- signing_key:
86
+ rubygems_version: 4.0.10
88
87
  specification_version: 4
89
88
  summary: 'Fast, composable command menu for Phlex: a port of cmdk (React).'
90
89
  test_files: []