fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
masterplan-lock / check (push) Successful in 19s
ci / sonar (push) Failing after 21s
security / scan (push) Failing after 1m37s

Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i
server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma
strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
2026-11-10 09:37:22 +01:00
parent 077251ac94
commit e7f0070e84
6135 changed files with 1718997 additions and 4 deletions
@@ -0,0 +1,73 @@
import { describe, it, expect } from 'vitest'
import fs from 'node:fs'
import path from 'node:path'
const repoRoot = path.resolve(__dirname, '..', '..', '..')
function collectTsxFiles(dir: string, out: string[] = []): string[] {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
if (entry.name === 'node_modules' || entry.name.startsWith('.')) continue
const full = path.join(dir, entry.name)
if (entry.isDirectory()) {
collectTsxFiles(full, out)
} else if (entry.name.endsWith('.tsx')) {
out.push(full)
}
}
return out
}
function isClientComponent(source: string): boolean {
return /^\s*(['"])use client\1/.test(source)
}
/**
* EmptyState is a Client Component and its `icon` prop is a COMPONENT
* reference (`icon?: LucideIcon`), not an element. lucide builds every icon
* with forwardRef, so a Server Component that passes `icon={SomeIcon}` hands
* Flight a raw function and the render throws before the page ever reaches the
* browser: /byra/kpi 500'd into the dashboard error boundary for exactly this
* reason (digest 1621801304), and only for byråer with zero client companies,
* so it slipped through every manual pass.
*
* The sanctioned shape is a prop-free preset in empty-state.tsx: a client
* component reference IS serializable, and the icon never crosses a boundary.
*/
describe('EmptyState icon prop never crosses the RSC boundary', () => {
it('is only passed from client components', () => {
const files = [
...collectTsxFiles(path.join(repoRoot, 'app')),
...collectTsxFiles(path.join(repoRoot, 'components')),
]
const offenders = files.filter((file) => {
const source = fs.readFileSync(file, 'utf8')
if (isClientComponent(source)) return false
// `[^>]*` keeps the match inside a single JSX element, newlines included.
return /<EmptyState\b[^>]*\bicon=\{/.test(source)
})
expect(offenders.map((f) => path.relative(repoRoot, f))).toEqual([])
})
})
describe('byrå KPI empty state', () => {
const pagePath = path.join(repoRoot, 'app', '(dashboard)', 'byra', 'kpi', 'page.tsx')
it('renders the preset from the server page instead of passing an icon', () => {
const source = fs.readFileSync(pagePath, 'utf8')
expect(isClientComponent(source)).toBe(false)
expect(source).toMatch(/<EmptyByraClients\s*\/>/)
expect(source).not.toMatch(/from 'lucide-react'/)
})
it('keeps the icon and the copy in the preset', () => {
const source = fs.readFileSync(path.join(repoRoot, 'components', 'ui', 'empty-state.tsx'), 'utf8')
expect(source).toMatch(/export function EmptyByraClients\(\)/)
expect(source).toMatch(/icon=\{TrendingUp\}/)
// Variable-agnostic: the preset reads from the `byra` namespace under its
// own translator name, so assert the keys, not the caller's identifier.
expect(source).toMatch(/\w+\('kpi_empty_title'\)/)
expect(source).toMatch(/\w+\('kpi_empty_description'\)/)
})
})
@@ -0,0 +1,64 @@
import { describe, it, expect } from 'vitest'
import { createElement, isValidElement } from 'react'
import { coerceToastNode } from '../toaster'
/**
* The Toaster is a sibling of {children} in the ROOT layout, so a throw here
* escapes both app/error.tsx and app/(dashboard)/error.tsx and lands on
* global-error, blanking the whole app (and, because global-error reloads
* once, pinning the user on the fallback for that path).
*
* Call sites that forward an unchecked `await res.json()` field pass the
* canonical `{ code, message, … }` envelope OBJECT instead of a string, which
* React refuses to render. This coercion is the choke point.
*/
describe('coerceToastNode', () => {
it('passes strings and numbers through untouched', () => {
expect(coerceToastNode('Kunde inte spara')).toBe('Kunde inte spara')
expect(coerceToastNode(42)).toBe(42)
})
it('passes null/undefined through so the description simply does not render', () => {
expect(coerceToastNode(null)).toBeNull()
expect(coerceToastNode(undefined)).toBeUndefined()
})
it('keeps React elements renderable', () => {
const el = createElement('span', null, 'hej')
expect(coerceToastNode(el)).toBe(el)
expect(isValidElement(coerceToastNode(el))).toBe(true)
})
it('turns a canonical error envelope into a readable string instead of throwing', () => {
const result = coerceToastNode({
code: 'NOT_FOUND',
message: 'Leverantören hittades inte',
} as unknown as React.ReactNode)
expect(typeof result).toBe('string')
expect(result).toBe('Leverantören hittades inte')
})
it('turns any other object into a string rather than a React child throw', () => {
const result = coerceToastNode({ requestId: 'abc' } as unknown as React.ReactNode)
expect(typeof result).toBe('string')
expect((result as string).length).toBeGreaterThan(0)
})
it('coerces objects nested inside an array child', () => {
const el = createElement('span', { key: 'a' }, 'hej')
const result = coerceToastNode([
'text',
{ code: 'NOT_FOUND', message: 'Hittades inte' },
el,
] as unknown as React.ReactNode) as unknown[]
expect(result[0]).toBe('text')
expect(result[1]).toBe('Hittades inte')
// Elements pass through by identity so their keys survive.
expect(result[2]).toBe(el)
})
it('drops booleans, which React would render as nothing anyway', () => {
expect(coerceToastNode(true)).toBeNull()
expect(coerceToastNode(false)).toBeNull()
})
})
+133
View File
@@ -0,0 +1,133 @@
'use client'
import { useMemo } from 'react'
import { getAccountDescription, type AccountType } from '@/lib/bookkeeping/account-descriptions'
import { useBasReference } from '@/lib/bookkeeping/use-bas-reference'
import { useAccounts } from '@/lib/reference-data/hooks'
import {
Tooltip,
TooltipTrigger,
TooltipContent,
} from '@/components/ui/info-tooltip'
import { cn } from '@/lib/utils'
const TYPE_COLORS: Record<AccountType, string> = {
asset: 'bg-success',
liability: 'bg-warning',
equity: 'bg-primary',
revenue: 'bg-muted-foreground',
expense: 'bg-destructive',
untaxed_reserves: 'bg-warning',
}
const TYPE_LABELS: Record<AccountType, string> = {
asset: 'Tillgång',
liability: 'Skuld',
equity: 'Eget kapital',
revenue: 'Intäkt',
expense: 'Kostnad',
untaxed_reserves: 'Obeskattade reserver',
}
interface AccountNumberProps {
number: string
name?: string
showName?: boolean
size?: 'sm' | 'default'
className?: string
}
export function AccountNumber({
number,
name,
showName,
size = 'default',
className,
}: AccountNumberProps) {
// Loads the BAS chart chunk after mount and re-renders once names and
// descriptions for non-hardcoded accounts are available.
useBasReference()
// Inactive accounts included: historical verifikat keep referencing them
// long after they leave the active chart.
const { accounts } = useAccounts(false)
const companyName = useMemo(
() => accounts.find((a) => a.account_number === number)?.account_name,
[accounts, number],
)
const desc = getAccountDescription(number)
// The company's own account name wins over the BAS reference name: a chart
// row is user-editable data and must never be visually overridden by our
// hardcoded copy. Call sites that already know the row pass `name`; the
// rest (verifikat views) fall back to the shared reference-data cache, so
// off-catalog accounts (e.g. SIE-imported 1580) still get their names.
// The tooltip still shows the BAS name as reference.
const displayName = name || companyName || desc?.name
const numberElement = (
<span
className={cn(
'font-mono',
size === 'sm' ? 'text-xs' : 'text-sm',
className,
)}
>
{number}
</span>
)
if (!desc) {
return (
<>
{numberElement}
{showName && displayName && (
<span className="ml-1">{displayName}</span>
)}
</>
)
}
return (
<Tooltip>
<TooltipTrigger asChild>
<span
className={cn(
'inline-flex items-center gap-1 cursor-help',
'decoration-dotted underline underline-offset-4 decoration-muted-foreground/40',
)}
>
<span
className={cn(
'font-mono',
size === 'sm' ? 'text-xs' : 'text-sm',
className,
)}
>
{number}
</span>
{showName && displayName && (
<span className={size === 'sm' ? 'text-xs' : 'text-sm'}>
{displayName}
</span>
)}
</span>
</TooltipTrigger>
<TooltipContent side="top" className="max-w-xs p-3">
<div className="space-y-1.5">
<div className="flex items-center gap-2">
<span className={cn('h-2 w-2 rounded-full shrink-0', TYPE_COLORS[desc.type])} />
<span className="text-xs text-muted-foreground">
{desc.classLabel} &middot; {TYPE_LABELS[desc.type]}
</span>
</div>
<div className="font-medium">
<span className="font-mono mr-1.5">{number}</span>
{desc.name}
</div>
<p className="text-xs text-muted-foreground leading-relaxed">
{desc.explanation}
</p>
</div>
</TooltipContent>
</Tooltip>
)
}
+41
View File
@@ -0,0 +1,41 @@
'use client'
import { cn } from '@/lib/utils'
interface Props {
// When true, render the dot. The parent owns the "did this value come from
// AI extraction?" question: usually by comparing the current input value
// against the originally-prefilled value, and clearing the flag once the
// user edits the field.
active: boolean
// Visible label next to the dot. Defaults to none (just the dot, with
// tooltip text on hover). Set to "AI-fyllt" or similar when the field
// has room.
label?: string
className?: string
// Tooltip / aria-label for the dot.
title?: string
}
// Tiny indicator that a form field's value was pre-filled by the AI
// extraction pipeline. Sits to the right of the field label or inside the
// input's right padding. Fades when the user edits the field: see how
// supplier-invoices/new wires it.
//
// Design: a small filled dot, success color when the extraction succeeded.
// Optional uppercase micro-label for forms where space allows.
export default function AiFilledIndicator({ active, label, className, title }: Props) {
if (!active) return null
return (
<span
title={title ?? 'Värdet är ifyllt av AI baserat på dokumentet'}
className={cn(
'inline-flex items-center gap-1 text-[10px] uppercase tracking-wider text-muted-foreground',
className,
)}
>
<span aria-hidden className="inline-block h-1.5 w-1.5 rounded-full bg-success" />
{label ?? <span className="sr-only">AI-fyllt</span>}
</span>
)
}
+50
View File
@@ -0,0 +1,50 @@
import Link from 'next/link'
import { cn } from '@/lib/utils'
interface AttnLineProps {
children: React.ReactNode
/** Optional inline action at the end of the sentence. */
action?: { label: string; href?: string; onClick?: () => void }
/**
* Optional quiet controls rendered inside the sentence after the action
* (e.g. the notice line's "+N till" expander and dismiss). Style them
* muted; the ochre tone belongs to the sentence and its action alone.
*/
trailing?: React.ReactNode
className?: string
}
/**
* Attention is one ochre sentence, not a banner (UI-migration convention 6):
* a single 12.5px line in the attn tone with an optional embedded action
* link. Max one per page.
*/
export function AttnLine({ children, action, trailing, className }: AttnLineProps) {
return (
<p className={cn('text-[12.5px] leading-5 text-attn', className)}>
{children}
{action && (
<>
{' '}
{action.href ? (
<Link
href={action.href}
className="underline underline-offset-2 hover:opacity-80"
>
{action.label}
</Link>
) : (
<button
type="button"
onClick={action.onClick}
className="underline underline-offset-2 hover:opacity-80"
>
{action.label}
</button>
)}
</>
)}
{trailing}
</p>
)
}
+45
View File
@@ -0,0 +1,45 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
// Chips are pills (concept .chip): 99px radius, 11.5px, quiet padding.
const badgeVariants = cva(
"inline-flex items-center rounded-full border px-2.5 py-[3px] text-[11.5px] font-medium leading-none transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary/10 text-primary",
secondary:
"border-transparent bg-secondary text-secondary-foreground",
destructive:
"border-transparent bg-destructive/10 text-destructive",
outline:
"border-border text-foreground bg-transparent",
success:
"border-transparent bg-success/10 text-success",
// No amber fill: status colors are data, not chrome (convention 12).
// The exception reads through the ochre text on a hairline chip.
warning:
"border-border bg-transparent text-attn",
},
},
defaultVariants: {
variant: "default",
},
}
)
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
// data-ph-unmask: status chips are static i18n chrome in session replays;
// a badge carrying user data adds data-ph-mask at the call site.
return (
<div data-ph-unmask="" className={cn(badgeVariants({ variant }), className)} {...props} />
)
}
export { Badge, badgeVariants }
+72
View File
@@ -0,0 +1,72 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
// Buttons are pills (radius 99px): a deliberate app-wide divergence from the
// shadcn 8px default, locked in the UI-migration conventions. Change it here,
// never per call site.
const buttonVariants = cva(
"inline-flex items-center justify-center whitespace-nowrap rounded-full font-medium transition-colors duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-50",
{
variants: {
variant: {
// active: mirrors hover: on every variant. Tailwind 4 gates hover:
// behind (hover: hover), so on touch devices these are the only
// pointer-down feedback a button gives.
default:
"bg-primary text-primary-foreground hover:bg-primary/90 active:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90 active:bg-destructive/90",
outline:
"border border-input bg-transparent hover:bg-secondary active:bg-secondary",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/70 active:bg-secondary/70",
ghost:
"hover:bg-secondary hover:text-secondary-foreground active:bg-secondary active:text-secondary-foreground",
link:
"text-primary underline-offset-4 hover:underline active:underline",
success:
"bg-success text-success-foreground hover:bg-success/90 active:bg-success/90",
},
size: {
default: "px-4 py-[7px] text-[13px]",
sm: "h-9 px-4 text-xs",
lg: "h-11 px-8 text-base",
icon: "h-10 w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
// data-ph-unmask: button labels are static i18n chrome in session
// replays. Combobox-style triggers render a selected VALUE (user data),
// so they stay masked; a call site whose label carries user data adds
// data-ph-mask, which wins over unmask on the same element.
const phUnmask = props.role === "combobox" ? {} : { "data-ph-unmask": "" }
return (
<Comp
{...phUnmask}
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
)
}
)
Button.displayName = "Button"
export { Button, buttonVariants }
+82
View File
@@ -0,0 +1,82 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"rounded-lg border border-border bg-card text-card-foreground",
className
)}
{...props}
/>
))
Card.displayName = "Card"
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 p-6", className)}
{...props}
/>
))
CardHeader.displayName = "CardHeader"
const CardTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
// data-ph-unmask: card titles are static i18n chrome in session replays;
// a title carrying user data adds data-ph-mask at the call site.
<h3
ref={ref}
data-ph-unmask=""
className={cn(
"font-display text-xl leading-none tracking-tight",
className
)}
{...props}
/>
))
CardTitle.displayName = "CardTitle"
const CardDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<p
ref={ref}
data-ph-unmask=""
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
CardDescription.displayName = "CardDescription"
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
))
CardContent.displayName = "CardContent"
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
))
CardFooter.displayName = "CardFooter"
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
+29
View File
@@ -0,0 +1,29 @@
"use client"
import * as React from "react"
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
import { Check } from "lucide-react"
import { cn } from "@/lib/utils"
const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(({ className, ...props }, ref) => (
<CheckboxPrimitive.Root
ref={ref}
className={cn(
"peer h-4 w-4 shrink-0 rounded-sm border border-input transition-colors duration-200 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/35 focus-visible:border-primary/60 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:border-primary data-[state=checked]:text-primary-foreground hover:border-primary/50",
className
)}
{...props}
>
<CheckboxPrimitive.Indicator
className={cn("flex items-center justify-center text-current")}
>
<Check className="h-3 w-3" strokeWidth={3} />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
))
Checkbox.displayName = CheckboxPrimitive.Root.displayName
export { Checkbox }
+104
View File
@@ -0,0 +1,104 @@
'use client'
import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { cn } from '@/lib/utils'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Loader2 } from 'lucide-react'
interface ConfirmDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
title: string
/**
* Body text that DESCRIBES THE OUTCOME up front ("Bokförs som verifikat
* A-217 med 1 250,00 kr ...") instead of the page commenting afterwards
* (UI-migration convention 10).
*/
description?: React.ReactNode
/** Optional richer body (e.g. a kontering preview) rendered below the description. */
children?: React.ReactNode
confirmLabel: string
cancelLabel?: string
/** Await-able: the dialog shows a pending state until the promise settles. */
onConfirm: () => void | Promise<void>
/** Terracotta confirm for destructive outcomes (avvisa, makulera). */
destructive?: boolean
}
/**
* Small centered confirmation dialog (min 460px on desktop): confirm before
* acting, describing the outcome, rather than commenting after the fact.
*/
export function ConfirmDialog({
open,
onOpenChange,
title,
description,
children,
confirmLabel,
cancelLabel,
onConfirm,
destructive = false,
}: ConfirmDialogProps) {
const tCommon = useTranslations('common')
const [pending, setPending] = useState(false)
const handleConfirm = async () => {
try {
setPending(true)
await onConfirm()
onOpenChange(false)
} finally {
setPending(false)
}
}
return (
<Dialog open={open} onOpenChange={(next) => !pending && onOpenChange(next)}>
<DialogContent className="sm:min-w-[460px] sm:max-w-md">
<DialogHeader>
{/* data-ph-mask: confirm dialogs describe the object being acted
on (convention 10), so title and description are user data in
session replays, not chrome. Mask wins over the primitives'
own data-ph-unmask. */}
<DialogTitle data-ph-mask="" className="font-display text-lg tracking-tight">
{title}
</DialogTitle>
{description && (
<DialogDescription data-ph-mask="" className="text-[13px] leading-relaxed">
{description}
</DialogDescription>
)}
</DialogHeader>
{children}
<DialogFooter className="gap-2 sm:gap-2">
<Button
variant="ghost"
onClick={() => onOpenChange(false)}
disabled={pending}
>
{cancelLabel ?? tCommon('cancel')}
</Button>
<Button
variant={destructive ? 'destructive' : 'default'}
onClick={() => void handleConfirm()}
disabled={pending}
className={cn(pending && 'cursor-wait')}
>
{pending && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
{confirmLabel}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
+105
View File
@@ -0,0 +1,105 @@
'use client'
import { ReactNode, useRef } from 'react'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { AttnLine } from '@/components/ui/attn-line'
import { ClipboardCheck, Loader2 } from 'lucide-react'
interface ConfirmationDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
onConfirm: () => void
isSubmitting: boolean
title: string
warningText?: string
confirmLabel?: string
extraActions?: ReactNode
children: ReactNode
// When true, initial focus lands on the confirm button so Enter fires the
// primary action. Opt-in: never arm Enter on unrelated/destructive dialogs.
autoFocusConfirm?: boolean
}
export function ConfirmationDialog({
open,
onOpenChange,
onConfirm,
isSubmitting,
title,
// No default warning: an accounting-immutability sentence used to be baked
// in here, which put it into dialogs whose authors never asked for one.
// Callers that commit a voucher directly pass their own warningText.
warningText,
confirmLabel = 'Bekräfta & skapa',
extraActions,
children,
autoFocusConfirm,
}: ConfirmationDialogProps) {
const confirmRef = useRef<HTMLButtonElement>(null)
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
className="sm:max-w-2xl border-t-2 border-primary p-0 gap-0 max-h-[95dvh] sm:max-h-[90dvh] flex flex-col"
onOpenAutoFocus={autoFocusConfirm ? (e) => {
e.preventDefault()
confirmRef.current?.focus()
} : undefined}
>
<DialogHeader className="px-4 sm:px-6 pt-4 sm:pt-6 pb-3 sm:pb-4 shrink-0">
<div className="flex items-center gap-3">
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary/10 shrink-0">
<ClipboardCheck className="h-5 w-5 text-primary" />
</div>
<div>
{/* data-ph-mask on the title: confirm dialogs describe the
object being acted on (convention 10), so the title is user
data in session replays. The description is a static
sentence and stays readable. */}
<DialogTitle data-ph-mask="" className="text-lg sm:text-xl">{title}</DialogTitle>
<DialogDescription>Granska uppgifterna innan du bekräftar</DialogDescription>
</div>
</div>
</DialogHeader>
<div className="overflow-y-auto flex-1 min-h-0 px-4 sm:px-6 pb-4">
{children}
</div>
<div className="border-t px-4 sm:px-6 py-3 sm:py-4 space-y-3 sm:space-y-4 shrink-0">
{/* Attention is one ochre sentence, not a banner (convention 6). */}
{warningText && <AttnLine>{warningText}</AttnLine>}
<DialogFooter>
<Button
variant="outline"
onClick={() => onOpenChange(false)}
disabled={isSubmitting}
className="min-h-11 w-full sm:w-auto"
>
Tillbaka
</Button>
{extraActions}
<Button ref={confirmRef} onClick={onConfirm} disabled={isSubmitting} className="min-h-11 w-full sm:w-auto">
{isSubmitting ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Skapar...
</>
) : (
confirmLabel
)}
</Button>
</DialogFooter>
</div>
</DialogContent>
</Dialog>
)
}
+208
View File
@@ -0,0 +1,208 @@
import * as React from "react"
import { cn } from "@/lib/utils"
/**
* DataList: unified list surface (one bordered container, hairline rows).
*
* Replaces the per-row Card pattern across Granskning, Transactions, and
* similar list pages. Visual contract is flat-with-hairlines per CLAUDE.md:
* no shadows on the container, no state-tinted borders, secondary token for
* selected/hover.
*/
const DataList = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"rounded-lg border border-border bg-card text-card-foreground overflow-hidden [&>*]:border-b [&>*]:border-border [&>*:last-child]:border-b-0",
className
)}
{...props}
/>
))
DataList.displayName = "DataList"
const DataListHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"flex flex-wrap items-center gap-3 border-b border-border bg-secondary/40 px-4 py-2",
className
)}
{...props}
/>
))
DataListHeader.displayName = "DataListHeader"
interface DataListRowProps extends React.HTMLAttributes<HTMLDivElement> {
leading?: React.ReactNode
trailing?: React.ReactNode
selected?: boolean
expanded?: boolean
expandedContent?: React.ReactNode
rowClassName?: string
}
const DataListRow = React.forwardRef<HTMLDivElement, DataListRowProps>(
(
{
className,
leading,
trailing,
selected,
expanded,
expandedContent,
rowClassName,
onClick,
children,
...props
},
ref
) => {
const isInteractive = Boolean(onClick)
return (
<div
ref={ref}
className={cn(
"transition-colors",
selected ? "bg-secondary/50" : "hover:bg-secondary/40",
className
)}
{...props}
>
<div
className={cn(
"flex items-start gap-3 px-4 py-3",
isInteractive && "cursor-pointer",
rowClassName
)}
onClick={onClick}
>
{leading != null && (
<div className="flex shrink-0 items-center pt-0.5">{leading}</div>
)}
<div className="min-w-0 flex-1">{children}</div>
{trailing != null && (
<div className="flex shrink-0 items-center gap-3">{trailing}</div>
)}
</div>
{expandedContent != null && (
<div
className={cn(
"grid transition-[grid-template-rows] duration-200 motion-reduce:transition-none",
expanded ? "grid-rows-[1fr]" : "grid-rows-[0fr]"
)}
>
<div className="overflow-hidden">
<div className="border-t border-border bg-secondary/20 px-4 py-3">
{expandedContent}
</div>
</div>
</div>
)}
</div>
)
}
)
DataListRow.displayName = "DataListRow"
const DataListPrimary = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<p
ref={ref}
className={cn("truncate text-sm font-medium leading-snug", className)}
{...props}
/>
))
DataListPrimary.displayName = "DataListPrimary"
const DataListMeta = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"mt-0.5 flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-xs text-muted-foreground",
className
)}
{...props}
/>
))
DataListMeta.displayName = "DataListMeta"
const DataListMetaSeparator = () => (
<span className="text-muted-foreground/50" aria-hidden>
·
</span>
)
DataListMetaSeparator.displayName = "DataListMetaSeparator"
interface DataListEmptyProps {
icon?: React.ReactNode
/** Chrome in session replays (data-ph-unmask): wrap any user data (e.g. a
search term) in a data-ph-mask element. */
title: React.ReactNode
description?: React.ReactNode
action?: React.ReactNode
className?: string
}
const DataListEmpty = ({
icon,
title,
description,
action,
className,
}: DataListEmptyProps) => (
// data-ph-unmask: list empty states are static i18n chrome in session replays.
<div
data-ph-unmask=""
className={cn(
"flex flex-col items-center justify-center px-6 py-16 text-center",
className
)}
>
{icon != null && (
<div className="mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-muted text-muted-foreground">
{icon}
</div>
)}
<p className="font-medium">{title}</p>
{description != null && (
<p className="mt-1 max-w-sm text-sm text-muted-foreground">{description}</p>
)}
{action != null && <div className="mt-4">{action}</div>}
</div>
)
DataListEmpty.displayName = "DataListEmpty"
const DataListLoading = ({ className }: { className?: string }) => (
<div
className={cn(
"flex items-center justify-center px-6 py-16 text-muted-foreground",
className
)}
>
<span className="inline-block h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent motion-reduce:animate-none" />
</div>
)
DataListLoading.displayName = "DataListLoading"
export {
DataList,
DataListHeader,
DataListRow,
DataListPrimary,
DataListMeta,
DataListMetaSeparator,
DataListEmpty,
DataListLoading,
}
@@ -0,0 +1,224 @@
'use client'
import { useState, useCallback, useRef } from 'react'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { AlertTriangle, Loader2 } from 'lucide-react'
import { cn } from '@/lib/utils'
interface DestructiveConfirmDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
title: string
description: string
confirmLabel?: string
cancelLabel?: string
variant?: 'destructive' | 'warning'
onConfirm: () => void | Promise<void>
}
export function DestructiveConfirmDialog({
open,
onOpenChange,
title,
description,
confirmLabel = 'Bekräfta',
cancelLabel = 'Avbryt',
variant = 'destructive',
onConfirm,
}: DestructiveConfirmDialogProps) {
const [isLoading, setIsLoading] = useState(false)
const handleConfirm = async () => {
setIsLoading(true)
try {
await onConfirm()
} finally {
setIsLoading(false)
onOpenChange(false)
}
}
return (
<Dialog
open={open}
onOpenChange={(v) => {
if (isLoading) return
onOpenChange(v)
}}
>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<div className="flex items-start gap-4">
<div
className={cn(
'flex-shrink-0 flex items-center justify-center h-10 w-10 rounded-full',
variant === 'destructive'
? 'bg-destructive/10 text-destructive'
: 'bg-muted text-attn'
)}
>
<AlertTriangle className="h-5 w-5" />
</div>
<div className="space-y-1">
{/* data-ph-mask: confirm dialogs describe the object being
acted on (convention 10), so title and description are user
data in session replays, not chrome. */}
<DialogTitle data-ph-mask="">{title}</DialogTitle>
{/* pre-line so callers can pass newline-separated paragraphs
(e.g. the salary unapprove confirm assembles its copy
dynamically); single-line descriptions render unchanged. */}
<DialogDescription data-ph-mask="" className="whitespace-pre-line">
{description}
</DialogDescription>
</div>
</div>
</DialogHeader>
<DialogFooter className="gap-2 sm:gap-0">
<Button
variant="outline"
onClick={() => onOpenChange(false)}
disabled={isLoading}
className="min-h-11 w-full sm:w-auto"
>
{cancelLabel}
</Button>
{/* Warning-variant confirms use the default primary button: in
chrome only --destructive survives as a colored action. */}
<Button
variant={variant === 'destructive' ? 'destructive' : 'default'}
onClick={handleConfirm}
disabled={isLoading}
className="min-h-11 w-full sm:w-auto"
>
{isLoading ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : null}
{confirmLabel}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
interface ConfirmOptions {
title: string
description: string
confirmLabel?: string
cancelLabel?: string
variant?: 'destructive' | 'warning'
}
interface UseDestructiveConfirmReturn {
dialogProps: DestructiveConfirmDialogProps
confirm: (options: ConfirmOptions, action?: () => void | Promise<void>) => Promise<boolean>
}
/**
* Hook that returns a `confirm()` function as a drop-in replacement for `window.confirm()`.
* Returns `Promise<boolean>`: true if user confirms, false if they cancel.
*
* Pass the destructive operation itself as the second argument to run it
* INSIDE the confirm: the dialog stays open with its pending spinner (and
* blocks dismissal) until the action settles, instead of closing on click and
* leaving the fetch to run with no visible state anywhere. The action owns its
* own error feedback (toast); if it throws, `confirm` resolves `false` so a
* caller's success tail is skipped.
*
* Usage:
* ```
* const { dialogProps, confirm } = useDestructiveConfirm()
*
* async function handleDelete() {
* const ok = await confirm({ title: '...', description: '...' }, async () => {
* // the DELETE runs while the dialog shows its spinner
* })
* if (!ok) return
* // confirmed and the action completed
* }
*
* return <><DestructiveConfirmDialog {...dialogProps} /></>
* ```
*/
export function useDestructiveConfirm(): UseDestructiveConfirmReturn {
const [open, setOpen] = useState(false)
const [options, setOptions] = useState<ConfirmOptions>({
title: '',
description: '',
})
const resolveRef = useRef<((value: boolean) => void) | null>(null)
const actionRef = useRef<(() => void | Promise<void>) | null>(null)
const runningRef = useRef(false)
const confirm = useCallback(
(opts: ConfirmOptions, action?: () => void | Promise<void>): Promise<boolean> => {
setOptions(opts)
actionRef.current = action ?? null
setOpen(true)
return new Promise<boolean>((resolve) => {
resolveRef.current = resolve
})
},
[],
)
const handleOpenChange = useCallback((v: boolean) => {
setOpen(v)
if (!v) {
actionRef.current = null
if (resolveRef.current) {
resolveRef.current(false)
resolveRef.current = null
}
}
}, [])
const handleConfirm = useCallback(async () => {
// Re-entry guard: a second confirm firing while the action is still in
// flight must not resolve the promise early (the dialog disables its
// button on isLoading, this covers the same-tick edge).
if (runningRef.current) return
runningRef.current = true
const action = actionRef.current
actionRef.current = null
let completed = true
if (action) {
try {
// Awaited by the dialog's own handleConfirm, so its isLoading spinner
// shows for the duration and the dialog closes only when this settles.
await action()
} catch {
// The action surfaces its own error (toast); resolving false here
// keeps the caller's post-confirm tail from running on a failure.
completed = false
}
}
if (resolveRef.current) {
resolveRef.current(completed)
resolveRef.current = null
}
runningRef.current = false
}, [])
return {
dialogProps: {
open,
onOpenChange: handleOpenChange,
title: options.title,
description: options.description,
confirmLabel: options.confirmLabel,
cancelLabel: options.cancelLabel,
variant: options.variant,
onConfirm: handleConfirm,
},
confirm,
}
}
+73
View File
@@ -0,0 +1,73 @@
import { cn } from '@/lib/utils'
/**
* Register-detail document grammar (customers, suppliers, articles).
*
* A detail page is one flowing document, not a pile of cards: each group of
* facts is introduced by an uppercase hairline kicker and set as aligned
* label/value rows. The kicker's hairline is the only rule; groups are
* separated by whitespace, never borders (Living Paper, design.md).
*/
export function DetailSection({
kicker,
help,
aside,
children,
className,
}: {
kicker: string
/** Section help behind a "?" right after the kicker (convention 7). Pass a <HelpPopover>. */
help?: React.ReactNode
/** Optional right-aligned element on the kicker line: a count, a quiet action. */
aside?: React.ReactNode
children: React.ReactNode
className?: string
}) {
return (
<section className={className}>
<div className="flex items-baseline justify-between gap-4 border-b border-border pb-2">
{/* data-ph-unmask: kickers are static i18n chrome in session replays. */}
<h2 data-ph-unmask="" className="flex items-center gap-2 text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
{kicker}
{help}
</h2>
{aside}
</div>
<div className="mt-3">{children}</div>
</section>
)
}
export function DefRow({
label,
children,
className,
}: {
label: string
children: React.ReactNode
className?: string
}) {
return (
<div
className={cn(
'grid grid-cols-[8rem_1fr] gap-x-6 py-2 text-sm sm:grid-cols-[10rem_1fr]',
className,
)}
>
{/* data-ph-unmask on the label only: values (children) are user data
and stay masked in session replays. */}
<div data-ph-unmask="" className="text-muted-foreground">{label}</div>
<div className="min-w-0">{children}</div>
</div>
)
}
/**
* Muted placeholder for a value that matters but is not filled in. The en dash
* is the literal rendered value (same vocabulary as the orders list), which is
* why it is allowed to be a dash at all.
*/
export function DefEmpty() {
return <span className="text-muted-foreground">{'–'}</span>
}
+23
View File
@@ -0,0 +1,23 @@
'use client'
import { useTranslations } from 'next-intl'
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'
import { Skeleton } from '@/components/ui/skeleton'
export function DialogLoadingSkeleton() {
const t = useTranslations('common')
return (
<Dialog open>
<DialogContent className="sm:max-w-2xl">
<DialogTitle className="sr-only">{t('loading')}</DialogTitle>
<div className="space-y-4 py-4" role="status">
<Skeleton className="h-7 w-48" />
<Skeleton className="h-10 w-full" />
<Skeleton className="h-10 w-full" />
<Skeleton className="h-24 w-full" />
</div>
</DialogContent>
</Dialog>
)
}
+194
View File
@@ -0,0 +1,194 @@
"use client"
import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
const Dialog = DialogPrimitive.Root
const DialogTrigger = DialogPrimitive.Trigger
const DialogPortal = DialogPrimitive.Portal
const DialogClose = DialogPrimitive.Close
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-black/50 dark:bg-black/60 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
/>
))
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, onInteractOutside, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
// Companion overlays (AccountCombobox's dropdown, HelpPopover panels)
// are portaled to document.body so this content's overflow-y-auto can
// never clip them. DOM-wise that puts them OUTSIDE the dialog, so Radix
// would otherwise dismiss the dialog on a pointerdown inside them:
// anything marked data-dialog-companion counts as inside. The agent
// sheet and its trigger (data-agent-ui) count as inside for the same
// reason: writing to the assistant must never dismiss a dialog.
onInteractOutside={(event) => {
onInteractOutside?.(event)
const target = event.target
if (target instanceof Element && target.closest('[data-dialog-companion], [data-agent-ui]')) {
event.preventDefault()
}
}}
className={cn(
// grid-cols-[minmax(0,1fr)]: the implicit auto track sizes to the widest
// child's min-content, and nowrap text (truncate) counts at full width
// there, so one long description widens every sibling past the dialog
// edge. minmax(0,1fr) caps the track at the content box.
// left: centered in the viewport MINUS the docked agent sheet.
// --agent-sheet-w exists as an inline var on <html> ONLY while the
// sheet is docked open (AgentSheetProvider); closed/floating falls to
// the 0px fallback, making this exactly left-[50%]. Do NOT read
// --agent-dock-w here: globals.css seeds that at 10px permanently.
// Without the shift a wide dialog centers under the sheet and its
// right edge becomes unreachable (sheet is z-60).
"fixed left-[calc((100vw-var(--agent-sheet-w,0px))/2)] top-[50%] z-50 grid grid-cols-[minmax(0,1fr)] w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-[var(--shadow-md)] max-h-[calc(100dvh-2rem)] overflow-y-auto scrollbar-visible data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-98 data-[state=open]:zoom-in-98 sm:rounded-xl",
className
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
))
DialogContent.displayName = DialogPrimitive.Content.displayName
/**
* Backdrop for non-modal dialogs. Radix renders no Overlay when the root has
* `modal={false}`, so dialogs that opt out of modality (to keep the agent
* sheet interactive above them) render this alongside DialogContent to keep
* the standard veil. z-40 sits under DialogContent (z-50) and the agent
* sheet (z-60).
*/
const DialogVeil = () => (
<DialogPortal>
<div
aria-hidden="true"
className="fixed inset-0 z-40 bg-black/50 dark:bg-black/60 animate-in fade-in-0"
/>
</DialogPortal>
)
// Ref-counted so overlapping non-modal dialogs (e.g. the template picker
// closing in the same commit as the booking dialog opens) cannot fight over
// the flag: the shell stays inert until the LAST open dialog releases it.
let dashShellInertCount = 0
/**
* Hand-rolled page modality for `modal={false}` dialogs. Radix non-modal mode
* drops the focus trap, aria-hiding, and body pointer-events lock, so the
* page behind the DialogVeil would stay keyboard/AT/tap-reachable. `inert` on
* the dash shell blocks all of that while the agent sheet and its trigger
* (both outside the shell) stay live. Pair with DialogVeil.
*/
const useDashShellInert = (open: boolean) => {
React.useEffect(() => {
if (!open) return
const shell = document.getElementById('dash-shell')
if (!shell) return
dashShellInertCount++
shell.inert = true
return () => {
dashShellInertCount--
if (dashShellInertCount <= 0) shell.inert = false
}
}, [open])
}
const DialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-1.5 text-center sm:text-left",
className
)}
{...props}
/>
)
DialogHeader.displayName = "DialogHeader"
const DialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end sm:space-x-2 sm:gap-0",
className
)}
{...props}
/>
)
DialogFooter.displayName = "DialogFooter"
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
// data-ph-unmask: dialog titles are static i18n chrome in session replays;
// a title carrying user data adds data-ph-mask at the call site.
<DialogPrimitive.Title
ref={ref}
data-ph-unmask=""
className={cn(
"break-words text-lg leading-none tracking-tight",
className
)}
{...props}
/>
))
DialogTitle.displayName = DialogPrimitive.Title.displayName
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
data-ph-unmask=""
className={cn("break-words text-sm text-muted-foreground", className)}
{...props}
/>
))
DialogDescription.displayName = DialogPrimitive.Description.displayName
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogClose,
DialogTrigger,
DialogContent,
DialogVeil,
useDashShellInert,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
}
+108
View File
@@ -0,0 +1,108 @@
"use client"
import * as React from "react"
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
import { Check } from "lucide-react"
import { cn } from "@/lib/utils"
const DropdownMenu = DropdownMenuPrimitive.Root
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger
const DropdownMenuGroup = DropdownMenuPrimitive.Group
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup
const DropdownMenuContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 min-w-[10rem] origin-[var(--radix-dropdown-menu-content-transform-origin)] overflow-hidden rounded-lg border border-border bg-popover p-1 text-popover-foreground shadow-[var(--shadow-md)] data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95",
className
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
))
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName
const DropdownMenuItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-secondary focus:text-secondary-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
inset && "pl-8",
className
)}
{...props}
/>
))
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName
const DropdownMenuRadioItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<DropdownMenuPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-secondary focus:text-secondary-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Check className="h-3.5 w-3.5 text-primary" strokeWidth={2.5} />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
))
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName
const DropdownMenuLabel = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.Label
ref={ref}
className={cn(
"px-2 py-1.5 text-[11px] font-medium uppercase tracking-wider text-muted-foreground",
className
)}
{...props}
/>
))
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName
const DropdownMenuSeparator = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-border", className)}
{...props}
/>
))
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName
export {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuGroup,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuLabel,
DropdownMenuSeparator,
}
+62
View File
@@ -0,0 +1,62 @@
'use client'
import { useEffect, useState } from 'react'
// Concept dry-table (scenes 9/10): borderless table straight on the panel,
// uppercase hairline heads, 13px rows, hover-revealed row controls. Shared by
// the verifikat list and the transaction inbox so the two read as the same
// instrument. Keep these in sync with .claude/rules/design.md; page-specific
// tweaks belong at the call site via cn(), not here.
export const TH_CLASS =
'px-4 py-2.5 text-left text-[11px] font-medium uppercase tracking-[0.07em] text-muted-foreground border-b border-border whitespace-nowrap'
export const TD_CLASS = 'px-4 py-[11px] border-b border-border align-top'
export const VTH_CLASS =
'py-2 pr-4 text-left text-[10.5px] font-medium uppercase tracking-[0.07em] text-muted-foreground border-b border-border'
export const VTD_CLASS = 'py-[7px] pr-4 border-b border-border/60 align-top'
export const QUIET_LINK_CLASS =
'text-[12.5px] text-muted-foreground underline decoration-border underline-offset-4 transition-colors duration-150 hover:text-foreground'
// Row controls that stay out of the way until the row is hovered. Coarse
// pointers never fire hover, so without pointer-coarse: the control would be
// permanently invisible and the action unreachable on touch. Always use this
// constant instead of hand-rolling `opacity-0 group-hover:opacity-100`.
//
// focus-within is what makes this safe on a WRAPPER: focus-visible only matches
// the element itself, so a non-focusable <span> holding the buttons would stay
// transparent while a keyboard user tabbed through the controls inside it.
export const HOVER_REVEAL_CLASS =
'opacity-0 transition-opacity group-hover:opacity-100 focus-visible:opacity-100 focus-within:opacity-100 pointer-coarse:opacity-100'
// Row SELECTION checkboxes are not hover-reveal controls: bulk-select is a
// primary workflow on list pages, and an invisible 16px target forces a
// precise hover-then-aim per row (user feedback: "sjukt pilligt"). They rest
// always-visible at muted opacity and go solid on hover/focus/coarse
// pointers; call sites force opacity-100 when checked. Action controls
// (chevrons, buttons) keep HOVER_REVEAL_CLASS above.
//
// Call sites must also put `border-foreground` (unconditionally) on the
// Checkbox itself: the primitive's border-input is ~1.4:1 against the page,
// which composited at opacity-50 lands ~1.2:1, under the WCAG 3:1 non-text
// minimum. border-foreground composites to >=3.4:1 at rest in every theme.
// It lives at the call site, not in this constant, because the constant is
// sometimes applied to a borderless WRAPPER around the checkbox.
export const CHECKBOX_REVEAL_CLASS =
'opacity-50 transition-opacity group-hover:opacity-100 focus-visible:opacity-100 pointer-coarse:opacity-100'
// Animated row expansion (concept vwrap/vinner): grid-rows 0fr -> 1fr on
// mount; the global reduced-motion rule collapses the transition.
export function RowFoldout({ children }: { children: React.ReactNode }) {
const [open, setOpen] = useState(false)
useEffect(() => {
const raf = requestAnimationFrame(() => setOpen(true))
return () => cancelAnimationFrame(raf)
}, [])
return (
<div
className="grid transition-[grid-template-rows] duration-300 ease-out"
style={{ gridTemplateRows: open ? '1fr' : '0fr' }}
>
<div className="min-h-0 overflow-hidden">{children}</div>
</div>
)
}
+137
View File
@@ -0,0 +1,137 @@
'use client'
import * as React from 'react'
import Link from 'next/link'
import { useTranslations } from 'next-intl'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import {
Users,
Plus,
TrendingUp,
type LucideIcon,
} from 'lucide-react'
import { SupportLink } from '@/components/ui/support-link'
interface EmptyStateProps {
icon?: LucideIcon
/**
* Usually static i18n strings. The empty state is data-ph-unmask chrome in
* session replays, so a title or description carrying user data (e.g. an
* interpolated search term) must wrap that part in a data-ph-mask element.
*/
title: React.ReactNode
description: React.ReactNode
actionLabel?: string
actionHref?: string
onAction?: () => void
secondaryActionLabel?: string
secondaryActionHref?: string
supportHint?: boolean
className?: string
children?: React.ReactNode
}
/**
* EmptyState: friendly placeholder shown when there is no data.
*/
export function EmptyState({
icon: Icon,
title,
description,
actionLabel,
actionHref,
onAction,
secondaryActionLabel,
secondaryActionHref,
supportHint,
className,
children,
}: EmptyStateProps) {
const t = useTranslations('empty')
return (
// data-ph-unmask: empty states are static i18n chrome in session replays.
<div data-ph-unmask="" className={cn('flex flex-col items-center justify-center py-12 px-4 text-center', className)}>
{Icon && (
<div className="mb-6">
<div className="p-4 rounded-full bg-muted">
<Icon className="h-8 w-8 text-muted-foreground" />
</div>
</div>
)}
<h3 className="text-lg mb-2">{title}</h3>
<p className="text-sm text-muted-foreground max-w-sm mb-6 text-balance">{description}</p>
{supportHint && (
<div className="mb-6">
<SupportLink variant="muted" subject={t('support_hint_subject')}>
{t('support_hint_label')}
</SupportLink>
</div>
)}
{(actionLabel || children) && (
<div className="flex flex-col sm:flex-row items-center gap-3">
{actionHref && actionLabel && (
<Link href={actionHref}>
<Button>
<Plus className="mr-2 h-4 w-4" />
{actionLabel}
</Button>
</Link>
)}
{onAction && actionLabel && (
<Button onClick={onAction}>
<Plus className="mr-2 h-4 w-4" />
{actionLabel}
</Button>
)}
{secondaryActionHref && secondaryActionLabel && (
<Link href={secondaryActionHref}>
<Button variant="outline">{secondaryActionLabel}</Button>
</Link>
)}
{children}
</div>
)}
</div>
)
}
// Preset empty states for common pages
export function EmptyCustomers({ onAction }: { onAction?: () => void } = {}) {
const t = useTranslations('empty')
return (
<EmptyState
icon={Users}
title={t('preset_customers_title')}
description={t('preset_customers_description')}
actionLabel={t('preset_customers_action')}
actionHref={onAction ? undefined : '/customers/new'}
onAction={onAction}
/>
)
}
/**
* Byrå cockpit: no client companies yet. A preset, not a bare <EmptyState
* icon={TrendingUp} />, because the only caller is a Server Component: a
* lucide icon is a forwardRef object that cannot cross the RSC boundary as a
* prop, while a reference to this client component can. The copy lives in the
* byra namespace, where the byrå surfaces already keep it.
*/
export function EmptyByraClients() {
// Named tByra, not t: this is the only preset here that reads from a
// namespace other than `empty`, and i18n/__tests__/message-keys.test.ts maps
// one variable name to one namespace per file. Reusing `t` would silently
// re-point every other preset's key in this file at `byra`.
const tByra = useTranslations('byra')
return (
<EmptyState
icon={TrendingUp}
title={tByra('kpi_empty_title')}
description={tByra('kpi_empty_description')}
/>
)
}
+79
View File
@@ -0,0 +1,79 @@
'use client'
import { Loader2, Check, AlertCircle, FileWarning } from 'lucide-react'
import { cn } from '@/lib/utils'
import type { ExtractionStatus } from '@/lib/hooks/use-document-extraction'
interface Props {
status: ExtractionStatus
elapsedMs?: number
className?: string
}
// Inline status indicator for an AI extraction in flight. Sits next to a
// freshly-attached document in upload flows. Five visual states map to the
// useDocumentExtraction hook output. "disabled" renders nothing: the free
// tier has no AI extraction and shouldn't see scary UI.
//
// Copy is intentionally short and Swedish. The status changes inline; the
// layout doesn't shift between states (icon + single line).
export default function ExtractionStatus({ status, elapsedMs = 0, className }: Props) {
if (status === 'idle' || status === 'disabled') return null
const slow = elapsedMs > 8_000
if (status === 'running') {
return (
<span
className={cn(
'inline-flex items-center gap-1.5 text-xs text-muted-foreground',
className,
)}
>
<Loader2 className="h-3.5 w-3.5 animate-spin" />
{slow ? 'Tar lite längre än vanligt…' : 'Läser dokumentet…'}
</span>
)
}
if (status === 'succeeded') {
return (
<span
className={cn(
'inline-flex items-center gap-1.5 text-xs text-success',
className,
)}
>
<Check className="h-3.5 w-3.5" />
Inläst av AI
</span>
)
}
if (status === 'unsupported') {
return (
<span
className={cn(
'inline-flex items-center gap-1.5 text-xs text-muted-foreground',
className,
)}
>
<FileWarning className="h-3.5 w-3.5" />
Filtypen kan inte läsas automatiskt
</span>
)
}
// failed
return (
<span
className={cn(
'inline-flex items-center gap-1.5 text-xs text-warning',
className,
)}
>
<AlertCircle className="h-3.5 w-3.5" />
Kunde inte läsa automatiskt: fyll i manuellt
</span>
)
}
+104
View File
@@ -0,0 +1,104 @@
'use client'
import { useState, useRef, useEffect, useCallback } from 'react'
import { createPortal } from 'react-dom'
import { useTranslations } from 'next-intl'
import { cn } from '@/lib/utils'
interface HelpPopoverProps {
/** Popover body: the page's help text (i18n `help_*` keys per namespace). */
children: React.ReactNode
className?: string
}
/**
* Page help behind a small "?" (UI-migration convention 7): a 17px circular
* button right after the H1 opening a popover anchored at the button. No
* instructional copy in the page flow.
*/
export function HelpPopover({ children, className }: HelpPopoverProps) {
const tNav = useTranslations('nav')
const [open, setOpen] = useState(false)
const triggerRef = useRef<HTMLButtonElement>(null)
const panelRef = useRef<HTMLDivElement>(null)
const [pos, setPos] = useState({ top: 0, left: 0 })
const updatePosition = useCallback(() => {
if (!triggerRef.current || !panelRef.current) return
const t = triggerRef.current.getBoundingClientRect()
const p = panelRef.current.getBoundingClientRect()
const margin = 8
const left = Math.max(margin, Math.min(t.left, window.innerWidth - p.width - margin))
const top = Math.min(t.bottom + 6, window.innerHeight - p.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)) &&
(!panelRef.current || !panelRef.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)}
aria-expanded={open}
aria-label={tNav('help')}
className={cn(
'inline-flex h-[17px] w-[17px] items-center justify-center rounded-full border border-border',
'text-[11px] leading-none text-muted-foreground transition-colors duration-150',
'hover:border-foreground/30 hover:text-foreground',
className,
)}
>
?
</button>
{open &&
createPortal(
<div
ref={panelRef}
role="note"
data-help-popover=""
// Inside a modal dialog the panel is DOM-outside DialogContent:
// data-dialog-companion keeps a click in it from dismissing the
// dialog, and pointer-events-auto undoes the modal body lock.
data-dialog-companion=""
// data-ph-unmask: page help is static i18n chrome in session replays.
data-ph-unmask=""
className="pointer-events-auto fixed z-[60] w-[300px] rounded-lg border border-border bg-popover p-4 text-[13px] leading-relaxed text-foreground shadow-lg animate-in fade-in slide-in-from-top-1 duration-150"
style={{ top: pos.top, left: pos.left }}
>
{children}
</div>,
document.body,
)}
</>
)
}
+168
View File
@@ -0,0 +1,168 @@
'use client'
import * as React from 'react'
import * as TooltipPrimitive from '@radix-ui/react-tooltip'
import { Info, HelpCircle } from 'lucide-react'
import { cn } from '@/lib/utils'
const TooltipProvider = TooltipPrimitive.Provider
const Tooltip = TooltipPrimitive.Root
const TooltipTrigger = TooltipPrimitive.Trigger
const TooltipContent = React.forwardRef<
React.ElementRef<typeof TooltipPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
// Portal the content to document.body so the tooltip is never clipped by an
// ancestor with overflow (e.g. a scrollable DialogContent: the send-invoice
// and journal-review dialogs use overflow-y-auto, which otherwise crops it).
<TooltipPrimitive.Portal>
{/* data-ph-unmask: tooltip help text is static i18n chrome in session
replays; content carrying user data adds data-ph-mask at the call site. */}
<TooltipPrimitive.Content
ref={ref}
sideOffset={sideOffset}
data-ph-unmask=""
className={cn(
'z-50 overflow-hidden rounded-lg border border-border/60 bg-popover px-3 py-2 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
className
)}
{...props}
/>
</TooltipPrimitive.Portal>
))
TooltipContent.displayName = TooltipPrimitive.Content.displayName
interface InfoTooltipProps {
content: React.ReactNode
children?: React.ReactNode
className?: string
iconClassName?: string
side?: 'top' | 'right' | 'bottom' | 'left'
align?: 'start' | 'center' | 'end'
variant?: 'info' | 'help'
maxWidth?: string
}
/**
* InfoTooltip - En återanvändbar tooltip-komponent för kontextuell hjälp
*
* Användning:
* <InfoTooltip content="Förklaring här">
* <span>Text att förklara</span>
* </InfoTooltip>
*
* Eller som fristående info-ikon:
* <InfoTooltip content="Förklaring här" />
*/
function InfoTooltip({
content,
children,
className,
iconClassName,
side = 'top',
align = 'center',
variant = 'info',
maxWidth = '280px',
}: InfoTooltipProps) {
const Icon = variant === 'help' ? HelpCircle : Info
return (
<Tooltip>
<TooltipTrigger asChild>
{children ? (
<span className={cn('inline-flex items-center gap-1.5 cursor-help', className)}>
{children}
<Icon
className={cn(
'h-3.5 w-3.5 text-muted-foreground/70 hover:text-muted-foreground transition-colors flex-shrink-0',
iconClassName
)}
/>
</span>
) : (
<button
type="button"
className={cn(
'inline-flex items-center justify-center rounded-full p-0.5 text-muted-foreground/70 hover:text-muted-foreground hover:bg-muted/50 transition-colors cursor-help',
className
)}
>
<Icon className={cn('h-4 w-4', iconClassName)} />
<span className="sr-only">Mer information</span>
</button>
)}
</TooltipTrigger>
<TooltipContent
side={side}
align={align}
className="max-w-[var(--tooltip-max-width)]"
style={{ '--tooltip-max-width': maxWidth } as React.CSSProperties}
>
<div className="text-sm leading-relaxed">{content}</div>
</TooltipContent>
</Tooltip>
)
}
interface InfoTextProps {
term: string
explanation: string
className?: string
termClassName?: string
}
/**
* InfoText - Kombination av primär text med fackterm i parentes
*
* Användning:
* <InfoText term="Enkla avdrag" explanation="schablonavdrag" />
* Visar: "Enkla avdrag (schablonavdrag)"
*/
function InfoText({ term, explanation, className, termClassName }: InfoTextProps) {
return (
<span className={className}>
{term}
<span className={cn('text-muted-foreground ml-1', termClassName)}>
({explanation})
</span>
</span>
)
}
interface HelpLinkProps {
href: string
children: React.ReactNode
className?: string
external?: boolean
}
/**
* HelpLink - Länk till mer information (t.ex. Skatteverket)
*/
function HelpLink({ href, children, className, external = true }: HelpLinkProps) {
return (
<a
href={href}
className={cn(
'inline-flex items-center gap-1 text-primary hover:text-primary/80 underline-offset-4 hover:underline transition-colors text-sm',
className
)}
{...(external && { target: '_blank', rel: 'noopener noreferrer' })}
>
{children}
</a>
)
}
export {
InfoTooltip,
InfoText,
HelpLink,
Tooltip,
TooltipTrigger,
TooltipContent,
TooltipProvider,
}
+37
View File
@@ -0,0 +1,37 @@
import * as React from "react"
import { cn } from "@/lib/utils"
export type InputProps = React.InputHTMLAttributes<HTMLInputElement>
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, onWheel, ...props }, ref) => {
// Prevent the mouse wheel from silently mutating a focused number input
// (e.g. scrolling the page over a salary field turning 20000 into 19998).
// Blurring drops focus so the wheel scrolls the page instead of the value.
const handleWheel = React.useCallback(
(e: React.WheelEvent<HTMLInputElement>) => {
if (type === 'number') {
e.currentTarget.blur()
}
onWheel?.(e)
},
[type, onWheel]
)
return (
<input
type={type}
className={cn(
"flex h-10 w-full rounded-lg border border-input bg-card px-4 py-2 text-sm transition-colors duration-150 file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground/60 focus-visible:outline-none focus-visible:border-primary focus-visible:ring-1 focus-visible:ring-primary/20 aria-invalid:border-destructive aria-invalid:focus-visible:border-destructive aria-invalid:focus-visible:ring-destructive/20 disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
onWheel={handleWheel}
{...props}
/>
)
}
)
Input.displayName = "Input"
export { Input }
+30
View File
@@ -0,0 +1,30 @@
"use client"
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
)
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
// data-ph-unmask: form field labels are static i18n chrome, readable under
// the deny-by-default replay masking (see lib/analytics/replay-masking.ts).
// A call site whose label text is user data must add data-ph-mask, which
// wins over this default.
<LabelPrimitive.Root
ref={ref}
data-ph-unmask=""
className={cn(labelVariants(), className)}
{...props}
/>
))
Label.displayName = LabelPrimitive.Root.displayName
export { Label }
+67
View File
@@ -0,0 +1,67 @@
'use client'
import Link from 'next/link'
import { ExternalLink } from 'lucide-react'
import { useTranslations } from 'next-intl'
import { cn } from '@/lib/utils'
import { HOVER_REVEAL_CLASS } from '@/components/ui/dry-table'
/**
* Escape hatch out of a list without losing it.
*
* Working a filtered list (kontoavstämning, granskning) means opening one
* record, fixing it, and coming back to the same list. Navigating in place
* throws away the filter, the page and the scroll position, so the only way
* to keep them is to open the record in a second tab. Most of our row links
* are plain anchors, so cmd-click already works, but nothing on screen ever
* says so and a few call sites are buttons where it does not work at all.
*
* Sits next to the record's own link rather than replacing it: the primary
* click keeps navigating in place, which is what people expect. Hover-revealed
* per the row-control convention, and always visible on coarse pointers.
*/
export function OpenInNewTab({
href,
label,
className,
}: {
href: string
/** Overrides the default "Öppna i ny flik" for a more specific target. */
label?: string
className?: string
}) {
const t = useTranslations('common')
const text = label ?? t('open_in_new_tab')
return (
<Link
href={href}
target="_blank"
rel="noopener noreferrer"
// Named by the visually-hidden text below rather than aria-label, so the
// title renders a tooltip for sighted users without screen readers
// announcing the same string twice.
title={text}
onClick={(e) => e.stopPropagation()}
// Rows that own this control are themselves interactive: JournalEntryList
// gives its <tr> an Enter/Space handler that calls preventDefault() and
// expands the row. Without this, Enter on a focused link would expand the
// row instead of opening the voucher, so the control would be usable with
// a mouse but not a keyboard.
onKeyDown={(e) => e.stopPropagation()}
className={cn(
HOVER_REVEAL_CLASS,
'relative inline-flex shrink-0 items-center rounded-sm p-1 text-muted-foreground',
// The icon stays 14px so the row keeps its density, but the pointer
// target is padded out to the 40px the design rules require.
'before:absolute before:left-1/2 before:top-1/2 before:h-10 before:w-10',
'before:-translate-x-1/2 before:-translate-y-1/2 before:content-[""]',
'transition-colors duration-150 hover:text-foreground',
className,
)}
>
<ExternalLink className="h-3.5 w-3.5" aria-hidden="true" />
<span className="sr-only">{text}</span>
</Link>
)
}
+38
View File
@@ -0,0 +1,38 @@
import * as React from 'react'
interface PageHeaderProps {
/**
* Usually a static i18n string. The header is data-ph-unmask chrome in
* session replays, so a title or description that carries user data must
* wrap that part in a data-ph-mask element (hence ReactNode).
*/
title: React.ReactNode
description?: React.ReactNode
action?: React.ReactNode
/**
* Page help content, rendered as a small "?" popover right after the H1
* (UI-migration convention 7). Pass a <HelpPopover>...</HelpPopover>.
*/
help?: React.ReactNode
}
export function PageHeader({ title, description, action, help }: PageHeaderProps) {
return (
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between mb-8">
<div>
<div className="flex items-center gap-2">
{/* Locked at exactly 24px/32px (UI-migration convention 2).
data-ph-unmask: page titles are static i18n chrome in session
replays; a page whose title carries user data must wrap it in
data-ph-mask at the call site. */}
<h1 data-ph-unmask="" className="font-display text-2xl leading-8 tracking-tight">{title}</h1>
{help}
</div>
{description && (
<p data-ph-unmask="" className="text-muted-foreground mt-1 text-balance">{description}</p>
)}
</div>
{action && <div className="w-full sm:w-auto [&>*]:w-full [&>*]:sm:w-auto">{action}</div>}
</div>
)
}
+27
View File
@@ -0,0 +1,27 @@
"use client"
import * as React from "react"
import * as ProgressPrimitive from "@radix-ui/react-progress"
import { cn } from "@/lib/utils"
const Progress = React.forwardRef<
React.ElementRef<typeof ProgressPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root>
>(({ className, value, ...props }, ref) => (
<ProgressPrimitive.Root
ref={ref}
className={cn(
"relative h-4 w-full overflow-hidden rounded-full bg-secondary",
className
)}
{...props}
>
<ProgressPrimitive.Indicator
className="h-full w-full flex-1 bg-primary transition-transform duration-300 ease-linear"
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
/>
</ProgressPrimitive.Root>
))
Progress.displayName = ProgressPrimitive.Root.displayName
export { Progress }
File diff suppressed because one or more lines are too long
+76
View File
@@ -0,0 +1,76 @@
'use client'
import Link from 'next/link'
import { useTranslations } from 'next-intl'
import { AlertTriangle } from 'lucide-react'
import { cn } from '@/lib/utils'
import { getBranding } from '@/lib/branding/service'
interface RetentionNoticeProps {
variant: 'company' | 'account'
className?: string
}
/**
* Shared BFL retention notice shown before destructive actions that
* affect bookkeeping data. Keeps the legal copy consistent between the
* account danger zone and the company danger zone.
*
* Swedish Bokföringslagen (BFL) 7 kap. 2§ requires räkenskapsinformation
* to be retained for 7 years. Accounted is the system of record, so deleting
* a company or an account does not remove the underlying data: it only
* hides it from the UI and anonymizes PII where applicable.
*/
export function RetentionNotice({ variant, className }: RetentionNoticeProps) {
const t = useTranslations('retention_notice')
const { appName } = getBranding()
const copy =
variant === 'company'
? {
title: t('company_title'),
body: (
<>
{t('company_body_prefix', { appName: appName.toLowerCase() })}
<Link
href="/settings/backup"
className="underline underline-offset-2 hover:text-foreground"
>
{t('company_body_link')}
</Link>
{t('company_body_suffix')}
</>
),
}
: {
title: t('account_title'),
body: (
<>
{t('account_body_prefix')}
<Link
href="/settings/backup"
className="underline underline-offset-2 hover:text-foreground"
>
{t('account_body_link')}
</Link>
{t('account_body_suffix')}
</>
),
}
return (
<div
className={cn(
'rounded-lg border border-destructive/30 bg-destructive/5 p-4',
className
)}
>
<div className="flex gap-3">
<AlertTriangle className="h-5 w-5 text-destructive shrink-0 mt-0.5" />
<div className="space-y-1 text-sm">
<p className="font-medium text-destructive">{copy.title}</p>
<p className="text-muted-foreground">{copy.body}</p>
</div>
</div>
</div>
)
}
+25
View File
@@ -0,0 +1,25 @@
import { Badge, type BadgeProps } from '@/components/ui/badge'
export interface RowStatusDescriptor {
label: string
/**
* True when the row DEVIATES from the normal state (Utkast, Förfallen,
* Ej bokförd). Normal states render as muted text; a table where every
* row carries the same chip is wrong (UI-migration convention 5).
*/
exception?: boolean
/** Badge variant for exception states. */
variant?: BadgeProps['variant']
}
/**
* Chips mark exceptions: renders a status as muted text for normal states
* and as a Badge only when the row deviates. Pages define their status map
* as `Record<Status, RowStatusDescriptor>` and pass the resolved entry.
*/
export function RowStatus({ status }: { status: RowStatusDescriptor }) {
if (status.exception) {
return <Badge variant={status.variant ?? 'warning'}>{status.label}</Badge>
}
return <span className="text-xs text-muted-foreground">{status.label}</span>
}

Some files were not shown because too many files have changed in this diff Show More