feat(ui): shared migration primitives (UI migration PR 3) (#1122)
* feat(ui): shared migration primitives (UI migration PR 3) The component kit every page migration (PR 4-8) builds on: - ContextPicker: the one-per-page chip-dropdown context scope (convention 8), right-aligned popover with checks and muted annotations - FyPicker: fiscal-year picker on ContextPicker with the same controlled API and per-company localStorage key as FiscalYearSelector, which it replaces page by page from PR 4 - SplitButton: primary + caret menu, last-used mode persisted per user via ui_state.create_mode (lib/ui-state/client, unit-tested); nav persistence refactored onto the same helper - ConfirmDialog: centered min-460px confirm-up-front dialog (convention 10) with pending state on an awaitable onConfirm - HelpPopover: 17px "?" after the H1 opening an anchored popover (convention 7); PageHeader gets a `help` slot - AttnLine: the one-ochre-sentence attention pattern (convention 6) with optional inline action; new AA-safe --attn token pair - RowStatus: chips-mark-exceptions helper (convention 5) - SlideOver: right review panel, 480px, 18px inset, rounded, veil + Esc (convention 13), with header kicker / body / footer slots - Stagger: .stagger-enter applied to the five target pages' list containers (bookkeeping, transactions, pending, invoices, supplier-invoices); structural loading.tsx added for supplier-invoices, customers, kpi, pending, deadlines No page adopts the new pickers/dialogs yet: that is PR 4-8, one page per PR against this kit. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ui): FyPicker chip must not double the Rakenskapsar label Real fiscal periods are often named "Rakenskapsar 2026" already; only prefix the label when the period name lacks it. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
d59e4708cf
commit
5b5ee8e429
@@ -0,0 +1,158 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useRef, useEffect, useCallback } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { Check, ChevronDown } from 'lucide-react'
|
||||
|
||||
export interface ContextPickerItem {
|
||||
id: string
|
||||
label: string
|
||||
/** Muted right-side note on the row, e.g. "stängt" for a closed fiscal year. */
|
||||
annotation?: string
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
interface ContextPickerProps {
|
||||
items: ContextPickerItem[]
|
||||
/** Selected item id. */
|
||||
value: string | null
|
||||
onChange: (id: string) => void
|
||||
/** Chip text, e.g. "Räkenskapsår 2026" or "Alla källor · 24 300 kr". */
|
||||
triggerLabel: string
|
||||
disabled?: boolean
|
||||
ariaLabel?: string
|
||||
className?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* The page context picker (UI-migration convention 8): a chip-dropdown that
|
||||
* scopes the page to a fiscal year, account or source. One per page, far
|
||||
* right in the toolbar. A chip that looks like a picker must be a picker;
|
||||
* this is that picker.
|
||||
*/
|
||||
export function ContextPicker({
|
||||
items,
|
||||
value,
|
||||
onChange,
|
||||
triggerLabel,
|
||||
disabled = false,
|
||||
ariaLabel,
|
||||
className,
|
||||
}: ContextPickerProps) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const triggerRef = useRef<HTMLButtonElement>(null)
|
||||
const listRef = useRef<HTMLDivElement>(null)
|
||||
const [pos, setPos] = useState({ top: 0, left: 0 })
|
||||
|
||||
const updatePosition = useCallback(() => {
|
||||
if (!triggerRef.current || !listRef.current) return
|
||||
const t = triggerRef.current.getBoundingClientRect()
|
||||
const l = listRef.current.getBoundingClientRect()
|
||||
const margin = 8
|
||||
// Right-aligned under the chip (the picker lives far right in the
|
||||
// toolbar), clamped to the viewport.
|
||||
const left = Math.max(margin, Math.min(t.right - l.width, window.innerWidth - l.width - margin))
|
||||
const top = Math.min(t.bottom + 4, window.innerHeight - l.height - margin)
|
||||
setPos({ top, left })
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const raf = requestAnimationFrame(() => updatePosition())
|
||||
return () => cancelAnimationFrame(raf)
|
||||
}, [open, updatePosition])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
function handleClick(e: MouseEvent) {
|
||||
const target = e.target as HTMLElement
|
||||
if (!target.isConnected) return
|
||||
if (
|
||||
(!triggerRef.current || !triggerRef.current.contains(target)) &&
|
||||
(!listRef.current || !listRef.current.contains(target))
|
||||
) {
|
||||
setOpen(false)
|
||||
}
|
||||
}
|
||||
function handleKey(e: KeyboardEvent) {
|
||||
if (e.key === 'Escape') setOpen(false)
|
||||
}
|
||||
document.addEventListener('mousedown', handleClick)
|
||||
document.addEventListener('keydown', handleKey)
|
||||
return () => {
|
||||
document.removeEventListener('mousedown', handleClick)
|
||||
document.removeEventListener('keydown', handleKey)
|
||||
}
|
||||
}, [open])
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
ref={triggerRef}
|
||||
type="button"
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
disabled={disabled}
|
||||
aria-expanded={open}
|
||||
aria-haspopup="listbox"
|
||||
aria-label={ariaLabel}
|
||||
className={cn(
|
||||
'inline-flex items-center gap-1.5 whitespace-nowrap rounded-full border border-border px-3 py-[5px] text-[13px]',
|
||||
'text-foreground transition-colors duration-150',
|
||||
disabled
|
||||
? 'opacity-50 cursor-not-allowed'
|
||||
: 'hover:bg-secondary/60 cursor-pointer',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<span className="truncate max-w-[220px]">{triggerLabel}</span>
|
||||
<ChevronDown className="h-3.5 w-3.5 flex-shrink-0 text-muted-foreground" />
|
||||
</button>
|
||||
|
||||
{open &&
|
||||
createPortal(
|
||||
<div
|
||||
ref={listRef}
|
||||
role="listbox"
|
||||
className="fixed z-[60] min-w-[220px] max-w-[320px] rounded-lg border border-border bg-popover py-1 shadow-lg animate-in fade-in slide-in-from-top-1 duration-150"
|
||||
style={{ top: pos.top, left: pos.left }}
|
||||
>
|
||||
<div className="max-h-72 overflow-y-auto px-1">
|
||||
{items.map((item) => (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={item.id === value}
|
||||
disabled={item.disabled}
|
||||
onClick={() => {
|
||||
onChange(item.id)
|
||||
setOpen(false)
|
||||
}}
|
||||
className={cn(
|
||||
'flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left text-[13px] leading-snug transition-colors',
|
||||
item.disabled
|
||||
? 'text-muted-foreground/40 cursor-not-allowed'
|
||||
: item.id === value
|
||||
? 'bg-secondary/60 text-foreground'
|
||||
: 'text-muted-foreground hover:bg-secondary/60 hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
<span className="min-w-0 flex-1 truncate">{item.label}</span>
|
||||
{item.annotation && (
|
||||
<span className="flex-shrink-0 text-[11px] text-muted-foreground/70">
|
||||
{item.annotation}
|
||||
</span>
|
||||
)}
|
||||
{item.id === value && (
|
||||
<Check className="h-3.5 w-3.5 flex-shrink-0 text-primary" />
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { ContextPicker } from '@/components/common/ContextPicker'
|
||||
import {
|
||||
STORAGE_KEY_PREFIX,
|
||||
ALL_YEARS_VALUE,
|
||||
} from '@/components/common/FiscalYearSelector'
|
||||
import type { FiscalPeriod } from '@/types'
|
||||
|
||||
interface FyPickerProps {
|
||||
/** Current selection. `null` means "all years": no filter applied. */
|
||||
value: string | null
|
||||
/**
|
||||
* Called with the selected period id (or null for "all years") and the
|
||||
* matching FiscalPeriod so callers avoid an extra fetch.
|
||||
*/
|
||||
onChange: (periodId: string | null, period?: FiscalPeriod | null) => void
|
||||
/** Include an "Alla räkenskapsår" option that clears the filter. */
|
||||
includeAllOption?: boolean
|
||||
/** Only show periods that have started (Reports-style filter). */
|
||||
hideFuturePeriods?: boolean
|
||||
/** Fires once after the initial period load completes. */
|
||||
onReady?: () => void
|
||||
/** Server-loaded periods for the first render, scoped to initialCompanyId. */
|
||||
initialPeriods?: FiscalPeriod[]
|
||||
initialCompanyId?: string | null
|
||||
className?: string
|
||||
}
|
||||
|
||||
function preparePeriods(periods: FiscalPeriod[], hideFuturePeriods: boolean): FiscalPeriod[] {
|
||||
const today = new Date().toISOString().split('T')[0]
|
||||
return periods
|
||||
.filter((p) => !hideFuturePeriods || p.period_start <= today)
|
||||
.sort((a, b) => b.period_start.localeCompare(a.period_start))
|
||||
}
|
||||
|
||||
/**
|
||||
* Fiscal-year context picker (UI-migration plan PR 3): the chip-dropdown
|
||||
* "Räkenskapsår 2026" with a check on the active choice and closed/locked
|
||||
* years annotated. Same controlled API and per-company localStorage
|
||||
* persistence as FiscalYearSelector, which it replaces page by page from
|
||||
* PR 4 on.
|
||||
*/
|
||||
export function FyPicker({
|
||||
value,
|
||||
onChange,
|
||||
includeAllOption = true,
|
||||
hideFuturePeriods = false,
|
||||
onReady,
|
||||
initialPeriods,
|
||||
initialCompanyId,
|
||||
className,
|
||||
}: FyPickerProps) {
|
||||
const { company } = useCompany()
|
||||
const t = useTranslations('fiscal_year')
|
||||
const canUseInitial = initialCompanyId === company?.id && initialPeriods !== undefined
|
||||
const [periods, setPeriods] = useState<FiscalPeriod[]>(() =>
|
||||
canUseInitial ? preparePeriods(initialPeriods, hideFuturePeriods) : [],
|
||||
)
|
||||
const [loaded, setLoaded] = useState(canUseInitial)
|
||||
|
||||
useEffect(() => {
|
||||
if (!company?.id) {
|
||||
onReady?.()
|
||||
return
|
||||
}
|
||||
let cancelled = false
|
||||
;(async () => {
|
||||
let fetched: FiscalPeriod[]
|
||||
if (initialCompanyId === company.id && initialPeriods !== undefined) {
|
||||
fetched = preparePeriods(initialPeriods, hideFuturePeriods)
|
||||
} else {
|
||||
const res = await fetch('/api/bookkeeping/fiscal-periods')
|
||||
if (!res.ok) {
|
||||
if (!cancelled) {
|
||||
setLoaded(true)
|
||||
onReady?.()
|
||||
}
|
||||
return
|
||||
}
|
||||
const { data } = await res.json()
|
||||
fetched = preparePeriods(data || [], hideFuturePeriods)
|
||||
}
|
||||
if (cancelled) return
|
||||
|
||||
setPeriods(fetched)
|
||||
setLoaded(true)
|
||||
|
||||
// Restore last selection (same key as FiscalYearSelector so pages keep
|
||||
// their scope when the picker swaps in).
|
||||
if (value === null && typeof window !== 'undefined') {
|
||||
const stored = window.localStorage.getItem(STORAGE_KEY_PREFIX + company.id)
|
||||
if (stored === ALL_YEARS_VALUE) {
|
||||
if (includeAllOption) onChange(null, null)
|
||||
else if (fetched.length > 0) onChange(fetched[0].id, fetched[0])
|
||||
} else if (stored && fetched.some((p) => p.id === stored)) {
|
||||
onChange(stored, fetched.find((p) => p.id === stored) ?? null)
|
||||
} else if (!includeAllOption && fetched.length > 0) {
|
||||
onChange(fetched[0].id, fetched[0])
|
||||
}
|
||||
}
|
||||
|
||||
onReady?.()
|
||||
})()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
// onReady is a lifecycle callback: fire once per load, not on parent
|
||||
// re-renders that re-create it.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [company?.id, hideFuturePeriods, includeAllOption, initialCompanyId, initialPeriods])
|
||||
|
||||
const handleChange = (id: string) => {
|
||||
const nextId = id === ALL_YEARS_VALUE ? null : id
|
||||
if (company?.id && typeof window !== 'undefined') {
|
||||
window.localStorage.setItem(STORAGE_KEY_PREFIX + company.id, nextId ?? ALL_YEARS_VALUE)
|
||||
}
|
||||
onChange(nextId, nextId ? periods.find((p) => p.id === nextId) ?? null : null)
|
||||
}
|
||||
|
||||
const annotationFor = (p: FiscalPeriod) =>
|
||||
p.locked_at ? t('badge_locked').toLowerCase() : p.is_closed ? t('badge_closed').toLowerCase() : undefined
|
||||
|
||||
const selected = value ? periods.find((p) => p.id === value) : null
|
||||
// Real period names often already read "Räkenskapsår 2026"; only prefix
|
||||
// the label when the name is a bare year/name so the chip never doubles up.
|
||||
const chipLabel = (p: FiscalPeriod) =>
|
||||
p.name.toLowerCase().includes(t('label').toLowerCase())
|
||||
? p.name
|
||||
: `${t('label')} ${p.name}`
|
||||
const triggerLabel = selected
|
||||
? chipLabel(selected)
|
||||
: includeAllOption
|
||||
? t('all_years')
|
||||
: loaded
|
||||
? t('placeholder')
|
||||
: t('loading')
|
||||
|
||||
const items = [
|
||||
...(includeAllOption ? [{ id: ALL_YEARS_VALUE, label: t('all_years') }] : []),
|
||||
...periods.map((p) => ({
|
||||
id: p.id,
|
||||
label: p.name,
|
||||
annotation: annotationFor(p),
|
||||
})),
|
||||
]
|
||||
|
||||
return (
|
||||
<ContextPicker
|
||||
items={items}
|
||||
value={value ?? (includeAllOption ? ALL_YEARS_VALUE : null)}
|
||||
onChange={handleChange}
|
||||
triggerLabel={triggerLabel}
|
||||
disabled={!loaded || periods.length === 0}
|
||||
ariaLabel={t('label')}
|
||||
className={className}
|
||||
/>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user