@kolkrabbi/kol-component 0.264.0 → 0.266.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.
@@ -1,340 +1,11 @@
1
- import { useEffect, useId, useRef, useState } from 'react'
2
- import { Icon } from '@kolkrabbi/kol-icons'
3
- import SearchInput from '../molecules/SearchInput.jsx'
4
- import Tag from '../atoms/Tag.jsx'
5
- import Kbd from '../atoms/Kbd.jsx'
6
- import OptionRow from '../molecules/OptionRow.jsx'
7
-
8
- /* ONE COLUMN (2026-09-30): rows, headings and footer sit on the field's own
9
- * geometry — the p-2 inset, then the md control's 1px ring + 16px pad — so
10
- * every glyph and word lines up under the field's icon and caret. */
11
-
12
- /* Rows bucketed by `group` in first-seen order, rank kept inside a group —
13
- * one heading per group; arrows rove this order, not the engine's. */
14
- function groupRows(rows) {
15
- const order = []
16
- const byGroup = new Map()
17
- rows.forEach((r) => {
18
- const g = r.group ?? ''
19
- if (!byGroup.has(g)) { byGroup.set(g, []); order.push(g) }
20
- byGroup.get(g).push(r)
21
- })
22
- return order.flatMap((g) => byGroup.get(g))
23
- }
24
-
25
- /**
26
- * HighlightMatch — default row renderer: underlines the first
27
- * case-insensitive `query` slice inside `label` at full ink. Exported for
28
- * consumers building their own rows; not in the package barrel.
29
- *
30
- * @param {string} label full row label
31
- * @param {string} query current query (empty / no match → plain label)
32
- */
33
- export function HighlightMatch({ label, query, ranges }) {
34
- /* An engine that already knows where it matched (kol-search's `highlights`)
35
- * passes `ranges` — every hit, not just the first slice of the raw query. */
36
- if (Array.isArray(ranges)) {
37
- if (!ranges.length) return <span>{label}</span>
38
- const out = []
39
- let at = 0
40
- ranges.forEach(([s, e], i) => {
41
- if (s > at) out.push(<span key={`t${i}`}>{label.slice(at, s)}</span>)
42
- out.push(<span key={`m${i}`} className="text-fg underline decoration-2 underline-offset-[3px]">{label.slice(s, e)}</span>)
43
- at = e
44
- })
45
- if (at < label.length) out.push(<span key="rest">{label.slice(at)}</span>)
46
- return <>{out}</>
47
- }
48
- const idx = query ? label.toLowerCase().indexOf(query.toLowerCase()) : -1
49
- if (idx === -1) return <span>{label}</span>
50
- return (
51
- <>
52
- <span>{label.slice(0, idx)}</span>
53
- <span className="text-fg underline decoration-2 underline-offset-[3px]">
54
- {label.slice(idx, idx + query.length)}
55
- </span>
56
- <span>{label.slice(idx + query.length)}</span>
57
- </>
58
- )
59
- }
1
+ import CommandOverlay from './CommandOverlay.jsx'
60
2
 
61
3
  /**
62
- * ShellSearchOverlay — The ⌘K search modal. the ⌘K search modal: fullscreen dim + centered
63
- * panel, a bare SearchInput on top, result rows beneath (HighlightMatch
64
- * label, dim hint line, right-aligned group label). Distinct from Modal
65
- * (prompt/confirm only) — this is the search/command primitive.
66
- *
67
- * Content-agnostic: the consumer filters and passes `results`; selection
68
- * emits `onSelect(item)` (no navigation here — ported off react-router).
69
- * The ⌘K binding itself lives in the shell's key handler, not here.
70
- *
71
- * Keyboard: ArrowUp/ArrowDown rove the active row (mouse hover roves too),
72
- * Enter opens it (the top row from the first keystroke), ⌘/Ctrl+Enter opens every hit,
73
- * Escape closes. Focus trap: focus moves into the input on open, returns to
74
- * the opener on close, and Tab is pinned — rows are combobox options driven
75
- * via aria-activedescendant, never tab stops.
76
- *
77
- * @param {boolean} open mount/unmount the overlay
78
- * @param {Function} onClose () => void — backdrop click, Escape, post-select
79
- * @param {Array} results pre-filtered rows: { id, label, group?, hint?, icon?, disabled?, disabledHint? }
80
- * @param {Array} [suggestions] rows shown while the query is empty (same shape) —
81
- * the search modal opens on somewhere to go, not a blank box
82
- * @param {string} query controlled query (drives the highlight slice)
83
- * @param {Function} onQueryChange (string) => void — input change
84
- * @param {Function} onSelect (item) => void — row click / Enter; consumer navigates. A row
85
- * with `keepOpen` or `action` selects and the modal stays open
86
- * @param {string} placeholder input placeholder
87
- * @param {string} [enterLabel] what Enter does when no row is picked — shown as
88
- * the panel's last line, so Enter is never a surprise
89
- * (e.g. `All results for “q”`). Rows may carry
90
- * `highlights` ([start, end] ranges) from the engine.
91
- * @param {Function} [onOpenResults] (query) => void — ⌘/Ctrl+Enter: every hit, on the consumer's
92
- * own results surface. Plain Enter keeps its meaning.
93
- * @param {string} [resultsLabel] the footer's second line for ⌘Enter (e.g. `All results`)
94
- * @param {string} [selectLabel] the footer's Enter line while a row is highlighted (default
95
- * `Go to page`) — a modal whose rows are not pages says what
96
- * Enter does instead (the rack's module search: `Add module`)
4
+ * @deprecated 2026-10-17 — alias of CommandOverlay (CommandOverlayModes). Drops when nobody imports it (04-retirements.md).
5
+ * ShellSearchOverlay — Old name for CommandOverlay. The ⌘K search modal is now one overlay with modes; this
6
+ * name keeps every call-site working. Migrate imports to `CommandOverlay`.
97
7
  */
