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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 64fd7358d8d5c71ef5038a191b08dd08f735ac5cd64319ba65617591b9fd5944
4
- data.tar.gz: 796d52044bd196d61bdab9da53752a3fd1b12eac2612656531449506d67cd348
3
+ metadata.gz: 53c2c910049c17feb1a78ba920fd8854a553c3bbbdfd217731a176241f346ff0
4
+ data.tar.gz: 283d5a36d930e1de4bbf6a64d4340f88b4b1b15de6ded10ec1d40494553d3de3
5
5
  SHA512:
6
- metadata.gz: 980b9a9b18c6965cf967a5f0fc1580294879f46f8a657dd3178bc7fd86f8f6dde2fefadb5b12604fefaa27cb188b9096fb44690419b1690b584e4c9feb666172
7
- data.tar.gz: 7cb81bd470337f4278bf1388b47c39dcf127b76fbe6cb44f84737335d43c9fa20ffad6e55fa7b2de2a1c8275915861beaa074e40a4f035ec677e876bf545b73f
6
+ metadata.gz: b822531b91de17df484e48cbd2df4c2f6351d04860b1dbbd205bdd9a95389504c67fe71d53ec457105ac17ee1959fd4c3f599ea097910b2eb8007fcf5db303ba
7
+ data.tar.gz: c68a0799b1d0af19513c36bf7ccd1f1111e6cb96c0de21fe6986789395ba62897533c774444ffbb5e91efcbb62ea58754ec8e13f88b734d1d234c87bbefb7948
data/CHANGELOG.md CHANGED
@@ -1,5 +1,64 @@
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
+
54
+ ## 0.1.1 — 2026-06-15
55
+
56
+ - docs: correct the Stimulus base controller import (the bare `cmdk`
57
+ specifier, not `./cmdk.js`); document `dialog_attributes:` and the
58
+ `cmdk-dialog-frame` theme class
59
+ - internal: idiomatic Phlex content-block forwarding; deterministic group
60
+ heading ids (monotonic, replacing a random suffix). No markup or API changes.
61
+
3
62
  ## 0.1.0 — 2026-06-15
4
63
 
5
64
  Initial release: a feature-parity Phlex port of the cmdk React command menu.
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,13 +253,33 @@ 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
+
261
+ Extra attributes on `Cmdk::Dialog(...)` go to the inner `Cmdk::Root`; to set
262
+ attributes on the `<dialog>` element itself, pass `dialog_attributes:`. The
263
+ shipped themes style the dialog frame (transparent border, entry animation)
264
+ behind a `cmdk-dialog-frame` class, opt in the same way you opt into the menu
265
+ theme - by asking for the class:
266
+
267
+ ```ruby
268
+ Cmdk::Dialog(label: 'Command Menu', hotkey: 'k', class: 'cmdk',
269
+ dialog_attributes: { class: 'cmdk-dialog-frame' }) do
270
+ Cmdk::Input()
271
+ Cmdk::List() { ... }
272
+ end
273
+ ```
274
+
150
275
  By default the dialog renders as a top-third, horizontally centered palette; on
151
276
  viewports ≤640px it becomes a top-anchored, full-width sheet (the GitHub/Jira
152
277
  pattern - the software keyboard owns the bottom of the screen, so the input
153
278
  belongs at the top), sized with `dvh` units so dynamic viewports behave. CSS
154
279
  resets (e.g. Tailwind preflight's universal `margin: 0`) break native `<dialog>`
155
280
  centering, so the runtime injects these defaults with zero specificity (`:where()`)
156
- - 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)):
157
283
 
158
284
  ```css
159
285
  dialog[cmdk-dialog] { margin-top: 30vh; } /* overrides the default placement */
@@ -280,7 +406,8 @@ The bubbling events work with plain action descriptors - no controller required:
280
406
 
281
407
  For more structure, the gem ships an optional base controller
282
408
  (`Cmdk.stimulus_controller_path`; serve it next to the runtime, it imports
283
- `./cmdk.js` and `@hotwired/stimulus`). Extend it and override the hooks:
409
+ the runtime as the bare specifier `cmdk` and `@hotwired/stimulus`). Extend it
410
+ and override the hooks:
284
411
 
285
412
  ```js
286
413
  import CmdkController from 'cmdk_controller' // pin to Cmdk.stimulus_controller_path
@@ -294,7 +421,29 @@ export default class extends CmdkController {
294
421
  Hooks: `itemSelected`, `valueChanged`, `searchChanged`, `scopeChanged`. API and
295
422
  actions: `open`/`close`/`toggle` (dialog), `setSearch`, `setValue`, `enterScope`
296
423
  (param-friendly: `data-action="cmdk#enterScope" data-cmdk-scope-param="fruits"`),
297
- `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) |
298
447
 
299
448
  ### Styling
300
449
 
@@ -370,7 +519,7 @@ per color. The Lookbook previews expose this as a Theme dropdown in the preview
370
519
  | `filter={fn}` | `Cmdk.setFilter(fn)` or `Cmdk.setFilter(root, fn)` - same `(value, search, keywords) → 0..1` signature |
371
520
  | `<Command.Input value onValueChange>` | `Cmdk::Input(value:)`; `Cmdk.setSearch(root, q)`; `cmdk-search-change` |
372
521
  | `<Command.List label>` | `Cmdk::List(label:)` |
373
- | `<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 |
374
523
  | `<Command.Group heading value forceMount>` | `Cmdk::Group(heading:, value:, force_mount:)` |
375
524
  | `<Command.Separator alwaysRender>` | `Cmdk::Separator(always_render:)` |
376
525
  | `<Command.Empty>` / `<Command.Loading progress label>` | `Cmdk::Empty()` / `Cmdk::Loading(progress:, label:)` |
@@ -379,18 +528,25 @@ per color. The Lookbook previews expose this as a Theme dropdown in the preview
379
528
  | vim bindings, Home/End, alt/meta arrows, IME guard | identical, ported from the same keydown logic |
380
529
 
381
530
  Extensions beyond the React API: `Cmdk::Item(href:)` visits a URL on select (via Turbo when
382
- present), and clearing the search restores the server-rendered order (React leaves the
383
- 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).
384
533
 
385
534
  ## Demo, previews & tests
386
535
 
387
536
  ```sh
388
537
  bundle install
389
- bundle exec rake test # component markup contract tests
390
- bundle exec rake demo # builds Tailwind CSS, serves http://localhost:9292
391
- 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
392
545
  ```
393
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
+
394
550
  The [Lookbook](https://lookbook.build) previews live in [lookbook/](lookbook/) - Lookbook is a
395
551
  Rails engine, so a minimal single-file Rails host ([lookbook/app.rb](lookbook/app.rb)) boots it;
396
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;