codeburn/app/renderer/components/Dropdown.tsx
Resham Joshi 8fb478904e
feat: group a deleted sibling clone with its repository by folder name (#1692)
* feat(app): transient project selector in the desktop top bar

Scopes every report to one project path for the current session through
the same narrowing the VS Code workspace scope uses. The saved project
filter is never written; a restart is back on all projects.

* fix(app): let the name pickers ellipsize before the top bar overflows

* fix: key the daily project split per real path, not per label

A project label can span several paths: every Claude session started from the
home folder shares -Users-<name>, while its cwd puts it in a different project.
The day rollup keyed by label kept the first path it saw, so a rooted
--project headline took the whole label bucket on some days and missed it on
others. Key per (label, path), read old label-keyed days unchanged, bump the
daily cache to v68.

* fix(app): list only selectable, non-zero projects in the top bar picker

Rows with no session cwd (the Cursor and Grok Bot imports, provider label
fallbacks) report their label as the path, so the picker offered names the
bridge refuses and dash-to-slash guesses like eywa/lab. Keep only absolute
paths, and drop rows whose lifetime cost rounds to $0.00. The old test that
rooted a slashless Codex path is replaced: Codex now records the absolute cwd,
and a slashless path is always the label fallback.

* fix(app): show a toast when a project pick is refused

The pick was dropped silently. Also pin that an encoded -Users-... label
never reaches the picker list.

* feat: group projects by git repository

Clones and worktrees that share an origin remote are one project in every
project list (report JSON, By Project, the top bar picker, the terminal
dashboard), with the checkouts listed under the row. A --project path inside
a checkout scopes to the whole repository; --exact-project keeps the old
single-folder match. The origin is learned while the folder exists, kept in
git-origins.json and on each day's project entry (daily cache v69), so a
deleted scratch clone stays in its repository. The report JSON project list
now comes from the durable day set, so a row costs what selecting it reports.

* fix: a picked project row selects that row exactly

The top bar pick sends =<path>: a checkout in a repository still selects the
whole repository, and a plain folder selects itself without the folders under
it, which are rows of their own. So the picker row and the headline it opens
are the same set. Typed --project paths keep their prefix match. Days adopted
from an older cache learn the origin of every checkout that still exists, and
lookups outside a parse are saved on exit.

* fix: key the status snapshot on --exact-project

* feat: one Temporary folders row for scratch folders outside a repository

Every project path under a temp root (os.tmpdir(), /tmp, /var/folders and
their /private spellings) that is not a checkout of a known repository folds
into one row, in the report JSON, By Project, the terminal dashboard, the top
bar picker and the Settings Projects pane. Its pattern @temp selects or hides
all of them. The Projects pane leaves out rows that round to $0.00 unless a
saved pattern names them, and a saved pattern naming any checkout of a
repository row now names the whole row in the renderer too.

* feat: group a deleted sibling folder with its repository by folder name

A deleted folder with no recorded origin, named <checkout>-<suffix> or
<checkout>_<suffix> next to exactly one repository's checkout, joins that
repository row. The checkout entry carries matchedByFolderName and the Spend
drill-down labels it. Existing folders and names two repositories could claim
are left alone.

* feat: the longest checkout name wins a folder-name match

A deleted folder that fits several sibling checkouts joins the one with the
longest name; it is skipped only when the longest fits belong to two
repositories. The report project type declares matchedByFolderName.

* fix(claude): attribute each call to the project of its own cwd

* test: fold the temp roots the tests set, compare checkout ids as identities (Windows)

* test: compare folder-name checkout ids as identities (Windows)

* fix(claude): keep subfolder cwds in their project, count and show a split session once

* fix: an exclude path hides that checkout only, repository rows count a session once

* feat: mark folder-name matches in the CLI report and the project picker

* fix(claude): a deleted subfolder stays its own project
2026-10-08 06:54:41 +02:00

182 lines
6.7 KiB
TypeScript

import { useEffect, useRef, useState, type ReactNode } from 'react'
import { useEscape } from '../hooks/useEscape'
import { AnchoredSurface } from './AnchoredSurface'
import { Icon } from './icons'
export type DropdownOption = { value: string; label: string; muted?: boolean; note?: string; title?: string }
/** A query box above the options. The caller filters `options` on `value`. */
export type DropdownSearch = { value: string; onChange: (query: string) => void; placeholder: string; ariaLabel: string }
export function Dropdown({
value,
options,
onChange,
ariaLabel,
id,
width,
renderIcon,
footer,
search,
onOpen,
}: {
value: string
options: DropdownOption[]
onChange: (value: string) => void
ariaLabel: string
id: string
width?: React.CSSProperties['width']
/** Optional leading glyph (e.g. a provider logo) shown in the trigger and each option. */
renderIcon?: (value: string) => ReactNode
/** Optional non-interactive note pinned below the options in the open menu. */
footer?: ReactNode
search?: DropdownSearch
onOpen?: () => void
}) {
const [open, setOpen] = useState(false)
const selectedIndex = Math.max(0, options.findIndex(option => option.value === value))
const [activeIndex, setActiveIndex] = useState(selectedIndex)
const wrapRef = useRef<HTMLDivElement>(null)
const triggerRef = useRef<HTMLButtonElement>(null)
const menuRef = useRef<HTMLDivElement>(null)
const optionRefs = useRef<Array<HTMLButtonElement | null>>([])
const searchRef = useRef<HTMLInputElement>(null)
const menuId = `${id}-menu`
const selected = options.find(option => option.value === value)
// A search can filter the selected option out; the trigger keeps its name.
const lastSelected = useRef<DropdownOption | undefined>(undefined)
if (selected) lastSelected.current = selected
const last = lastSelected.current
const label = selected?.label ?? (last && last.value === value ? last.label : value)
useEffect(() => {
if (!open) return
const onPointerDown = (event: MouseEvent) => {
const target = event.target as Node
if (!wrapRef.current?.contains(target) && !menuRef.current?.contains(target)) setOpen(false)
}
document.addEventListener('mousedown', onPointerDown)
return () => document.removeEventListener('mousedown', onPointerDown)
}, [open])
// With a search box, index -1 is the box itself.
useEffect(() => {
if (!open) return
if (activeIndex < 0) searchRef.current?.focus()
else optionRefs.current[activeIndex]?.focus()
}, [activeIndex, open])
useEscape(open, () => close(true))
const show = (index = selectedIndex) => {
setActiveIndex(search ? -1 : index)
setOpen(true)
onOpen?.()
}
const close = (restoreFocus = false) => {
setOpen(false)
search?.onChange('')
if (restoreFocus) triggerRef.current?.focus()
}
const choose = (index: number) => {
const option = options[index]
if (!option) return
onChange(option.value)
close(true)
}
const move = (offset: number) => {
if (options.length === 0) return
setActiveIndex(current => search && current + offset < 0 ? -1 : (current + offset + options.length) % options.length)
}
return (
<div className="pop-wrap dropdown" ref={wrapRef} style={{ width: 'max-content', minWidth: width }}>
<button
id={id}
ref={triggerRef}
type="button"
className="pop dropdown-trigger"
aria-label={ariaLabel}
aria-haspopup="listbox"
aria-expanded={open}
aria-controls={menuId}
onClick={() => open ? close() : show()}
onKeyDown={event => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault()
if (open) choose(activeIndex)
else show()
} else if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
event.preventDefault()
show(event.key === 'ArrowDown' ? selectedIndex : Math.max(0, options.length - 1))
}
}}
>
{renderIcon?.(value)}
<span className="dropdown-label">{label}</span>
<Icon name="chevron-down" className="dropdown-chevron" />
</button>
{open && (
<AnchoredSurface anchor={triggerRef} surfaceRef={menuRef} matchWidth id={menuId} className="pop-menu dropdown-menu" role="listbox" aria-label={ariaLabel}>
{search && (
<input
ref={searchRef}
className="pop-search"
type="search"
aria-label={search.ariaLabel}
placeholder={search.placeholder}
value={search.value}
onChange={event => search.onChange(event.target.value)}
onFocus={() => setActiveIndex(-1)}
onKeyDown={event => {
if (event.key === 'ArrowDown') {
event.preventDefault()
if (options.length > 0) setActiveIndex(0)
} else if (event.key === 'Enter') {
event.preventDefault()
choose(0)
} else if (event.key === 'Tab') {
close()
}
}}
/>
)}
{options.map((option, index) => (
<button
key={option.value}
ref={node => { optionRefs.current[index] = node }}
type="button"
title={option.title}
className={`pop-item${option.value === value ? ' on' : ''}${option.muted ? ' muted' : ''}`}
role="option"
aria-selected={option.value === value}
tabIndex={index === activeIndex ? 0 : -1}
onClick={() => choose(index)}
onFocus={() => setActiveIndex(index)}
onKeyDown={event => {
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
event.preventDefault()
move(event.key === 'ArrowDown' ? 1 : -1)
} else if (event.key === 'Home' || event.key === 'End') {
event.preventDefault()
setActiveIndex(event.key === 'Home' ? 0 : options.length - 1)
} else if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault()
choose(index)
} else if (event.key === 'Tab') {
close()
}
}}
>
{renderIcon?.(option.value)}
<span className="pop-item-label">{option.label}</span>
{option.note && <span className="pop-item-note">{option.note}</span>}
</button>
))}
{footer && <div className="dropdown-foot">{footer}</div>}
</AnchoredSurface>
)}
</div>
)
}