@kolkrabbi/kol-component 0.281.0 → 0.283.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kolkrabbi/kol-component",
3
- "version": "0.281.0",
3
+ "version": "0.283.0",
4
4
  "description": "The core component library",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -26,8 +26,8 @@
26
26
  "embla-carousel-react": "^8.6.0",
27
27
  "pdfjs-dist": "^6.3.289",
28
28
  "react-syntax-highlighter": "^16.1.1",
29
- "@kolkrabbi/kol-search": "^0.3.0",
30
- "@kolkrabbi/kol-markdown": "^0.1.3"
29
+ "@kolkrabbi/kol-markdown": "^0.1.3",
30
+ "@kolkrabbi/kol-search": "^0.3.0"
31
31
  },
32
32
  "peerDependencies": {
33
33
  "@kolkrabbi/kol-icons": ">=0.22.0",
@@ -0,0 +1,67 @@
1
+ import { useState, useEffect } from 'react'
2
+
3
+ /**
4
+ * Logomark — An inlined SVG mark. fetches and INLINES an SVG so currentColor theming works: an
5
+ * <img> renders a currentColor mark black in dark mode (invisible). Ported
6
+ * verbatim from the kol-mirror cut (module-level cache; async resolve even on
7
+ * cache hit — sync setState in an effect cascades renders).
8
+ *
9
+ * The fetched markup is SANITIZED before injection — `<style>`/`<script>`
10
+ * stripped, `on*` attributes dropped (LogomarkInlineStyleLeak, kol-chess
11
+ * 2026-09-01). An SVG *document* may legitimately carry its own `<style>` — a
12
+ * theme-aware favicon does — but once inlined, that `<style>` is
13
+ * DOCUMENT-GLOBAL: kol-chess pointed `svgUrl` at its favicon and every <svg>
14
+ * in the app took OS-keyed ink and ignored `data-theme`, presenting two
15
+ * packages away as "the theme toggle is broken". A mark that needs its own
16
+ * styling inlines it as attributes, not a stylesheet.
17
+ */
18
+
19
+ const svgCache = new Map()
20
+
21
+ /* strip what must never escape into the host document: stylesheets (global
22
+ * once inlined), scripts and event handlers (this is a fetch → innerHTML
23
+ * boundary). DOMParser is the correct tool; the regex fallback only runs if
24
+ * the markup does not even parse as SVG. */
25
+ function sanitizeSvg(svg) {
26
+ try {
27
+ const doc = new DOMParser().parseFromString(svg, 'image/svg+xml')
28
+ if (doc.querySelector('parsererror')) throw new Error('unparseable')
29
+ doc.querySelectorAll('style, script').forEach((el) => el.remove())
30
+ doc.querySelectorAll('*').forEach((el) => {
31
+ for (const a of [...el.attributes]) if (/^on/i.test(a.name)) el.removeAttribute(a.name)
32
+ })
33
+ return new XMLSerializer().serializeToString(doc)
34
+ } catch {
35
+ return svg
36
+ .replace(/<(style|script)[\s\S]*?<\/\1\s*>/gi, '')
37
+ .replace(/\son[a-z]+\s*=\s*("[^"]*"|'[^']*')/gi, '')
38
+ }
39
+ }
40
+
41
+ export default function Logomark({ svgUrl, size = 20, className = '', ...props }) {
42
+ const [svgContent, setSvgContent] = useState(() => svgCache.get(svgUrl) || null)
43
+
44
+ useEffect(() => {
45
+ if (!svgUrl) return
46
+ let active = true
47
+ Promise.resolve(
48
+ svgCache.get(svgUrl) ?? fetch(svgUrl).then(res => res.text()).then(raw => { const svg = sanitizeSvg(raw); svgCache.set(svgUrl, svg); return svg })
49
+ )
50
+ .then(svg => { if (active) setSvgContent(svg) })
51
+ .catch(() => {})
52
+ return () => { active = false }
53
+ }, [svgUrl])
54
+
55
+ if (!svgContent) return <span style={{ width: size, height: size, display: 'inline-block' }} />
56
+
57
+ return (
58
+ <span
59
+ className={className}
60
+ style={{ width: size, height: size, display: 'inline-flex', color: 'currentColor' }}
61
+ dangerouslySetInnerHTML={{
62
+ __html: svgContent.replace('<svg', `<svg width="${size}" height="${size}"`),
63
+ }}
64
+ {...props}
65
+ />
66
+ )
67
+ }
@@ -0,0 +1,28 @@
1
+ import { createContext, useContext, useMemo, useState } from 'react'
2
+
3
+ /**
4
+ * RailSlotProvider / useRailSlot — a consumer slot in NavRail's opened width (NavRailConsumerSlot,
5
+ * kol-monitor 2026-10-15). The rail renders in AppShell's own tree, outside the page's providers,
6
+ * so it cannot read page state and the page cannot render into it. The rail publishes its slot's
7
+ * DOM node here instead, and the page portals into it with its own state:
8
+ *
9
+ * <RailSlotProvider><AppStudio … /></RailSlotProvider>
10
+ * const rail = useRailSlot(); rail?.slot && createPortal(<Panel />, rail.slot)
11
+ *
12
+ * The provider goes ABOVE the shell so the rail and the page both see it. No provider → no slot,
13
+ * and the rail renders as it did. `railOpen` mirrors the rail's open state for the page.
14
+ *
15
+ * Monitor's shape (`src/hooks/useRailSlot.jsx`), shipped so its NavRail fork can retire.
16
+ */
17
+ const RailSlotContext = createContext(null)
18
+
19
+ export function useRailSlot() {
20
+ return useContext(RailSlotContext)
21
+ }
22
+
23
+ export function RailSlotProvider({ children }) {
24
+ const [slot, setSlot] = useState(null)
25
+ const [railOpen, setRailOpen] = useState(false)
26
+ const value = useMemo(() => ({ slot, setSlot, railOpen, setRailOpen }), [slot, railOpen])
27
+ return <RailSlotContext.Provider value={value}>{children}</RailSlotContext.Provider>
28
+ }
package/src/index.js CHANGED
@@ -172,6 +172,11 @@ export { default as EmblaNav } from './molecules/EmblaNav.jsx'
172
172
  export { default as MobileTabBar } from './molecules/MobileTabBar.jsx'
173
173
  export { default as ContentFilters } from './organisms/ContentFilters.jsx'
174
174
  export { default as PageHeader, PAGE_HEADER_ROLES } from './molecules/PageHeader.jsx'
175
+ /* the one nav rail (2026-10-22) — `variant` app (the flat 48px rail) · site (the grouped site
176
+ * sidebar, kol-framework's SideNav until then). Moved from kol-shell, which re-exports all three. */
177
+ export { default as NavRail } from './organisms/NavRail.jsx'
178
+ export { default as Logomark } from './atoms/Logomark.jsx'
179
+ export { RailSlotProvider, useRailSlot } from './hooks/railSlot.jsx'
175
180
  export { MastheadContext, MASTHEADS, useMasthead, mastheadTitleClass } from './utilities/masthead.js'
176
181
  export { default as ErrorBoundary } from './utilities/ErrorBoundary.jsx'
177
182
  export { default as FeatureSplit } from './organisms/FeatureSplit.jsx'
@@ -138,11 +138,13 @@ export default function SearchInput({
138
138
 
139
139
  /* Escape closes, and so does clicking away — a field that can only be closed
140
140
  * by emptying it and blurring is a trap, and this one had neither wired. The
141
- * listener only exists while open. */
141
+ * listener only exists while open. A click away closes an EMPTY field only: with a query in it,
142
+ * the results below are what you are clicking (the icon catalog lost its filter on every tile
143
+ * click, 2026-10-20), so the query stays until Escape or the clear. */
142
144
  const shellRef = useRef(null)
143
145
  useEffect(() => {
144
146
  if (!expanding || !isOpen) return undefined
145
- const away = (e) => { if (shellRef.current && !shellRef.current.contains(e.target)) setOpen(false) }
147
+ const away = (e) => { if (shellRef.current && !shellRef.current.contains(e.target) && !inputRef.current?.value) setOpen(false) }
146
148
  const esc = (e) => { if (e.key === 'Escape') setOpen(false) }
147
149
  document.addEventListener('mousedown', away)
148
150
  document.addEventListener('keydown', esc)
@@ -1071,7 +1071,7 @@ export default function MediaLibrary({
1071
1071
  /* THE PICKER — the browse surface in the modal card. Read-only (no verbs, no drop, no trash: a
1072
1072
  * picker picks). Its settings are held here and never saved, so a consumer's stored browse
1073
1073
  * settings are untouched. The views take the card's height less its chrome. */
1074
- const PICKER_CHROME = 280 // ponytail: hand-measured header + count line + footer; tune if the chrome changes
1074
+ const PICKER_CHROME = 252 // ponytail: hand-measured header + count line + footer (280 less the 28px close lane, 2026-10-20); tune if the chrome changes
1075
1075
  function PickerBrowse({ client, accept, onClose, onSelect, title = 'MEDIA', ...browseProps }) {
1076
1076
  const [settings, setSettings] = useState(() => ({ ...SETTINGS_BASE, columnHeight: `calc(var(--kol-media-picker-h) - ${PICKER_CHROME}px)` }))
1077
1077
  const [bucket, setBucket] = useState(browseProps.bucket)
@@ -1082,13 +1082,11 @@ function PickerBrowse({ client, accept, onClose, onSelect, title = 'MEDIA', ...b
1082
1082
  onClose?.()
1083
1083
  }
1084
1084
  return (
1085
- /* THE X SITS ON THE HEADER ROW (MediaPickerCloseOnTheHeaderRow, kol-fxr 2026-10-10 — user: *"x
1086
- * close is in a weird place, align better"*). The overlay's corner close floated ~100px above
1087
- * the header and lined up with nothing. In the control cluster after the gear it read as one more
1088
- * control (media-picker-close-and-title, kol-mirror 2026-10-15), so it is the header's own ×:
1089
- * alone at the far end of the title's row, the drawer's shape. */
1085
+ /* NO X (user 2026-10-20: *"at this point just use escape"*). Escape, the backdrop and Cancel close it.
1086
+ * The X moved three times (overlay corner → title row, 2026-10-10 → beside the gear → corner again)
1087
+ * and was wrong each time; without it the card's block-start lane goes too (`pt-5`). */
1090
1088
  <FullscreenOverlay open scrim onClose={onClose} closeButton={false}>
1091
- <div className="kol-media-picker gap-4">
1089
+ <div className="kol-media-picker gap-4 pt-5">
1092
1090
  <MediaLibraryBrowse
1093
1091
  {...browseProps}
1094
1092
  client={client}
@@ -1098,7 +1096,6 @@ function PickerBrowse({ client, accept, onClose, onSelect, title = 'MEDIA', ...b
1098
1096
  settings={settings}
1099
1097
  onSettingsChange={setSettings}
1100
1098
  onPickFile={setFile}
1101
- onHeaderClose={onClose}
1102
1099
  />
1103
1100
  <div className="mt-auto flex items-center justify-end gap-4">
1104
1101
  <span className="kol-mono-12 text-fg-48 truncate mr-auto">{file ? file.key : 'Select a file'}</span>
@@ -0,0 +1,424 @@
1
+ import { useEffect, useRef, useState } from 'react'
2
+ import gsap from 'gsap'
3
+ /* taxonomy-ok: organism — nests Button (atom) + Logomark (atom) + Tooltip (utility). Moved
4
+ * from kol-shell 2026-10-22 (the one nav rail, user: "lets go for your recommendation"): the
5
+ * app rail and the site rail are one component, and a site must not install the app shell
6
+ * for its sidebar — the PageHeader precedent. kol-shell re-exports it. */
7
+ import Button from '../atoms/Button.jsx'
8
+ import { Tooltip } from '../utilities/Popover.jsx'
9
+ import { GRAB } from '../utilities/motion.js'
10
+ /* the grab pill's proximity wake, travel and dwell — ONE implementation, shared
11
+ * with kol-framework's useDragResize (OneGrabGestureBothRails, kol-fxr
12
+ * 2026-08-30: two rails on one screen felt different because each package had
13
+ * built the gesture itself). It lived here until then. */
14
+ import useGrabEdge from '../hooks/useGrabEdge.js'
15
+ import { Icon } from '@kolkrabbi/kol-icons'
16
+ import Logomark from '../atoms/Logomark.jsx'
17
+ import { useRailSlot } from '../hooks/railSlot.jsx'
18
+ import NavRailSite from './NavRailSite.jsx'
19
+
20
+ /**
21
+ * NavRail — the flat rail. ONE fixed column, every child a direct child of it
22
+ * (RailFlatGrabOpen, kol-mirror 2026-08-28 — user, on the monitor rail he
23
+ * measured it against: "the div structure is super simple ok … it's 1 div
24
+ * parent and everything is just in that container", and on the SideNav-backed
25
+ * rail that had replaced it: it was "impossible" to get this shape out of it).
26
+ *
27
+ * This REVERSES RailSideNavPixelParity (0.13.0), which made the rail a collapsed
28
+ * kol-framework `SideNav`. That ticket's pixel argument is settled the other way:
29
+ * the rail does not share pixels with the brand sidebar because it never becomes
30
+ * one. `RailLogomarkAtTop` stands — the mark is at the top in both states.
31
+ *
32
+ * THE GRAB OPENS IT (user: "when you grab it should not move the icons one
33
+ * pixel, only reveal the title, and a chevron to see sub categories" · "when it
34
+ * opens it should push the main content inside"). Closed, every row is the rail
35
+ * minus its gutter — the 32px rung alone shows and the label and chevron exist
36
+ * but are clipped by the row's own width. Open, the clip reveals them. Nothing
37
+ * in the icon column moves between the two states, and the content column
38
+ * follows because AppShell offsets by the same live variable.
39
+ *
40
+ * ONE WIDTH VARIABLE: `--kol-shell-rail-width` on `:root` — this rail is that
41
+ * wide and AppShell's content is offset by it, written per pointermove during a
42
+ * drag and tweened on release, so the page is pushed live through both. A drag
43
+ * writes the DOM, not React state: a pointermove per frame is not a render.
44
+ *
45
+ * The pill is kol-r2b2's, verbatim (user: "make it like it is in kol-r2b2, it
46
+ * has animation and gsap") — `.kol-rail-grab` in kol-theme's kol-animation.css,
47
+ * its pointer numbers in kol-component's `utilities/motion` (`GRAB`).
48
+ *
49
+ * TWO LEVELS (RailTwoLevelSections, kol-fxr 2026-08-28 — user: "the NAV has 20px
50
+ * icons in 32px containers, maybe level below has 12px icons in 20px container
51
+ * aligned to right? … you expand you see that they have main 56 items each, which
52
+ * you won't be aware of until you actually open labs, which should not happen
53
+ * automatically"). An item with `sub` is a SECTION: the same L1 row, plus a caret.
54
+ * Its rows are L2 — a 12px glyph in a 20px box, indented so its glyph column sits
55
+ * to the RIGHT of L1's (glyph x 14 → 30), resting a rung quieter at `oq-64` and
56
+ * going `oq-96` when it is the route. fxr's labs chrome is ~44 rows across four
57
+ * method sections; on one level they flatten into an icon column built for five
58
+ * destinations and the section names have nowhere to render at all.
59
+ *
60
+ * L2 is NOT a `Button`: the icon-button ladder is 22/26/32/40 (2026-09-03) and this
61
+ * rung is 20 — there is nothing below sm, and adding one is a change to that
62
+ * ladder's law, which is the user's call and not this ticket's. The row is
63
+ * written directly and keys `aria-current`, so kol-theme's
64
+ * `.kol-shell-rail .kol-btn-nav` active rules still reach it. A sub row with no
65
+ * `icon` renders label-only, as it did before this level existed.
66
+ *
67
+ * NOTHING AUTO-EXPANDS. An L2 row is behind BOTH the rail's clipped width and its
68
+ * section's own disclosure, and `open` starts `false` with no prop to get it
69
+ * wrong — arriving on a route reveals nothing, by construction rather than by a
70
+ * flag a consumer has to remember.
71
+ *
72
+ * @param {Array} items `{ icon, path, label, sub?: [{ icon?, path, label }] }`
73
+ * a section (`sub`) with `to` is a FOLDER NOTE: its icon and label open `to`, its chevron folds
74
+ * @param {Array} bottomItems pinned below the rule (Settings)
75
+ * @param {Object} logomark `{ svgUrl, title }` — the mark, and the app name beside it when open
76
+ * @param {string} currentPath active match: '/' exact, else prefix → aria-current="page"
77
+ * @param {Function} onNavigate `(path) => void` — every click, the mark included
78
+ * @param {boolean} drawer off-canvas mode: no grab, no drag, no token writes, rows always
79
+ * labelled, and the rail sizes itself from `--kol-shell-drawer-width` (default 240px).
80
+ * AppShell sets this from `touch="drawer"` — see ShellRailNoDrawerOnMobile, 2026-08-31.
81
+ * Under a `RailSlotProvider` the opened width also carries a CONSUMER SLOT below the rows
82
+ * (NavRailConsumerSlot, kol-monitor 2026-10-15) — content that is not a row list (monitor's module
83
+ * catalog: rows that insert, not paths). Always mounted so portalled content keeps its state across
84
+ * open/close; zero tall and clipped while closed. No provider → no slot, the render unchanged.
85
+ *
86
+ * @param {boolean} [fade=true] the list fades out at its foot — the workshop rail's fade
87
+ * (2026-10-01), here too on the user's word (2026-10-02). The rows sit in their own scroll
88
+ * region between the mark and the pinned bottom rows, so a list longer than the window scrolls
89
+ * and runs out under the fade instead of being cut by the edge. `false` draws the list plain.
90
+ */
91
+ const RAIL_W = '--kol-shell-rail-width'
92
+ const CLOSED = 48
93
+
94
+ /* the OPEN width is the rail's own ladder (`--kol-shell-rail-open` in kol-theme: 264, 320
95
+ * from 1536), read at drag time so the rail lands on whichever rung the window is on */
96
+ const openWidth = () => {
97
+ const v = getComputedStyle(document.documentElement).getPropertyValue('--kol-shell-rail-open').trim()
98
+ const px = parseFloat(v)
99
+ return Number.isFinite(px) ? (v.endsWith('rem') ? px * 16 : px) : 264
100
+ }
101
+
102
+ /* THE GRAB EDGE — proximity, not contact: the pill wakes within `GRAB.near` of
103
+ * the line and sleeps only past `GRAB.sleep` (hovering the line itself flapped
104
+ * the class every frame and restarted the fade). Along the line it DWELLS (user
105
+ * ruling 2026-08-28: "make it come to the cursor but have some sticky time where
106
+ * it lands, so it's not constantly jerking"): it targets the pointer's own
107
+ * position and re-targets only once the pointer is `GRAB.stick` px away, so it
108
+ * lands on you, holds while you move inside the radius, then travels to where you
109
+ * are now — inside `GRAB.range`, the middle band of the edge, so it never rides
110
+ * up beside the logomark. One window listener, rAF-throttled. */
111
+
112
+ /* THE DRAG — hold the pill and the width follows the pointer between closed and
113
+ * open; release snaps to the nearer state, a click (no travel past GRAB.slop)
114
+ * toggles. `onSnap` reports the resting state once — the sub rows render only
115
+ * while open, because closed they would still take their height and push the
116
+ * rungs below them. */
117
+ function useRailDrag(railRef, grabRef, onSnap, snapRef, enabled = true) {
118
+ useEffect(() => {
119
+ const strip = grabRef.current, rail = railRef.current, root = document.documentElement
120
+ /* A DRAWER IS NOT A DRAGGABLE RAIL (ShellRailNoDrawerOnMobile, kol-chess
121
+ * 2026-08-31). In drawer mode the rail is off-canvas at a fixed width and
122
+ * the content owns the whole viewport, so the drag must not run at all —
123
+ * it writes `--kol-shell-rail-width` on `:root` per pointermove, which is
124
+ * exactly the inline token a consumer could not reach without `!important`. */
125
+ if (!enabled) return undefined
126
+ if (!strip || !rail) return undefined
127
+ gsap.set(root, { [RAIL_W]: `${CLOSED}px` })
128
+ let drag = null
129
+ const snapTo = (w) => {
130
+ gsap.to(root, { [RAIL_W]: `${w}px`, ...GRAB.snap, overwrite: 'auto' })
131
+ onSnap(w !== CLOSED)
132
+ }
133
+ /* the ONLY way out of this effect (RailSectionPressOpensRail, kol-fxr
134
+ * 2026-08-30). `snapTo` closes over the animation and the CLOSED/open
135
+ * ladder, so a section press has to reach it rather than reimplement it —
136
+ * a consumer setting `--kol-shell-rail-width` from outside widens the rail
137
+ * but leaves `railOpen` false, and the L2 rows render behind it: a wide,
138
+ * EMPTY rail, worse than the dead press this fixes. */
139
+ /* `(false)` closes, anything else opens — the same seam the L2 rows use
140
+ * to open, now also the tap opener's toggle */
141
+ if (snapRef) snapRef.current = (open = true) => snapTo(open === false ? CLOSED : openWidth())
142
+ const onDown = (e) => {
143
+ strip.setPointerCapture(e.pointerId)
144
+ gsap.killTweensOf(root)
145
+ drag = { x: e.clientX, w: rail.offsetWidth, open: openWidth(), moved: false }
146
+ strip.classList.add('is-dragging')
147
+ }
148
+ const onMove = (e) => {
149
+ if (!drag) return
150
+ const dx = e.clientX - drag.x
151
+ if (Math.abs(dx) > GRAB.slop) drag.moved = true
152
+ root.style.setProperty(RAIL_W, `${Math.min(Math.max(drag.w + dx, CLOSED), drag.open)}px`)
153
+ }
154
+ const onUp = () => {
155
+ if (!drag) return
156
+ const w = rail.offsetWidth
157
+ const open = drag.open
158
+ snapTo(drag.moved ? (w > (CLOSED + open) / 2 ? open : CLOSED) : (drag.w > CLOSED ? CLOSED : open))
159
+ drag = null
160
+ strip.classList.remove('is-dragging')
161
+ }
162
+ strip.addEventListener('pointerdown', onDown)
163
+ strip.addEventListener('pointermove', onMove)
164
+ strip.addEventListener('pointerup', onUp)
165
+ strip.addEventListener('pointercancel', onUp)
166
+ return () => {
167
+ strip.removeEventListener('pointerdown', onDown)
168
+ strip.removeEventListener('pointermove', onMove)
169
+ strip.removeEventListener('pointerup', onUp)
170
+ strip.removeEventListener('pointercancel', onUp)
171
+ }
172
+ }, [railRef, grabRef, onSnap, snapRef])
173
+ }
174
+
175
+ /* one row: the rung exactly where the closed rail had it, then the label and
176
+ * (with `sub`) the chevron — the row clips to the rail's width */
177
+ /* the L2 glyph goes through the same injection seam Button gives L1 */
178
+ function IconAt({ name, size, component }) {
179
+ const Cmp = component || Icon
180
+ return <Cmp name={name} size={size} />
181
+ }
182
+
183
+ function RailItem({ icon, path, to, label, sub, currentPath, onNavigate, iconComponent, railOpen, onOpenRail, onEnter }) {
184
+ const [open, setOpen] = useState(false)
185
+ /* A SECTION ROW IS NOT A DESTINATION (RailSectionPressOpensRail, kol-fxr
186
+ * 2026-08-30 — user: *"if I press effects from collapsed nav it should maybe
187
+ * open? currently pressing it does nothing"*).
188
+ *
189
+ * Closed, the row clips to 48px and the disclosure caret sits OUTSIDE that
190
+ * clip, so the only reachable control was the icon — which called
191
+ * `onNavigate` with a path no consumer dispatches, because a section has no
192
+ * action. A guaranteed dead press, in the rail's default state.
193
+ *
194
+ * Pressing it now opens the rail and expands that section. This is the
195
+ * behaviour `SideNav` had before the flat-rail reversal. It does not fight
196
+ * "nothing auto-expands" — that rule is about ARRIVING on a route; this is an
197
+ * explicit press. */
198
+ const isSection = sub?.length > 0
199
+ /* …AND IN AN OPEN RAIL THE SAME PRESS FOLDS AND UNFOLDS IT (2026-10-05, labs on a phone). Open,
200
+ * it still fell through to `onNavigate` with that path no consumer dispatches: dead at a desk,
201
+ * and worse on a touch drawer, where AppShell closes the drawer on every navigate — pressing a
202
+ * section's name shut the nav and loaded nothing. */
203
+ /* FOLDER NOTE (2026-10-22, user: "like foldernote in obsidian where a parent/group/folder can
204
+ * also be a note"). Opt-in per section: give it `to` and its icon and label open that page,
205
+ * while the chevron alone folds or enters — `RailSection`'s `to` split in kol-workshop. A
206
+ * section without `to` is unchanged. */
207
+ const press = () => {
208
+ if (isSection && to) { onNavigate?.(to); return }
209
+ if (isSection && onEnter) { if (!railOpen) onOpenRail?.(); onEnter(); return }
210
+ if (isSection) { if (!railOpen) onOpenRail?.(); setOpen((v) => !railOpen || !v); return }
211
+ onNavigate?.(path)
212
+ }
213
+ const target = to ?? path
214
+ const active = target === '/' ? currentPath === '/' : currentPath.startsWith(target)
215
+ return (
216
+ <>
217
+ <div className="flex items-center gap-3 w-full overflow-hidden shrink-0">
218
+ {/* the DS tooltip, not the browser's (the native-title sweep, 2026-09-26) — to the RIGHT,
219
+ * out over the page, since the collapsed rail's glyph is all there is to read */}
220
+ <Tooltip label={label} placement="right" triggerClassName="inline-flex shrink-0">
221
+ <Button
222
+ iconOnly={icon}
223
+ iconSize={20}
224
+ iconComponent={iconComponent}
225
+ variant="nav"
226
+ size="md"
227
+ className="shrink-0"
228
+ /* nav ACTIVE keys off aria-current="page" (kol-components-atoms.css) —
229
+ * a brighter glyph, never the pressed fill */
230
+ aria-current={active ? 'page' : undefined}
231
+ /* oq-96 on every rung: the nav variant's oq-64 rest is site-nav quiet
232
+ * and too dim on an icon rail (user: "make the color .96 on every icon
233
+ * in the rail") */
234
+ style={{ color: 'var(--kol-oq-96)' }}
235
+ onClick={press}
236
+ aria-label={label}
237
+ />
238
+ </Tooltip>
239
+ <span
240
+ className="kol-helper-12 uppercase text-oq-96 flex-1 min-w-0 truncate cursor-pointer"
241
+ onClick={press}
242
+ >
243
+ {label}
244
+ </span>
245
+ {sub?.length > 0 && (
246
+ <Tooltip label={label} placement="right" triggerClassName="inline-flex shrink-0">
247
+ <Button
248
+ iconOnly={onEnter ? 'chevron-right' : open ? 'chevron-down' : 'chevron-right'}
249
+ iconSize={16}
250
+ iconComponent={iconComponent}
251
+ variant="nav"
252
+ /* md, the row's rung — at sm it stood 26 beside the 32 glyph button (render gate R1,
253
+ * one row one size, found on apps/editor's labs rail 2026-09-29) */
254
+ size="md"
255
+ className="shrink-0"
256
+ style={{ color: 'var(--kol-oq-96)' }}
257
+ aria-expanded={onEnter ? undefined : open}
258
+ onClick={onEnter ? () => { if (!railOpen) onOpenRail?.(); onEnter() } : () => setOpen((v) => !v)}
259
+ aria-label={`${label} sub categories`}
260
+ />
261
+ </Tooltip>
262
+ )}
263
+ </div>
264
+ {railOpen && open && !onEnter && sub.map((s) => {
265
+ const on = s.path === '/' ? currentPath === '/' : currentPath.startsWith(s.path)
266
+ return (
267
+ <Tooltip key={s.path} label={s.label} placement="right" asChild>
268
+ <div
269
+ /* 18px of gutter puts the 20px box at x 26, so its 12px glyph starts
270
+ * at 30 — one step right of L1's 20-in-32 at 14 (measured in fxr). A row
271
+ * with no glyph starts its label on L1's label column instead — 32px
272
+ * rung + 12px gap (2026-10-22, kol-branding: label-only rows sat under
273
+ * the icon column, left of their own section's name) */
274
+ className={`flex items-center gap-3 w-full overflow-hidden shrink-0 cursor-pointer ${s.icon ? 'pl-[18px]' : 'pl-11'}`}
275
+ onClick={() => onNavigate?.(s.path)}
276
+ aria-current={on ? 'page' : undefined}
277
+ >
278
+ {s.icon && (
279
+ <span
280
+ className="w-5 h-5 shrink-0 inline-flex items-center justify-center"
281
+ style={{ color: on ? 'var(--kol-oq-96)' : 'var(--kol-oq-64)' }}
282
+ aria-hidden="true"
283
+ >
284
+ <IconAt name={s.icon} size={12} component={iconComponent} />
285
+ </span>
286
+ )}
287
+ <span
288
+ className="kol-helper-12 uppercase flex-1 min-w-0 truncate"
289
+ style={{ color: on ? 'var(--kol-oq-96)' : 'var(--kol-oq-64)' }}
290
+ >
291
+ {s.label}
292
+ </span>
293
+ </div>
294
+ </Tooltip>
295
+ )
296
+ })}
297
+ </>
298
+ )
299
+ }
300
+
301
+ /* ONE RAIL, TWO VARIANTS (2026-10-22, the one nav rail — user: "should it not be a variant of
302
+ * NavRail? since they are so similar"). `app` (default) is the flat 48px rail below; `site` is the
303
+ * grouped site sidebar that was kol-framework's `SideNav`, carried class-for-class so a site
304
+ * renders exactly as before — it takes SideNav's props (`navTree`, `isActive`, `background`,
305
+ * `currentPath`, `onNavigate(event, to)` …). kol-framework's `SideNav` is that variant under the
306
+ * old name, with react-router and the theme toggle wired in. */
307
+ export default function NavRail({ variant = 'app', ...props }) {
308
+ return variant === 'site' ? <NavRailSite {...props} /> : <AppRail {...props} />
309
+ }
310
+
311
+ function AppRail({
312
+ items = [],
313
+ bottomItems = [],
314
+ logomark,
315
+ currentPath = '',
316
+ onNavigate,
317
+ iconComponent,
318
+ hidden = false,
319
+ drawer = false,
320
+ fade = true,
321
+ sections = 'fold',
322
+ }) {
323
+ const railRef = useRef(null)
324
+ const grabRef = useRef(null)
325
+ const [railOpen, setRailOpen] = useState(false)
326
+ /* ENTER MODE (`sections="enter"`, 2026-10-06 — the user, on labs: "having a 'enter' mode in the
327
+ * left sidebar instead of collapse folder?"): pressing a section replaces the list with that
328
+ * section's rows under a Back row, instead of unfolding it in place. `fold` is the accordion
329
+ * every rail had and keeps. Per consumer, not a law: labs' catalog is five sections of up to
330
+ * ten rows each, which is where an accordion stops reading. */
331
+ const [entered, setEntered] = useState(null)
332
+ const snapOpenRef = useRef(null)
333
+ const slotRef = useRef(null)
334
+ const ctx = useRailSlot()
335
+ const setSlot = ctx?.setSlot
336
+ const setCtxOpen = ctx?.setRailOpen
337
+ const slotOpen = drawer || railOpen
338
+ useEffect(() => { setSlot?.(slotRef.current); return () => setSlot?.(null) }, [setSlot, hidden])
339
+ useEffect(() => { setCtxOpen?.(slotOpen) }, [setCtxOpen, slotOpen])
340
+ /* the grab strip is not rendered in drawer mode, so the hook's ref stays null
341
+ * and it no-ops on its own — no second argument needed */
342
+ useGrabEdge(grabRef)
343
+ useRailDrag(railRef, grabRef, setRailOpen, snapOpenRef, !drawer)
344
+ if (hidden) return null
345
+ const enterMode = sections === 'enter'
346
+ const section = enterMode && entered ? items.find((i) => i.path === entered) : null
347
+ const row = (item) => (
348
+ <RailItem key={item.path} {...item} currentPath={currentPath} onNavigate={onNavigate} iconComponent={iconComponent} railOpen={drawer || railOpen} onOpenRail={() => snapOpenRef.current?.()}
349
+ onEnter={enterMode ? () => setEntered(item.path) : undefined} />
350
+ )
351
+ return (
352
+ <div
353
+ ref={railRef}
354
+ /* ONE SIDE, ALWAYS LEFT (ShellDrawerSideCorrection, kol-chess 2026-09-01).
355
+ * 0.34.0 mirrored the panel to fix a button: the complaint was the
356
+ * trigger travelling to mid-screen, never the navigation's side. The
357
+ * trigger is now pinned top-right in both states, so a left panel has
358
+ * nothing to collide with and the drawer opens where the rail lives. */
359
+ className="kol-shell-rail bg-surface-primary fixed inset-y-0 left-0 flex flex-col items-start pt-4 pb-4 px-2 gap-2 border-r border-fg-08"
360
+ /* A drawer takes its own width, NOT the live rail token — that token is
361
+ * zeroed in drawer mode so the content gets the whole viewport back. */
362
+ style={{ width: drawer ? 'var(--kol-shell-drawer-width, 240px)' : `var(${RAIL_W})` }}
363
+ >
364
+ {!drawer && (
365
+ /* A BUTTON, and on touch A THICKER LINE (ShellRailCollapsedWithTapOpen,
366
+ * kol-mirror 2026-09-01; corrected by RailGrabTapIsALine, kol-monitor
367
+ * 2026-09-02 — user: "it was a thicker line" · "who decided it should be
368
+ * a chevron?"): `touch="shell"` keeps the 48px rail visible and its
369
+ * only opener was this 8px strip, whose pill wakes on pointer
370
+ * PROXIMITY — a thumb never hovers. The 0.38.0 answer was a disc with a
371
+ * chevron; that was the DS agent's shape, not the user's ruling. The
372
+ * opener is the strip ITSELF: under `(pointer: coarse)` the theme
373
+ * widens it to a thumb-sized hit and shows the pill thick at rest — the
374
+ * same affordance a fine pointer drags, no glyph. A press with no travel
375
+ * already toggled; it just had no hit area on touch. The drag hook binds
376
+ * pointer events, so a button works exactly as the div did, and it says
377
+ * what it is. Enter/Space toggle for the keyboard. */
378
+ <button
379
+ type="button"
380
+ ref={grabRef}
381
+ className="kol-rail-grab"
382
+ aria-label={railOpen ? 'Collapse navigation' : 'Expand navigation'}
383
+ aria-expanded={railOpen}
384
+ onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); snapOpenRef.current?.(!railOpen) } }}
385
+ />
386
+ )}
387
+ {logomark && (
388
+ /* the mark, and the app name beside it when open — uppercase like the
389
+ * rows (user 2026-08-28: "uppercase CONSISTENCY"). The `w-8` centring box
390
+ * puts the 20px mark on the same x as the 20px glyphs below it. */
391
+ <Tooltip label={logomark.title} placement="right" asChild>
392
+ <div
393
+ onClick={() => onNavigate?.('/')}
394
+ className="text-oq-96 cursor-pointer flex items-center gap-3 w-full overflow-hidden shrink-0 pt-1 mb-4"
395
+ >
396
+ <span className="w-8 flex justify-center shrink-0"><Logomark svgUrl={logomark.svgUrl} size={20} /></span>
397
+ <span className="kol-helper-12 uppercase flex-1 min-w-0 truncate">{logomark.title}</span>
398
+ </div>
399
+ </Tooltip>
400
+ )}
401
+ {/* THE LIST IS ITS OWN REGION (2026-10-02): it takes the room between the mark and the pinned
402
+ * bottom rows — what the bare spacer used to hold — scrolls when the rows outrun the window,
403
+ * and fades at its foot unless `fade={false}`. Same column, same gap, as the rail's own. */}
404
+ <div style={ctx && slotOpen ? { flex: '0 1 auto' } : undefined} className={`kol-shell-rail-list flex min-h-0 w-full flex-1 flex-col items-start gap-2 overflow-y-auto overflow-x-hidden ${fade ? 'kol-shell-rail-list--fade' : ''}`.trim()}>
405
+ {section ? (
406
+ <>
407
+ <RailItem icon="arrow-left" path={section.path} label={section.label} currentPath="" onNavigate={() => setEntered(null)} iconComponent={iconComponent} railOpen={drawer || railOpen} />
408
+ {section.sub.map((s) => <RailItem key={s.path} {...s} currentPath={currentPath} onNavigate={onNavigate} iconComponent={iconComponent} railOpen={drawer || railOpen} />)}
409
+ </>
410
+ ) : items.map(row)}
411
+ </div>
412
+ {ctx && (
413
+ <div
414
+ ref={slotRef}
415
+ className="kol-shell-rail-slot w-full min-h-0 overflow-x-hidden"
416
+ style={{ flex: slotOpen ? '1 1 auto' : '0 0 0px', overflowY: slotOpen ? 'auto' : 'hidden' }}
417
+ />
418
+ )}
419
+ {/* the rule runs the full rail width, out past the px-2 */}
420
+ {bottomItems.length > 0 && <div className="self-stretch -mx-2 border-t border-fg-08" />}
421
+ {bottomItems.map(row)}
422
+ </div>
423
+ )
424
+ }
@@ -0,0 +1,481 @@
1
+ import { useEffect, useLayoutEffect, useRef, useState } from 'react'
2
+ import { createPortal } from 'react-dom'
3
+ import { Icon } from '@kolkrabbi/kol-icons'
4
+ import { Tooltip } from '../utilities/Popover.jsx'
5
+ import useDragResize from '../hooks/useDragResize.js'
6
+
7
+ /* taxonomy-ok: organism — NavRail's site variant; nests Tooltip (utility) + kol-icons' Icon.
8
+ * Carried class-for-class from kol-framework's SideNav.jsx (2026-10-22, the one nav rail):
9
+ * the router read and the theme toggle stay in kol-framework, which wraps this as `SideNav`.
10
+ * ponytail: its box CSS still lives in kol-framework.css (`.kol-sidenav*`, the brand layout
11
+ * grid), so a site on this variant loads kol-framework.css as SideNav always required; move
12
+ * those rules to kol-theme when a consumer without kol-framework wants the site look. */
13
+
14
+ /**
15
+ * NavRail variant="site" — the grouped navigation rail (kol-framework's SideNav until 2026-10-22).
16
+ *
17
+ * REPLICATED from the elder reference (kol-website/apps/brand
18
+ * src/components/framework/SideNav.jsx, 2026-08-09 user mandate: "there is a
19
+ * better version in kol-website apps:brand") — the brand app's evolved fork
20
+ * folded back into the package, generic seams kept.
21
+ *
22
+ * A category is a grouping LABEL — a disclosure <button> with a trailing
23
+ * caret, no route. A page is a route. The ONE exception: a category with `to`
24
+ * and no `pages` (Home) renders as a plain link row — it has nothing to
25
+ * disclose.
26
+ *
27
+ * The 2026-08-01 "TWO LEVELS ONLY" ruling was the BRAND APP's, about its
28
+ * scroll-spied `#anchor` section layer — that layer stays dead (an `{ id }`
29
+ * leaf is dropped). It was inscribed here as a law for every consumer, and
30
+ * kol-studio lost two groups and six routes from its rail on adopting 0.23.0.
31
+ * User, 2026-08-26, verbatim: "ok that is such a problem, sometimes Im
32
+ * talking about a specific thing and it gets applied as a literal fit-all
33
+ * rule, which isnt the case. its very hard to work in such uncertainty."
34
+ * Re-scoped (sidenav-nested-groups, 0.24.0): nested ROUTE groups are
35
+ * supported. A `{ label, children }` node inside a category renders as a
36
+ * non-routing group header with its rows indented one step under it,
37
+ * recursively. The tree shape is the opt-in — there is no prop — and a tree
38
+ * with no group nodes renders byte-for-byte as before.
39
+ *
40
+ * navTree: [{ id, label, icon, to?, pages?: [{ label, to } | { label, children }] }]
41
+ * (legacy `children` on a category is read as `pages`; section anchors are not.)
42
+ *
43
+ * WORKSPACE RAILS (WorkspaceSidebarGeometry, kol-fxr 2026-08-27 — user: "I see
44
+ * these 3 as very similar things … I would rather all use the same geometry
45
+ * layout"; three forks, ~1,370 lines, wearing this component's classes):
46
+ *
47
+ * ACTION LEAVES — `{ label, onSelect, active? }` beside `{ label, to }`, at
48
+ * any depth and as a category (`{ id, label, icon, onSelect, active? }`): a
49
+ * rail that DISPATCHES (labs swaps an effect, monitor picks a module, mirror
50
+ * selects a surface) instead of navigating. A <button>, lit by `active`;
51
+ * never a route, so no history is walked (labs' `?preset=` replace-not-push
52
+ * stays what it is).
53
+ *
54
+ * ROUTER-AGNOSTIC — pass `currentPath` and the component never touches
55
+ * react-router: route leaves render `<a href>` and call `onNavigate(event,
56
+ * to)` (kol-shell's contract); a router-free app can mount it. Without
57
+ * `currentPath` it is the NavLink rail it always was.
58
+ *
59
+ * THE COLLAPSE RULE — a row that can survive collapse HAS AN ICON; one that
60
+ * cannot is not a row, it is a LABEL. A top-level node with no `icon` (and no
61
+ * `to` / `onSelect`) renders `.kol-sidenav-section` — the eyebrow voice, hidden
62
+ * on collapse — over its `pages`; the icon rows beneath stay, so the rail
63
+ * reads as one thing narrowing, the brand sidebar's model.
64
+ *
65
+ * Collapse: the pill-marked grab edge is THE single control (user build
66
+ * order 2026-08-09, completing SideNavGrabResize — the chip Button is gone
67
+ * in both states). Click toggles expand↔collapse, drag resizes with
68
+ * snap-collapse and snap-to-default, keyboard on the separator: arrows /
69
+ * Home / Enter / Space. One contract: `:root[data-sidenav="collapsed"]` +
70
+ * the `kol-sidenav` storage schema, owned by useDragResize. Collapsed rows
71
+ * get a DS Tooltip — the glyph is otherwise the only thing naming them.
72
+ *
73
+ * THE SHELL RAIL IS THIS COMPONENT (RailSideNavPixelParity, kol-fxr 2026-08-28
74
+ * — user, on the brand sidebar's drag: "same component both states super
75
+ * nice"): kol-shell's `AppShell` mounts a SideNav — collapsed by default, the
76
+ * drag opens it — so an app rail and the brand sidebar are one geometry to the
77
+ * pixel (fxr measured 48 vs 56 wide, 20 vs 16px glyphs, 40 vs 38 pitch, first
78
+ * glyph at y 76 vs 26 between the old NavRail and this rail collapsed). The
79
+ * seams the shell needed, all opt-in, a tree with none of them renders as before:
80
+ * `header` a node ABOVE the tree, outside the scroll region, in the
81
+ * hop's geometry (`.kol-sidenav-header`, kol-framework.css)
82
+ * — the app's logomark (RailLogomarkAtTop, 2026-08-28 —
83
+ * user: "why did you move the logo from top to bottom?").
84
+ * Give it a `.kol-sidenav-hop-icon` span (20px mark on the
85
+ * icon column) and, optionally, a `.kol-sidenav-hop-label`;
86
+ * both follow the collapse. Same node in every consumer =
87
+ * the first tree glyph at one y — the parity contract
88
+ * PANEL LEAF `{ id, label, icon, panel }` — a top-level node (tree or
89
+ * `bottomItems`) whose row is a DISCLOSURE: click opens,
90
+ * click again closes, lit while open (RailSettingsDisclosure,
91
+ * kol-fxr 2026-08-28 — user: "sidebar setting should open
92
+ * close on click and click again" · "put the theme toggle in
93
+ * the settings and out of the sidebar"). `panel` is a node or
94
+ * `({ collapsed, close }) => node`, PORTALLED to <body>
95
+ * directly above the row at the rail's own width (left/width
96
+ * from the aside, bottom = viewport − the row's top,
97
+ * `--kol-z-tooltip`), so it works collapsed (icon column)
98
+ * and expanded (rows) alike. Escape closes; any navigation
99
+ * or dispatch closes. fxr's RailSettings.jsx, promoted.
100
+ * `bottomItems` top-level nodes pinned BELOW the theme slot, above the
101
+ * footer (the shell pins theme → Settings; a Settings row in
102
+ * the tree landed above the theme instead — "same rail, two
103
+ * bottoms")
104
+ * `footer` the footer box's content: undefined = the Kolkrabbi link
105
+ * (K / wordmark, as ever); `false` = no footer; a node =
106
+ * that node (the shell's logomark → '/')
107
+ * `themeToggle` `false` drops the theme slot (default `true`)
108
+ * `iconComponent` the hop glyph's renderer, kol-shell's seam — `(props:
109
+ * { name, size }) => element`; default the DS `Icon`
110
+ * `expandOnSelect` `false` keeps the rail collapsed when a row navigates or
111
+ * dispatches — an app rail stays a rail. Default `true`, the
112
+ * brand ruling ("pressing any icon would expand the sidebar")
113
+ * `defaultCollapsed` boots collapsed when nothing is stored (useDragResize)
114
+ * `background` (2026-08-09, prop): `true` (default) paints the rail surface;
115
+ * `false` renders chromeless so the rail can float over a consumer's media
116
+ * (the brand-hero model — the consumer owns the plane). `hairline` (2026-08-26,
117
+ * default `false`) paints the right-edge `border-r border-fg-08` — split out
118
+ * of `background` so the line is a choice of its own.
119
+ */
120
+
121
+ const pageBase =
122
+ 'kol-sidenav-link kol-helper-10 block relative py-[4px] pl-14 pr-6 no-underline transition-colors duration-150'
123
+
124
+ /* The active-dot pseudo-element is positioned by `--kol-sidenav-dot-left`
125
+ * (kol-components-atoms.css). The page row indents 3.5rem (pl-14); the dot
126
+ * sits 0.875rem inside that, in the gutter the icon column leaves. */
127
+ const pageStyle = { '--kol-sidenav-dot-left': '2.625rem' }
128
+ /* Category and page must not share a stop: category `emphasis`, page `strong`
129
+ * — two rungs of one ladder, so the tree reads as hierarchy (elder ruling). */
130
+ const pageCls = `${pageBase} text-strong hover:text-emphasis`
131
+ const pageActiveCls = `${pageBase} is-active`
132
+
133
+ /* A category's rows: route leaves (`to`) and route groups (`children`).
134
+ * `#anchor` leaves (`id` only) are dropped — that layer died with the brand
135
+ * app's 2026-08-01 ruling and is not reopened here. */
136
+ const rowsOf = (nodes) => nodes.filter((c) => c.to || c.children || c.onSelect)
137
+ const pagesOf = (cat) => rowsOf(cat.pages ?? cat.children ?? [])
138
+ /* Every route leaf under a set of rows, through any depth of groups. */
139
+ const leavesOf = (rows) => rows.flatMap((r) => (r.children ? leavesOf(rowsOf(r.children)) : [r]))
140
+ /* A nested row sits one --kol-spacing-3 step further in per depth. Inline,
141
+ * not a rule: `pl-14` rides the leaf as a utility and outranks anything in
142
+ * this layer. Depth 0 carries no indent so a flat tree renders unchanged. */
143
+ const indentOf = (depth) => `calc(3.5rem + ${depth} * var(--kol-spacing-3))`
144
+
145
+ export default function NavRailSite({
146
+ currentPath: pathname = '',
147
+ /* `(to) => href` — the router's basename on the link a modified click opens (kol-framework's
148
+ * SideNav passes it); the click itself still goes to `onNavigate` with the bare route */
149
+ hrefFor,
150
+ drawerOpen = false,
151
+ onCloseDrawer,
152
+ navTree = [],
153
+ onNavigate,
154
+ isActive,
155
+ background = true,
156
+ /* the right-edge hairline is OPT-IN (sidenav-rail-hairline, kol-studio
157
+ * 2026-08-26 — user: the footer's border-t is right, the border-r is wrong
158
+ * as a default). It used to ride `background` — two decisions under one
159
+ * name; a rail floating over media and a rail without a line are different
160
+ * choices. */
161
+ hairline = false,
162
+ header,
163
+ bottomItems = [],
164
+ footer,
165
+ themeToggle = true,
166
+ iconComponent,
167
+ expandOnSelect = true,
168
+ defaultCollapsed = false,
169
+ }) {
170
+ const Glyph = iconComponent ?? Icon
171
+ const isPageActive = (to) => (isActive ? isActive(to) : pathname === to)
172
+ /* a leaf is lit by its route, or — an action leaf — by its own `active` */
173
+ const isLeafActive = (leaf) => (leaf.onSelect ? !!leaf.active : isPageActive(leaf.to))
174
+ const isActiveCat = (cat) => (cat.onSelect ? !!cat.active : leavesOf(pagesOf(cat)).some(isLeafActive))
175
+
176
+ /* Every navigation closes the mobile drawer — the prop sat accepted-but-
177
+ * unread until the kol-website session flagged it (2026-08-09) — and, from
178
+ * the collapsed rail, expands the sidebar ("pressing any icon would expand
179
+ * the sidebar", same ruling as the chip removal). */
180
+ const handleNavigate = (e, to) => {
181
+ onNavigate?.(e, to)
182
+ onCloseDrawer?.()
183
+ setOpenPanel(null)
184
+ if (collapsed && expandOnSelect) toggleCollapsed()
185
+ }
186
+ /* an action leaf dispatches — same drawer / rail behaviour as a navigation */
187
+ const handleSelect = (e, row) => {
188
+ row.onSelect(e)
189
+ onCloseDrawer?.()
190
+ setOpenPanel(null)
191
+ if (collapsed && expandOnSelect) toggleCollapsed()
192
+ }
193
+ /* the route leaf is always an `<a href>` handing the route to `onNavigate(event, to)` — the
194
+ * router lives in the consumer (kol-framework's `SideNav` wraps this with react-router). A
195
+ * modified click (cmd, ctrl, shift, middle) is left to the browser, as a NavLink left it. */
196
+ const RouteLeaf = ({ to, className, style, children }) => {
197
+ const active = isPageActive(to)
198
+ return (
199
+ <a href={hrefFor ? hrefFor(to) : to} style={style} className={className(active)} aria-current={active ? 'page' : undefined}
200
+ onClick={(e) => { if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) return; e.preventDefault(); handleNavigate(e, to) }}>{children}</a>
201
+ )
202
+ }
203
+
204
+ /* Which categories are disclosed. INDEPENDENT per category (elder ruling
205
+ * 2026-08-01) — arriving somewhere must not silently close wherever you
206
+ * were. Loads closed, in-memory only (elder ruling 2026-08-06). */
207
+ const [openCats, setOpenCats] = useState(() => new Set())
208
+ /* the ONE open panel leaf (by id) and where its panel sits */
209
+ const [openPanel, setOpenPanel] = useState(null)
210
+ const [panelBox, setPanelBox] = useState(null)
211
+ const toggleCat = (id) => setOpenCats((prev) => {
212
+ const next = new Set(prev)
213
+ next.has(id) ? next.delete(id) : next.add(id)
214
+ return next
215
+ })
216
+ const discloseCat = (id) => setOpenCats((prev) => new Set(prev).add(id))
217
+
218
+ /* One collapse contract, two gestures — the hook owns the stamp, the
219
+ * storage schema and the state; the chip Button and the grab edge both
220
+ * drive it. */
221
+ const asideRef = useRef(null)
222
+ const { collapsed, toggleCollapsed, grabProps } = useDragResize(asideRef, { defaultCollapsed })
223
+
224
+ /* the panel's anchor: its row — the panel's bottom edge meets the row's top
225
+ * edge, its width is the rail's; re-placed on resize and on collapse */
226
+ useLayoutEffect(() => {
227
+ if (!openPanel) { setPanelBox(null); return undefined }
228
+ const place = () => {
229
+ const rail = asideRef.current
230
+ const row = rail?.querySelector(`[data-panel-trigger="${CSS.escape(String(openPanel))}"]`)
231
+ if (!rail || !row) return
232
+ const rr = rail.getBoundingClientRect(), tr = row.getBoundingClientRect()
233
+ setPanelBox({ left: rr.left, width: rr.width, bottom: window.innerHeight - tr.top })
234
+ }
235
+ place()
236
+ window.addEventListener('resize', place)
237
+ return () => window.removeEventListener('resize', place)
238
+ }, [openPanel, collapsed])
239
+ useEffect(() => {
240
+ if (!openPanel) return undefined
241
+ const onKey = (e) => { if (e.key === 'Escape') setOpenPanel(null) }
242
+ window.addEventListener('keydown', onKey)
243
+ return () => window.removeEventListener('keydown', onKey)
244
+ }, [openPanel])
245
+ const panelNode = openPanel != null ? [...navTree, ...bottomItems].find((c) => c.id === openPanel) : null
246
+
247
+ /* Rows under a category: a leaf is a route link; a group is a non-routing
248
+ * header over its own rows, one step further in (recursive). A group lights
249
+ * up the way a category does — when one of its leaves is the current route. */
250
+ const renderRows = (rows, depth) => rows.map((row, i) => {
251
+ if (row.children) {
252
+ const lit = leavesOf(rowsOf(row.children)).some(isLeafActive)
253
+ return (
254
+ <li key={row.id ?? `${row.label}-${i}`}>
255
+ <div
256
+ className={`kol-sidenav-group kol-helper-10${lit ? ' text-emphasis' : ' text-subtle'}`}
257
+ style={depth ? { paddingLeft: indentOf(depth) } : undefined}
258
+ >
259
+ {row.label}
260
+ </div>
261
+ <ul className="kol-sidenav-list">{renderRows(rowsOf(row.children), depth + 1)}</ul>
262
+ </li>
263
+ )
264
+ }
265
+ /* the dot keeps its 0.875rem lead on the text at every depth */
266
+ const leafStyle = depth ? { paddingLeft: indentOf(depth), '--kol-sidenav-dot-left': `calc(2.625rem + ${depth} * var(--kol-spacing-3))` } : pageStyle
267
+ if (row.onSelect) {
268
+ return (
269
+ <li key={row.id ?? `${row.label}-${i}`}>
270
+ <button
271
+ type="button"
272
+ style={leafStyle}
273
+ className={`${row.active ? pageActiveCls : pageCls} w-full bg-transparent border-0 cursor-pointer text-left truncate`}
274
+ aria-pressed={!!row.active}
275
+ onClick={(e) => handleSelect(e, row)}
276
+ >
277
+ {row.label}
278
+ </button>
279
+ </li>
280
+ )
281
+ }
282
+ return (
283
+ <li key={row.to}>
284
+ <RouteLeaf to={row.to} style={leafStyle} className={(active) => (active ? pageActiveCls : pageCls)}>
285
+ {row.label}
286
+ </RouteLeaf>
287
+ </li>
288
+ )
289
+ })
290
+
291
+ /* one renderer for the tree and the pinned rows (RailSideNavPixelParity) */
292
+ const renderCat = (cat, ci) => {
293
+ const pages = pagesOf(cat)
294
+ const isOpen = openCats.has(cat.id)
295
+ const isLink = !pages.length && cat.to
296
+ const isPanel = !pages.length && !cat.to && !!cat.panel
297
+ const isAction = !pages.length && !cat.to && !isPanel && cat.onSelect
298
+ /* THE COLLAPSE RULE: no icon, no route, no action = a LABEL over
299
+ * its rows, not a row — `.kol-sidenav-section` hides on collapse
300
+ * and the icon rows beneath it stay */
301
+ if (!cat.icon && !cat.to && !cat.onSelect && !cat.panel) {
302
+ return (
303
+ <li key={cat.id ?? `${cat.label}-${ci}`} className="relative">
304
+ <div className="kol-sidenav-section kol-eyebrow text-strong">{cat.label}</div>
305
+ {pages.length > 0 && <ul className="kol-sidenav-list">{renderRows(pages, 0)}</ul>}
306
+ </li>
307
+ )
308
+ }
309
+ /* Box utilities deliberately absent — the hop's layout lives in
310
+ * .kol-sidenav-hop (kol-framework.css): a utility here would
311
+ * outrank the collapsed-state overrides (2026-08-09 defect). */
312
+ const rowCls = 'kol-sidenav-hop kol-helper-12 text-emphasis no-underline'
313
+ const glyph = (
314
+ <span className="kol-sidenav-hop-icon inline-flex items-center justify-center w-5 h-5 shrink-0" aria-hidden="true">
315
+ <Glyph name={cat.icon} size={16} />
316
+ </span>
317
+ )
318
+ /* A category is a <button>, not a link — it has no route by
319
+ definition, and an <a href> would promise a page that does
320
+ not exist. Clicking it discloses its pages. */
321
+ const head = isLink ? (
322
+ <RouteLeaf to={cat.to} className={(active) => `${rowCls}${active ? ' is-active' : ''}`}>
323
+ {glyph}
324
+ <span className="kol-sidenav-hop-label flex-1 min-w-0">{cat.label}</span>
325
+ </RouteLeaf>
326
+ ) : isPanel ? (
327
+ <button
328
+ type="button"
329
+ data-panel-trigger={cat.id}
330
+ className={`${rowCls} bg-transparent border-0 cursor-pointer text-left${openPanel === cat.id ? ' is-active' : ''}`}
331
+ aria-expanded={openPanel === cat.id}
332
+ onClick={() => setOpenPanel((o) => (o === cat.id ? null : cat.id))}
333
+ >
334
+ {glyph}
335
+ <span className="kol-sidenav-hop-label flex-1 min-w-0">{cat.label}</span>
336
+ </button>
337
+ ) : isAction ? (
338
+ <button
339
+ type="button"
340
+ className={`${rowCls} bg-transparent border-0 cursor-pointer text-left${cat.active ? ' is-active' : ''}`}
341
+ aria-pressed={!!cat.active}
342
+ onClick={(e) => handleSelect(e, cat)}
343
+ >
344
+ {glyph}
345
+ <span className="kol-sidenav-hop-label flex-1 min-w-0">{cat.label}</span>
346
+ </button>
347
+ ) : (
348
+ <button
349
+ type="button"
350
+ className={`${rowCls} bg-transparent border-0 cursor-pointer text-left${isActiveCat(cat) ? ' is-active' : ''}`}
351
+ aria-expanded={isOpen}
352
+ /* Collapsed rail: the click meant "open this" — expand the
353
+ * rail AND disclose the category, or the tap is wasted on
354
+ * an expand that lands on a closed tree. */
355
+ onClick={() => {
356
+ if (collapsed) {
357
+ toggleCollapsed()
358
+ discloseCat(cat.id)
359
+ } else {
360
+ toggleCat(cat.id)
361
+ }
362
+ }}
363
+ >
364
+ {glyph}
365
+ <span className="kol-sidenav-hop-label flex-1 min-w-0">{cat.label}</span>
366
+ {/* plain wrapper span — Icon stamps inline-flex on its own
367
+ * element, which would outrank the rail's display:none */}
368
+ <span
369
+ className={`kol-sidenav-hop-caret transition-transform duration-150${isOpen ? '' : ' -rotate-90'}`}
370
+ aria-hidden="true"
371
+ >
372
+ <Icon name="chevron-down" size={12} />
373
+ </span>
374
+ </button>
375
+ )
376
+ return (
377
+ <li key={cat.id} className="relative">
378
+ {/* Collapsed rail hides the label — the tooltip is the only
379
+ thing naming the row. Portalled, so overflow can't clip it. */}
380
+ {collapsed ? (
381
+ <Tooltip label={cat.label} placement="right" triggerClassName="block">
382
+ {head}
383
+ </Tooltip>
384
+ ) : head}
385
+
386
+ {!isLink && !isAction && !isPanel && isOpen && (
387
+ <ul className="kol-sidenav-list">{renderRows(pages, 0)}</ul>
388
+ )}
389
+ </li>
390
+ )
391
+ }
392
+
393
+ return (
394
+ <aside
395
+ ref={asideRef}
396
+ /* Box utilities deliberately absent (SideNavMobilePosition, 2026-08-25):
397
+ * the aside's position/height/stack live in .kol-sidenav
398
+ * (kol-framework.css). `sticky … h-dvh z-20` here outranked the 767px
399
+ * drawer rule's `position: fixed`, so every consumer page opened one
400
+ * viewport down on phones. Only color utilities ride the element. */
401
+ className={`kol-sidenav${background ? ' bg-surface-primary' : ''}${hairline ? ' border-r border-fg-08' : ''}${collapsed ? ' is-collapsed' : ''}${drawerOpen ? ' is-drawer-open' : ''}`}
402
+ >
403
+ {/* NO chip Button in either state (user build order 2026-08-09 — "MAKE
404
+ * IT"; supersedes the elder A/B): the pill-marked grab edge below is
405
+ * THE single collapse/resize control — click toggles, drag resizes,
406
+ * snap-to-default on release, Home/Enter/Space on the keyboard. */}
407
+
408
+ {header && <div className="kol-sidenav-header">{header}</div>}
409
+
410
+ {/* ONLY the tree scrolls (fxr's re-measure, 2026-08-28): the theme slot
411
+ * and the pinned rows used to sit inside this region, so on a 26-row
412
+ * collapsed tree they scrolled off below the footer — "pinned" only
413
+ * held while the tree was shorter than the rail. They are the block
414
+ * after it now, above the footer, the tree scrolling underneath. */}
415
+ <div className="kol-sidenav-scroll flex-1 overflow-y-auto pt-4 pb-4 [scrollbar-width:thin]">
416
+ <nav aria-label="Sections">
417
+ <ul className="kol-sidenav-tree flex flex-col gap-[2px]">
418
+ {navTree.map(renderCat)}
419
+ </ul>
420
+ </nav>
421
+ </div>
422
+
423
+ {/* hop-bare carries its own gutter padding; collapsed falls back to
424
+ `icon` — a full-width label can't sit in the collapsed rail. */}
425
+ <div className="pb-4">
426
+ {/* the theme slot is the consumer's: kol-component cannot import kol-framework's
427
+ * toggle, so `themeToggle` is a render function `({ collapsed }) => node` (kol-framework's
428
+ * SideNav passes its own); anything else renders no slot */}
429
+ {typeof themeToggle === 'function' && (
430
+ <div className="kol-sidenav-theme-slot flex">
431
+ {themeToggle({ collapsed })}
432
+ </div>
433
+ )}
434
+ {/* pinned rows — BELOW the theme, above the footer: the shell's bottom
435
+ * pair (theme → Settings), specified once */}
436
+ {bottomItems.length > 0 && (
437
+ <nav aria-label="Pinned">
438
+ <ul className="kol-sidenav-tree flex flex-col gap-[2px]">{bottomItems.map(renderCat)}</ul>
439
+ </nav>
440
+ )}
441
+ </div>
442
+
443
+ {footer !== false && footer !== null && (
444
+ <div className="kol-sidenav-footer flex items-center h-14 border-t border-fg-08 min-w-0">
445
+ {footer !== undefined ? footer : (
446
+ <a
447
+ href="https://kolkrabbi.io"
448
+ target="_blank"
449
+ rel="noopener"
450
+ className="kol-helper-10 !font-normal no-underline group whitespace-nowrap overflow-hidden text-ellipsis min-w-0"
451
+ >
452
+ {/* Collapsed rail shows the initial alone; the full wordmark
453
+ overflows it. Both live in one <a> so the link survives either
454
+ state (CSS swaps them on the data-sidenav stamp). */}
455
+ <span className="kol-sidenav-footer-mark text-body group-hover:text-emphasis">K</span>
456
+ <span className="kol-sidenav-footer-full">
457
+ <span className="text-body group-hover:text-emphasis">Kolkrabbi Vinnustofa</span>
458
+ <span className="text-meta group-hover:text-emphasis"> · {new Date().getFullYear()}</span>
459
+ </span>
460
+ </a>
461
+ )}
462
+ </div>
463
+ )}
464
+
465
+ {/* the open panel leaf's panel — a portal above its row, the rail's width */}
466
+ {panelNode && panelBox && createPortal(
467
+ <div
468
+ className="kol-sidenav-panel fixed flex flex-col gap-[2px] py-2 bg-surface-primary border-t border-r border-fg-08"
469
+ style={{ left: panelBox.left, width: panelBox.width, bottom: panelBox.bottom, zIndex: 'var(--kol-z-tooltip)' }}
470
+ >
471
+ {typeof panelNode.panel === 'function' ? panelNode.panel({ collapsed, close: () => setOpenPanel(null) }) : panelNode.panel}
472
+ </div>,
473
+ document.body,
474
+ )}
475
+
476
+ {/* Grab edge — width/cursor/focus chrome in kol-framework.css
477
+ * (.kol-sidenav-grab); hidden below lg by the narrow-mode block. */}
478
+ <div className="kol-sidenav-grab absolute top-0 right-0 bottom-0 z-[1]" {...grabProps} />
479
+ </aside>
480
+ )
481
+ }