98
- export default function ShellSearchOverlay({
99
- open,
100
- onClose,
101
- results: rawResults = [],
102
- suggestions = [],
103
- /* EXPANDED — the search modal's second state (user ruling 2026-08-01). Enter
104
- * commits the query and opens `children` as the results body; the search modal
105
- * and the old tag overlay are one surface with two states, not two
106
- * components. `chips` are the committed tag facets of the same query. */
107
- expanded = false,
108
- onExpand,
109
- chips = [],
110
- onRemoveChip,
111
- children,
112
- query = '',
113
- onQueryChange,
114
- onSelect,
115
- placeholder = 'Search…',
116
- enterLabel,
117
- onOpenResults,
118
- resultsLabel = 'All results',
119
- selectLabel = 'Go to page',
120
- }) {
121
- const panelRef = useRef(null)
122
- const listRef = useRef(null)
123
- const listId = useId()
124
- const [activeIndex, setActiveIndex] = useState(0)
125
- /* Has the user actually chosen a row? See the Enter branch — without this,
126
- * index 0 counts as a selection and Enter navigates somewhere unasked. */
127
- const [navigated, setNavigated] = useState(false)
128
- const results = groupRows(query ? rawResults : suggestions)
129
- /* a `disabled` row is drawn but never active: ↑↓ step over it, Enter and click never reach
130
- * `onSelect` (ShellSearchDisabledRow, kol-monitor 2026-10-15 — a module with no room on the rack) */
131
- const clamped = Math.min(activeIndex, results.length - 1)
132
- const active = clamped >= 0 && !results[clamped].disabled ? clamped : -1
133
- const step = (from, dir) => {
134
- for (let i = from + dir; i >= 0 && i < results.length; i += dir) if (!results[i].disabled) return i
135
- return from
136
- }
137
-
138
- /* Focus in on open, restore the opener on close. querySelector instead of
139
- * a ref through SearchInput — ref-as-prop needs React 19 and the package
140
- * peer range still allows 18. */
141
- useEffect(() => {
142
- if (!open) return undefined
143
- const prev = document.activeElement
144
- panelRef.current?.querySelector('input')?.focus()
145
- return () => { if (prev instanceof HTMLElement) prev.focus() }
146
- }, [open])
147
-
148
- /* Roving row resets to the top on every query change / reopen — and when the ROWS change under an
149
- * unchanged query (ShellSearchOverlayActionKeepsOpen, kol-fxr 2026-10-13: a drill-in swaps the
150
- * suggestions for a category's presets). Keyed on the row ids, not the array's identity, so a
151
- * consumer passing a fresh array every render does not snap the highlight back to the top. */
152
- const rowsKey = results.map((r) => r.id).join('\u0000')
153
- useEffect(() => { setActiveIndex(Math.max(0, results.findIndex((r) => !r.disabled))); setNavigated(false) }, [query, open, rowsKey]) // eslint-disable-line react-hooks/exhaustive-deps
154
-
155
- /* Keep the active row visible inside the scrolling list. */
156
- useEffect(() => {
157
- if (active < 0) return
158
- listRef.current?.querySelectorAll('[role="option"]')[active]?.scrollIntoView({ block: 'nearest' })
159
- }, [active])
160
-
161
- if (!open) return null
162
-
163
- /* A row that KEEPS THE MODAL OPEN — `keepOpen`, or an `action` row (the contract below always said
164
- * so; until 0.252.0 every pick closed — ShellSearchOverlayActionKeepsOpen, kol-fxr 2026-10-13). It
165
- * still reaches `onSelect`, and the closure stays the consumer's to run there: the overlay running
166
- * it too would fire it twice in every shell that already does (workshop's tag rows). */
167
- const select = (item) => {
168
- if (item?.disabled) return
169
- onSelect?.(item)
170
- if (!(item?.keepOpen || typeof item?.action === 'function')) onClose?.()
171
- }
172
-
173
- const optionId = (item) => `${listId}-${item.id}`
174
-
175
- const handleKeyDown = (e) => {
176
- if (e.key === 'Escape') {
177
- e.preventDefault()
178
- onClose?.()
179
- } else if (e.key === 'ArrowDown') {
180
- e.preventDefault()
181
- setNavigated(true)
182
- setActiveIndex((i) => step(Math.min(i, results.length - 1), 1))
183
- } else if (e.key === 'ArrowUp') {
184
- e.preventDefault()
185
- setNavigated(true)
186
- setActiveIndex((i) => step(Math.min(i, results.length - 1), -1))
187
- } else if (e.key === 'Enter') {
188
- e.preventDefault()
189
- /* ⌘ENTER OPENS EVERY HIT (user 2026-09-30: *"enter would focus searched item, and maybe
190
- * command enter would open the results page"*) — only where the consumer has a place for them. */
191
- if ((e.metaKey || e.ctrlKey) && onOpenResults && query) { onOpenResults(query); onClose?.(); return }
192
- /* ENTER OPENS THE HIGHLIGHTED ROW (user 2026-10-01: *"I think enter should also take you to
193
- * the atom but something like command enter take you to the index"* — reverses the
194
- * 2026-08-01 "Enter commits, it only selects once you have arrowed"). The top row is drawn
195
- * highlighted from the first keystroke, so Enter goes where the highlight says. With no
196
- * rows there is nothing to open and Enter commits the query. */
197
- if (active >= 0) select(results[active])
198
- else onExpand?.()
199
- } else if (e.key === 'Tab') {
200
- /* Focus trap — the input is the search modal's only tab stop. */
201
- e.preventDefault()
202
- }
203
- }
204
-
205
- return (
206
- <div className="fixed inset-0 flex items-start justify-center pt-[20vh]" style={{ zIndex: 'var(--kol-z-modal, 100)' }}>
207
- {/* A BUTTON, not a div (OverlayScrimTapDismiss, 2026-09-01): iOS Safari
208
- * does not bubble tap-clicks from non-interactive elements, so the div's
209
- * onClick never fired on a phone and the only way out was the close
210
- * control. A button always fires — and it ends the other half of the
211
- * defect, an interactive target carrying `aria-hidden`. */}
212
- <button
213
- type="button"
214
- aria-label="Close search"
215
- className="absolute inset-0 kol-overlay-scrim"
216
- onClick={onClose}
217
- />
218
- <div
219
- ref={panelRef}
220
- role="dialog"
221
- aria-modal="true"
222
- aria-label="Search"
223
- className={`kol-overlay-panel mx-4 ${expanded ? 'max-w-[var(--kol-content-panel)]' : 'max-w-lg'}`}
224
- >
225
- {/* THE MODE, said out loud (user 2026-08-01: "how do you set search
226
- * mode? theres no helper, message or mode clearly readble"). Two
227
- * modes exist — FILTER (tags narrow a set) and FIND (a keyword jumps
228
- * to a destination) — and the only signal was whether chips happened
229
- * to be present. The chips ARE the mode, so they get a label. */}
230
- {chips.length > 0 && (
231
- <div className="flex flex-wrap items-center gap-1.5 px-4 pt-3">
232
- <span className="kol-helper-10 text-fg-48 shrink-0">FILTERING BY</span>
233
- {chips.map((t) => (
234
- <Tag key={t} onRemove={() => onRemoveChip?.(t)}>{t}</Tag>
235
- ))}
236
- </div>
237
- )}
238
- {/* A REAL FIELD, inset in the panel (2026-09-30, shadcn's search modal as
239
- * the aim) — the flush `bare` strip read as a hole, not a control. */}
240
- <div className="kol-tone-grey p-2">
241
- <SearchInput
242
- className="w-full"
243
- value={query}
244
- onChange={(e) => onQueryChange?.(e.target.value)}
245
- placeholder={chips.length > 0 ? 'Narrow these results…' : placeholder}
246
- onKeyDown={handleKeyDown}
247
- role="combobox"
248
- aria-expanded={results.length > 0}
249
- aria-controls={listId}
250
- aria-activedescendant={active >= 0 ? optionId(results[active]) : undefined}
251
- />
252
- </div>
253
-
254
- {/* WHY THIS IS NOT `molecules/Dropdown` (asked 2026-08-01). Dropdown is
255
- * a SELECT: a trigger, a `value`, `onChange(value)`, and rows that are
256
- * options. This is a COMBOBOX — a text query filtering a live list
257
- * whose rows carry a `group`, a `hint`, and may fire an `action`
258
- * instead of selecting a value. Same ARIA family, different control.
259
- * Folding one into the other would mean giving Dropdown a query, a
260
- * hint slot and an action escape hatch, i.e. building this inside it.
261
- *
262
- * THE ROW CONTRACT (was documented nowhere):
263
- * label the row's text, match-highlighted against the query
264
- * group section heading the row files under — 'Atoms', 'Documentation', 'Tags'
265
- * icon optional leading glyph (kol-icons name)
266
- * hint subtext shown when the LABEL was not what matched
267
- * href a destination; dismisses the search modal
268
- * action a closure, run by the consumer's `onSelect`; the search modal STAYS OPEN (tag rows)
269
- * disabled drawn muted, skipped by ↑↓, never reaches `onSelect`; `disabledHint` replaces
270
- * `hint` with the reason (a full rack: "no room")
271
- * keepOpen the row selects and the search modal STAYS OPEN — a drill-in (category →
272
- * its items, a "← All" row back); the consumer swaps `suggestions`/`results`
273
- * Built by `buildShellSearchItems` (showcase/src/nav/shell-nav.js). */}
274
- {expanded ? (
275
- <div className="border-t border-fg-08 max-h-[70vh] overflow-y-auto">{children}</div>
276
- ) : results.length > 0 && (
277
- /* FIXED BODY HEIGHT — the panel holds still while the list narrows. */
278
- <ul
279
- ref={listRef}
280
- id={listId}
281
- role="listbox"
282
- className="kol-tone-grey h-80 overflow-y-auto px-2 pb-2"
283
- >
284
- {results.map((item, i) => {
285
- const heading = (item.group ?? '') !== (results[i - 1]?.group ?? '') || i === 0
286
- return (
287
- <li key={item.id} role="presentation">
288
- {heading && item.group && (
289
- <p className="kol-helper-12 text-fg-48 px-4 border-x border-transparent pt-3 pb-2">{item.group}</p>
290
- )}
291
- <OptionRow
292
- id={optionId(item)}
293
- role="option"
294
- aria-selected={i === active}
295
- aria-disabled={item.disabled || undefined}
296
- active={i === active}
297
- disabled={item.disabled}
298
- icon={item.icon}
299
- label={<HighlightMatch label={item.label} query={query} ranges={item.highlights} />}
300
- hint={(item.disabled && item.disabledHint) || item.hint}
301
- /* preventDefault keeps focus in the input through the click */
302
- onMouseDown={(e) => e.preventDefault()}
303
- onClick={() => select(item)}
304
- onMouseEnter={() => { if (!item.disabled) { setActiveIndex(i); setNavigated(true) } }}
305
- />
306
- </li>
307
- )
308
- })}
309
- </ul>
310
- )}
311
- {/* THE FOOTER SAYS WHAT ENTER DOES — always, not only once typing. */}
312
- {!expanded && (results.length > 0 || (query && (enterLabel || onOpenResults))) && (
313
- <div className="border-t border-fg-08 py-2">
314
- {/* Enter's line names what Enter does NOW: a row is highlighted → it opens that row;
315
- * no rows → it commits the query. */}
316
- {(results.length > 0 || enterLabel) && (
317
- <p className="flex items-center gap-2 kol-helper-12 text-fg-48 mx-2 px-4 border-x border-transparent">
318
- <Kbd icon="corner-down-left" />
319
- {results.length > 0 ? selectLabel : enterLabel}
320
- </p>
321
- )}
322
- {/* THE RESULTS LINE IS A LINK (user 2026-10-01: *"make 'all results...' at the bottom
323
- * also be a link to the results page"*) — the same door ⌘Enter opens. */}
324
- {query && onOpenResults && (
325
- <button
326
- type="button"
327
- className="flex items-center gap-2 kol-helper-12 text-fg-48 hover:text-fg-default transition-colors mx-2 px-4 border-x border-transparent pt-1"
328
- onMouseDown={(e) => e.preventDefault()}
329
- onClick={() => { onOpenResults(query); onClose?.() }}
330
- >
331
- <Kbd icon="command"><Icon name="corner-down-left" size={12} /></Kbd>
332
- {resultsLabel}
333
- </button>
334
- )}
335
- </div>
336
- )}
337
- </div>
338
- </div>
339
- )
8
+ export default function ShellSearchOverlay(props) {
9
+ return <CommandOverlay {...props} />
340
10
  }
11
+ export { HighlightMatch } from './CommandOverlay.jsx'
@@ -41,8 +41,16 @@ import SettingsSections from './SettingsSections.jsx'
41
41
  *
42
42
  * @param {Array} props.shortcuts - `[{ label, combo }]` or `[{ section, items: [{ id, label, combo }] }]` — the same array `SettingsShortcuts` takes (ShellHomeSystemMonitorGaps, kol-monitor 2026-08-27: the overlay read `keys` while the settings block read `combo`; `combo` is the name, `keys` is tolerated for a release)
43
43
  * @param {Function} props.onClose
44
+ * @param {string} [props.currentPath] sections may carry `routes: ['/rack']` (CommandOverlayModes, kol-monitor
45
+ * 2026-10-17 — user: *"im in dev, how can I cable lock here?"*): with a path, the sections that work here come
46
+ * first and the rest sit muted under ELSEWHERE, never as if they worked here. A section without `routes`
47
+ * works everywhere. Bind keys from the same scope with `shortcutInScope`.
44
48
  */
45
49
 
50
+ /** Does a shortcut section work on `path`? No `routes` → everywhere; a route matches itself and below it. */
51
+ export const shortcutInScope = (section, path) => !section?.routes?.length || path == null
52
+ || section.routes.some((r) => path === r || path.startsWith(`${r.replace(/\/$/, '')}/`))
53
+
46
54
  const isSectioned = (list) => Array.isArray(list?.[0]?.items)
47
55
 
48
56
  /* A shortcut as a settings ROW: the label on the left, the combo as the row's
@@ -57,7 +65,7 @@ const toRow = ({ label, combo, keys }) => ({
57
65
  value: <span className="text-fg-32 kol-helper-12 sm:whitespace-nowrap">{combo ?? keys}</span>,
58
66
  })
59
67
 
60
- export default function ShortcutsOverlay({ shortcuts = [], onClose }) {
68
+ export default function ShortcutsOverlay({ shortcuts = [], onClose, currentPath }) {
61
69
  useEffect(() => {
62
70
  const onKey = (e) => { if (e.key === 'Escape') onClose?.() }
63
71
  window.addEventListener('keydown', onKey)
@@ -65,6 +73,8 @@ export default function ShortcutsOverlay({ shortcuts = [], onClose }) {
65
73
  }, [onClose])
66
74
 
67
75
  const sectioned = isSectioned(shortcuts)
76
+ const here = sectioned ? shortcuts.filter((s) => shortcutInScope(s, currentPath)) : []
77
+ const elsewhere = sectioned ? shortcuts.filter((s) => !shortcutInScope(s, currentPath)) : []
68
78
 
69
79
  return (
70
80
  <div
@@ -95,9 +105,15 @@ export default function ShortcutsOverlay({ shortcuts = [], onClose }) {
95
105
  >
96
106
  <SettingsSections
97
107
  sections={sectioned
98
- ? shortcuts.map(({ section, items = [] }) => ({ label: section, rowGap: 1, rows: items.map(toRow) }))
108
+ ? here.map(({ section, items = [] }) => ({ label: section, rowGap: 1, rows: items.map(toRow) }))
99
109
  : [{ rowGap: 1, rows: shortcuts.map(toRow) }]}
100
110
  />
111
+ {elsewhere.length > 0 && (
112
+ <div className="flex flex-col gap-4 opacity-[var(--kol-opacity-disabled)]">
113
+ <span className="kol-helper-10 text-fg-48">ELSEWHERE</span>
114
+ <SettingsSections sections={elsewhere.map(({ section, items = [] }) => ({ label: section, rowGap: 1, rows: items.map(toRow) }))} />
115
+ </div>
116
+ )}
101
117
  </div>
102
118
  </div>
103
119
  )