This commit is contained in:
Maurus Decimus committed 2026-10-30 17:26:45 +01:00
1 parent f835f4fd62
commit f10408be22
109 files changed
+2750 -1395

No files matched your search

+12
View File
@@ -2,6 +2,18 @@
All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/).
## [2.0.4] - Unreleased
### Added
- New WebUI design with more pizzazz:
- Cleaner generated forms: two-column fields that stack on mobile, simpler nested objects, collapsible list items, segmented variant pickers, a section index on wide screens and a floating save bar.
- Dashboards support a layout with stat, chart, headline and ranking tiles, plus column and row spans, tones and delta polarity, all defined in the schema.
- Custom OAuth scopes can be requested through the `oauth-scopes` meta tag; they are added to the scopes required by the server.
### Changed
### Fixed
## [2.0.3] - 2026-10-29
### Added
+1
View File
@@ -5,6 +5,7 @@
<meta charset="UTF-8" />
<base href="/" />
<meta name="oauth-client-id" content="" />
<meta name="oauth-scopes" content="" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Portal</title>
+32 -2
View File
@@ -1,14 +1,17 @@
{
"name": "stalwart-webui",
"version": "2.0.3",
"version": "2.0.4",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "stalwart-webui",
"version": "2.0.3",
"version": "2.0.4",
"dependencies": {
"@daypicker/react": "^10.0.2",
"@fontsource-variable/inter": "^5.3.0",
"@fontsource-variable/jetbrains-mono": "^5.3.0",
"@fontsource-variable/plus-jakarta-sans": "^5.3.0",
"@noble/hashes": "^2.4.0",
"@radix-ui/react-alert-dialog": "^1.2.1",
"@radix-ui/react-checkbox": "^1.4.1",
@@ -584,6 +587,33 @@
"integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==",
"license": "MIT"
},
"node_modules/@fontsource-variable/inter": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/inter/-/inter-5.3.0.tgz",
"integrity": "sha512-OupL48va4JNofb97w6NYeF9S7W/kHNKM0Er8Dem5nqi4jeOLrVJDoE8tZEpnMJmtkvNbB1EIPPwHcdkF6b1oUA==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/jetbrains-mono": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/jetbrains-mono/-/jetbrains-mono-5.3.0.tgz",
"integrity": "sha512-F32xpS2NsGYoQi2ADSkKTgpJj7ozajsGgDJ8woTnqjmIB+dxDIqImjl4pXZVEExu8UFZ2ndhmX18EBS/hdz3Lw==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/plus-jakarta-sans": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/plus-jakarta-sans/-/plus-jakarta-sans-5.3.0.tgz",
"integrity": "sha512-/l/4r0yyWK9JzAlmA0LiYgGgmJe/Gswt4jTJEzr5QhJfwMbvJZDmYWyW0M4X7yCK69BajMVlV/Lx8g7WDc1+sw==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@humanfs/core": {
"version": "0.19.2",
"resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz",
+4 -1
View File
@@ -1,7 +1,7 @@
{
"name": "stalwart-webui",
"private": true,
"version": "2.0.3",
"version": "2.0.4",
"stalwart": {
"minServerVersion": "1.0.0"
},
@@ -18,6 +18,9 @@
},
"dependencies": {
"@daypicker/react": "^10.0.2",
"@fontsource-variable/inter": "^5.3.0",
"@fontsource-variable/jetbrains-mono": "^5.3.0",
"@fontsource-variable/plus-jakarta-sans": "^5.3.0",
"@noble/hashes": "^2.4.0",
"@radix-ui/react-alert-dialog": "^1.2.1",
"@radix-ui/react-checkbox": "^1.4.1",
+33 -32
View File
@@ -7,18 +7,18 @@
import type { ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { Check } from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { cn } from '@/lib/utils';
import { CopyButton } from '@/components/common/CopyButton';
import { DefaultLogo } from '@/components/common/Logo';
import type { Fields } from '@/types/schema';
export function WizardShell({ children }: { children: ReactNode }) {
return (
<div className="flex min-h-screen flex-col bg-content-background">
<header className="flex items-center px-6 py-4 border-b bg-background">
<div className="flex min-h-screen flex-col bg-background">
<header className="sticky top-0 z-20 flex h-16 items-center bg-background/80 px-6 backdrop-blur-md">
<DefaultLogo />
</header>
<main className="flex-1 overflow-auto p-6">
<main className="flex-1 overflow-auto px-4 pb-10 pt-4 sm:px-6">
<div className="mx-auto max-w-3xl">{children}</div>
</main>
</div>
@@ -29,15 +29,16 @@ export function ProgressIndicator({ total, current }: { total: number; current:
const { t } = useTranslation();
return (
<div
className="flex items-center gap-2"
className="flex items-center gap-1.5"
aria-label={t('bootstrap.stepOf', 'Step {{current}} of {{total}}', { current: current + 1, total })}
>
{Array.from({ length: total }, (_, i) => (
<div
key={i}
className={`h-2 w-2 rounded-full transition-colors ${
i < current ? 'bg-primary' : i === current ? 'bg-primary' : 'bg-muted-foreground/20'
}`}
className={cn(
'h-1.5 rounded-full transition-all duration-300 ease-bento',
i === current ? 'w-8 bg-primary' : i < current ? 'w-4 bg-primary/45' : 'w-4 bg-muted-strong',
)}
/>
))}
</div>
@@ -62,14 +63,14 @@ export function SuccessScreen({
const hasCredentials = entries.length > 0;
return (
<div className="space-y-6">
<div className="flex flex-col items-start gap-3">
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary/10">
<Check className="h-5 w-5 text-primary" />
</div>
<div className="space-y-3.5">
<div className="flex flex-col items-start gap-4 px-1 pb-2 pt-3">
<span className="grid size-11 place-items-center rounded-[13px] bg-success-soft text-success">
<Check className="h-5 w-5" aria-hidden="true" />
</span>
<div>
<h2 className="text-2xl font-semibold tracking-tight">{t('bootstrap.complete', 'Setup complete')}</h2>
<p className="text-sm text-muted-foreground mt-1">
<h1 className="page-title">{t('bootstrap.complete', 'Setup complete')}</h1>
<p className="mt-1.5 text-sm text-muted-foreground">
{hasCredentials
? t(
'bootstrap.credentialsCreated',
@@ -81,26 +82,26 @@ export function SuccessScreen({
</div>
{hasCredentials && (
<Card>
<CardContent className="pt-6 space-y-4">
{entries.map(([key, value]) => {
const field = fields.properties[key];
const label = labelsByName.get(key) ?? field?.description?.split('\n')[0] ?? key;
return (
<div key={key} className="space-y-1.5">
<div className="text-sm font-medium">{label}</div>
<div className="flex gap-2">
<code className="flex-1 rounded bg-muted p-2 text-sm break-all select-all">{value}</code>
<CopyButton value={value} label={label} />
</div>
<section className="tile divide-y divide-border px-5 sm:px-6">
{entries.map(([key, value]) => {
const field = fields.properties[key];
const label = labelsByName.get(key) ?? field?.description?.split('\n')[0] ?? key;
return (
<div key={key} className="space-y-2 py-4">
<div className="text-[13.5px] font-semibold">{label}</div>
<div className="flex items-center gap-2">
<code className="flex-1 select-all break-all rounded-xl bg-muted px-3 py-2.5 font-mono text-sm">
{value}
</code>
<CopyButton value={value} label={label} />
</div>
);
})}
</CardContent>
</Card>
</div>
);
})}
</section>
)}
<div className="rounded-md border border-primary/20 bg-primary/5 p-4">
<div className="rounded-xl bg-info-soft p-4 text-info">
<p className="text-sm">
<span className="font-medium">{t('bootstrap.nextStepLabel', 'Next step:')}</span>{' '}
{t(
+40 -45
View File
@@ -8,7 +8,7 @@ import { useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { cn } from '@/lib/utils';
import { ArrowLeft, ArrowRight, Loader2, Rocket } from 'lucide-react';
import { useSchemaStore } from '@/stores/schemaStore';
@@ -208,8 +208,8 @@ export function BootstrapWizard() {
if (!schema || !resolved) {
return (
<WizardShell>
<div className="flex items-center justify-center p-12 text-muted-foreground">
<Loader2 className="h-6 w-6 animate-spin mr-2" />
<div className="flex items-center justify-center p-12 text-muted-foreground" role="status">
<Loader2 className="mr-2 h-6 w-6 animate-spin text-brand-text" aria-hidden="true" />
{t('form.loadingSchema', 'Loading schema...')}
</div>
</WizardShell>
@@ -219,8 +219,8 @@ export function BootstrapWizard() {
if (loading) {
return (
<WizardShell>
<div className="flex items-center justify-center p-12 text-muted-foreground">
<Loader2 className="h-6 w-6 animate-spin mr-2" />
<div className="flex items-center justify-center p-12 text-muted-foreground" role="status">
<Loader2 className="mr-2 h-6 w-6 animate-spin text-brand-text" aria-hidden="true" />
{t('bootstrap.loadingSetup', 'Loading setup...')}
</div>
</WizardShell>
@@ -230,7 +230,7 @@ export function BootstrapWizard() {
if (loadError) {
return (
<WizardShell>
<div className="space-y-4 rounded-md border border-destructive/20 bg-destructive/10 p-4">
<div className="mt-3 space-y-4 rounded-xl bg-destructive-soft p-4">
<p className="text-sm text-destructive" role="alert">
{loadError}
</p>
@@ -262,7 +262,7 @@ export function BootstrapWizard() {
if (sections.length === 0) {
return (
<WizardShell>
<div className="rounded-md border border-destructive/20 bg-destructive/10 p-4 text-sm text-destructive">
<div className="mt-3 rounded-xl bg-destructive-soft p-4 text-sm text-destructive">
{t('bootstrap.emptyForm', 'Setup form is empty. The server did not return any bootstrap fields.')}
</div>
</WizardShell>
@@ -273,52 +273,47 @@ export function BootstrapWizard() {
return (
<WizardShell>
<div className="space-y-6">
<div>
<h2 className="text-2xl font-semibold tracking-tight">{t('bootstrap.welcome', 'Welcome to Stalwart')}</h2>
<p className="text-sm text-muted-foreground mt-1">
{t('bootstrap.welcomeSubtitle', "Let's get your server set up.")}
</p>
<div className="space-y-3.5">
<div className="flex flex-wrap items-end justify-between gap-4 px-1 pb-2 pt-3">
<div>
<h1 className="page-title">{t('bootstrap.welcome', 'Welcome to Stalwart')}</h1>
<p className="mt-1.5 text-sm text-muted-foreground">
{t('bootstrap.welcomeSubtitle', "Let's get your server set up.")}
</p>
</div>
<ProgressIndicator total={sections.length} current={currentPage} />
</div>
<ProgressIndicator total={sections.length} current={currentPage} />
{generalError && (
<div className="rounded-md bg-destructive/10 border border-destructive/20 p-4">
<p className="text-sm text-destructive whitespace-pre-line">{generalError}</p>
<div className="rounded-xl bg-destructive-soft p-4" role="alert">
<p className="whitespace-pre-line text-sm text-destructive">{generalError}</p>
</div>
)}
<Card>
{current.title && (
<CardHeader>
<CardTitle className="text-base">{current.title}</CardTitle>
</CardHeader>
)}
<CardContent className={current.title ? '' : 'pt-6'}>
<fieldset disabled={saving} className="min-w-0 space-y-6">
<FormProvider schema={schema} mode="create" hideEnterprise>
{current.fields.map(({ formField, field }) => (
<FieldRow
key={formField.name}
field={field}
formField={formField}
value={formData[formField.name]}
onChange={(v) => handleFieldChange(formField.name, v)}
error={fieldErrors[formField.name]}
/>
))}
</FormProvider>
</fieldset>
</CardContent>
</Card>
<section className="tile @container px-5 pb-1.5 sm:px-6">
{current.title && <h2 className="section-title pb-1 pt-5">{current.title}</h2>}
<fieldset disabled={saving} className={cn('min-w-0 divide-y divide-border', !current.title && 'pt-1')}>
<FormProvider schema={schema} mode="create" hideEnterprise>
{current.fields.map(({ formField, field }) => (
<FieldRow
key={formField.name}
field={field}
formField={formField}
value={formData[formField.name]}
onChange={(v) => handleFieldChange(formField.name, v)}
error={fieldErrors[formField.name]}
/>
))}
</FormProvider>
</fieldset>
</section>
<div className="flex items-center justify-between pt-2">
<div className="flex items-center justify-between gap-3 pt-2">
<Button type="button" variant="outline" onClick={handleBack} disabled={!canGoBack || saving}>
<ArrowLeft className="h-4 w-4 mr-2" />
<ArrowLeft aria-hidden="true" />
{t('common.back', 'Back')}
</Button>
<div className="text-xs text-muted-foreground">
<div className="text-xs font-medium text-dim">
{t('bootstrap.stepOf', 'Step {{current}} of {{total}}', {
current: currentPage + 1,
total: sections.length,
@@ -326,13 +321,13 @@ export function BootstrapWizard() {
</div>
{isLastPage ? (
<Button type="button" onClick={handleSubmit} disabled={saving}>
{saving ? <Loader2 className="h-4 w-4 mr-2 animate-spin" /> : <Rocket className="h-4 w-4 mr-2" />}
{saving ? <Loader2 className="animate-spin" aria-hidden="true" /> : <Rocket aria-hidden="true" />}
{t('bootstrap.finishSetup', 'Finish setup')}
</Button>
) : (
<Button type="button" onClick={handleNext} disabled={saving}>
{t('common.next', 'Next')}
<ArrowRight className="h-4 w-4 ml-2" />
<ArrowRight aria-hidden="true" />
</Button>
)}
</div>
+7 -5
View File
@@ -50,7 +50,7 @@ export function CommandPalette({ open, onOpenChange }: CommandPaletteProps) {
<Command
shouldFilter={false}
loop
className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5"
className="[&_[cmdk-group-heading]]:px-2.5 [&_[cmdk-group-heading]]:pt-2.5 [&_[cmdk-group-heading]]:text-[11px] [&_[cmdk-group-heading]]:font-semibold [&_[cmdk-group-heading]]:uppercase [&_[cmdk-group-heading]]:tracking-wider [&_[cmdk-group-heading]]:text-dim [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-14 [&_[cmdk-item]]:gap-3 [&_[cmdk-item]]:rounded-xl [&_[cmdk-item]]:px-2.5 [&_[cmdk-item]]:py-2 [&_[cmdk-item][data-selected=true]]:bg-muted [&_[cmdk-item]_svg]:h-4 [&_[cmdk-item]_svg]:w-4 [&_[cmdk-list]]:max-h-[min(60vh,420px)] [&_[cmdk-list]]:pb-2"
>
<CommandInput
placeholder={t('globalSearch.placeholder', 'Search pages, fields, settings...')}
@@ -59,7 +59,7 @@ export function CommandPalette({ open, onOpenChange }: CommandPaletteProps) {
trailing={
<kbd
aria-hidden="true"
className="pointer-events-none ml-2 inline-flex h-5 shrink-0 select-none items-center rounded-md border bg-muted px-1.5 font-mono text-[10px] font-medium text-muted-foreground"
className="pointer-events-none ml-2 inline-flex h-5 shrink-0 select-none items-center rounded-md bg-muted px-1.5 font-mono text-[10px] font-medium text-dim"
>
ESC
</kbd>
@@ -79,12 +79,14 @@ export function CommandPalette({ open, onOpenChange }: CommandPaletteProps) {
return (
<CommandItem key={itemValue} value={itemValue} onSelect={() => selectEntry(entry)}>
<ActionIcon aria-hidden="true" className="mr-2 h-4 w-4 shrink-0 text-muted-foreground" />
<span className="grid size-8 shrink-0 place-items-center rounded-[10px] bg-highlight text-highlight-foreground">
<ActionIcon aria-hidden="true" className="h-4 w-4" />
</span>
<div className="flex flex-1 flex-col overflow-hidden">
<span className="truncate font-medium">{friendlyName(entry.text)}</span>
<span className="truncate text-xs text-muted-foreground">{entry.breadcrumb}</span>
<span className="truncate text-xs text-dim">{entry.breadcrumb}</span>
</div>
<span className="ml-auto shrink-0 pl-2 text-xs text-muted-foreground">{actionLabel}</span>
<span className="ml-auto shrink-0 pl-2 text-xs font-medium text-dim">{actionLabel}</span>
</CommandItem>
);
})}
+8 -1
View File
@@ -5,6 +5,7 @@
*/
import { useTranslation } from 'react-i18next';
import { Sparkles } from 'lucide-react';
import {
Dialog,
@@ -28,6 +29,12 @@ export function EnterpriseUpsell({ open, onClose }: EnterpriseUpsellProps) {
<Dialog open={open} onOpenChange={(isOpen) => !isOpen && onClose()}>
<DialogContent className="gap-6">
<DialogHeader className="space-y-4">
<span
className="grid size-11 place-items-center rounded-[13px] bg-highlight text-highlight-foreground max-sm:mx-auto"
aria-hidden="true"
>
<Sparkles className="h-5 w-5" />
</span>
<DialogTitle>{t('enterprise.trialTitle')}</DialogTitle>
<DialogDescription>{t('enterprise.trialDescription')}</DialogDescription>
</DialogHeader>
@@ -36,7 +43,7 @@ export function EnterpriseUpsell({ open, onClose }: EnterpriseUpsellProps) {
href="https://stalw.art/compare#why-isnt-feature-x-open-source"
target="_blank"
rel="noopener noreferrer"
className="text-center text-xs text-muted-foreground underline-offset-4 hover:underline sm:mr-auto sm:text-left"
className="text-center text-xs font-medium text-muted-foreground underline-offset-4 hover:text-brand-text hover:underline sm:mr-auto sm:text-left"
>
{t('enterprise.whyNotFree')}
</a>
@@ -0,0 +1,29 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import type { ReactNode } from 'react';
export function FloatingActionBar({ label, children }: { label?: string; children: ReactNode }) {
return (
<div className="pointer-events-none sticky bottom-4 z-20 flex justify-center pt-2">
<div
role={label ? 'group' : undefined}
aria-label={label}
className="pointer-events-auto flex max-w-full items-center gap-1.5 rounded-full bg-ink p-1.5 text-ink-foreground shadow-ink"
>
{children}
</div>
</div>
);
}
export function FloatingActionDivider() {
return <span className="mx-0.5 h-5 w-px bg-ink-foreground/15" aria-hidden="true" />;
}
export function FloatingActionDot() {
return <span className="h-2 w-2 shrink-0 rounded-full bg-ink-accent" aria-hidden="true" />;
}
+1 -1
View File
@@ -31,7 +31,7 @@ export function HelpTooltip({ content, label, side = 'top', icon: Icon = HelpCir
type="button"
aria-label={ariaLabel}
className={cn(
'inline-flex shrink-0 cursor-help items-center rounded-sm text-muted-foreground/60 hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring',
'inline-flex shrink-0 cursor-help items-center rounded-full text-dim transition-colors hover:text-brand-text focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
className,
)}
onClick={(e) => e.preventDefault()}
+8 -3
View File
@@ -11,9 +11,14 @@ import { cn } from '@/lib/utils';
export function LoadingFallback({ fullScreen = false }: { fullScreen?: boolean }) {
const { t } = useTranslation();
return (
<div className={cn('flex flex-col items-center justify-center gap-3', fullScreen ? 'min-h-screen' : 'p-8')}>
<Loader2 className="h-8 w-8 animate-spin text-primary" />
<p className="text-muted-foreground">{t('common.loading')}</p>
<div
className={cn(
'flex flex-col items-center justify-center gap-3',
fullScreen ? 'min-h-screen bg-background' : 'p-8',
)}
>
<Loader2 className="h-7 w-7 animate-spin text-brand-text" aria-hidden="true" />
<p className="text-sm text-muted-foreground">{t('common.loading')}</p>
</div>
);
}
+1 -1
View File
@@ -19,7 +19,7 @@ export function Markdown({ source, className }: MarkdownProps) {
return (
<div
className={cn(
'[&_a]:underline [&_code]:font-mono [&_ol]:list-decimal [&_ol]:pl-4 [&_p+p]:mt-1 [&_ul]:list-disc [&_ul]:pl-4',
'[&_a]:font-medium [&_a]:underline [&_a]:underline-offset-2 [&_code]:rounded [&_code]:bg-current/10 [&_code]:px-1 [&_code]:py-px [&_code]:font-mono [&_code]:text-[0.92em] [&_ol]:list-decimal [&_ol]:pl-4 [&_p+p]:mt-1 [&_ul]:list-disc [&_ul]:pl-4',
className,
)}
>
+8 -8
View File
@@ -8,7 +8,7 @@ import { useTranslation } from 'react-i18next';
import { Loader2, X } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { ObjectSearchPopover } from '@/components/common/ObjectSearchPopover';
import { ObjectFieldFrame, ObjectSearchPopover } from '@/components/common/ObjectSearchPopover';
import { useNoPermissionMessage } from '@/lib/objectOptions';
import { useObjectOptions, useDisplayName } from '@/data/objectOptions';
import type { Schema } from '@/types/schema';
@@ -36,11 +36,11 @@ export function ObjectPicker({ schema, objectName, label, value, onChange, onCle
const noPermissionMessage = useNoPermissionMessage(schema, objectName);
return (
<div className="flex items-center gap-2 flex-wrap">
<ObjectFieldFrame disabled={!!noPermissionMessage}>
{value && (
<Badge variant="secondary" className="gap-1 pr-1.5 text-sm max-w-xs">
<Badge variant="secondary" className="h-7 max-w-xs gap-1 pl-3 pr-1 text-[13px] font-medium">
{labelLoading ? (
<Loader2 className="h-3 w-3 animate-spin" />
<Loader2 className="h-3 w-3 animate-spin" aria-hidden="true" />
) : (
<span className="truncate" title={display ?? value}>
{display ?? value}
@@ -50,17 +50,17 @@ export function ObjectPicker({ schema, objectName, label, value, onChange, onCle
<button
type="button"
onClick={onClear}
className="ml-1 rounded-full hover:bg-muted-foreground/20 p-0.5"
className="grid size-5 shrink-0 place-items-center rounded-full bg-card text-muted-foreground transition-colors hover:bg-highlight hover:text-highlight-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
aria-label={t('field.clearValue', 'Clear {{name}}', { name: label })}
>
<X className="h-3 w-3" />
<X className="h-3 w-3" aria-hidden="true" />
</button>
)}
</Badge>
)}
{!value && placeholder && <span className="text-sm text-muted-foreground">{placeholder}</span>}
<ObjectSearchPopover
label={t('field.chooseValue', 'Choose {{name}}', { name: label })}
placeholder={value ? '' : (placeholder ?? t('field.selectEllipsis', 'Select...'))}
options={list.options}
loading={list.loading}
error={list.error}
@@ -68,6 +68,6 @@ export function ObjectPicker({ schema, objectName, label, value, onChange, onCle
onSelect={onChange}
disabledMessage={noPermissionMessage}
/>
</div>
</ObjectFieldFrame>
);
}
+47 -9
View File
@@ -6,12 +6,14 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Loader2, Search } from 'lucide-react';
import type { ReactNode } from 'react';
import { ChevronsUpDown, Loader2, Search } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from '@/components/ui/command';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { errorMessage } from '@/lib/jmapErrors';
import { cn } from '@/lib/utils';
import type { ObjectOption } from '@/data/objectOptions';
import type { ControlProps } from '@/components/forms/widgets/types';
@@ -25,8 +27,26 @@ export interface ObjectSearchPopoverProps {
disabled?: boolean;
label: string;
control?: ControlProps;
placeholder?: string;
}
export function ObjectFieldFrame({ disabled, children }: { disabled?: boolean; children: ReactNode }) {
return (
<div
data-slot="object-field"
className={cn(
'field-surface flex min-h-9 w-full flex-wrap items-center gap-1.5 rounded-lg p-1',
disabled && 'opacity-60',
)}
>
{children}
</div>
);
}
const INLINE_TRIGGER =
'h-7 min-w-[6rem] flex-1 justify-between gap-2 rounded-md px-2 text-sm font-normal text-dim shadow-none hover:bg-transparent hover:text-foreground focus-visible:ring-0 focus-visible:ring-offset-0';
export function ObjectSearchPopover({
options,
loading,
@@ -37,6 +57,7 @@ export function ObjectSearchPopover({
disabled,
label,
control,
placeholder,
}: ObjectSearchPopoverProps) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
@@ -50,8 +71,11 @@ export function ObjectSearchPopover({
{...control}
type="button"
variant="ghost"
size="icon"
className="h-7 w-7 cursor-not-allowed opacity-60"
size={placeholder === undefined ? 'icon' : 'sm'}
className={cn(
'cursor-not-allowed',
placeholder === undefined ? 'h-8 w-8 bg-muted opacity-60' : INLINE_TRIGGER,
)}
aria-label={label}
aria-disabled="true"
onClick={(e) => {
@@ -60,7 +84,7 @@ export function ObjectSearchPopover({
setTooltipOpen(true);
}}
>
<Search className="h-4 w-4" aria-hidden="true" />
<TriggerContent placeholder={placeholder} />
</Button>
</TooltipTrigger>
<TooltipContent>{disabledMessage}</TooltipContent>
@@ -81,15 +105,19 @@ export function ObjectSearchPopover({
{...control}
type="button"
variant="ghost"
size="icon"
className="h-7 w-7"
size={placeholder === undefined ? 'icon' : 'sm'}
className={
placeholder === undefined
? 'h-8 w-8 bg-muted hover:bg-highlight hover:text-highlight-foreground'
: INLINE_TRIGGER
}
aria-label={label}
disabled={disabled}
>
<Search className="h-4 w-4" aria-hidden="true" />
<TriggerContent placeholder={placeholder} />
</Button>
</PopoverTrigger>
<PopoverContent className="w-72 p-0" align="start">
<PopoverContent className="w-72 overflow-hidden p-0" align="start">
<Command>
<CommandInput placeholder={t('common.searchPlaceholder', 'Search...')} />
<CommandList>
@@ -100,7 +128,7 @@ export function ObjectSearchPopover({
</div>
)}
{!loading && error && (
<div className="space-y-2 px-3 py-4 text-center text-sm" role="alert">
<div className="m-2 space-y-2 rounded-xl bg-destructive-soft px-3 py-4 text-center text-sm" role="alert">
<p className="text-destructive">
{errorMessage(error, t('field.optionsLoadFailed', 'Failed to load options.'))}
</p>
@@ -133,3 +161,13 @@ export function ObjectSearchPopover({
</Popover>
);
}
function TriggerContent({ placeholder }: { placeholder?: string }) {
if (placeholder === undefined) return <Search className="h-4 w-4" aria-hidden="true" />;
return (
<>
<span className="truncate">{placeholder}</span>
<ChevronsUpDown className="h-4 w-4 shrink-0 opacity-60" aria-hidden="true" />
</>
);
}
+13 -15
View File
@@ -10,7 +10,7 @@ import { useBufferedValue } from '@/hooks/useBufferedValue';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Separator } from '@/components/ui/separator';
import { cn } from '@/lib/utils';
import { X, Plus } from 'lucide-react';
@@ -98,12 +98,12 @@ export function ExpressionEditor({ value, onChange, readOnly = false, label, con
};
return (
<div className="rounded-lg border bg-card p-4 space-y-3">
<div className="space-y-2.5 rounded-xl bg-muted p-3">
{matchEntries.map(([key, entry], index) => (
<div key={key}>
<div className="rounded-md border bg-muted/30 p-3 space-y-2">
<div className="space-y-2 rounded-lg bg-card p-3">
<div className="flex items-center gap-2">
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground w-12 shrink-0">
<span className="w-12 shrink-0 text-[11px] font-semibold uppercase tracking-wider text-dim">
{t('expression.if', 'IF')}
</span>
<BufferedExprInput
@@ -117,18 +117,18 @@ export function ExpressionEditor({ value, onChange, readOnly = false, label, con
{!readOnly && (
<Button
type="button"
variant="ghost"
size="icon"
className="h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive"
variant="ghost-danger"
size="icon-sm"
className="shrink-0"
onClick={() => handleRemove(key)}
aria-label={t('expression.removeCondition', 'Remove condition {{n}}', { n: index + 1 })}
>
<X className="h-4 w-4" />
<X aria-hidden="true" />
</Button>
)}
</div>
<div className="flex items-center gap-2">
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground w-12 shrink-0">
<span className="w-12 shrink-0 text-[11px] font-semibold uppercase tracking-wider text-dim">
{t('expression.then', 'THEN')}
</span>
<BufferedExprInput
@@ -142,7 +142,6 @@ export function ExpressionEditor({ value, onChange, readOnly = false, label, con
{!readOnly && <div className="w-8 shrink-0" />}
</div>
</div>
{index < matchEntries.length - 1 && <Separator className="my-3" />}
</div>
))}
@@ -153,18 +152,17 @@ export function ExpressionEditor({ value, onChange, readOnly = false, label, con
variant="ghost"
size="sm"
onClick={handleAdd}
className="h-7 gap-1 px-2 text-xs text-muted-foreground hover:text-foreground"
className="h-7 gap-1 px-3 text-xs hover:bg-card"
>
<Plus className="h-3 w-3" />
<Plus className="!size-3.5" aria-hidden="true" />
{t('expression.addCondition', 'Add condition')}
</Button>
</div>
)}
{matchEntries.length > 0 && <Separator />}
<div className="flex items-center gap-2">
<div className={cn('flex items-center gap-2', matchEntries.length > 0 && 'border-t border-border pt-2.5')}>
{matchEntries.length > 0 && (
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground w-12 shrink-0">
<span className="w-12 shrink-0 text-[11px] font-semibold uppercase tracking-wider text-dim">
{t('expression.else', 'ELSE')}
</span>
)}
+6 -4
View File
@@ -48,16 +48,18 @@ export function CreatedValuesDialog({ values, labels, onContinue }: CreatedValue
)}
</DialogDescription>
</DialogHeader>
<div className="space-y-3 py-2">
<div className="space-y-1 divide-y divide-border rounded-xl bg-muted px-4 py-1">
{values &&
Object.entries(values).map(([key, value]) => {
const text = displayValue(value);
const label = labels.get(key) ?? key;
return (
<div key={key} className="flex flex-col gap-1">
<span className="text-sm font-medium">{label}</span>
<div key={key} className="flex flex-col gap-1.5 py-3">
<span className="text-[13px] font-semibold text-muted-foreground">{label}</span>
<div className="flex items-start gap-2">
<code className="flex-1 rounded bg-muted p-2 text-sm break-all select-all">{text}</code>
<code className="flex-1 select-all break-all rounded-lg bg-card px-3 py-2 font-mono text-sm">
{text}
</code>
<CopyButton value={text} label={label} />
</div>
</div>
+163 -59
View File
@@ -4,12 +4,13 @@
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import { useState } from 'react';
import { useEffect, useId, useState, useSyncExternalStore } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { ArrowLeft, Loader2, RefreshCw, Save, Trash2 } from 'lucide-react';
import { ArrowLeft, Check, Loader2, RefreshCw, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { ConfirmDialog } from '@/components/common/ConfirmDialog';
import { FloatingActionBar, FloatingActionDivider, FloatingActionDot } from '@/components/common/FloatingActionBar';
import { useCanAccess } from '@/hooks/usePermissions';
import { coerceLabel } from '@/lib/objectOptions';
import { TENANT_PROPERTY } from '@/lib/schemaResolver';
@@ -19,6 +20,10 @@ import { FormSections } from '@/components/forms/FormSections';
import { UnsavedChangesDialog } from '@/components/forms/UnsavedChangesDialog';
import { formFieldLabels } from '@/components/forms/formLogic';
import { useDynamicForm, type DynamicFormModel } from '@/components/forms/useDynamicForm';
import type { RenderableSection } from '@/components/forms/formLogic';
import { cn } from '@/lib/utils';
const SECTION_INDEX_MIN = 3;
interface DynamicFormProps {
viewName: string;
@@ -44,6 +49,80 @@ function useFormTitle(model: DynamicFormModel): string {
: t('form.editTitle', 'Edit {{name}}', { name });
}
const WIDE_QUERY = '(min-width: 80rem)';
function subscribeWide(onChange: () => void): () => void {
const query = window.matchMedia(WIDE_QUERY);
query.addEventListener('change', onChange);
return () => query.removeEventListener('change', onChange);
}
function isWide(): boolean {
return window.matchMedia(WIDE_QUERY).matches;
}
function useActiveSection(ids: readonly string[]): string | undefined {
const [active, setActive] = useState<string | undefined>(ids[0]);
const key = ids.join('|');
useEffect(() => {
if (!key) return;
const list = key.split('|');
const visible = new Set<string>();
const observer = new IntersectionObserver(
(entries) => {
for (const entry of entries) {
if (entry.isIntersecting) visible.add(entry.target.id);
else visible.delete(entry.target.id);
}
const first = list.find((id) => visible.has(id));
if (first) setActive(first);
},
{ rootMargin: '-80px 0px -55% 0px' },
);
for (const id of list) {
const el = document.getElementById(id);
if (el) observer.observe(el);
}
return () => observer.disconnect();
}, [key]);
return active;
}
function SectionIndex({ sections, sectionId }: { sections: RenderableSection[]; sectionId: (key: string) => string }) {
const { t } = useTranslation();
const titled = sections.filter((s) => s.title);
const active = useActiveSection(titled.map((s) => sectionId(s.key)));
return (
<nav
aria-label={t('form.sectionIndex', 'Form sections')}
className="sticky top-20 flex max-h-[calc(100vh-6rem)] flex-col gap-0.5 overflow-y-auto pt-1"
>
{titled.map((section) => {
const id = sectionId(section.key);
return (
<button
key={section.key}
type="button"
aria-current={active === id ? 'location' : undefined}
onClick={() => {
const section = document.getElementById(id);
section?.scrollIntoView({ behavior: 'smooth', block: 'start' });
section?.focus({ preventScroll: true });
}}
className={cn(
'rounded-[10px] px-3 py-1.5 text-left text-[13px] font-medium text-muted-foreground transition-colors hover:bg-card hover:text-foreground',
active === id &&
'bg-highlight font-semibold text-highlight-foreground hover:bg-highlight hover:text-highlight-foreground',
)}
>
{section.title}
</button>
);
})}
</nav>
);
}
function Loading({ label }: { label: string }) {
return (
<div className="flex items-center justify-center p-12 text-muted-foreground" role="status">
@@ -62,6 +141,8 @@ export function DynamicForm({ viewName, objectId }: DynamicFormProps) {
const { schema, resolved, mode, isSingleton, state, isDirty, saving, loading, loadError } = model;
const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
const title = useFormTitle(model);
const sectionPrefix = useId();
const wide = useSyncExternalStore(subscribeWide, isWide, () => false);
if (!schema || !resolved) return <Loading label={t('form.loadingSchema', 'Loading schema...')} />;
if (loading) return <Loading label={t('form.loadingData', 'Loading data...')} />;
@@ -72,18 +153,19 @@ export function DynamicForm({ viewName, objectId }: DynamicFormProps) {
const subtitle = (model.parentForm ?? model.variantForm)?.subtitle;
const errorText = state.generalError ?? loadError;
const header = (
<div className="flex items-center gap-4">
<div className="flex items-start gap-3.5 px-1 pb-1 pt-3">
<Button
type="button"
variant="ghost"
size="icon"
variant="outline"
size="icon-lg"
className="shrink-0"
onClick={() => navigate(-1)}
aria-label={t('common.back', 'Back')}
>
<ArrowLeft className="h-5 w-5" aria-hidden="true" />
</Button>
<div className="flex-1">
<h1 className="text-2xl font-semibold tracking-tight">{title}</h1>
<div className="min-w-0 flex-1 pt-1">
<h1 className="page-title break-words">{title}</h1>
{subtitle && <p className="mt-1 text-sm text-muted-foreground">{subtitle}</p>}
</div>
</div>
@@ -91,9 +173,9 @@ export function DynamicForm({ viewName, objectId }: DynamicFormProps) {
if (model.loadFailed) {
return (
<div className="mx-auto max-w-4xl space-y-6">
<div className="mx-auto max-w-5xl space-y-5">
{header}
<div className="rounded-md border border-destructive/20 bg-destructive/10 p-4" role="alert">
<div className="rounded-xl bg-destructive-soft p-4" role="alert">
<p className="whitespace-pre-line text-sm text-destructive">{loadError}</p>
</div>
<Button type="button" variant="outline" onClick={model.retryLoad}>
@@ -110,68 +192,90 @@ export function DynamicForm({ viewName, objectId }: DynamicFormProps) {
).toLowerCase();
const sch = resolved.resolvedSchema;
const tenantValue = state.data[TENANT_PROPERTY];
const sectionId = (key: string) => `${sectionPrefix}-section-${key.replace(/[^A-Za-z0-9_-]/g, '_')}`;
const showIndex = model.sections.filter((s) => s.title).length >= SECTION_INDEX_MIN;
return (
<div className="mx-auto max-w-4xl space-y-6">
<div className={cn('mx-auto space-y-5', showIndex ? 'max-w-6xl' : 'max-w-5xl')}>
{header}
{errorText && (
<div className="rounded-md border border-destructive/20 bg-destructive/10 p-4" role="alert">
<div className="rounded-xl bg-destructive-soft p-4" role="alert">
<p className="whitespace-pre-line text-sm text-destructive">{errorText}</p>
</div>
)}
<FormProvider
schema={schema}
mode={mode}
readOnly={readOnly}
recordLabel={model.recordLabel}
baseline={state.original}
tenantId={typeof tenantValue === 'string' ? tenantValue : null}
>
<FormSections
sections={model.sections}
data={state.data}
errors={state.fieldErrors}
readOnly={readOnly}
onFieldChange={model.setField}
variant={
sch.type === 'multiple'
? { variants: sch.variants, value: state.variant, onChange: model.setVariant }
: undefined
}
/>
</FormProvider>
<div className="flex items-center justify-between pb-8 pt-2">
<div>
{canDelete && (
<Button type="button" variant="destructive" disabled={saving} onClick={() => setDeleteConfirmOpen(true)}>
<Trash2 className="mr-2 h-4 w-4" aria-hidden="true" />
{t('common.delete', 'Delete')}
</Button>
)}
</div>
<div className="flex items-center gap-3">
{isDirty && (
<span className="text-xs text-muted-foreground">{t('form.unsavedChangesLabel', 'Unsaved changes')}</span>
)}
<Button type="button" variant="outline" onClick={() => navigate(-1)} disabled={saving}>
{t('common.cancel', 'Cancel')}
</Button>
{!readOnly && (
<Button type="button" onClick={() => void model.save()} disabled={saving || (!isCreate && !isDirty)}>
{saving ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden="true" />
) : (
<Save className="mr-2 h-4 w-4" aria-hidden="true" />
)}
{isCreate ? t('common.create', 'Create') : t('common.save', 'Save')}
</Button>
)}
<div className={cn(showIndex && 'xl:grid xl:grid-cols-[11rem_minmax(0,1fr)] xl:items-start xl:gap-6')}>
{showIndex && wide && <SectionIndex sections={model.sections} sectionId={sectionId} />}
<div className="space-y-3.5">
<FormProvider
schema={schema}
mode={mode}
readOnly={readOnly}
recordLabel={model.recordLabel}
baseline={state.original}
tenantId={typeof tenantValue === 'string' ? tenantValue : null}
>
<FormSections
sections={model.sections}
sectionId={sectionId}
data={state.data}
errors={state.fieldErrors}
readOnly={readOnly}
onFieldChange={model.setField}
variant={
sch.type === 'multiple'
? { variants: sch.variants, value: state.variant, onChange: model.setVariant }
: undefined
}
/>
</FormProvider>
</div>
</div>
<FloatingActionBar label={t('form.actions', 'Form actions')}>
{canDelete && (
<>
<Button
type="button"
variant="ink-danger"
size="sm"
disabled={saving}
onClick={() => setDeleteConfirmOpen(true)}
>
<Trash2 className="h-4 w-4" aria-hidden="true" />
<span className="max-sm:sr-only">{t('common.delete', 'Delete')}</span>
</Button>
<FloatingActionDivider />
</>
)}
{isDirty && (
<span className="flex items-center gap-2 px-2 text-[13px] text-ink-muted max-sm:hidden">
<FloatingActionDot />
{t('form.unsavedChangesLabel', 'Unsaved changes')}
</span>
)}
<Button type="button" variant="ink" size="sm" onClick={() => navigate(-1)} disabled={saving}>
{t('common.cancel', 'Cancel')}
</Button>
{!readOnly && (
<Button
type="button"
size="sm"
className="shadow-none"
onClick={() => void model.save()}
disabled={saving || (!isCreate && !isDirty)}
>
{saving ? (
<Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />
) : (
<Check className="h-4 w-4" aria-hidden="true" />
)}
{isCreate ? t('common.create', 'Create') : t('common.save', 'Save')}
</Button>
)}
</FloatingActionBar>
<UnsavedChangesDialog blocker={model.guard.blocker} />
<ConfirmDialog
+39 -22
View File
@@ -44,16 +44,16 @@ interface FieldLabelProps {
export function FieldLabel({ id, htmlFor, label, marker, locked }: FieldLabelProps) {
const { t } = useTranslation();
return (
<div className="flex items-center gap-2">
<Label id={id} htmlFor={htmlFor} className="text-sm font-medium">
<div className="flex items-center gap-1.5">
<Label id={id} htmlFor={htmlFor} className="text-[13.5px] font-semibold leading-snug">
{label}
{marker === 'required' && (
<span className="ml-0.5 text-destructive" aria-hidden="true">
<span className="ml-1 text-brand-text" aria-hidden="true">
*
</span>
)}
{marker === 'optional' && (
<span className="ml-1.5 text-xs font-normal text-muted-foreground">{t('field.optional', '(optional)')}</span>
<span className="ml-1.5 text-xs font-normal text-dim">{t('field.optional', '(optional)')}</span>
)}
</Label>
{locked && (
@@ -70,7 +70,7 @@ export function FieldLabel({ id, htmlFor, label, marker, locked }: FieldLabelPro
export function FieldError({ id, error }: { id: string; error?: string }) {
if (!error) return null;
return (
<p id={id} className="text-xs text-destructive">
<p id={id} className="text-xs font-medium text-destructive">
{error}
</p>
);
@@ -132,32 +132,49 @@ export function FieldRow({ field, formField, value, onChange, error, readOnly: f
if (traits.labelMode === 'none') {
return (
<div className="space-y-1.5">
<div data-slot="field-row" className="space-y-1.5 py-4">
{body}
<FieldError id={ids.errorId} error={error} />
</div>
);
}
const layout = asValue && traits.layout === 'inline' ? 'side' : traits.layout;
return (
<div className="space-y-1.5">
<FieldLabel
id={ids.labelId}
htmlFor={traits.labelMode === 'control' && !asValue ? ids.inputId : undefined}
label={formField.label}
marker={marker}
locked={locked}
/>
{field.description && (
<div id={ids.descriptionId}>
<Markdown source={field.description} className="text-xs text-muted-foreground" />
<div
data-slot="field-row"
className={cn(
'py-4',
layout === 'side' ? 'field-grid' : 'grid gap-x-8 gap-y-2',
layout === 'inline' && 'grid-cols-[minmax(0,1fr)_auto]',
)}
>
<div className={cn('min-w-0 space-y-1', layout === 'side' && '@xl:pt-2')}>
<FieldLabel
id={ids.labelId}
htmlFor={traits.labelMode === 'control' && !asValue ? ids.inputId : undefined}
label={formField.label}
marker={marker}
locked={locked}
/>
{field.description && (
<div id={ids.descriptionId}>
<Markdown source={field.description} className="text-[12.5px] leading-relaxed text-muted-foreground" />
</div>
)}
</div>
<div className={cn('min-w-0 space-y-1.5', layout === 'inline' && 'pt-0.5', asValue && '@xl:pt-2')}>
<div className={cn(locked && 'opacity-60')}>{body}</div>
{ft.type === 'string' && ft.format === 'sieve' && (
<SievepadButton scriptName={ctx.recordLabel} source={typeof value === 'string' ? value : ''} />
)}
{layout !== 'inline' && <FieldError id={ids.errorId} error={error} />}
</div>
{layout === 'inline' && error && (
<div className="col-span-full">
<FieldError id={ids.errorId} error={error} />
</div>
)}
<div className={cn(locked && 'opacity-60')}>{body}</div>
{ft.type === 'string' && ft.format === 'sieve' && (
<SievepadButton scriptName={ctx.recordLabel} source={typeof value === 'string' ? value : ''} />
)}
<FieldError id={ids.errorId} error={error} />
</div>
);
}
+21 -14
View File
@@ -5,10 +5,10 @@
*/
import type { ReactNode } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { FieldRow } from '@/components/forms/FieldRow';
import { VariantSelect } from '@/components/forms/VariantSelect';
import type { EmbeddedVariant } from '@/lib/embeddedSchema';
import { cn } from '@/lib/utils';
import type { FieldErrors, FieldValues, RenderableSection } from '@/components/forms/formLogic';
interface VariantControl {
@@ -19,6 +19,7 @@ interface VariantControl {
interface FormSectionsProps {
sections: RenderableSection[];
sectionId?: (key: string) => string;
data: FieldValues;
errors: FieldErrors;
readOnly: boolean;
@@ -26,11 +27,19 @@ interface FormSectionsProps {
variant?: VariantControl;
}
export function FormSections({ sections, data, errors, readOnly, onFieldChange, variant }: FormSectionsProps) {
export function FormSections({
sections,
sectionId,
data,
errors,
readOnly,
onFieldChange,
variant,
}: FormSectionsProps) {
return (
<>
{sections.map((section) => (
<FormSectionCard key={section.key} title={section.title}>
<FormSectionCard key={section.key} id={sectionId?.(section.key)} title={section.title}>
{section.fields.map(({ formField, field }) => {
if (!field) {
if (!variant) return null;
@@ -62,17 +71,15 @@ export function FormSections({ sections, data, errors, readOnly, onFieldChange,
);
}
export function FormSectionCard({ title, children }: { title?: string; children: ReactNode }) {
export function FormSectionCard({ id, title, children }: { id?: string; title?: string; children: ReactNode }) {
return (
<Card>
{title && (
<CardHeader>
<CardTitle className="text-base">{title}</CardTitle>
</CardHeader>
)}
<CardContent className={title ? '' : 'pt-6'}>
<div className="space-y-6">{children}</div>
</CardContent>
</Card>
<section
id={id}
tabIndex={id ? -1 : undefined}
className="tile @container scroll-mt-20 px-5 pb-1.5 outline-none sm:px-6"
>
{title && <h2 className="section-title pb-1 pt-5">{title}</h2>}
<div className={cn('divide-y divide-border', !title && 'pt-1')}>{children}</div>
</section>
);
}
+3 -3
View File
@@ -48,8 +48,8 @@ export function SievepadButton({ scriptName, source }: SievepadButtonProps) {
return (
<>
<div className="flex justify-end">
<Button type="button" variant="outline" size="sm" onClick={handleClick} disabled={!source.trim()}>
<Bug className="h-4 w-4" />
<Button type="button" variant="secondary" size="sm" onClick={handleClick} disabled={!source.trim()}>
<Bug aria-hidden="true" />
{t('sievepad.debug', 'Debug')}
</Button>
</div>
@@ -64,7 +64,7 @@ export function SievepadButton({ scriptName, source }: SievepadButtonProps) {
confirmLabel={t('common.continue')}
onConfirm={handleContinue}
>
<div className="flex items-center gap-2">
<div className="flex items-center gap-2.5 rounded-xl bg-muted px-3.5 py-3">
<Checkbox
id="sievepad-dont-show-again"
checked={dontShowAgain}
+132 -17
View File
@@ -4,12 +4,17 @@
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import type { KeyboardEvent } from 'react';
import { useTranslation } from 'react-i18next';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { FieldLabel } from '@/components/forms/FieldRow';
import { fieldIds, useFieldScope, useFormContext } from '@/components/forms/formContext';
import { fieldIds, useFieldScope, useFormContext, useInPanel } from '@/components/forms/formContext';
import { VARIANT_FIELD } from '@/components/forms/formLogic';
import type { EmbeddedVariant } from '@/lib/embeddedSchema';
import { cn } from '@/lib/utils';
const SEGMENTED_MAX_VARIANTS = 4;
const SEGMENTED_MAX_LABEL_CHARS = 44;
interface VariantSelectProps {
label?: string;
@@ -21,6 +26,102 @@ interface VariantSelectProps {
readOnly: boolean;
}
function isSegmented(variants: readonly EmbeddedVariant[]): boolean {
return (
variants.length > 1 &&
variants.length <= SEGMENTED_MAX_VARIANTS &&
variants.reduce((sum, v) => sum + v.label.length, 0) <= SEGMENTED_MAX_LABEL_CHARS
);
}
interface VariantControlProps {
id: string;
labelledBy?: string;
ariaLabel?: string;
variants: readonly EmbeddedVariant[];
value: string;
onChange: (variant: string) => void;
readOnly: boolean;
}
const ROVING_KEYS: Record<string, number> = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 };
function moveRadioFocus(e: KeyboardEvent<HTMLDivElement>) {
const step = Object.hasOwn(ROVING_KEYS, e.key) ? ROVING_KEYS[e.key] : 0;
if (!step && e.key !== 'Home' && e.key !== 'End') return;
const radios = Array.from(e.currentTarget.querySelectorAll<HTMLButtonElement>('[role="radio"]'));
if (radios.length === 0) return;
e.preventDefault();
const current = radios.indexOf(document.activeElement as HTMLButtonElement);
const next =
e.key === 'Home'
? 0
: e.key === 'End'
? radios.length - 1
: (Math.max(current, 0) + step + radios.length) % radios.length;
radios[next].focus();
}
function SegmentedVariants({ id, labelledBy, ariaLabel, variants, value, onChange, readOnly }: VariantControlProps) {
const inPanel = useInPanel();
const hasChecked = variants.some((v) => v.name === value);
return (
<div
role="radiogroup"
id={id}
aria-labelledby={labelledBy}
aria-label={ariaLabel}
aria-disabled={readOnly || undefined}
onKeyDown={moveRadioFocus}
className={cn(
'inline-flex max-w-full flex-wrap gap-0.5 rounded-full p-1',
inPanel ? 'bg-muted-strong' : 'bg-muted',
)}
>
{variants.map((v, i) => {
const checked = v.name === value;
return (
<button
key={v.name}
type="button"
role="radio"
aria-checked={checked}
tabIndex={checked || (!hasChecked && i === 0) ? 0 : -1}
disabled={readOnly}
onClick={() => {
if (!checked) onChange(v.name);
}}
className={cn(
'inline-flex h-7 items-center rounded-full px-3 text-[13px] font-semibold text-muted-foreground outline-none transition-[color,background-color,box-shadow] duration-200 focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-60',
checked ? 'bg-card text-foreground shadow-tile' : 'hover:text-foreground',
)}
>
{v.label}
</button>
);
})}
</div>
);
}
function DropdownVariants({ id, labelledBy, ariaLabel, variants, value, onChange, readOnly }: VariantControlProps) {
const { t } = useTranslation();
return (
<Select value={value} onValueChange={onChange} disabled={readOnly}>
<SelectTrigger id={id} className="w-full" aria-labelledby={labelledBy} aria-label={ariaLabel}>
<SelectValue placeholder={t('form.selectType', 'Select type...')} />
</SelectTrigger>
<SelectContent>
{variants.map((v) => (
<SelectItem key={v.name} value={v.name}>
{v.label}
</SelectItem>
))}
</SelectContent>
</Select>
);
}
export function VariantSelect({
label,
labelledBy,
@@ -35,29 +136,43 @@ export function VariantSelect({
const scope = useFieldScope();
const ids = fieldIds(ctx.idPrefix, [...scope.path, VARIANT_FIELD]);
const external = !!labelledBy || !!ariaLabel;
const segmented = isSegmented(variants);
const Control = segmented ? SegmentedVariants : DropdownVariants;
const controlProps = {
id: ids.inputId,
variants,
value,
onChange,
readOnly,
};
if (external) {
return (
<div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2">
<span className="text-xs font-semibold uppercase tracking-wider text-dim" aria-hidden="true">
{t('field.type', 'Type')}
</span>
<div className={cn('min-w-0', !segmented && 'w-full max-w-sm')}>
<Control {...controlProps} labelledBy={labelledBy} ariaLabel={ariaLabel} />
</div>
</div>
);
}
return (
<div className="space-y-1.5">
{!external && (
<div data-slot="field-row" className="field-grid py-4">
<div className="@xl:pt-2">
<FieldLabel
id={ids.labelId}
htmlFor={ids.inputId}
htmlFor={segmented ? undefined : ids.inputId}
label={label || t('field.type', 'Type')}
marker={null}
locked={false}
/>
)}
<Select value={value} onValueChange={onChange} disabled={readOnly}>
<SelectTrigger id={ids.inputId} className="w-full" aria-labelledby={labelledBy} aria-label={ariaLabel}>
<SelectValue placeholder={t('form.selectType', 'Select type...')} />
</SelectTrigger>
<SelectContent>
{variants.map((v) => (
<SelectItem key={v.name} value={v.name}>
{v.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="min-w-0">
<Control {...controlProps} labelledBy={segmented ? ids.labelId : undefined} />
</div>
</div>
);
}
+6
View File
@@ -30,6 +30,8 @@ export const FormContext = createContext<FormContextValue | null>(null);
export const FieldScopeContext = createContext<FieldScope>({ path: [], readOnly: false });
export const PanelContext = createContext(false);
export function useFormContext(): FormContextValue {
const ctx = useContext(FormContext);
if (!ctx) throw new Error('Form widgets must be rendered inside a FormProvider');
@@ -40,6 +42,10 @@ export function useFieldScope(): FieldScope {
return useContext(FieldScopeContext);
}
export function useInPanel(): boolean {
return useContext(PanelContext);
}
export function isEnterpriseLockedIn(ctx: FormContextValue, enterprise: boolean | undefined): boolean {
return !!enterprise && ctx.isCommunity;
}
+4 -3
View File
@@ -27,7 +27,7 @@ export function BlobWidget({ value, onChange, readOnly, control }: WidgetProps<F
if (blobId && blob.isPending) {
return (
<div className="flex items-center gap-2 py-2 text-sm text-muted-foreground" role="status">
<Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />
<Loader2 className="h-4 w-4 animate-spin text-brand-text" aria-hidden="true" />
{t('field.loadingContent', 'Loading content...')}
</div>
);
@@ -35,7 +35,7 @@ export function BlobWidget({ value, onChange, readOnly, control }: WidgetProps<F
if (blobId && (blob.isError || blob.data === null)) {
return (
<div className="flex items-center justify-between gap-2 rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2">
<div className="flex items-center justify-between gap-3 rounded-xl bg-destructive-soft py-2.5 pl-4 pr-2.5">
<p className="text-sm text-destructive" role="alert">
{blob.isError
? errorMessage(blob.error, t('field.blobLoadFailed', 'Failed to load content.'))
@@ -45,6 +45,7 @@ export function BlobWidget({ value, onChange, readOnly, control }: WidgetProps<F
type="button"
variant="outline"
size="sm"
className="shrink-0"
onClick={() => void blob.refetch()}
disabled={blob.isFetching}
>
@@ -68,7 +69,7 @@ export function BlobWidget({ value, onChange, readOnly, control }: WidgetProps<F
className="font-mono text-xs"
/>
{isOwnEdit && (
<p className="text-xs text-muted-foreground">
<p className="text-xs font-medium text-warning">
{t('field.contentModified', 'Content modified (will be saved as a new blob)')}
</p>
)}
@@ -40,6 +40,7 @@ export function BufferedInput({ value, onCommit, onBlur, onKeyDown, ...rest }: B
}
interface BufferedTextareaProps extends Omit<TextareaHTMLAttributes<HTMLTextAreaElement>, 'onChange' | 'value'> {
variant?: 'field' | 'bare';
value: string;
onCommit: (v: string) => void;
}
@@ -20,7 +20,7 @@ const Calendar = lazy(() => import('@/components/ui/calendar').then((m) => ({ de
function CalendarFallback() {
return (
<div className="flex h-72 w-64 items-center justify-center" role="status">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" aria-hidden="true" />
<Loader2 className="h-5 w-5 animate-spin text-brand-text" aria-hidden="true" />
</div>
);
}
@@ -50,15 +50,15 @@ export function DateTimeWidget({ type, value, onChange, readOnly, control }: Wid
<Button
{...control}
type="button"
variant="outline"
variant="field"
disabled={readOnly}
className={cn('flex-1 justify-start text-left font-normal', !selected && 'text-muted-foreground')}
className={cn('flex-1 justify-start px-3 text-left', !selected && 'text-dim')}
>
<CalendarIcon className="mr-2 h-4 w-4" aria-hidden="true" />
<CalendarIcon className="text-dim" aria-hidden="true" />
{selected ? formatDateTime(selected) : t('field.pickDate', 'Pick a date')}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<PopoverContent className="w-auto overflow-hidden p-0" align="start">
<Suspense fallback={<CalendarFallback />}>
<Calendar
mode="single"
@@ -70,7 +70,7 @@ export function DateTimeWidget({ type, value, onChange, readOnly, control }: Wid
}}
/>
</Suspense>
<div className="border-t p-3">
<div className="border-t border-border bg-muted/60 p-3">
<Input
type="time"
value={localTime}
@@ -92,7 +92,7 @@ export function DateTimeWidget({ type, value, onChange, readOnly, control }: Wid
onClick={() => onChange(null)}
aria-label={t('common.clear', 'Clear')}
>
<X className="h-4 w-4" />
<X aria-hidden="true" />
</Button>
)}
</div>
@@ -8,10 +8,11 @@ import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { FieldRow } from '@/components/forms/FieldRow';
import { VariantSelect } from '@/components/forms/VariantSelect';
import { useFormContext } from '@/components/forms/formContext';
import { PanelContext, useFormContext, useInPanel } from '@/components/forms/formContext';
import { buildEmbeddedDefaults } from '@/lib/schemaResolver';
import { embeddedEntries, isRecord, resolveEmbedded, switchVariantValues } from '@/lib/embeddedSchema';
import type { ControlProps, WidgetProps } from '@/components/forms/widgets/types';
import { cn } from '@/lib/utils';
import type { FieldTypeObject } from '@/types/schema';
interface EmbeddedObjectEditorProps {
@@ -20,11 +21,20 @@ interface EmbeddedObjectEditorProps {
value: unknown;
onChange: (value: unknown) => void;
readOnly: boolean;
bare?: boolean;
}
function EmbeddedObjectEditor({ objectName, control, value, onChange, readOnly }: EmbeddedObjectEditorProps) {
export function EmbeddedObjectEditor({
objectName,
control,
value,
onChange,
readOnly,
bare = false,
}: EmbeddedObjectEditorProps) {
const { t } = useTranslation();
const { schema, mode, baseline } = useFormContext();
const inPanel = useInPanel();
const [initial, setInitial] = useState({ baseline, value });
if (initial.baseline !== baseline) setInitial({ baseline, value });
const resolved = resolveEmbedded(schema, objectName, value);
@@ -46,28 +56,46 @@ function EmbeddedObjectEditor({ objectName, control, value, onChange, readOnly }
};
const entries = embeddedEntries(resolved).filter(({ field }) => field.update !== 'serverSet');
if (!resolved.variants && entries.length === 0) return null;
const frame = bare ? 'bare' : inPanel ? 'rule' : 'panel';
return (
<div className="space-y-4 rounded-md border p-4">
{resolved.variants && (
<VariantSelect
labelledBy={control?.['aria-labelledby']}
ariaLabel={control?.['aria-label']}
variants={resolved.variants}
value={resolved.variant?.name ?? ''}
onChange={changeVariant}
readOnly={readOnly}
/>
)}
{entries.map(({ formField, field }) => (
<FieldRow
key={formField.name}
field={field}
formField={formField}
value={obj[formField.name]}
onChange={(v) => onChange({ ...obj, [formField.name]: v })}
/>
))}
</div>
<PanelContext value={true}>
<div
data-slot="embedded-object"
className={cn(
'@container',
frame === 'panel' && 'rounded-xl bg-muted px-4',
frame === 'rule' && 'border-l-2 border-input pl-4',
)}
>
{resolved.variants && (
<div className={cn(frame === 'panel' ? 'py-3' : 'py-2', entries.length > 0 && 'border-b border-border')}>
<VariantSelect
labelledBy={control?.['aria-labelledby']}
ariaLabel={control?.['aria-label']}
variants={resolved.variants}
value={resolved.variant?.name ?? ''}
onChange={changeVariant}
readOnly={readOnly}
/>
</div>
)}
{entries.length > 0 && (
<div className={cn('divide-y divide-border', frame === 'rule' && '[&>[data-slot=field-row]]:py-3')}>
{entries.map(({ formField, field }) => (
<FieldRow
key={formField.name}
field={field}
formField={formField}
value={obj[formField.name]}
onChange={(v) => onChange({ ...obj, [formField.name]: v })}
/>
))}
</div>
)}
</div>
</PanelContext>
);
}
+13 -8
View File
@@ -98,7 +98,7 @@ export function EnumMultiSelect({ enumName, items, onChange, readOnly, minItems,
const checkboxItem = (v: EnumVariant, idPrefix: string) => {
const id = `${idPrefix}-${v.name.replace(/[^A-Za-z0-9_-]/g, '_')}`;
return (
<div key={v.name} className="flex items-center gap-2 py-0.5">
<div key={v.name} className="flex items-center gap-2.5 rounded-lg px-2 py-1.5 transition-colors hover:bg-muted">
<Checkbox
id={id}
checked={items.includes(v.name)}
@@ -116,7 +116,11 @@ export function EnumMultiSelect({ enumName, items, onChange, readOnly, minItems,
if (variants.length <= SEARCHABLE_THRESHOLD) {
return (
<div className={variants.length > GRID_THRESHOLD ? 'grid grid-cols-2 gap-2' : 'space-y-2'}>
<div
className={
variants.length > GRID_THRESHOLD ? '-mx-2 grid gap-x-2 gap-y-0.5 sm:grid-cols-2' : '-mx-2 space-y-0.5'
}
>
{variants.map((v) => checkboxItem(v, baseId))}
</div>
);
@@ -150,22 +154,23 @@ export function EnumMultiSelect({ enumName, items, onChange, readOnly, minItems,
)}
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button {...control} type="button" variant="outline" size="sm" className="gap-1" disabled={readOnly}>
<Search className="h-4 w-4" aria-hidden="true" />
<Button {...control} type="button" variant="secondary" size="sm" disabled={readOnly}>
<Search aria-hidden="true" />
{t('field.selectOptions', 'Select options...')}
</Button>
</PopoverTrigger>
<PopoverContent className="w-72 p-0" align="start">
<div className="border-b p-2">
<PopoverContent className="w-72 overflow-hidden p-0" align="start">
<div className="p-2 pb-1">
<Input
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder={t('common.searchPlaceholder', 'Search...')}
aria-label={t('common.search', 'Search')}
className="h-8"
variant="pill"
className="h-8 px-3.5"
/>
</div>
<div className="max-h-60 space-y-1 overflow-y-auto p-2">
<div className="max-h-60 space-y-0.5 overflow-y-auto p-1.5">
{filtered.length === 0 && (
<p className="py-2 text-center text-sm text-muted-foreground">{t('field.noMatches', 'No matches')}</p>
)}
+127 -67
View File
@@ -4,22 +4,24 @@
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import { useState, type KeyboardEvent } from 'react';
import { useId, useState, type KeyboardEvent } from 'react';
import { useTranslation } from 'react-i18next';
import { ChevronRight, Loader2, Plus, X } from 'lucide-react';
import { ChevronRight, Loader2, Plus, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { ObjectSearchPopover } from '@/components/common/ObjectSearchPopover';
import { FieldScopeProvider } from '@/components/forms/FormProvider';
import { useFormContext } from '@/components/forms/formContext';
import { PanelContext, useFormContext, useInPanel } from '@/components/forms/formContext';
import { FieldControl } from '@/components/forms/widgets/FieldControl';
import { EmbeddedObjectEditor } from '@/components/forms/widgets/EmbeddedObjectWidget';
import { formatPlaceholder } from '@/components/forms/widgets/placeholders';
import { widgetKey } from '@/components/forms/widgets/registry';
import { useNoPermissionMessage } from '@/lib/objectOptions';
import { useDisplayName, useObjectOptions } from '@/data/objectOptions';
import { buildNewObjectValue, getEnum, getEnumVariant } from '@/lib/schemaResolver';
import { isRecord } from '@/lib/embeddedSchema';
import { cn } from '@/lib/utils';
import type { WidgetProps } from '@/components/forms/widgets/types';
import type { Field, FieldType, FieldTypeMap, MapValueType, ScalarType } from '@/types/schema';
@@ -37,6 +39,8 @@ function defaultMapValue(valueClass: MapValueType, newObject: (objectName: strin
export function MapWidget({ type, formField, value, onChange, readOnly }: WidgetProps<FieldTypeMap>) {
const { t } = useTranslation();
const { schema } = useFormContext();
const inPanel = useInPanel();
const baseId = useId();
const map = isRecord(value) ? value : {};
const entries = Object.entries(map);
const [newKey, setNewKey] = useState('');
@@ -78,77 +82,133 @@ export function MapWidget({ type, formField, value, onChange, readOnly }: Widget
}
};
const objectValues = valueField.type.type === 'object' && widgetKey(valueField.type) !== 'object:x:Rate';
const valueLabel = formField.valueLabel ?? '';
const removeButton = (key: string) =>
!readOnly && (
<Button
type="button"
variant="ghost-danger"
size="icon-sm"
className="shrink-0"
onClick={() => removeEntry(key)}
disabled={!canRemove}
aria-label={t('field.removeEntry', 'Remove entry {{name}}', { name: key })}
>
<Trash2 className="h-4 w-4" aria-hidden="true" />
</Button>
);
const valueControl = (key: string, val: unknown) => (
<FieldScopeProvider name={key} readOnly={readOnly}>
{valueField.type.type === 'object' && widgetKey(valueField.type) === 'object' ? (
<EmbeddedObjectEditor
bare
objectName={valueField.type.objectName}
control={{ 'aria-label': valueLabel || key }}
value={val}
onChange={(v) => onChange({ ...map, [key]: v })}
readOnly={readOnly}
/>
) : (
<FieldControl
type={valueField.type}
field={valueField}
formField={{ name: key, label: valueLabel }}
value={val}
onChange={(v) => onChange({ ...map, [key]: v })}
readOnly={readOnly}
control={{ 'aria-label': valueLabel || key }}
/>
)}
</FieldScopeProvider>
);
return (
<div className="space-y-3">
{entries.map(([key, val]) => (
<Collapsible key={key} open={expanded.has(key)} onOpenChange={(open) => setOpen(key, open)}>
<div className="rounded-md border">
<div className="flex items-center">
<CollapsibleTrigger asChild>
<PanelContext value={true}>
<div
data-slot="map-widget"
className={cn('space-y-0.5 rounded-xl p-1.5', inPanel ? 'bg-card shadow-tile' : 'bg-muted')}
>
{!objectValues && entries.length > 0 && (formField.keyLabel || formField.valueLabel) && (
<div
aria-hidden="true"
className="grid grid-cols-[minmax(0,1fr)_minmax(0,1.2fr)_2rem] gap-3 px-3 pb-0.5 pt-1.5 text-[11px] font-semibold uppercase tracking-wider text-dim"
>
<span>{formField.keyLabel}</span>
<span>{formField.valueLabel}</span>
</div>
)}
{entries.map(([key, val]) =>
objectValues ? (
<div key={key} className={cn('rounded-lg', expanded.has(key) && (inPanel ? 'bg-muted' : 'bg-card'))}>
<div className="flex items-center gap-1 pr-1">
<button
type="button"
className="flex flex-1 items-center gap-2 rounded-t-md p-3 text-sm font-medium transition-colors hover:bg-accent/50 [&[data-state=open]>svg]:rotate-90"
onClick={() => setOpen(key, !expanded.has(key))}
aria-expanded={expanded.has(key)}
aria-controls={`${baseId}-${key}`}
className="flex min-w-0 flex-1 items-center gap-2.5 rounded-lg px-2.5 py-2 text-left text-[13.5px] font-semibold outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<ChevronRight className="h-4 w-4 shrink-0 transition-transform duration-200" aria-hidden="true" />
<MapKeyLabel keyClass={type.keyClass} keyValue={key} />
<ChevronRight
className={cn(
'h-4 w-4 shrink-0 text-dim transition-transform duration-200',
expanded.has(key) && 'rotate-90',
)}
aria-hidden="true"
/>
<span className="truncate">
<MapKeyLabel keyClass={type.keyClass} keyValue={key} />
</span>
</button>
</CollapsibleTrigger>
{!readOnly && (
<Button
type="button"
variant="ghost"
size="icon"
className="mr-2 h-7 w-7 shrink-0"
onClick={() => removeEntry(key)}
disabled={!canRemove}
aria-label={t('field.removeEntry', 'Remove entry {{name}}', { name: key })}
>
<X className="h-4 w-4" aria-hidden="true" />
</Button>
{removeButton(key)}
</div>
{expanded.has(key) && (
<div id={`${baseId}-${key}`} className="border-t border-border px-4">
{valueControl(key, val)}
</div>
)}
</div>
<CollapsibleContent>
<div className="px-4 pb-4 pt-1">
<FieldScopeProvider name={key} readOnly={readOnly}>
<FieldControl
type={valueField.type}
field={valueField}
formField={{ name: key, label: formField.valueLabel ?? '' }}
value={val}
onChange={(v) => onChange({ ...map, [key]: v })}
readOnly={readOnly}
control={{ 'aria-label': formField.valueLabel ?? key }}
/>
</FieldScopeProvider>
</div>
</CollapsibleContent>
) : (
<div
key={key}
className="grid grid-cols-[minmax(0,1fr)_minmax(0,1.2fr)_2rem] items-center gap-3 rounded-lg py-1 pl-3 transition-colors hover:bg-muted-strong/60"
>
<span className="truncate text-sm font-medium">
<MapKeyLabel keyClass={type.keyClass} keyValue={key} />
</span>
<div className="min-w-0">{valueControl(key, val)}</div>
{removeButton(key)}
</div>
),
)}
{!readOnly && canAdd && (
<div className="flex items-center gap-2 p-1">
<MapKeyInput
keyClass={type.keyClass}
label={formField.keyLabel ?? t('field.newKey', 'New key')}
value={newKey}
onChange={setNewKey}
onKeyDown={handleKeyDown}
existingKeys={map}
/>
<Button
type="button"
variant="outline"
size="sm"
onClick={addEntry}
disabled={!trimmedKey || Object.hasOwn(map, trimmedKey)}
className="shrink-0"
>
<Plus className="h-4 w-4" aria-hidden="true" />
{t('field.add', 'Add')}
</Button>
</div>
</Collapsible>
))}
{!readOnly && canAdd && (
<div className="flex items-center gap-2">
<MapKeyInput
keyClass={type.keyClass}
label={formField.keyLabel ?? t('field.newKey', 'New key')}
value={newKey}
onChange={setNewKey}
onKeyDown={handleKeyDown}
existingKeys={map}
/>
<Button
type="button"
variant="outline"
size="sm"
onClick={addEntry}
disabled={!trimmedKey || Object.hasOwn(map, trimmedKey)}
className="shrink-0 gap-1"
>
<Plus className="h-4 w-4" aria-hidden="true" />
{t('field.add', 'Add')}
</Button>
</div>
)}
</div>
)}
{readOnly && entries.length === 0 && (
<p className="px-2.5 py-2 text-sm text-muted-foreground">{t('field.none', 'None')}</p>
)}
</div>
</PanelContext>
);
}
@@ -143,7 +143,7 @@ function UnitNumberWidget({
onClick={() => onChange(null)}
aria-label={t('common.clear', 'Clear')}
>
<X className="h-4 w-4" />
<X aria-hidden="true" />
</Button>
)}
</div>
@@ -6,7 +6,7 @@
import { useTranslation } from 'react-i18next';
import { Loader2 } from 'lucide-react';
import { ObjectSearchPopover } from '@/components/common/ObjectSearchPopover';
import { ObjectFieldFrame, ObjectSearchPopover } from '@/components/common/ObjectSearchPopover';
import { useNoPermissionMessage } from '@/lib/objectOptions';
import { useObjectOptions, useDisplayName, type ObjectOption } from '@/data/objectOptions';
import { useFormContext } from '@/components/forms/formContext';
@@ -52,30 +52,38 @@ export function ObjectIdWidget({
const list = useObjectOptions(type.objectName, schema, tenantId);
const noPermissionMessage = useNoPermissionMessage(schema, type.objectName);
const pill = id ? (
<ObjectIdPill
objectName={type.objectName}
id={id}
options={list.options}
onRemove={!readOnly && type.nullable ? () => onChange(null) : undefined}
/>
) : null;
if (readOnly) {
return (
<div className="flex flex-wrap items-center gap-2">
{pill ?? <span className="text-sm text-dim">{t('field.none', 'None')}</span>}
</div>
);
}
return (
<div className="flex flex-wrap items-center gap-2">
{id && (
<ObjectIdPill
objectName={type.objectName}
id={id}
options={list.options}
onRemove={!readOnly && type.nullable ? () => onChange(null) : undefined}
/>
)}
{!id && readOnly && <span className="text-sm text-muted-foreground">{t('field.none', 'None')}</span>}
{!readOnly && (
<ObjectSearchPopover
control={control}
label={t('field.chooseValue', 'Choose {{name}}', { name: formField.label })}
options={list.options}
loading={list.loading}
error={list.error}
ensureLoaded={list.ensureLoaded}
onSelect={(next) => onChange(next)}
disabledMessage={noPermissionMessage}
/>
)}
</div>
<ObjectFieldFrame disabled={!!noPermissionMessage}>
{pill}
<ObjectSearchPopover
control={control}
label={t('field.chooseValue', 'Choose {{name}}', { name: formField.label })}
placeholder={id ? '' : t('field.selectEllipsis', 'Select...')}
options={list.options}
loading={list.loading}
error={list.error}
ensureLoaded={list.ensureLoaded}
onSelect={(next) => onChange(next)}
disabledMessage={noPermissionMessage}
/>
</ObjectFieldFrame>
);
}
@@ -105,33 +113,40 @@ export function ObjectIdMultiSelect({
const available = list.options.filter((o) => !items.includes(o.id));
const atMinimum = minItems != null && items.length <= minItems;
const pills = items.map((id) => (
<ObjectIdPill
key={id}
objectName={objectName}
id={id}
options={list.options}
removeDisabled={atMinimum}
onRemove={readOnly ? undefined : () => onChange(items.filter((i) => i !== id))}
/>
));
if (readOnly) {
return (
<div className="flex flex-wrap items-center gap-2">
{pills}
{items.length === 0 && <span className="text-sm text-dim">{t('field.none', 'None')}</span>}
</div>
);
}
return (
<div className="flex flex-wrap items-center gap-2">
{items.map((id) => (
<ObjectIdPill
key={id}
objectName={objectName}
id={id}
options={list.options}
removeDisabled={atMinimum}
onRemove={readOnly ? undefined : () => onChange(items.filter((i) => i !== id))}
/>
))}
{!readOnly && (
<ObjectSearchPopover
control={control}
label={t('field.addValue', 'Add {{name}}', { name: label })}
options={available}
loading={list.loading}
error={list.error}
ensureLoaded={list.ensureLoaded}
onSelect={(id) => onChange([...items, id])}
disabledMessage={noPermissionMessage}
/>
)}
{items.length === 0 && readOnly && (
<span className="text-sm text-muted-foreground">{t('field.none', 'None')}</span>
)}
</div>
<ObjectFieldFrame disabled={!!noPermissionMessage}>
{pills}
<ObjectSearchPopover
control={control}
label={t('field.addValue', 'Add {{name}}', { name: label })}
placeholder={items.length === 0 ? t('field.selectEllipsis', 'Select...') : ''}
options={available}
loading={list.loading}
error={list.error}
ensureLoaded={list.ensureLoaded}
onSelect={(id) => onChange([...items, id])}
disabledMessage={noPermissionMessage}
/>
</ObjectFieldFrame>
);
}
@@ -4,14 +4,19 @@
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import { useId, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Plus, X } from 'lucide-react';
import { ChevronRight, Plus, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { FieldScopeProvider } from '@/components/forms/FormProvider';
import { useFormContext } from '@/components/forms/formContext';
import { PanelContext, useFormContext, useInPanel } from '@/components/forms/formContext';
import { FieldControl } from '@/components/forms/widgets/FieldControl';
import { EmbeddedObjectEditor } from '@/components/forms/widgets/EmbeddedObjectWidget';
import { widgetKey } from '@/components/forms/widgets/registry';
import { FieldValue } from '@/components/values/FieldValue';
import { buildNewObjectValue } from '@/lib/schemaResolver';
import { isRecord } from '@/lib/embeddedSchema';
import { embeddedSummary, isRecord } from '@/lib/embeddedSchema';
import { cn } from '@/lib/utils';
import type { WidgetProps } from '@/components/forms/widgets/types';
import type { Field, FieldTypeObject, FieldTypeObjectList } from '@/types/schema';
@@ -22,16 +27,28 @@ export function ObjectListWidget({
value,
onChange,
readOnly,
control,
}: WidgetProps<FieldTypeObjectList>) {
const { t } = useTranslation();
const { schema } = useFormContext();
const inPanel = useInPanel();
const baseId = useId();
const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(() => new Set());
const itemType: FieldTypeObject = { type: 'object', objectName: type.objectName };
const itemField: Field = { description: '', type: itemType, update: field.update, enterprise: field.enterprise };
const embedded = widgetKey(itemType) === 'object';
const items = isRecord(value) ? value : {};
const entries = Object.entries(items).sort(([a], [b]) => Number(a) - Number(b));
const canRemove = type.minItems == null || entries.length > type.minItems;
const canAdd = type.maxItems == null || entries.length < type.maxItems;
const toggle = (key: string) =>
setCollapsed((prev) => {
const next = new Set(prev);
if (!next.delete(key)) next.add(key);
return next;
});
const addItem = () => {
const next = entries.length > 0 ? Math.max(...entries.map(([k]) => Number(k) || 0)) + 1 : 0;
onChange({ ...items, [String(next)]: buildNewObjectValue(schema, type.objectName) });
@@ -41,45 +58,99 @@ export function ObjectListWidget({
const copy = { ...items };
delete copy[key];
onChange(copy);
if (collapsed.has(key)) toggle(key);
};
return (
<div className="space-y-3">
<div className="space-y-2">
{entries.map(([key, item], position) => {
const itemLabel = t('field.itemN', '{{label}} {{n}}', { label: formField.label, n: position + 1 });
const summary = embeddedSummary(schema, type.objectName, item);
const open = !!control['aria-invalid'] || !collapsed.has(key);
const bodyId = `${baseId}-${key}`;
return (
<div key={key} className="space-y-3 rounded-md border p-4">
{!readOnly && (
<div className="flex justify-end">
<div
key={key}
data-slot="object-list-item"
className={cn('overflow-hidden rounded-xl', inPanel ? 'bg-card shadow-tile' : 'bg-muted')}
>
<div className="flex items-center gap-1 py-1.5 pl-1.5 pr-1.5">
<button
type="button"
onClick={() => toggle(key)}
aria-expanded={open}
aria-controls={bodyId}
className="flex min-w-0 flex-1 items-center gap-2.5 rounded-lg px-1.5 py-1 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<ChevronRight
className={cn('h-4 w-4 shrink-0 text-dim transition-transform duration-200', open && 'rotate-90')}
aria-hidden="true"
/>
<span className="flex min-w-0 flex-col">
<span className="truncate text-[13.5px] font-semibold">{summary.variantLabel ?? itemLabel}</span>
{summary.summary && (
<span className="truncate text-[12.5px] text-muted-foreground">
{summary.summary.type ? (
<FieldValue
schema={schema}
type={summary.summary.type}
value={summary.summary.value}
variant="compact"
/>
) : (
String(summary.summary.value)
)}
</span>
)}
</span>
</button>
{!readOnly && (
<Button
type="button"
variant="ghost"
size="icon"
className="h-7 w-7"
variant="ghost-danger"
size="icon-sm"
className="shrink-0"
onClick={() => removeItem(key)}
disabled={!canRemove}
aria-label={t('field.removeItemN', 'Remove item {{n}}', { n: position + 1 })}
>
<X className="h-4 w-4" aria-hidden="true" />
<Trash2 className="h-4 w-4" aria-hidden="true" />
</Button>
</div>
)}
<FieldScopeProvider name={key} readOnly={readOnly}>
<FieldControl
type={itemType}
field={itemField}
formField={{ name: key, label: itemLabel }}
value={item}
onChange={(v) => onChange({ ...items, [key]: v })}
readOnly={readOnly}
control={{ 'aria-label': itemLabel }}
/>
</FieldScopeProvider>
)}
</div>
<div id={bodyId} hidden={!open} className="border-t border-border px-4">
<PanelContext value={true}>
<FieldScopeProvider name={key} readOnly={readOnly}>
{embedded ? (
<EmbeddedObjectEditor
bare
objectName={type.objectName}
control={{ 'aria-label': itemLabel }}
value={item}
onChange={(v) => onChange({ ...items, [key]: v })}
readOnly={readOnly}
/>
) : (
<div className="py-3">
<FieldControl
type={itemType}
field={itemField}
formField={{ name: key, label: itemLabel }}
value={item}
onChange={(v) => onChange({ ...items, [key]: v })}
readOnly={readOnly}
control={{ 'aria-label': itemLabel }}
/>
</div>
)}
</FieldScopeProvider>
</PanelContext>
</div>
</div>
);
})}
{!readOnly && canAdd && (
<Button type="button" variant="outline" size="sm" onClick={addItem} className="gap-1">
<Button type="button" variant="secondary" size="sm" onClick={addItem}>
<Plus className="h-4 w-4" aria-hidden="true" />
{t('field.addItem', 'Add item')}
</Button>
+15 -11
View File
@@ -133,7 +133,7 @@ export function OtpAuthField({ value, onChange, readOnly }: WidgetProps<FieldTyp
if (!isConfigured && setupUrl) {
return (
<div className="rounded-md border bg-muted/30 p-4 space-y-4">
<div className="space-y-4 rounded-xl bg-muted p-4">
<div className="space-y-2">
<p className="text-sm font-medium">{t('otp.scanPrompt', 'Scan with your authenticator app')}</p>
<p className="text-xs text-muted-foreground">
@@ -150,11 +150,11 @@ export function OtpAuthField({ value, onChange, readOnly }: WidgetProps<FieldTyp
alt={t('otp.qrCodeAlt', 'TOTP QR code')}
width={220}
height={220}
className="rounded-md border bg-white p-2"
className="rounded-xl bg-white p-2 shadow-tile"
/>
) : (
<div className="flex h-[220px] w-[220px] items-center justify-center text-muted-foreground">
<Loader2 className="h-6 w-6 animate-spin" />
<Loader2 className="h-6 w-6 animate-spin text-brand-text" aria-hidden="true" />
</div>
)}
</div>
@@ -168,7 +168,9 @@ export function OtpAuthField({ value, onChange, readOnly }: WidgetProps<FieldTyp
)}
</p>
<div className="flex gap-2">
<code className="flex-1 rounded bg-muted p-2 text-sm font-mono break-all select-all">{setupSecret}</code>
<code className="flex-1 select-all break-all rounded-lg bg-card px-3 py-2 font-mono text-sm">
{setupSecret}
</code>
{setupTotp && <CopyButton value={setupTotp.secret.base32} label={t('otp.secret', 'secret')} />}
</div>
</div>
@@ -197,11 +199,11 @@ export function OtpAuthField({ value, onChange, readOnly }: WidgetProps<FieldTyp
)}
</div>
<div className="flex items-center justify-end gap-2">
<Button type="button" variant="outline" size="sm" onClick={cancelSetup}>
<Button type="button" variant="ghost" size="sm" onClick={cancelSetup}>
{t('common.cancel', 'Cancel')}
</Button>
<Button type="button" size="sm" onClick={confirmSetup}>
<ShieldCheck className="mr-2 h-4 w-4" />
<ShieldCheck aria-hidden="true" />
{t('common.confirm', 'Confirm')}
</Button>
</div>
@@ -215,8 +217,8 @@ export function OtpAuthField({ value, onChange, readOnly }: WidgetProps<FieldTyp
<span className="text-sm text-muted-foreground">
{t('otp.statusDisabled', 'Two-factor authentication is not enabled.')}
</span>
<Button type="button" variant="outline" size="sm" onClick={startSetup}>
<ShieldCheck className="mr-2 h-4 w-4" />
<Button type="button" variant="secondary" size="sm" onClick={startSetup}>
<ShieldCheck aria-hidden="true" />
{t('otp.setUp', 'Set up TOTP')}
</Button>
</div>
@@ -224,9 +226,11 @@ export function OtpAuthField({ value, onChange, readOnly }: WidgetProps<FieldTyp
}
return (
<div className="rounded-md border bg-muted/30 p-4 space-y-3">
<div className="space-y-3 rounded-xl bg-muted p-4">
<div className="flex items-center gap-2">
<ShieldCheck className="h-4 w-4 text-green-600" />
<span className="grid size-7 place-items-center rounded-[9px] bg-success-soft text-success">
<ShieldCheck className="h-4 w-4" aria-hidden="true" />
</span>
<span className="text-sm font-medium">{t('otp.statusEnabled', 'Two-factor authentication is enabled.')}</span>
</div>
<p className="text-xs text-muted-foreground">
@@ -253,7 +257,7 @@ export function OtpAuthField({ value, onChange, readOnly }: WidgetProps<FieldTyp
</div>
<div className="flex items-center justify-end">
<Button type="button" variant="destructive" size="sm" onClick={handleDisable} disabled={!otpCodeValue.trim()}>
<ShieldOff className="mr-2 h-4 w-4" />
<ShieldOff aria-hidden="true" />
{t('otp.disable', 'Disable')}
</Button>
</div>
+5 -5
View File
@@ -48,7 +48,7 @@ export function RateWidget({ type, value, onChange, readOnly, control }: WidgetP
};
if (readOnly) {
if (isNull) return <span className="text-sm italic text-muted-foreground">{t('field.notSet', 'Not set')}</span>;
if (isNull) return <span className="text-sm italic text-dim">{t('field.notSet', 'Not set')}</span>;
return (
<span className="text-sm">
{t('rate.summary', '{{amount}} per {{period}}', {
@@ -62,15 +62,15 @@ export function RateWidget({ type, value, onChange, readOnly, control }: WidgetP
if (isNull) {
return (
<div className="flex items-center gap-2">
<span className="text-sm italic text-muted-foreground">{t('field.notSet', 'Not set')}</span>
<span className="text-sm italic text-dim">{t('field.notSet', 'Not set')}</span>
<Button
{...control}
type="button"
variant="outline"
variant="secondary"
size="sm"
onClick={() => onChange({ count: 1, period: 1000 })}
>
<Plus className="mr-1 h-4 w-4" aria-hidden="true" />
<Plus aria-hidden="true" />
{t('field.enable', 'Enable')}
</Button>
</div>
@@ -128,7 +128,7 @@ export function RateWidget({ type, value, onChange, readOnly, control }: WidgetP
onClick={() => onChange(null)}
aria-label={t('common.clear', 'Clear')}
>
<X className="h-4 w-4" />
<X aria-hidden="true" />
</Button>
)}
</div>
@@ -8,6 +8,7 @@ import type { ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { X } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { cn } from '@/lib/utils';
interface RemovablePillProps {
label: string;
@@ -19,7 +20,10 @@ interface RemovablePillProps {
export function RemovablePill({ label, onRemove, removeDisabled, children }: RemovablePillProps) {
const { t } = useTranslation();
return (
<Badge variant="secondary" className="gap-1 pr-1 text-sm">
<Badge
variant="secondary"
className={cn('h-7 max-w-full gap-1 text-[13px] font-medium', onRemove ? 'pl-3 pr-1' : 'px-3')}
>
{children ?? label}
{onRemove && (
<button
@@ -27,7 +31,7 @@ export function RemovablePill({ label, onRemove, removeDisabled, children }: Rem
onClick={onRemove}
disabled={removeDisabled}
aria-label={t('field.removeItem', 'Remove {{name}}', { name: label })}
className="ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20 disabled:cursor-not-allowed disabled:opacity-50"
className="grid size-5 shrink-0 place-items-center rounded-full bg-card text-muted-foreground transition-colors hover:bg-highlight hover:text-highlight-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
>
<X className="h-3 w-3" aria-hidden="true" />
</button>
+4 -3
View File
@@ -128,13 +128,14 @@ function TagInput({ label, items, onChange, readOnly, minItems, maxItems, placeh
/>
<Button
type="button"
variant="outline"
size="sm"
variant="secondary"
size="icon"
className="shrink-0"
onClick={addTag}
disabled={!inputValue.trim() || full}
aria-label={t('field.addValue', 'Add {{name}}', { name: label })}
>
<Plus className="h-4 w-4" aria-hidden="true" />
<Plus aria-hidden="true" />
</Button>
</div>
)}
@@ -58,15 +58,16 @@ export function MultilineWidget(props: WidgetProps<FieldTypeString>) {
if (type.format === 'html') {
return (
<div className="rounded-md border bg-muted/30">
<div className="flex items-center gap-2 border-b px-3 py-1.5 text-xs text-muted-foreground">
<div className="field-surface overflow-hidden rounded-xl">
<div className="flex items-center gap-2 bg-muted px-3.5 py-1.5 text-[11px] font-semibold uppercase tracking-wider text-dim">
<span className="font-mono">HTML</span>
</div>
<BufferedTextarea
{...common}
rows={10}
spellCheck={false}
className="resize-y rounded-none rounded-b-md border-0 bg-transparent font-mono text-xs focus-visible:ring-0"
variant="bare"
className="resize-y font-mono text-xs"
/>
</div>
);
@@ -90,7 +91,7 @@ export function ColorWidget(props: WidgetProps<FieldTypeString>) {
onChange={(e) => commit(e.target.value)}
disabled={readOnly}
aria-label={t('field.colorPicker', 'Color picker')}
className="h-9 w-14 cursor-pointer rounded-md border border-input bg-transparent p-1"
className="h-9 w-14 cursor-pointer field-surface rounded-full p-1 [&::-moz-color-swatch]:rounded-full [&::-moz-color-swatch]:border-0 [&::-webkit-color-swatch]:rounded-full [&::-webkit-color-swatch]:border-0 [&::-webkit-color-swatch-wrapper]:p-0"
/>
<BufferedInput
{...control}
@@ -138,14 +139,14 @@ export function SecretWidget(props: WidgetProps<FieldTypeString>) {
<Button
type="button"
variant="ghost"
size="icon"
className="h-8 w-8 shrink-0"
size="icon-sm"
className="shrink-0"
onClick={() => setVisible((p) => !p)}
aria-label={visible ? t('field.hideValue', 'Hide value') : t('field.showValue', 'Show value')}
aria-pressed={visible}
tabIndex={-1}
>
{visible ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
{visible ? <EyeOff aria-hidden="true" /> : <Eye aria-hidden="true" />}
</Button>
);
@@ -10,7 +10,7 @@ import type { WidgetProps } from '@/components/forms/widgets/types';
export function UnsupportedWidget({ type }: WidgetProps) {
const { t } = useTranslation();
return (
<p className="text-sm text-muted-foreground">
<p className="rounded-xl bg-muted px-4 py-3 text-sm text-muted-foreground">
{t('field.unsupportedType', 'Unsupported field type: {{type}}', { type: (type as { type?: string }).type ?? '' })}
</p>
);
+24 -21
View File
@@ -8,9 +8,12 @@ import type { FieldType } from '@/types/schema';
export type LabelMode = 'control' | 'group' | 'none';
type RowLayout = 'side' | 'block' | 'inline';
export interface WidgetTraits {
labelMode: LabelMode;
readOnlyAsValue: boolean;
layout: RowLayout;
}
export type WidgetKey =
@@ -81,27 +84,27 @@ export function widgetKey(type: FieldType): WidgetKey {
}
const TRAITS: Record<WidgetKey, WidgetTraits> = {
string: { labelMode: 'control', readOnlyAsValue: true },
'string:secret': { labelMode: 'control', readOnlyAsValue: true },
'string:multiline': { labelMode: 'control', readOnlyAsValue: true },
'string:color': { labelMode: 'control', readOnlyAsValue: true },
number: { labelMode: 'control', readOnlyAsValue: true },
'number:size': { labelMode: 'control', readOnlyAsValue: true },
'number:duration': { labelMode: 'control', readOnlyAsValue: true },
utcDateTime: { labelMode: 'control', readOnlyAsValue: true },
boolean: { labelMode: 'control', readOnlyAsValue: true },
enum: { labelMode: 'control', readOnlyAsValue: true },
blobId: { labelMode: 'control', readOnlyAsValue: false },
objectId: { labelMode: 'control', readOnlyAsValue: true },
object: { labelMode: 'group', readOnlyAsValue: false },
'object:x:Expression': { labelMode: 'group', readOnlyAsValue: false },
'object:x:Rate': { labelMode: 'control', readOnlyAsValue: false },
'object:x:OtpAuth': { labelMode: 'none', readOnlyAsValue: false },
objectList: { labelMode: 'group', readOnlyAsValue: false },
set: { labelMode: 'control', readOnlyAsValue: true },
'set:enum': { labelMode: 'group', readOnlyAsValue: true },
map: { labelMode: 'group', readOnlyAsValue: false },
unsupported: { labelMode: 'none', readOnlyAsValue: false },
string: { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
'string:secret': { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
'string:multiline': { labelMode: 'control', readOnlyAsValue: true, layout: 'block' },
'string:color': { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
number: { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
'number:size': { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
'number:duration': { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
utcDateTime: { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
boolean: { labelMode: 'control', readOnlyAsValue: true, layout: 'inline' },
enum: { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
blobId: { labelMode: 'control', readOnlyAsValue: false, layout: 'block' },
objectId: { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
object: { labelMode: 'group', readOnlyAsValue: false, layout: 'block' },
'object:x:Expression': { labelMode: 'group', readOnlyAsValue: false, layout: 'block' },
'object:x:Rate': { labelMode: 'control', readOnlyAsValue: false, layout: 'side' },
'object:x:OtpAuth': { labelMode: 'none', readOnlyAsValue: false, layout: 'block' },
objectList: { labelMode: 'group', readOnlyAsValue: false, layout: 'block' },
set: { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
'set:enum': { labelMode: 'group', readOnlyAsValue: true, layout: 'side' },
map: { labelMode: 'group', readOnlyAsValue: false, layout: 'block' },
unsupported: { labelMode: 'none', readOnlyAsValue: false, layout: 'block' },
};
export function widgetTraits(type: FieldType): WidgetTraits {
+7 -5
View File
@@ -5,6 +5,7 @@
*/
import { Component, type ErrorInfo, type ReactNode } from 'react';
import { TriangleAlert } from 'lucide-react';
import { Button } from '@/components/ui/button';
import i18n from '@/i18n';
@@ -50,11 +51,12 @@ export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundarySt
}
return (
<div role="alert" className="flex flex-col items-center justify-center gap-4 p-8">
<div className="text-destructive text-lg font-semibold">
{i18n.t('errorBoundary.title', 'Something went wrong')}
</div>
<p className="text-muted-foreground text-sm max-w-md text-center">
<div role="alert" className="mx-auto mt-6 flex max-w-lg flex-col items-center gap-4 tile p-8 text-center">
<span className="grid size-11 place-items-center rounded-[13px] bg-destructive-soft text-destructive">
<TriangleAlert className="h-5 w-5" aria-hidden="true" />
</span>
<div className="section-title text-lg">{i18n.t('errorBoundary.title', 'Something went wrong')}</div>
<p className="max-w-md text-sm text-muted-foreground">
{this.state.error?.message ?? i18n.t('errors.unexpectedError', 'An unexpected error occurred.')}
</p>
<Button variant="outline" onClick={this.handleReset}>
+2 -2
View File
@@ -108,7 +108,7 @@ function renderView(
}
// SPDX-SnippetEnd
return (
<div className="rounded-lg border border-dashed p-12 text-center text-muted-foreground">
<div className="mt-3 rounded-2xl bg-muted p-10 text-center text-muted-foreground">
{t('errors.unknownComponent', 'Unknown component: {{name}}', { name: componentName })}
</div>
);
@@ -121,7 +121,7 @@ function renderView(
const resolved = resolveObject(schema, viewName);
if (!resolved) {
return (
<div role="alert" className="flex items-center justify-center p-8 text-destructive">
<div role="alert" className="mt-3 rounded-xl bg-destructive-soft p-4 text-center text-sm text-destructive">
{t('errors.unknownView', 'Unknown view: {{name}}', { name: viewName })}
</div>
);
+33 -38
View File
@@ -4,12 +4,12 @@
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import { useEffect, useId, useRef, useState, type CSSProperties } from 'react';
import { useEffect, useId, useRef, useState } from 'react';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { ChevronDown, Lock } from 'lucide-react';
import { ChevronRight, Lock } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Button, buttonVariants } from '@/components/ui/button';
import { Button } from '@/components/ui/button';
import { DynamicIcon } from '@/components/common/DynamicIcon';
import { EnterpriseUpsell } from '@/components/common/EnterpriseUpsell';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
@@ -20,11 +20,12 @@ import { layoutNavNodes, navNodeKey, pathMatchesView, someLink, viewPath, type N
import { SIDEBAR_ID, SidebarNavContext, useSidebarNav } from './sidebarContext';
import { useLayoutNavigation } from './useLayoutNavigation';
function indent(depth: number): CSSProperties | undefined {
return depth > 0 ? { paddingInlineStart: `${(depth + 1) * 12 + 8}px` } : undefined;
}
const itemClass =
'flex w-full items-center gap-2.5 rounded-[10px] px-2.5 text-left font-medium text-muted-foreground outline-none transition-colors duration-200 hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring';
const itemClass = 'w-full justify-start gap-2 font-normal';
function itemSize(depth: number) {
return depth > 0 ? 'h-8 text-[13px]' : 'h-9 text-sm';
}
function NavLink({ node, depth }: { node: Extract<NavNode, { kind: 'link' }>; depth: number }) {
const { t } = useTranslation();
@@ -45,17 +46,11 @@ function NavLink({ node, depth }: { node: Extract<NavNode, { kind: 'link' }>; de
<span className="truncate">{label}</span>
</>
);
const className = cn(buttonVariants({ variant: 'ghost' }), itemClass, depth > 0 && 'text-sm');
const className = cn(itemClass, itemSize(depth));
if (nav.isLocked(node.viewName)) {
return (
<button
type="button"
className={className}
style={indent(depth)}
onClick={nav.openUpsell}
aria-describedby={nav.lockedHintId}
>
<button type="button" className={className} onClick={nav.openUpsell} aria-describedby={nav.lockedHintId}>
{content}
<Lock aria-hidden="true" className="ml-auto h-3 w-3 text-muted-foreground" />
</button>
@@ -67,8 +62,11 @@ function NavLink({ node, depth }: { node: Extract<NavNode, { kind: 'link' }>; de
ref={ref}
to={viewPath(nav.sectionName, node.viewName)}
aria-current={isActive ? 'page' : undefined}
className={cn(className, isActive && 'bg-accent text-accent-foreground')}
style={indent(depth)}
className={cn(
className,
isActive &&
'bg-highlight font-semibold text-highlight-foreground hover:bg-highlight hover:text-highlight-foreground',
)}
>
{content}
</Link>
@@ -92,25 +90,19 @@ function NavContainer({ node, depth }: { node: Extract<NavNode, { kind: 'contain
return (
<Collapsible open={open} onOpenChange={setOpen}>
<CollapsibleTrigger asChild>
<Button variant="ghost" className={cn(itemClass, depth > 0 && 'text-sm')} style={indent(depth)}>
{depth > 0 && (
<ChevronDown
aria-hidden="true"
className="h-3 w-3 shrink-0 transition-transform duration-200 [[data-state=closed]>&]:rotate-[-90deg]"
/>
)}
<button type="button" className={cn(itemClass, itemSize(depth))}>
{node.icon && <DynamicIcon name={node.icon} className="h-4 w-4 shrink-0" />}
<span className="truncate">{node.name}</span>
{depth === 0 && (
<ChevronDown
aria-hidden="true"
className="ml-auto h-3 w-3 shrink-0 transition-transform duration-200 [[data-state=closed]>&]:rotate-[-90deg]"
/>
)}
</Button>
<ChevronRight
aria-hidden="true"
className="ml-auto h-3.5 w-3.5 shrink-0 opacity-60 transition-transform duration-200 [[data-state=open]>&]:rotate-90"
/>
</button>
</CollapsibleTrigger>
<CollapsibleContent>
<NavNodes nodes={node.children} depth={depth + 1} />
<div className="my-0.5 ml-[18px] flex flex-col gap-0.5 border-l border-input pl-2">
<NavNodes nodes={node.children} depth={depth + 1} />
</div>
</CollapsibleContent>
</Collapsible>
);
@@ -136,7 +128,7 @@ function SectionSwitcher({ layouts, activeSection }: { layouts: Layout[]; active
<div
role="group"
aria-label={t('sections', 'Sections')}
className="flex items-center justify-around border-t bg-background px-2 py-2"
className="m-2.5 mt-0 flex items-center gap-0.5 rounded-full bg-muted p-1"
>
{layouts.map((target) => {
const isActive = target.name === activeSection;
@@ -154,7 +146,10 @@ function SectionSwitcher({ layouts, activeSection }: { layouts: Layout[]; active
const path = landingPath(target);
if (path) navigate(path);
}}
className={cn('h-9 w-9', isActive && 'bg-accent text-accent-foreground')}
className={cn(
'h-8 flex-1 rounded-full',
isActive && 'bg-card text-foreground shadow-tile hover:bg-card hover:text-foreground',
)}
>
<DynamicIcon name={target.icon} className="h-4 w-4" />
</Button>
@@ -198,19 +193,19 @@ export function Sidebar() {
<>
<div
aria-hidden="true"
className="fixed inset-0 top-14 z-20 bg-black/40 md:hidden"
className="fixed inset-0 top-16 z-20 bg-overlay md:hidden"
onClick={() => setSidebarOpen(false)}
/>
<aside
id={SIDEBAR_ID}
aria-label={t('sidebar.label', 'Sidebar')}
className="fixed bottom-0 left-0 top-14 z-30 flex w-64 flex-col border-r bg-background"
className="fixed bottom-3 left-3 top-16 z-30 flex w-60 flex-col tile overflow-hidden"
>
<span id={lockedHintId} className="sr-only">
{t('enterprise.featureHint', 'Enterprise feature')}
</span>
<div className="flex-1 overflow-y-auto py-2 [scrollbar-width:thin]">
<nav aria-label={layout.name} className="flex flex-col gap-0.5 px-2">
<div className="flex-1 overflow-y-auto py-2.5 [scrollbar-width:thin]">
<nav aria-label={layout.name} className="flex flex-col gap-0.5 px-2.5">
<SidebarNavContext value={nav}>
<NavNodes nodes={layoutNavNodes(layout)} depth={0} />
</SidebarNavContext>
+7 -7
View File
@@ -63,7 +63,7 @@ export function TopBar() {
}, []);
return (
<header className="sticky top-0 z-40 flex h-14 items-center gap-4 border-b bg-background px-4">
<header className="sticky top-0 z-40 flex h-16 items-center gap-4 bg-background/80 px-4 backdrop-blur-xl backdrop-saturate-150 sm:px-5">
<Button
variant="ghost"
size="icon"
@@ -78,7 +78,7 @@ export function TopBar() {
<Tooltip>
<TooltipTrigger asChild>
<Link to="/" className="flex shrink-0 items-center">
<Link to="/" className="flex shrink-0 items-center md:w-[228px]">
<Logo />
</Link>
</TooltipTrigger>
@@ -87,24 +87,24 @@ export function TopBar() {
</TooltipContent>
</Tooltip>
<div className="hidden min-w-0 flex-1 items-center justify-center px-4 md:flex">
<div className="hidden min-w-0 flex-1 items-center md:flex">
<button
type="button"
onClick={() => setPaletteOpen(true)}
className="flex h-9 w-full max-w-md items-center gap-2 rounded-md border border-input bg-transparent px-3 text-sm text-muted-foreground shadow-sm transition-colors hover:bg-accent"
className="flex h-10 w-full max-w-md items-center gap-2.5 rounded-full bg-card pl-4 pr-2 text-sm text-dim shadow-tile transition-shadow duration-200 hover:shadow-lift"
>
<Search aria-hidden="true" className="h-4 w-4" />
<span className="flex-1 text-left">{t('globalSearch.placeholder', 'Search pages, fields, settings...')}</span>
<kbd
aria-hidden="true"
className="pointer-events-none flex h-5 select-none items-center rounded border bg-muted px-1.5 font-mono text-[10px] font-medium"
className="pointer-events-none flex h-6 select-none items-center rounded-full bg-muted px-2.5 font-mono text-[11px] font-medium text-muted-foreground"
>
{IS_MAC ? '⌘K' : 'Ctrl K'}
</kbd>
</button>
</div>
<div className="ml-auto flex items-center gap-2 md:ml-0">
<div className="ml-auto flex items-center gap-1.5">
{isCommunity && <EnterpriseUpsell open={upsellOpen} onClose={() => setUpsellOpen(false)} />}
<Button
@@ -129,7 +129,7 @@ export function TopBar() {
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" aria-label={t('userMenu', 'User menu')}>
<Button variant="outline" size="icon-lg" aria-label={t('userMenu', 'User menu')}>
<User aria-hidden="true" className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
+7 -4
View File
@@ -10,6 +10,9 @@ import { ArrowUpDown, ChevronDown, ChevronUp } from 'lucide-react';
import type { Column } from '@/types/schema';
import type { ListSort } from './listUrlState';
export const HEADER_CELL =
'px-3.5 py-2.5 first:pl-5 last:pr-5 text-left text-[11px] font-semibold uppercase tracking-wider text-dim';
interface ColumnHeaderProps {
column: Column;
sortable: boolean;
@@ -20,7 +23,7 @@ interface ColumnHeaderProps {
export function ColumnHeader({ column, sortable, sort, onSort }: ColumnHeaderProps) {
const { t } = useTranslation();
const direction = sort?.field === column.name ? (sort.ascending ? 'ascending' : 'descending') : 'none';
const className = 'px-3 py-3 text-left font-medium text-muted-foreground';
const className = HEADER_CELL;
if (!sortable) {
return (
@@ -43,13 +46,13 @@ export function ColumnHeader({ column, sortable, sort, onSort }: ColumnHeaderPro
type="button"
onClick={() => onSort(column.name)}
title={hint}
className="-mx-1 inline-flex items-center gap-1 rounded px-1 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
className="-mx-1 inline-flex items-center gap-1 rounded-md px-1 uppercase tracking-wider hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
{column.label}
{direction === 'ascending' ? (
<ChevronUp className="h-4 w-4" aria-hidden />
<ChevronUp className="h-3.5 w-3.5" aria-hidden />
) : direction === 'descending' ? (
<ChevronDown className="h-4 w-4" aria-hidden />
<ChevronDown className="h-3.5 w-3.5" aria-hidden />
) : (
<ArrowUpDown className="h-3 w-3" aria-hidden />
)}
+90 -88
View File
@@ -197,105 +197,107 @@ function DynamicListView({ viewName, schema, resolved, list }: DynamicListViewPr
const viewFor = (name: string) => layoutViewFor(schema, viewToSection, name, viewName);
return (
<div className="relative space-y-4">
<div className="flex items-start justify-between gap-4">
<div>
<h1 className="text-2xl font-bold tracking-tight">{list.title}</h1>
<div className="space-y-3.5">
<div className="flex flex-wrap items-end justify-between gap-4 px-1 pb-1 pt-3">
<div className="min-w-0">
<h1 className="page-title">{list.title}</h1>
{list.subtitle && <p className="mt-1 text-sm text-muted-foreground">{list.subtitle}</p>}
</div>
<div className="flex items-center gap-2">
{massActions.length > 0 && selectedCount > 0 && (
<MassActionBar
actions={massActions}
count={selectedCount}
disabled={actions.pending}
onSelect={confirmMassAction}
/>
)}
{canCreate && section && (
<Button onClick={() => navigate(`/${section}/${viewName}/new`)}>
<Plus className="mr-2 h-4 w-4" aria-hidden />
{t('list.create', 'Create {{name}}', { name: list.singularName })}
</Button>
)}
</div>
{canCreate && section && (
<Button onClick={() => navigate(`/${section}/${viewName}/new`)}>
<Plus aria-hidden />
{t('list.create', 'Create {{name}}', { name: list.singularName })}
</Button>
)}
</div>
{visibleFilters.length > 0 && (
<FilterBar
schema={schema}
filters={visibleFilters}
applied={state.filters}
isXPrefixed={objectName.startsWith('x:')}
disabled={listState.isFetching}
onApply={listState.applyFilters}
onReset={listState.resetFilters}
/>
)}
{listState.error && <ListError message={listState.error} onRetry={listState.refetch} />}
{actions.error && <ListError message={actions.error} onDismiss={actions.clearError} />}
{massActions.length > 0 && selection.pageState === 'all' && (
<SelectionBanner
allMatching={selection.allMatching}
pageCount={selection.selectedIds.length}
total={total}
pluralName={list.pluralName}
onSelectAllMatching={selection.selectAllMatching}
<section className="tile relative overflow-hidden">
{visibleFilters.length > 0 && (
<FilterBar
schema={schema}
filters={visibleFilters}
applied={state.filters}
isXPrefixed={objectName.startsWith('x:')}
disabled={listState.isFetching}
onApply={listState.applyFilters}
onReset={listState.resetFilters}
/>
)}
{massActions.length > 0 && selection.pageState === 'all' && (
<SelectionBanner
allMatching={selection.allMatching}
pageCount={selection.selectedIds.length}
total={total}
pluralName={list.pluralName}
onSelectAllMatching={selection.selectAllMatching}
onClear={selection.clear}
/>
)}
<ListTable
caption={list.title}
columns={list.columns}
fields={fields}
items={items}
schema={schema}
objectName={objectName}
sort={state.sort}
sortable={new Set(list.sort ?? [])}
onSort={listState.toggleSort}
selection={massActions.length > 0 ? selection : null}
rowHref={(id) => (section ? `/${section}/${viewName}/${id}` : null)}
rowLabel={(item) => itemLabel(item, labelProperty)}
renderRowActions={
itemActions.length > 0
? (_item, id, label) => (
<RowActions
actions={itemActions}
label={label}
hrefFor={(action) => itemActionHref(action, id, sectionFor, section, viewFor)}
onMutation={(entry) => confirmItemAction(entry, id, label)}
onLocked={() => setUpsellOpen(true)}
disabled={actions.pending}
/>
)
: null
}
loading={listState.isLoading}
busy={busy}
/>
{(items.length > 0 || state.anchors.length > 0) && (
<Pagination
range={listState.range}
total={total}
count={items.length}
pluralName={list.pluralName}
disabled={listState.isFetching}
onPrev={listState.prevPage}
onNext={listState.nextPage}
/>
)}
{busy && items.length > 0 && (
<div className="absolute inset-0 flex items-center justify-center bg-card/50" aria-hidden>
<Loader2 className="h-6 w-6 animate-spin text-brand-text" />
</div>
)}
</section>
{massActions.length > 0 && selectedCount > 0 && (
<MassActionBar
actions={massActions}
count={selectedCount}
disabled={actions.pending}
onSelect={confirmMassAction}
onClear={selection.clear}
/>
)}
<ListTable
caption={list.title}
columns={list.columns}
fields={fields}
items={items}
schema={schema}
objectName={objectName}
sort={state.sort}
sortable={new Set(list.sort ?? [])}
onSort={listState.toggleSort}
selection={massActions.length > 0 ? selection : null}
rowHref={(id) => (section ? `/${section}/${viewName}/${id}` : null)}
rowLabel={(item) => itemLabel(item, labelProperty)}
renderRowActions={
itemActions.length > 0
? (_item, id, label) => (
<RowActions
actions={itemActions}
label={label}
hrefFor={(action) => itemActionHref(action, id, sectionFor, section, viewFor)}
onMutation={(entry) => confirmItemAction(entry, id, label)}
onLocked={() => setUpsellOpen(true)}
disabled={actions.pending}
/>
)
: null
}
loading={listState.isLoading}
busy={busy}
/>
{(items.length > 0 || state.anchors.length > 0) && (
<Pagination
range={listState.range}
total={total}
count={items.length}
pluralName={list.pluralName}
disabled={listState.isFetching}
onPrev={listState.prevPage}
onNext={listState.nextPage}
/>
)}
{busy && items.length > 0 && (
<div className="absolute inset-0 flex items-center justify-center bg-background/50" aria-hidden>
<Loader2 className="h-6 w-6 animate-spin" />
</div>
)}
<ConfirmDialog
open={confirm !== null}
onOpenChange={(open) => {
+38 -12
View File
@@ -9,6 +9,7 @@ import { useTranslation } from 'react-i18next';
import { ChevronDown, ChevronUp, Filter as FilterIcon, RotateCcw, Search } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import type { Filter, Schema } from '@/types/schema';
import { filtersKey } from './listUrlState';
@@ -50,23 +51,48 @@ export function FilterBar({ schema, filters, applied, isXPrefixed, disabled, onA
onReset();
};
const activeCount = filters.filter((f) => Object.hasOwn(applied, f.field) && applied[f.field] !== '').length;
return (
<Collapsible open={open} onOpenChange={setOpen}>
<CollapsibleTrigger asChild>
<Button variant="ghost" size="sm" className="gap-2" aria-controls={panelId}>
<FilterIcon className="h-4 w-4" aria-hidden />
{t('list.filters', 'Filters')}
{open ? <ChevronUp className="h-4 w-4" aria-hidden /> : <ChevronDown className="h-4 w-4" aria-hidden />}
</Button>
</CollapsibleTrigger>
<div className="flex flex-wrap items-center gap-2 p-2.5">
<CollapsibleTrigger asChild>
<button
type="button"
aria-controls={panelId}
className={cn(
'inline-flex h-8 items-center gap-1.5 rounded-full px-3.5 text-[13px] font-medium transition-colors duration-200 ease-bento focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
activeCount > 0 || open
? 'bg-highlight text-highlight-foreground hover:bg-highlight-strong'
: 'bg-muted text-muted-foreground hover:bg-muted-strong hover:text-foreground',
)}
>
<FilterIcon className="h-3.5 w-3.5" aria-hidden />
{t('list.filters', 'Filters')}
{activeCount > 0 && (
<span
className="grid h-[18px] min-w-[18px] place-items-center rounded-full bg-primary px-1 text-[11px] font-semibold text-primary-foreground"
aria-hidden
>
{activeCount}
</span>
)}
{open ? (
<ChevronUp className="h-3.5 w-3.5" aria-hidden />
) : (
<ChevronDown className="h-3.5 w-3.5" aria-hidden />
)}
</button>
</CollapsibleTrigger>
</div>
<CollapsibleContent id={panelId}>
<form
role="search"
aria-label={t('list.filters', 'Filters')}
onSubmit={handleSubmit}
className="mt-2 rounded-lg border bg-background shadow-sm"
className="mx-2.5 mb-2.5 rounded-xl bg-muted p-4"
>
<div className="grid gap-4 p-5 sm:grid-cols-2 lg:grid-cols-3">
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
{filters.map((filter) => (
<FilterField
key={filter.field}
@@ -79,13 +105,13 @@ export function FilterBar({ schema, filters, applied, isXPrefixed, disabled, onA
/>
))}
</div>
<div className="flex items-center justify-end gap-2 border-t px-5 py-3">
<div className="mt-4 flex items-center justify-end gap-2">
<Button type="button" variant="ghost" size="sm" onClick={handleReset} disabled={disabled}>
<RotateCcw className="mr-2 h-4 w-4" aria-hidden />
<RotateCcw aria-hidden />
{t('list.resetFilters', 'Reset')}
</Button>
<Button type="submit" size="sm" disabled={disabled}>
<Search className="mr-2 h-4 w-4" aria-hidden />
<Search aria-hidden />
{t('list.searchFilters', 'Search')}
</Button>
</div>
+2 -2
View File
@@ -34,7 +34,7 @@ function opField(filter: Filter): string {
function LabelledField({ id, label, children }: { id: string; label: string; children: ReactNode }) {
return (
<div className="flex flex-col gap-1.5">
<label htmlFor={id} className="text-xs font-medium text-muted-foreground">
<label htmlFor={id} className="text-[12.5px] font-semibold text-muted-foreground">
{label}
</label>
{children}
@@ -46,7 +46,7 @@ function GroupField({ label, children }: { label: string; children: ReactNode })
const labelId = useId();
return (
<div role="group" aria-labelledby={labelId} className="flex flex-col gap-1.5">
<span id={labelId} className="text-xs font-medium text-muted-foreground">
<span id={labelId} className="text-[12.5px] font-semibold text-muted-foreground">
{label}
</span>
{children}
+11 -6
View File
@@ -14,20 +14,20 @@ export function ListSpinner({ className }: { className?: string }) {
const { t } = useTranslation();
return (
<div role="status" className={className ?? 'flex items-center justify-center p-8'}>
<Loader2 className="h-6 w-6 animate-spin" aria-hidden />
<Loader2 className="h-6 w-6 animate-spin text-brand-text" aria-hidden />
<span className="sr-only">{t('common.loading', 'Loading...')}</span>
</div>
);
}
export function ListMessage({ children }: { children: ReactNode }) {
return <div className="p-8 text-center text-muted-foreground">{children}</div>;
return <div className="rounded-2xl bg-muted p-10 text-center text-muted-foreground">{children}</div>;
}
export function ListTableMessage({ colSpan, children }: { colSpan: number; children: ReactNode }) {
return (
<tr>
<td colSpan={colSpan} className="px-3 py-12 text-center text-muted-foreground">
<td colSpan={colSpan} className="border-t border-border px-3 py-12 text-center text-muted-foreground">
{children}
</td>
</tr>
@@ -47,12 +47,17 @@ export function ListError({
return (
<div
role="alert"
className="flex items-start justify-between gap-3 rounded-md border border-destructive/50 bg-destructive/10 p-3 text-sm text-destructive"
className="flex items-start justify-between gap-3 rounded-xl bg-destructive-soft p-4 text-sm text-destructive"
>
<span className="whitespace-pre-line">{message}</span>
<div className="flex shrink-0 items-center gap-1">
{onRetry && (
<Button variant="ghost" size="sm" className="h-7" onClick={onRetry}>
<Button
variant="ghost"
size="sm"
className="h-7 text-destructive hover:bg-destructive/10 hover:text-destructive"
onClick={onRetry}
>
{t('common.retry', 'Retry')}
</Button>
)}
@@ -60,7 +65,7 @@ export function ListError({
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
className="h-7 w-7 text-destructive hover:bg-destructive/10 hover:text-destructive"
onClick={onDismiss}
aria-label={t('common.close', 'Close')}
>
+105 -102
View File
@@ -9,10 +9,11 @@ import { Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Checkbox } from '@/components/ui/checkbox';
import { cn } from '@/lib/utils';
import type { Column, Field, Schema } from '@/types/schema';
import { isEmptyValue } from '@/lib/embeddedSchema';
import { ListCell } from './ListCell';
import { ColumnHeader } from './ColumnHeader';
import { ColumnHeader, HEADER_CELL } from './ColumnHeader';
import { ListSpinner, ListTableMessage } from './ListStates';
import { itemId, type ListItem } from './listQuery';
import type { ListSort } from './listUrlState';
@@ -36,8 +37,10 @@ interface ListTableProps {
busy: boolean;
}
const BODY_CELL = 'px-3.5 py-2.5 first:pl-5 last:pr-5 align-middle';
const STRETCHED_LINK =
"font-medium text-foreground hover:underline focus-visible:outline-none after:absolute after:inset-0 after:content-[''] focus-visible:after:ring-2 focus-visible:after:ring-inset focus-visible:after:ring-ring";
"font-semibold text-foreground hover:underline focus-visible:outline-none after:absolute after:inset-0 after:content-[''] focus-visible:after:ring-2 focus-visible:after:ring-inset focus-visible:after:ring-ring";
export function ListTable({
caption,
@@ -64,108 +67,108 @@ export function ListTable({
});
return (
<div className="rounded-lg border bg-background shadow-sm">
<div className="overflow-x-auto rounded-[calc(var(--radius-lg)-1px)]">
<table className="w-full text-sm" aria-busy={busy || undefined}>
<caption className="sr-only">{caption}</caption>
<thead>
<tr className="border-b bg-muted">
{selection && (
<th scope="col" className="w-10 px-3 py-3">
<Checkbox
checked={
selection.pageState === 'all' ? true : selection.pageState === 'some' ? 'indeterminate' : false
}
disabled={rows.length === 0}
onCheckedChange={selection.togglePage}
aria-label={t('list.selectAllOnPage', 'Select all on this page')}
/>
</th>
)}
{columns.map((col) => (
<ColumnHeader
key={col.name}
column={col}
sortable={sortable.has(col.name)}
sort={sort}
onSort={onSort}
<div className="overflow-x-auto">
<table className="w-full text-sm" aria-busy={busy || undefined}>
<caption className="sr-only">{caption}</caption>
<thead>
<tr>
{selection && (
<th scope="col" className="w-10 py-2.5 pl-5 pr-2 text-left align-middle">
<Checkbox
checked={
selection.pageState === 'all' ? true : selection.pageState === 'some' ? 'indeterminate' : false
}
disabled={rows.length === 0}
onCheckedChange={selection.togglePage}
aria-label={t('list.selectAllOnPage', 'Select all on this page')}
/>
))}
{renderRowActions && (
<th scope="col" className="w-12 px-3 py-3 text-right font-medium text-muted-foreground">
{t('list.actions', 'Actions')}
</th>
)}
</tr>
</thead>
<tbody>
{loading && rows.length === 0 ? (
<tr>
<td colSpan={colSpan} className="px-3 py-12">
<ListSpinner className="flex items-center justify-center" />
</td>
</tr>
) : rows.length === 0 ? (
<ListTableMessage colSpan={colSpan}>{t('list.noResults', 'No results found')}</ListTableMessage>
) : (
rows.map(({ item, id }) => {
const label = rowLabel(item);
const href = rowHref(id);
return (
<tr key={id} className="relative border-b transition-colors hover:bg-muted/50">
{selection && (
<td className="relative z-10 px-3 py-2">
<Checkbox
checked={selection.isSelected(id)}
onCheckedChange={() => selection.toggle(id)}
aria-label={t('list.selectNamed', 'Select {{label}}', { label })}
/>
</td>
)}
{columns.map((col, index) => {
const value = item[col.name];
const content = (
<ListCell
schema={schema}
objectName={objectName}
column={col.name}
field={fields[col.name]}
value={value}
/>
);
if (index === 0) {
return (
<th key={col.name} scope="row" className="px-3 py-2 text-left font-normal">
{href ? (
<Link
to={href}
className={STRETCHED_LINK}
aria-label={isEmptyValue(value) ? label : undefined}
>
{content}
</Link>
) : (
content
)}
</th>
);
}
return (
<td key={col.name} className="px-3 py-2">
{content}
</td>
);
})}
{renderRowActions && (
<td className="relative z-10 px-3 py-2 text-right">{renderRowActions(item, id, label)}</td>
)}
</tr>
);
})
</th>
)}
</tbody>
</table>
</div>
{columns.map((col) => (
<ColumnHeader key={col.name} column={col} sortable={sortable.has(col.name)} sort={sort} onSort={onSort} />
))}
{renderRowActions && (
<th scope="col" className={cn(HEADER_CELL, 'w-12 text-right last:pr-3')}>
<span className="sr-only">{t('list.actions', 'Actions')}</span>
</th>
)}
</tr>
</thead>
<tbody>
{loading && rows.length === 0 ? (
<tr>
<td colSpan={colSpan} className="border-t border-border px-3 py-12">
<ListSpinner className="flex items-center justify-center" />
</td>
</tr>
) : rows.length === 0 ? (
<ListTableMessage colSpan={colSpan}>{t('list.noResults', 'No results found')}</ListTableMessage>
) : (
rows.map(({ item, id }) => {
const label = rowLabel(item);
const href = rowHref(id);
return (
<tr
key={id}
className={cn(
'relative border-t border-border transition-colors duration-150',
selection?.isSelected(id) ? 'bg-highlight/70' : 'hover:bg-muted/55',
)}
>
{selection && (
<td className="relative z-10 w-10 py-2.5 pl-5 pr-2 align-middle">
<Checkbox
checked={selection.isSelected(id)}
onCheckedChange={() => selection.toggle(id)}
aria-label={t('list.selectNamed', 'Select {{label}}', { label })}
/>
</td>
)}
{columns.map((col, index) => {
const value = item[col.name];
const content = (
<ListCell
schema={schema}
objectName={objectName}
column={col.name}
field={fields[col.name]}
value={value}
/>
);
if (index === 0) {
return (
<th key={col.name} scope="row" className={cn(BODY_CELL, 'text-left font-normal')}>
{href ? (
<Link
to={href}
className={STRETCHED_LINK}
aria-label={isEmptyValue(value) ? label : undefined}
>
{content}
</Link>
) : (
content
)}
</th>
);
}
return (
<td key={col.name} className={BODY_CELL}>
{content}
</td>
);
})}
{renderRowActions && (
<td className="relative z-10 py-1.5 pl-2 pr-3 text-right align-middle">
{renderRowActions(item, id, label)}
</td>
)}
</tr>
);
})
)}
</tbody>
</table>
</div>
);
}
+40 -25
View File
@@ -5,9 +5,10 @@
*/
import { useTranslation } from 'react-i18next';
import { ChevronDown } from 'lucide-react';
import { ChevronUp, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { FloatingActionBar, FloatingActionDivider, FloatingActionDot } from '@/components/common/FloatingActionBar';
import {
DropdownMenu,
DropdownMenuContent,
@@ -24,33 +25,47 @@ interface MassActionBarProps {
count: number;
disabled: boolean;
onSelect: (action: RunnableMassAction) => void;
onClear: () => void;
}
export function MassActionBar({ actions, count, disabled, onSelect }: MassActionBarProps) {
export function MassActionBar({ actions, count, disabled, onSelect, onClear }: MassActionBarProps) {
const { t } = useTranslation();
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm" disabled={disabled}>
{t('list.massActionCount', 'Actions ({{count}})', { count })}
<ChevronDown className="ml-1 h-4 w-4" aria-hidden />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{actions.map(({ key, action }) =>
action.type === 'separator' ? (
<DropdownMenuSeparator key={key} />
) : (
<DropdownMenuItem
key={key}
className={action.type === 'delete' ? 'text-destructive' : undefined}
onSelect={() => onSelect(action)}
>
{action.label}
</DropdownMenuItem>
),
)}
</DropdownMenuContent>
</DropdownMenu>
<FloatingActionBar>
<span className="pl-2">
<FloatingActionDot />
</span>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ink" size="sm" className="text-ink-foreground" disabled={disabled}>
{t('list.massActionCount', 'Actions ({{count}})', { count })}
<ChevronUp aria-hidden />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="center" side="top" sideOffset={10}>
{actions.map(({ key, action }) =>
action.type === 'separator' ? (
<DropdownMenuSeparator key={key} />
) : (
<DropdownMenuItem
key={key}
className={
action.type === 'delete'
? 'text-destructive focus:bg-destructive-soft focus:text-destructive'
: undefined
}
onSelect={() => onSelect(action)}
>
{action.label}
</DropdownMenuItem>
),
)}
</DropdownMenuContent>
</DropdownMenu>
<FloatingActionDivider />
<Button variant="ink" size="icon-sm" onClick={onClear} aria-label={t('list.clearSelection', 'Clear selection')}>
<X aria-hidden />
</Button>
</FloatingActionBar>
);
}
+7 -4
View File
@@ -5,6 +5,7 @@
*/
import { useTranslation } from 'react-i18next';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { Button } from '@/components/ui/button';
import type { PageRange } from './listQuery';
@@ -24,7 +25,7 @@ export function Pagination({ range, total, count, pluralName, disabled, onPrev,
return (
<nav
aria-label={t('list.pagination', 'Pagination')}
className="flex items-center justify-between text-sm text-muted-foreground"
className="flex flex-wrap items-center justify-between gap-2 border-t border-border py-2.5 pl-5 pr-2.5 text-[13px] text-muted-foreground"
>
<p aria-live="polite">
{total !== null
@@ -36,12 +37,14 @@ export function Pagination({ range, total, count, pluralName, disabled, onPrev,
})
: t('list.showingItems', 'Showing {{count}} items', { count })}
</p>
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" disabled={!range.hasPrev || disabled} onClick={onPrev}>
<div className="flex items-center gap-1.5">
<Button variant="secondary" size="sm" disabled={!range.hasPrev || disabled} onClick={onPrev}>
<ChevronLeft aria-hidden />
{t('list.previous', 'Previous')}
</Button>
<Button variant="outline" size="sm" disabled={!range.hasNext || disabled} onClick={onNext}>
<Button variant="secondary" size="sm" disabled={!range.hasNext || disabled} onClick={onNext}>
{t('list.next', 'Next')}
<ChevronRight aria-hidden />
</Button>
</div>
</nav>
+7 -4
View File
@@ -37,8 +37,7 @@ export function RowActions({ actions, label, hrefFor, onMutation, onLocked, disa
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0"
size="icon-sm"
disabled={disabled}
aria-label={t('list.actionsFor', 'Actions for {{label}}', { label })}
>
@@ -52,7 +51,11 @@ export function RowActions({ actions, label, hrefFor, onMutation, onLocked, disa
return (
<DropdownMenuItem
key={entry.key}
className={entry.action.type === 'delete' ? 'text-destructive' : undefined}
className={
entry.action.type === 'delete'
? 'text-destructive focus:bg-destructive-soft focus:text-destructive'
: undefined
}
onSelect={() => onMutation(entry)}
>
{entry.action.label}
@@ -63,7 +66,7 @@ export function RowActions({ actions, label, hrefFor, onMutation, onLocked, disa
return (
<DropdownMenuItem key={entry.key} onSelect={onLocked}>
{entry.label}
<Lock className="ml-auto h-3 w-3 text-muted-foreground" aria-hidden />
<Lock className="ml-auto h-3 w-3 text-dim" aria-hidden />
<span className="sr-only">
{t('enterprise.featureDisabled', 'This feature requires an Enterprise license.')}
</span>
+10 -3
View File
@@ -24,11 +24,15 @@ export function SelectionBanner({
onClear,
}: SelectionBannerProps) {
const { t } = useTranslation();
const linkClass = 'text-primary underline hover:text-primary/80';
const linkClass =
'font-semibold text-brand-text underline-offset-4 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring rounded-sm';
if (allMatching) {
return (
<div role="status" className="rounded-md border border-primary/50 bg-primary/10 px-4 py-2 text-center text-sm">
<div
role="status"
className="border-t border-border first:border-t-0 bg-highlight/70 px-5 py-2.5 text-center text-[13px]"
>
{t('list.allMatchingSelected', 'All {{total}} {{name}} matching the current filters are selected.', {
total: total ?? 0,
name: pluralName,
@@ -43,7 +47,10 @@ export function SelectionBanner({
if (total === null || total <= pageCount) return null;
return (
<div role="status" className="rounded-md border bg-muted/50 px-4 py-2 text-center text-sm">
<div
role="status"
className="border-t border-border first:border-t-0 bg-muted/60 px-5 py-2.5 text-center text-[13px]"
>
{t('list.allPageSelected', 'All {{count}} items on this page are selected.', { count: pageCount })}{' '}
<button type="button" className={linkClass} onClick={onSelectAllMatching}>
{t('list.selectAllMatchingNamed', 'Select all {{total}} {{name}} matching the current filters', {
+3 -3
View File
@@ -27,7 +27,7 @@ function AlertDialogOverlay({ className, ...props }: React.ComponentProps<typeof
<AlertDialogPrimitive.Overlay
data-slot="alert-dialog-overlay"
className={cn(
'fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
'fixed inset-0 z-50 bg-overlay data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className,
)}
{...props}
@@ -42,7 +42,7 @@ function AlertDialogContent({ className, ...props }: React.ComponentProps<typeof
<AlertDialogPrimitive.Content
data-slot="alert-dialog-content"
className={cn(
'fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 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 sm:rounded-lg',
'fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 rounded-3xl bg-card p-6 shadow-pop duration-200 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}
@@ -76,7 +76,7 @@ function AlertDialogTitle({ className, ...props }: React.ComponentProps<typeof A
return (
<AlertDialogPrimitive.Title
data-slot="alert-dialog-title"
className={cn('text-lg font-semibold', className)}
className={cn('font-display text-lg font-bold tracking-[-0.015em]', className)}
{...props}
/>
);
+5 -5
View File
@@ -10,14 +10,14 @@ import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils';
const badgeVariants = cva(
'inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
'inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
{
variants: {
variant: {
default: 'border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80',
secondary: 'border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80',
destructive: 'border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80',
outline: 'text-foreground',
default: 'border-transparent bg-highlight text-highlight-foreground',
secondary: 'border-transparent bg-secondary text-secondary-foreground',
destructive: 'border-transparent bg-destructive-soft text-destructive',
outline: 'border-input text-foreground',
},
},
defaultVariants: {
+15 -9
View File
@@ -11,22 +11,28 @@ import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils';
const buttonVariants = cva(
'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0',
'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-full text-sm font-semibold transition-[color,background-color,box-shadow] duration-200 ease-bento 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 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0',
{
variants: {
variant: {
default: 'bg-primary text-primary-foreground shadow hover:bg-primary/90',
destructive: 'bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90',
outline: 'border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground',
secondary: 'bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80',
ghost: 'hover:bg-accent hover:text-accent-foreground',
link: 'text-primary underline-offset-4 hover:underline',
default: 'bg-primary text-primary-foreground shadow-primary hover:bg-primary-hover',
destructive: 'bg-destructive text-destructive-foreground hover:bg-destructive-hover',
outline: 'bg-card text-foreground shadow-tile hover:shadow-lift',
secondary: 'bg-secondary text-secondary-foreground hover:bg-highlight hover:text-highlight-foreground',
ghost: 'text-muted-foreground hover:bg-accent hover:text-accent-foreground',
link: 'text-brand-text underline-offset-4 hover:underline',
ink: 'text-ink-muted hover:bg-ink-2 hover:text-ink-foreground',
'ink-danger': 'text-ink-danger hover:bg-ink-danger/12',
'ghost-danger': 'text-muted-foreground hover:bg-destructive-soft hover:text-destructive',
field: 'field-surface rounded-lg font-normal text-foreground focus-visible:ring-0 focus-visible:ring-offset-0',
},
size: {
default: 'h-9 px-4 py-2',
sm: 'h-8 rounded-md px-3 text-xs',
lg: 'h-10 rounded-md px-8',
sm: 'h-8 px-3.5 text-[13px]',
lg: 'h-11 px-7',
icon: 'h-9 w-9',
'icon-sm': 'h-8 w-8',
'icon-lg': 'h-10 w-10',
},
},
defaultVariants: {
+1 -4
View File
@@ -62,10 +62,7 @@ function Calendar({
'flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium',
defaultClassNames.dropdowns,
),
dropdown_root: cn(
'relative rounded-md border border-input shadow-xs has-focus:border-ring has-focus:ring-[3px] has-focus:ring-ring/50',
defaultClassNames.dropdown_root,
),
dropdown_root: cn('field-surface relative rounded-lg', defaultClassNames.dropdown_root),
dropdown: cn('absolute inset-0 bg-popover opacity-0', defaultClassNames.dropdown),
caption_label: cn(
'font-medium select-none',
+9 -5
View File
@@ -12,19 +12,23 @@ function Card({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card"
className={cn('rounded-xl border bg-card text-card-foreground shadow', className)}
className={cn('rounded-2xl bg-card text-card-foreground shadow-tile', className)}
{...props}
/>
);
}
function CardHeader({ className, ...props }: React.ComponentProps<'div'>) {
return <div data-slot="card-header" className={cn('flex flex-col space-y-1.5 p-6', className)} {...props} />;
return <div data-slot="card-header" className={cn('flex flex-col space-y-1.5 p-5', className)} {...props} />;
}
function CardTitle({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div data-slot="card-title" className={cn('font-semibold leading-none tracking-tight', className)} {...props} />
<div
data-slot="card-title"
className={cn('font-display font-bold leading-tight tracking-[-0.012em]', className)}
{...props}
/>
);
}
@@ -33,11 +37,11 @@ function CardDescription({ className, ...props }: React.ComponentProps<'div'>) {
}
function CardContent({ className, ...props }: React.ComponentProps<'div'>) {
return <div data-slot="card-content" className={cn('p-6 pt-0', className)} {...props} />;
return <div data-slot="card-content" className={cn('p-5 pt-0', className)} {...props} />;
}
function CardFooter({ className, ...props }: React.ComponentProps<'div'>) {
return <div data-slot="card-footer" className={cn('flex items-center p-6 pt-0', className)} {...props} />;
return <div data-slot="card-footer" className={cn('flex items-center p-5 pt-0', className)} {...props} />;
}
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent };
+6 -6
View File
@@ -10,11 +10,11 @@ import type { TooltipPayload } from 'recharts/types/state/tooltipSlice';
import { cn } from '@/lib/utils';
export const CHART_COLORS = [
'hsl(var(--chart-1))',
'hsl(var(--chart-2))',
'hsl(var(--chart-3))',
'hsl(var(--chart-4))',
'hsl(var(--chart-5))',
'var(--chart-1)',
'var(--chart-2)',
'var(--chart-3)',
'var(--chart-4)',
'var(--chart-5)',
] as const;
export function getChartColor(index: number): string {
@@ -39,7 +39,7 @@ export function ChartTooltipContent({
if (!active || !payload?.length) return null;
return (
<div className="rounded-lg border bg-background p-2 shadow-md">
<div className="popover-surface p-2.5">
{label && <p className="mb-1 text-xs text-muted-foreground">{label}</p>}
{payload.map((entry, i) => (
<div key={i} className="flex items-center gap-2 text-sm">
+2 -2
View File
@@ -15,13 +15,13 @@ function Checkbox({ className, ...props }: React.ComponentProps<typeof CheckboxP
<CheckboxPrimitive.Root
data-slot="checkbox"
className={cn(
'peer h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground',
'peer h-[18px] w-[18px] shrink-0 rounded-[6px] border-0 bg-field shadow-[inset_0_0_0_1.5px_var(--input)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background data-[state=checked]:shadow-none data-[state=indeterminate]:bg-primary data-[state=indeterminate]:text-primary-foreground data-[state=indeterminate]:shadow-none disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground',
className,
)}
{...props}
>
<CheckboxPrimitive.Indicator className="flex items-center justify-center text-current">
<Check className="h-4 w-4" />
<Check className="h-3 w-3" strokeWidth={3} />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
);
+2 -2
View File
@@ -82,11 +82,11 @@ export function Combobox({
{...ariaProps}
ref={triggerRef}
type="button"
variant="outline"
variant="field"
role="combobox"
aria-expanded={open}
disabled={disabled}
className={cn('w-full justify-between font-normal', !selected && 'text-muted-foreground', className)}
className={cn('w-full justify-between px-3', !selected && 'text-dim', className)}
>
<span className="flex items-center gap-2 truncate">
{selected?.marker}
+2 -2
View File
@@ -17,7 +17,7 @@ function Command({ className, ...props }: React.ComponentProps<typeof CommandPri
<CommandPrimitive
data-slot="command"
className={cn(
'flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground',
'flex h-full w-full flex-col overflow-hidden rounded-2xl bg-popover text-popover-foreground',
className,
)}
{...props}
@@ -100,7 +100,7 @@ function CommandItem({ className, ...props }: React.ComponentProps<typeof Comman
<CommandPrimitive.Item
data-slot="command-item"
className={cn(
'relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50',
'relative flex cursor-default select-none items-center rounded-lg px-2.5 py-1.5 text-sm outline-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50',
className,
)}
{...props}
+4 -4
View File
@@ -37,7 +37,7 @@ function DialogOverlay({ className, ...props }: React.ComponentProps<typeof Dial
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
'fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
'fixed inset-0 z-50 bg-overlay data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className,
)}
{...props}
@@ -56,14 +56,14 @@ function DialogContent({
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
'fixed left-[50%] top-[50%] z-50 grid max-h-[calc(100dvh-2rem)] w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 overflow-y-auto border bg-background p-6 shadow-lg duration-200 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 sm:rounded-lg',
'fixed left-[50%] top-[50%] z-50 grid max-h-[calc(100dvh-2rem)] w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 overflow-y-auto rounded-3xl bg-card p-6 shadow-pop duration-200 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}
>
{children}
{showCloseButton && (
<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">
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-full p-1.5 opacity-70 hover:bg-muted 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>
@@ -97,7 +97,7 @@ function DialogTitle({ className, ...props }: React.ComponentProps<typeof Dialog
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn('text-lg font-semibold leading-none tracking-tight', className)}
className={cn('font-display text-lg font-bold leading-tight tracking-[-0.015em]', className)}
{...props}
/>
);
+6 -6
View File
@@ -44,7 +44,7 @@ function DropdownMenuSubTrigger({
<DropdownMenuPrimitive.SubTrigger
data-slot="dropdown-menu-sub-trigger"
className={cn(
'flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0',
'flex cursor-default gap-2 select-none items-center rounded-lg px-2.5 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0',
inset && 'pl-8',
className,
)}
@@ -64,7 +64,7 @@ function DropdownMenuSubContent({
<DropdownMenuPrimitive.SubContent
data-slot="dropdown-menu-sub-content"
className={cn(
'z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg 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 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',
'z-50 min-w-[8rem] overflow-hidden popover-surface p-1.5 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 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}
@@ -83,7 +83,7 @@ function DropdownMenuContent({
data-slot="dropdown-menu-content"
sideOffset={sideOffset}
className={cn(
'z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md',
'z-50 min-w-[8rem] overflow-hidden popover-surface p-1.5',
'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 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,
)}
@@ -102,7 +102,7 @@ function DropdownMenuItem({
<DropdownMenuPrimitive.Item
data-slot="dropdown-menu-item"
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-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&>svg]:size-4 [&>svg]:shrink-0',
'relative flex cursor-default select-none items-center gap-2 rounded-lg px-2.5 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&>svg]:size-4 [&>svg]:shrink-0',
inset && 'pl-8',
className,
)}
@@ -121,7 +121,7 @@ function DropdownMenuCheckboxItem({
<DropdownMenuPrimitive.CheckboxItem
data-slot="dropdown-menu-checkbox-item"
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-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
'relative flex cursor-default select-none items-center rounded-lg py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className,
)}
checked={checked}
@@ -146,7 +146,7 @@ function DropdownMenuRadioItem({
<DropdownMenuPrimitive.RadioItem
data-slot="dropdown-menu-radio-item"
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-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
'relative flex cursor-default select-none items-center rounded-lg py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className,
)}
{...props}
+10 -2
View File
@@ -8,13 +8,21 @@ import * as React from 'react';
import { cn } from '@/lib/utils';
function Input({ className, type, ...props }: React.ComponentProps<'input'>) {
function Input({
className,
type,
variant = 'field',
...props
}: React.ComponentProps<'input'> & { variant?: 'field' | 'pill' }) {
return (
<input
type={type}
data-slot="input"
className={cn(
'flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
'flex h-9 w-full px-3 py-1 text-base file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-dim focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
variant === 'field'
? 'field-surface rounded-lg'
: 'rounded-full border-0 bg-muted focus-visible:ring-2 focus-visible:ring-ring',
className,
)}
{...props}
+1 -1
View File
@@ -34,7 +34,7 @@ function PopoverContent({
align={align}
sideOffset={sideOffset}
className={cn(
'z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none 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 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',
'z-50 w-72 popover-surface p-4 outline-none 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 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}
+12 -4
View File
@@ -22,12 +22,20 @@ function SelectValue(props: React.ComponentProps<typeof SelectPrimitive.Value>)
return <SelectPrimitive.Value data-slot="select-value" {...props} />;
}
function SelectTrigger({ className, children, ...props }: React.ComponentProps<typeof SelectPrimitive.Trigger>) {
function SelectTrigger({
className,
children,
variant = 'field',
...props
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & { variant?: 'field' | 'pill' }) {
return (
<SelectPrimitive.Trigger
data-slot="select-trigger"
className={cn(
'flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1',
'flex items-center justify-between whitespace-nowrap placeholder:text-dim focus:outline-none disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1',
variant === 'field'
? 'field-surface h-9 w-full rounded-lg px-3 py-2 text-sm'
: 'h-8 w-auto gap-2 rounded-full bg-card px-3.5 text-[13px] font-semibold shadow-tile transition-shadow duration-200 hover:shadow-lift focus-visible:ring-2 focus-visible:ring-ring data-[state=open]:shadow-lift',
className,
)}
{...props}
@@ -78,7 +86,7 @@ function SelectContent({
<SelectPrimitive.Content
data-slot="select-content"
className={cn(
'relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground 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 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',
'relative z-50 max-h-96 min-w-[8rem] overflow-hidden popover-surface 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 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',
position === 'popper' &&
'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
className,
@@ -117,7 +125,7 @@ function SelectItem({ className, children, ...props }: React.ComponentProps<type
<SelectPrimitive.Item
data-slot="select-item"
className={cn(
'relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
'relative flex w-full cursor-default select-none items-center rounded-lg py-1.5 pl-2.5 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className,
)}
{...props}
+2 -2
View File
@@ -14,12 +14,12 @@ function Switch({ className, ...props }: React.ComponentProps<typeof SwitchPrimi
<SwitchPrimitives.Root
data-slot="switch"
className={cn(
'peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input',
'peer inline-flex h-6 w-10 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-muted-strong',
className,
)}
{...props}
>
<SwitchPrimitives.Thumb className="pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0" />
<SwitchPrimitives.Thumb className="pointer-events-none block h-5 w-5 rounded-full bg-card shadow-[0_1px_3px_rgb(0_0_0/0.25)] ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=checked]:bg-white data-[state=unchecked]:translate-x-0" />
</SwitchPrimitives.Root>
);
}
+2 -2
View File
@@ -18,7 +18,7 @@ function TabsList({ className, ...props }: React.ComponentProps<typeof TabsPrimi
<TabsPrimitive.List
data-slot="tabs-list"
className={cn(
'inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground',
'inline-flex h-10 items-center justify-center gap-0.5 rounded-full bg-muted p-1 text-muted-foreground',
className,
)}
{...props}
@@ -31,7 +31,7 @@ function TabsTrigger({ className, ...props }: React.ComponentProps<typeof TabsPr
<TabsPrimitive.Trigger
data-slot="tabs-trigger"
className={cn(
'inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow',
'inline-flex h-8 items-center justify-center gap-1.5 whitespace-nowrap rounded-full px-3.5 py-1 text-[13px] font-semibold ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 hover:text-foreground data-[state=active]:bg-card data-[state=active]:text-foreground data-[state=active]:shadow-tile',
className,
)}
{...props}
+7 -2
View File
@@ -8,12 +8,17 @@ import * as React from 'react';
import { cn } from '@/lib/utils';
function Textarea({ className, ...props }: React.ComponentProps<'textarea'>) {
function Textarea({
className,
variant = 'field',
...props
}: React.ComponentProps<'textarea'> & { variant?: 'field' | 'bare' }) {
return (
<textarea
data-slot="textarea"
className={cn(
'flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
'flex min-h-[60px] w-full px-3 py-2 text-base placeholder:text-dim focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
variant === 'field' ? 'field-surface rounded-lg' : 'border-0 bg-transparent',
className,
)}
{...props}
+7 -7
View File
@@ -24,15 +24,15 @@ function ToastViewport({ className, ...props }: React.ComponentProps<'ol'>) {
}
const toastVariants = cva(
'group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full',
'group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-2xl p-4 pr-7 shadow-pop ring-1 transition-all data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full',
{
variants: {
variant: {
default: 'border bg-background text-foreground',
destructive: 'destructive group border-destructive bg-destructive text-destructive-foreground',
success: 'border-green-500 bg-background text-foreground',
warning: 'border-yellow-500 bg-background text-foreground',
info: 'border-blue-500 bg-background text-foreground',
default: 'bg-popover text-popover-foreground ring-border',
destructive: 'destructive group bg-destructive-soft text-foreground ring-destructive/40',
success: 'bg-success-soft text-foreground ring-success/40',
warning: 'bg-warning-soft text-foreground ring-warning/40',
info: 'bg-info-soft text-foreground ring-info/40',
},
},
defaultVariants: {
@@ -71,7 +71,7 @@ function ToastClose({ className, ...props }: React.ComponentProps<'button'>) {
data-slot="toast-close"
aria-label="Close"
className={cn(
'absolute right-1 top-1 rounded-md p-1 text-foreground/60 transition-colors hover:text-foreground focus:outline-none focus:ring-1 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600',
'absolute right-1.5 top-1.5 rounded-full p-1 text-foreground/60 transition-colors hover:bg-muted hover:text-foreground focus:outline-none focus:ring-1 focus:ring-ring',
className,
)}
type="button"
+1 -1
View File
@@ -32,7 +32,7 @@ function TooltipContent({
data-slot="tooltip-content"
sideOffset={sideOffset}
className={cn(
'z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground 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',
'z-50 overflow-hidden rounded-lg bg-ink px-3 py-1.5 text-xs text-ink-foreground shadow-ink 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}
+9 -8
View File
@@ -8,6 +8,7 @@ import { Fragment, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { ChevronRight } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { cn } from '@/lib/utils';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { HelpTooltip } from '@/components/common/HelpTooltip';
import { formatDateTime } from '@/lib/format';
@@ -124,11 +125,11 @@ function SetValue({
);
}
return (
<span className="flex flex-wrap gap-1">
<span className="flex flex-wrap gap-1.5">
{items.map((item) => {
const color = itemType.type === 'enum' ? getEnumVariant(schema, itemType.enumName, item)?.color : undefined;
return (
<Badge key={item} variant="secondary" className="gap-1 text-xs">
<Badge key={item} variant="secondary" className="h-6 gap-1.5 font-medium">
{color && (
<span className="inline-block h-2 w-2 shrink-0 rounded-full" style={{ backgroundColor: color }} />
)}
@@ -169,7 +170,7 @@ function MapValue({
);
}
return (
<dl className="space-y-2">
<dl className="@container divide-y divide-border border-l-2 border-input pl-4">
{entries.map(([key, val]) => (
<ValueRow
key={key}
@@ -205,7 +206,7 @@ function ObjectListValue({
return <span>{t('value.itemCount', '{{count}} items', { count: entries.length })}</span>;
}
return (
<div className="space-y-2">
<div className="space-y-1.5">
{entries.map(([key, item]) => (
<ObjectValue key={key} schema={schema} objectName={objectName} value={item} />
))}
@@ -306,7 +307,7 @@ export function ObjectValue({
<CollapsibleTrigger asChild>
<button
type="button"
className="flex items-center gap-1.5 text-sm text-muted-foreground transition-colors hover:text-foreground [&[data-state=open]>svg]:rotate-90"
className="-ml-1 flex items-center gap-1.5 rounded-md px-1 py-0.5 text-sm text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring [&[data-state=open]>svg]:rotate-90"
>
<ChevronRight className="h-3.5 w-3.5 shrink-0 transition-transform duration-200" aria-hidden="true" />
{typeLabel || summary.summary ? (
@@ -317,7 +318,7 @@ export function ObjectValue({
</button>
</CollapsibleTrigger>
<CollapsibleContent>
<dl className="mt-2 ml-5 space-y-2 border-l-2 border-muted/40 pl-4">
<dl className="@container mt-1.5 ml-1.5 divide-y divide-border border-l-2 border-input pl-4">
{entries.map((entry) => (
<ValueRow
key={entry.key}
@@ -361,8 +362,8 @@ export interface ValueRowProps {
export function ValueRow({ schema, label, description, type, value }: ValueRowProps) {
const block = isBlockValue(type, value);
return (
<div className={block ? 'space-y-1' : 'flex items-baseline gap-2'}>
<dt className="flex min-w-[140px] shrink-0 items-center gap-1 text-sm text-muted-foreground">
<div data-slot="value-row" className={cn('py-3', block ? 'grid gap-y-1.5' : 'field-grid')}>
<dt className="flex min-w-0 items-center gap-1 text-[13px] font-medium text-muted-foreground">
{label}
{description && typeof label === 'string' && <HelpTooltip content={description} label={label} />}
</dt>
+16 -9
View File
@@ -19,8 +19,8 @@ export type ValueVariant = 'full' | 'compact';
export function EmptyValue({ variant = 'full' }: { variant?: ValueVariant }) {
const { t } = useTranslation();
if (variant === 'compact') return <span className="text-muted-foreground">-</span>;
return <span className="text-sm italic text-muted-foreground">{t('field.notSet', 'Not set')}</span>;
if (variant === 'compact') return <span className="text-dim">-</span>;
return <span className="text-sm italic text-dim">{t('field.notSet', 'Not set')}</span>;
}
export function StringValue({
@@ -39,7 +39,10 @@ export function StringValue({
if (format === 'color') {
return (
<span className="inline-flex items-center gap-2 text-sm">
<span className="inline-block h-3.5 w-3.5 shrink-0 rounded-sm border" style={{ backgroundColor: str }} />
<span
className="inline-block h-3.5 w-3.5 shrink-0 rounded-full shadow-[inset_0_0_0_1px_var(--input)]"
style={{ backgroundColor: str }}
/>
<span className="font-mono">{str}</span>
</span>
);
@@ -48,8 +51,8 @@ export function StringValue({
return (
<pre
className={cn(
'whitespace-pre-wrap break-words rounded bg-muted/50 font-mono text-xs',
variant === 'compact' ? 'max-w-md px-1.5 py-1' : 'p-2',
'whitespace-pre-wrap break-words bg-muted font-mono text-xs',
variant === 'compact' ? 'max-w-md rounded-lg px-2 py-1' : 'rounded-xl p-3',
format === 'text' && 'font-sans',
)}
>
@@ -72,9 +75,9 @@ export function NumberValue({ value, format }: { value: unknown; format: string
export function BooleanValue({ value }: { value: unknown }) {
const { t } = useTranslation();
return value === true ? (
<Check className="h-4 w-4 text-green-600" role="img" aria-label={t('common.yes', 'Yes')} />
<Check className="h-4 w-4 text-success" role="img" aria-label={t('common.yes', 'Yes')} />
) : (
<X className="h-4 w-4 text-red-500" role="img" aria-label={t('common.no', 'No')} />
<X className="h-4 w-4 text-destructive" role="img" aria-label={t('common.no', 'No')} />
);
}
@@ -83,7 +86,11 @@ export function EnumValue({ schema, enumName, value }: { schema: Schema; enumNam
const variant = getEnumVariant(schema, enumName, name);
if (!variant) return <span className="text-sm">{name}</span>;
return (
<Badge variant="secondary" style={variant.color ? { backgroundColor: variant.color, color: '#fff' } : undefined}>
<Badge
variant="secondary"
className={cn('h-6', variant.color && 'text-primary-foreground')}
style={variant.color ? { backgroundColor: variant.color } : undefined}
>
{variant.label}
</Badge>
);
@@ -104,7 +111,7 @@ export function ObjectIdValue({
const content = loading && !label ? <Loader2 className="h-3 w-3 animate-spin" /> : (label ?? id);
if (variant === 'compact') return <span>{content}</span>;
return (
<Badge variant="secondary" className="text-sm">
<Badge variant="secondary" className="h-6 font-medium">
{content}
</Badge>
);
+18 -28
View File
@@ -5,8 +5,8 @@
*/
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { ValueRow } from '@/components/values/FieldValue';
import { cn } from '@/lib/utils';
import { resolveForm, resolveSchema, resolveVariantForm } from '@/lib/schemaResolver';
import { isEmptyValue, variantLabel } from '@/lib/embeddedSchema';
import type { Field, Fields, Form, FormField, Schema } from '@/types/schema';
@@ -77,34 +77,24 @@ export function DynamicView({ schema, objectName, viewName, data, visibleFields
const typeLabel = variantLabel(schema, objectName, data['@type']);
return (
<div className="space-y-4">
{typeLabel && (
<Badge variant="secondary" className="text-xs">
{typeLabel}
</Badge>
)}
<div className="space-y-3.5">
{typeLabel && <Badge variant="default">{typeLabel}</Badge>}
{sections.map((section) => (
<Card key={section.key}>
{section.title && (
<CardHeader className="pb-3">
<CardTitle className="text-base">{section.title}</CardTitle>
</CardHeader>
)}
<CardContent className={section.title ? 'pt-0' : ''}>
<dl className="space-y-2">
{section.items.map(({ formField, field }) => (
<ValueRow
key={formField.name}
schema={schema}
label={formField.label}
description={field.description}
type={field.type}
value={data[formField.name]}
/>
))}
</dl>
</CardContent>
</Card>
<section key={section.key} className="tile @container px-5 pb-1.5 sm:px-6">
{section.title && <h2 className="section-title pb-1 pt-5">{section.title}</h2>}
<dl className={cn('divide-y divide-border', !section.title && 'pt-1')}>
{section.items.map(({ formField, field }) => (
<ValueRow
key={formField.name}
schema={schema}
label={formField.label}
description={field.description}
type={field.type}
value={data[formField.name]}
/>
))}
</dl>
</section>
))}
</div>
);
+17 -10
View File
@@ -41,19 +41,21 @@ export function DynamicViewPage({ viewName, objectId }: DynamicViewPageProps) {
if (loading) {
return (
<div className="flex items-center justify-center p-12">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
<Loader2 className="h-6 w-6 animate-spin text-brand-text" aria-hidden="true" />
</div>
);
}
if (error || !data || !schema) {
return (
<div className="space-y-4">
<div className="mx-auto max-w-5xl space-y-5 pt-3">
<Button variant="outline" size="sm" onClick={() => navigate(-1)}>
<ArrowLeft className="mr-2 h-4 w-4" />
<ArrowLeft aria-hidden="true" />
{t('common.back', 'Back')}
</Button>
<div className="text-destructive p-4">{error ?? t('view.failedToLoad', 'Failed to load')}</div>
<div className="rounded-xl bg-destructive-soft p-4 text-sm text-destructive" role="alert">
{error ?? t('view.failedToLoad', 'Failed to load')}
</div>
</div>
);
}
@@ -71,13 +73,18 @@ export function DynamicViewPage({ viewName, objectId }: DynamicViewPageProps) {
: singularName.charAt(0).toUpperCase() + singularName.slice(1);
return (
<div className="space-y-6">
<div className="flex items-center gap-3">
<Button variant="outline" size="sm" onClick={() => navigate(-1)}>
<ArrowLeft className="mr-2 h-4 w-4" />
{t('common.back', 'Back')}
<div className="mx-auto max-w-5xl space-y-5">
<div className="flex items-start gap-3.5 px-1 pb-1 pt-3">
<Button
variant="outline"
size="icon-lg"
className="shrink-0"
onClick={() => navigate(-1)}
aria-label={t('common.back', 'Back')}
>
<ArrowLeft className="h-5 w-5" aria-hidden="true" />
</Button>
<h1 className="text-xl font-semibold">{title}</h1>
<h1 className="page-title min-w-0 flex-1 break-words pt-1.5">{title}</h1>
</div>
<DynamicView schema={schema} objectName={resolved.objectName} viewName={viewName} data={data} />
+2 -2
View File
@@ -120,8 +120,8 @@ export function ActionPage({ viewName }: ActionPageProps) {
);
case 'submitting':
return (
<div role="status" className="flex flex-col items-center justify-center gap-3 py-16">
<Loader2 aria-hidden="true" className="h-8 w-8 animate-spin text-muted-foreground" />
<div role="status" className="flex flex-col items-center justify-center gap-3 rounded-2xl bg-muted py-16">
<Loader2 aria-hidden="true" className="size-8 animate-spin text-brand-text" />
<p className="text-muted-foreground">
{t('actions.executing', 'Executing {{label}}...', { label: state.variant.label })}
</p>
+32 -34
View File
@@ -6,10 +6,10 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Zap } from 'lucide-react';
import { ArrowLeft, Zap } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { FieldRow } from '@/components/forms/FieldRow';
import { FormSectionCard } from '@/components/forms/FormSections';
import { FormProvider } from '@/components/forms/FormProvider';
import { resolveVariantForm } from '@/lib/schemaResolver';
import type { ObjectVariant, Schema } from '@/types/schema';
@@ -55,56 +55,54 @@ export function ActionForm({ schema, variant, initialData, onSubmit, onBack }: A
return (
<form
className="space-y-6"
className="mx-auto max-w-5xl space-y-3.5"
noValidate
onSubmit={(e) => {
e.preventDefault();
handleSubmit();
}}
>
<div className="flex items-center gap-2">
<Button type="button" variant="outline" size="sm" onClick={onBack}>
{t('common.back', 'Back')}
<div className="flex items-start gap-3.5 px-1 pb-1 pt-3">
<Button
type="button"
variant="outline"
size="icon-lg"
className="shrink-0"
onClick={onBack}
aria-label={t('common.back', 'Back')}
>
<ArrowLeft className="h-5 w-5" aria-hidden="true" />
</Button>
<h1 className="text-xl font-semibold">{variant.label}</h1>
<h1 className="page-title min-w-0 flex-1 break-words pt-1">{variant.label}</h1>
</div>
<FormProvider schema={schema} mode="create">
{sections.map((section) => (
<Card key={section.fields.map((f) => f.name).join('|')}>
{section.title && (
<CardHeader className="pb-3">
<CardTitle className="text-base">{section.title}</CardTitle>
</CardHeader>
)}
<CardContent className={section.title ? 'pt-0' : undefined}>
<div className="space-y-4">
{section.fields.map((ff) => {
const def = fields.properties[ff.name];
if (!def) return null;
return (
<FieldRow
key={ff.name}
formField={ff}
field={def}
value={formData[ff.name]}
onChange={(v) => handleChange(ff.name, v)}
error={errors[ff.name]}
/>
);
})}
</div>
</CardContent>
</Card>
<FormSectionCard key={section.fields.map((f) => f.name).join('|')} title={section.title}>
{section.fields.map((ff) => {
const def = fields.properties[ff.name];
if (!def) return null;
return (
<FieldRow
key={ff.name}
formField={ff}
field={def}
value={formData[ff.name]}
onChange={(v) => handleChange(ff.name, v)}
error={errors[ff.name]}
/>
);
})}
</FormSectionCard>
))}
</FormProvider>
<div className="flex justify-end gap-2">
<div className="flex justify-end gap-2 pt-1">
<Button type="button" variant="outline" onClick={onBack}>
{t('common.cancel', 'Cancel')}
</Button>
<Button type="submit">
<Zap aria-hidden="true" className="mr-2 h-4 w-4" />
<Zap aria-hidden="true" />
{t('actions.execute', 'Execute')}
</Button>
</div>
@@ -26,23 +26,28 @@ function ActionGroupSection({
const headingId = useId();
return (
<section aria-labelledby={headingId}>
<h2 id={headingId} className="mb-2 text-sm font-medium text-muted-foreground">
<h2 id={headingId} className="mb-2 px-1 text-[11px] font-semibold uppercase tracking-wider text-dim">
{group.label}
</h2>
<div className="grid gap-2 sm:grid-cols-2">
<div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
{group.actions.map(({ variant, name }) => (
<Button
key={variant.name}
variant="outline"
className="h-auto justify-between px-4 py-3"
className="group h-auto justify-between gap-3 whitespace-normal rounded-2xl px-4 py-3 text-left font-medium"
disabled={disabled}
onClick={() => onPick(variant)}
>
<span className="flex items-center gap-2">
<Zap aria-hidden="true" className="h-4 w-4 shrink-0 text-muted-foreground" />
<span>{name}</span>
<span className="flex min-w-0 items-center gap-3">
<span className="grid size-8 shrink-0 place-items-center rounded-[10px] bg-highlight text-highlight-foreground">
<Zap aria-hidden="true" />
</span>
<span className="min-w-0">{name}</span>
</span>
<ChevronRight aria-hidden="true" className="h-4 w-4 text-muted-foreground" />
<ChevronRight
aria-hidden="true"
className="text-dim transition-transform duration-200 group-hover:translate-x-0.5"
/>
</Button>
))}
</div>
@@ -52,9 +57,9 @@ function ActionGroupSection({
export function ActionPicker({ title, subtitle, groups, disabled, onPick }: ActionPickerProps) {
return (
<div className="space-y-6">
<div>
<h1 className="text-xl font-semibold">{title}</h1>
<div className="space-y-3.5">
<div className="px-1 pb-1 pt-3">
<h1 className="page-title">{title}</h1>
{subtitle && <p className="mt-1 text-sm text-muted-foreground">{subtitle}</p>}
</div>
<div className="space-y-6">
@@ -23,11 +23,13 @@ export function ActionResult({ schema, variant, data, onNewAction }: ActionResul
const hasData = !!variant.schemaName && Object.keys(data).length > 0;
return (
<div className="space-y-6 pt-4">
<div role="status" className="flex items-center gap-3">
<CircleCheck aria-hidden="true" className="h-5 w-5 shrink-0 text-emerald-500" />
<div>
<h1 className="font-medium">{variant.label}</h1>
<div className="space-y-3.5">
<div role="status" className="flex items-center gap-3.5 px-1 pb-1 pt-3">
<span className="grid size-10 shrink-0 place-items-center rounded-full bg-success-soft text-success">
<CircleCheck aria-hidden="true" className="size-5" />
</span>
<div className="min-w-0">
<h1 className="page-title break-words">{variant.label}</h1>
<p className="text-sm text-muted-foreground">
{t('actions.executedSuccess', 'Action executed successfully.')}
</p>
@@ -43,15 +45,13 @@ export function ActionResult({ schema, variant, data, onNewAction }: ActionResul
visibleFields={new Set(Object.keys(data))}
/>
) : (
<Card>
<CardContent className="p-6 text-sm text-muted-foreground">
{t('actions.noAdditionalData', 'No additional data returned.')}
</CardContent>
</Card>
<div className="rounded-2xl bg-muted p-10 text-center text-sm text-muted-foreground">
{t('actions.noAdditionalData', 'No additional data returned.')}
</div>
)}
<Button onClick={onNewAction}>
<Zap aria-hidden="true" className="mr-2 h-4 w-4" />
<Zap aria-hidden="true" />
{t('actions.executeAnother', 'Execute another action')}
</Button>
</div>
@@ -63,12 +63,14 @@ export function ActionError({ error, onBack }: { error: string; onBack: () => vo
return (
<div className="mx-auto max-w-xl space-y-4 pt-8">
<Card>
<CardContent className="space-y-4 p-6">
<div role="alert" className="flex items-center gap-3">
<CircleAlert aria-hidden="true" className="h-5 w-5 shrink-0 text-destructive" />
<div>
<h1 className="font-medium">{t('actions.failedTitle', 'Action failed')}</h1>
<p className="mt-1 text-sm text-muted-foreground">{error}</p>
<CardContent className="space-y-5 p-6">
<div role="alert" className="flex items-start gap-3.5">
<span className="grid size-10 shrink-0 place-items-center rounded-full bg-destructive-soft text-destructive">
<CircleAlert aria-hidden="true" className="size-5" />
</span>
<div className="min-w-0 pt-0.5">
<h1 className="section-title text-lg">{t('actions.failedTitle', 'Action failed')}</h1>
<p className="mt-1 whitespace-pre-line break-words text-sm text-muted-foreground">{error}</p>
</div>
</div>
<Button variant="outline" onClick={onBack}>
@@ -5,35 +5,39 @@
*/
import { useEffect, useRef, useState, type ReactNode } from 'react';
import { cn } from '@/lib/utils';
export function ChartSizedContainer({
height,
fill = false,
children,
}: {
height: number;
fill?: boolean;
children: (width: number, height: number) => ReactNode;
}) {
const ref = useRef<HTMLDivElement>(null);
const [width, setWidth] = useState(0);
const [size, setSize] = useState({ width: 0, height: 0 });
useEffect(() => {
const el = ref.current;
if (!el) return;
const update = (rawWidth: number, rawHeight: number) => {
const width = Math.round(rawWidth);
const height = Math.round(rawHeight);
if (width <= 0 || height <= 0) return;
setSize((prev) => (prev.width === width && prev.height === height ? prev : { width, height }));
};
const ro = new ResizeObserver((entries) => {
for (const entry of entries) {
const w = entry.contentRect.width;
if (w > 0) setWidth(w);
}
for (const entry of entries) update(entry.contentRect.width, entry.contentRect.height);
});
ro.observe(el);
const w = el.getBoundingClientRect().width;
if (w > 0) setWidth(w);
const rect = el.getBoundingClientRect();
update(rect.width, rect.height);
return () => ro.disconnect();
}, []);
return (
<div ref={ref} style={{ height }}>
{width > 0 && children(width, height)}
<div ref={ref} className={cn('relative', fill ? 'min-h-[280px] flex-1' : 'h-[280px]')}>
{size.width > 0 && <div className="absolute inset-0">{children(size.width, size.height)}</div>}
</div>
);
}
@@ -5,38 +5,29 @@
*/
import { useMemo } from 'react';
import {
LineChart,
Line,
AreaChart,
Area,
BarChart,
Bar,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
} from 'recharts';
import { LineChart, Line, AreaChart, Area, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip } from 'recharts';
import { Info } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Card } from '@/components/ui/card';
import { HelpTooltip } from '@/components/common/HelpTooltip';
import { getChartColor } from '@/components/ui/chart';
import { ChartTooltipContent } from '@/components/ui/chart';
import type { Chart as ChartSchema } from '../types/schema';
import { ChartTooltipContent, getChartColor } from '@/components/ui/chart';
import type { Chart as ChartSchema, Placement } from '../types/schema';
import type { Metric, Period } from '../types/metrics';
import { bucketTimestamps, bucketValues, getBucketCount, formatTimeTick, formatValue } from '../helpers';
import { ChartSizedContainer } from './ChartSizedContainer';
import { toneClasses } from './tone';
import { cn } from '@/lib/utils';
interface DashboardChartProps {
chart: ChartSchema;
chart: ChartSchema & Placement;
historySamples: Metric[];
historyWindow: { from: Date; to: Date };
period: Period;
className?: string;
}
export function DashboardChart({ chart, historySamples, historyWindow, period }: DashboardChartProps) {
export function DashboardChart({ chart, historySamples, historyWindow, period, className }: DashboardChartProps) {
const toneClass = toneClasses(chart.tone);
const { from, to } = historyWindow;
const bucketCount = getBucketCount(period);
const valueFormat = chart.valueFormat ?? 'number';
@@ -82,7 +73,7 @@ export function DashboardChart({ chart, historySamples, historyWindow, period }:
data,
width: chartWidth,
height: chartHeight,
margin: { top: 5, right: 10, left: 10, bottom: 5 },
margin: { top: 6, right: 4, left: 0, bottom: 0 },
};
const seriesElements = chart.series.map((s, i) => {
@@ -97,8 +88,11 @@ export function DashboardChart({ chart, historySamples, historyWindow, period }:
type="monotone"
dataKey={key}
stroke={color}
strokeWidth={2}
strokeWidth={2.25}
strokeLinecap="round"
strokeLinejoin="round"
dot={false}
activeDot={{ r: 3.5, strokeWidth: 0 }}
isAnimationActive={false}
connectNulls
/>
@@ -111,8 +105,9 @@ export function DashboardChart({ chart, historySamples, historyWindow, period }:
dataKey={key}
stroke={color}
fill={color}
fillOpacity={0.3}
fillOpacity={chart.stacked ? 0.35 : 0.14}
strokeWidth={2}
activeDot={{ r: 3.5, strokeWidth: 0 }}
stackId={chart.stacked ? '1' : undefined}
isAnimationActive={false}
connectNulls
@@ -124,6 +119,8 @@ export function DashboardChart({ chart, historySamples, historyWindow, period }:
key={key}
dataKey={key}
fill={color}
radius={chart.stacked ? 0 : [4, 4, 0, 0]}
maxBarSize={28}
stackId={chart.stacked ? '1' : undefined}
isAnimationActive={false}
/>
@@ -133,23 +130,24 @@ export function DashboardChart({ chart, historySamples, historyWindow, period }:
const axes = (
<>
<CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
<CartesianGrid vertical={false} className="stroke-border" />
<XAxis
dataKey="timeLabel"
tick={{ fontSize: 11 }}
className="text-muted-foreground"
tick={{ fontSize: 10.5, fill: 'var(--dim)' }}
tickLine={false}
axisLine={false}
tickMargin={8}
minTickGap={16}
/>
<YAxis
tickFormatter={tickFormatter}
tick={{ fontSize: 11 }}
className="text-muted-foreground"
tick={{ fontSize: 10.5, fill: 'var(--dim)' }}
tickLine={false}
axisLine={false}
width={60}
width={56}
/>
<Tooltip
cursor={chart.kind === 'bar' ? { fill: 'var(--muted)', opacity: 0.6 } : { stroke: 'var(--input)' }}
content={({ active, payload, label }) => (
<ChartTooltipContent
active={active}
@@ -159,7 +157,6 @@ export function DashboardChart({ chart, historySamples, historyWindow, period }:
/>
)}
/>
<Legend iconType="circle" iconSize={8} wrapperStyle={{ fontSize: '12px' }} />
</>
);
@@ -189,16 +186,32 @@ export function DashboardChart({ chart, historySamples, historyWindow, period }:
};
return (
<Card role="figure" aria-label={chart.title}>
<CardHeader className="pb-2">
<div className="flex items-center gap-2">
<CardTitle className="text-base">{chart.title}</CardTitle>
<Card
role="figure"
aria-label={chart.title}
className={cn('flex flex-col gap-3 px-5 pb-3.5 pt-[18px]', toneClass.surface, className)}
>
<div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2">
<div className="flex min-w-0 items-center gap-2">
<h2 className="section-title truncate">{chart.title}</h2>
{chart.description && <HelpTooltip content={chart.description} label={chart.title} icon={Info} />}
</div>
</CardHeader>
<CardContent>
<ChartSizedContainer height={288}>{(width, height) => renderChart(width, height)}</ChartSizedContainer>
</CardContent>
{chart.series.length > 0 && (
<ul className={cn('flex flex-wrap gap-x-3.5 gap-y-1 text-[12.5px]', toneClass.muted)}>
{chart.series.map((s, i) => (
<li key={`${s.label}-${i}`} className="inline-flex items-center gap-1.5">
<span
aria-hidden="true"
className="size-2 shrink-0 rounded-full"
style={{ backgroundColor: getChartColor(i) }}
/>
{s.label}
</li>
))}
</ul>
)}
</div>
<ChartSizedContainer fill={chart.rows === 2}>{(width, height) => renderChart(width, height)}</ChartSizedContainer>
</Card>
);
}
@@ -10,20 +10,57 @@ import { useTranslation } from 'react-i18next';
import { AlertCircle } from 'lucide-react';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useSchemaStore } from '@/stores/schemaStore';
import type { Dashboard } from '../types/schema';
import type { Dashboard, DashboardItem } from '../types/schema';
import type { Metric } from '../types/metrics';
import { useDashboardStore } from '../stores/dashboardStore';
import { useLiveMetricsStore } from '../stores/liveMetricsStore';
import { useClusterNodes, useHistoryMetrics } from '../queries';
import { useCanAccess } from '@/hooks/usePermissions';
import { errorMessage } from '@/lib/jmapErrors';
import { collectHistoryMetricIds, collectLiveMetricIds, distinctNodeIds, nodeOptions, periodWindow } from '../helpers';
import {
collectHistoryMetricIds,
collectLiveMetricIds,
dashboardItems,
distinctNodeIds,
nodeOptions,
periodWindow,
} from '../helpers';
import { StatCard } from './StatCard';
import { DashboardChart } from './DashboardChart';
import { PeriodSelector } from './PeriodSelector';
import { NodeSelector } from './NodeSelector';
import { HeadlineTile } from './HeadlineTile';
import { RankingTile } from './RankingTile';
import { cn } from '@/lib/utils';
const EMPTY_METRICS: Metric[] = [];
const EMPTY_ITEMS: DashboardItem[] = [];
const SPAN_CLASSES = [
'col-span-12 md:col-span-6 xl:col-span-1',
'col-span-12 md:col-span-6 xl:col-span-2',
'col-span-12 md:col-span-6 xl:col-span-3',
'col-span-12 md:col-span-6 xl:col-span-4',
'col-span-12 xl:col-span-5',
'col-span-12 xl:col-span-6',
'col-span-12 xl:col-span-7',
'col-span-12 xl:col-span-8',
'col-span-12 xl:col-span-9',
'col-span-12 xl:col-span-10',
'col-span-12 xl:col-span-11',
'col-span-12',
] as const;
const DEFAULT_SPAN: Record<DashboardItem['type'], number> = {
stat: 3,
chart: 6,
headline: 4,
ranking: 4,
};
function placementClass(item: DashboardItem): string {
return cn(SPAN_CLASSES[(item.span ?? DEFAULT_SPAN[item.type]) - 1], item.rows === 2 && 'xl:row-span-2');
}
interface DashboardViewProps {
dashboardId: string;
@@ -52,11 +89,9 @@ export function DashboardView({ dashboardId, section }: DashboardViewProps) {
}
}, [dashboard, dashboards, navigate, section]);
const historyIds = useMemo(
() => (dashboard ? collectHistoryMetricIds(dashboard.cards, dashboard.charts) : new Set<string>()),
[dashboard],
);
const liveIds = useMemo(() => (dashboard ? collectLiveMetricIds(dashboard.cards) : new Set<string>()), [dashboard]);
const items = useMemo(() => (dashboard ? dashboardItems(dashboard) : EMPTY_ITEMS), [dashboard]);
const historyIds = useMemo(() => collectHistoryMetricIds(items), [items]);
const liveIds = useMemo(() => collectLiveMetricIds(items), [items]);
const history = useHistoryMetrics(period, historyIds, nodeId);
const allNodesHistory = useHistoryMetrics(period, historyIds, null, nodeId === null);
@@ -89,7 +124,7 @@ export function DashboardView({ dashboardId, section }: DashboardViewProps) {
if (!dashboard) {
if (dashboards.length === 0) {
return (
<div className="flex items-center justify-center p-8 text-muted-foreground">
<div className="rounded-2xl bg-muted p-10 text-center text-muted-foreground">
{t('dashboard.noDashboards', 'No dashboards configured.')}
</div>
);
@@ -98,8 +133,8 @@ export function DashboardView({ dashboardId, section }: DashboardViewProps) {
}
return (
<div className="space-y-6">
<div className="flex flex-wrap items-center justify-between gap-4">
<div className="space-y-3.5">
<div className="flex flex-wrap items-end justify-between gap-4 px-1 pb-1 pt-3">
{dashboards.length > 1 && (
<Tabs
className="min-w-0 max-w-full"
@@ -115,7 +150,7 @@ export function DashboardView({ dashboardId, section }: DashboardViewProps) {
</TabsList>
</Tabs>
)}
{dashboards.length === 1 && <h1 className="text-xl font-semibold">{dashboard.label}</h1>}
{dashboards.length === 1 && <h1 className="page-title">{dashboard.label}</h1>}
<div className="ml-auto flex flex-wrap items-center gap-2">
{showNodeSelector && <NodeSelector nodes={nodes} value={nodeId} onChange={setNodeId} />}
@@ -126,7 +161,7 @@ export function DashboardView({ dashboardId, section }: DashboardViewProps) {
{history.isError && (
<div
role="alert"
className="flex items-center gap-2 rounded-lg border border-destructive/50 bg-destructive/10 p-3 text-sm text-destructive"
className="flex items-center gap-2 rounded-xl bg-destructive-soft p-4 text-sm text-destructive"
>
<AlertCircle aria-hidden="true" className="h-4 w-4 shrink-0" />
{errorMessage(history.error, t('dashboard.failedFetchMetrics', 'Failed to fetch metrics'))}
@@ -136,37 +171,46 @@ export function DashboardView({ dashboardId, section }: DashboardViewProps) {
{liveStatus === 'error' && liveError && (
<div
role="alert"
className="flex items-center gap-2 rounded-lg border border-destructive/50 bg-destructive/10 p-3 text-sm text-destructive"
className="flex items-center gap-2 rounded-xl bg-destructive-soft p-4 text-sm text-destructive"
>
<AlertCircle aria-hidden="true" className="h-4 w-4 shrink-0" />
{liveError}
</div>
)}
{dashboard.cards && dashboard.cards.length > 0 && (
<div className="grid gap-4 grid-cols-[repeat(auto-fit,minmax(220px,1fr))]">
{dashboard.cards.map((card, i) => (
<StatCard
key={`${card.title}-${i}`}
card={card}
historySamples={historySamples}
historyWindow={historyWindow}
/>
))}
</div>
)}
{dashboard.charts && dashboard.charts.length > 0 && (
<div className="space-y-4">
{dashboard.charts.map((chart, i) => (
<DashboardChart
key={`${chart.title}-${i}`}
chart={chart}
historySamples={historySamples}
historyWindow={historyWindow}
period={period}
/>
))}
{items.length > 0 && (
<div className="grid grid-flow-row-dense grid-cols-12 gap-3.5 xl:grid-flow-row">
{items.map((item, i) => {
const key = `${item.type}-${item.title}-${i}`;
const className = placementClass(item);
switch (item.type) {
case 'stat':
return (
<StatCard
key={key}
card={item}
className={className}
historySamples={historySamples}
historyWindow={historyWindow}
/>
);
case 'chart':
return (
<DashboardChart
key={key}
chart={item}
className={className}
historySamples={historySamples}
historyWindow={historyWindow}
period={period}
/>
);
case 'headline':
return <HeadlineTile key={key} headline={item} className={className} historySamples={historySamples} />;
case 'ranking':
return <RankingTile key={key} ranking={item} className={className} historySamples={historySamples} />;
}
})}
</div>
)}
</div>
@@ -0,0 +1,46 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: LicenseRef-SEL
*/
import { useTranslation } from 'react-i18next';
import { Card } from '@/components/ui/card';
import { formatPercent } from '@/lib/format';
import { cn } from '@/lib/utils';
import type { Headline, Placement } from '../types/schema';
import type { Metric } from '../types/metrics';
import { headlineRatio } from '../helpers';
import { toneClasses } from './tone';
import { TileHeader } from './TileHeader';
interface HeadlineTileProps {
headline: Headline & Placement;
className?: string;
historySamples: Metric[];
}
export function HeadlineTile({ headline, className, historySamples }: HeadlineTileProps) {
const { t } = useTranslation();
const toneClass = toneClasses(headline.tone);
const ratio = headlineRatio(headline, historySamples);
return (
<Card
role="figure"
aria-label={headline.title}
className={cn('flex min-h-[148px] flex-col gap-3 px-5 pb-5 pt-[18px]', toneClass.surface, className)}
>
<TileHeader icon={headline.icon} title={headline.title} badgeClass={toneClass.badge} />
<div
data-slot="headline-value"
className="font-display text-[2.75rem] font-[750] leading-none tracking-[-0.035em] tabular-nums"
>
{ratio === null ? t('dashboard.noData', 'No data') : formatPercent(ratio * 100)}
</div>
{headline.description && (
<p className={cn('text-[13px] leading-relaxed', toneClass.muted)}>{headline.description}</p>
)}
</Card>
);
}
@@ -5,6 +5,7 @@
*/
import { useTranslation } from 'react-i18next';
import { Server } from 'lucide-react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import type { ClusterNodeInfo } from '../types/metrics';
@@ -30,7 +31,8 @@ export function NodeSelector({ nodes, value, onChange }: NodeSelectorProps) {
return (
<Select value={value === null ? ALL_NODES : String(value)} onValueChange={handleChange}>
<SelectTrigger className="w-44" aria-label={t('dashboard.node', 'Node')}>
<SelectTrigger variant="pill" aria-label={t('dashboard.node', 'Node')}>
<Server aria-hidden="true" className="size-3.5 shrink-0 text-muted-foreground" />
<SelectValue />
</SelectTrigger>
<SelectContent>
@@ -6,7 +6,7 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Calendar, RefreshCw } from 'lucide-react';
import { Calendar, CalendarClock, RefreshCw } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover';
@@ -59,7 +59,8 @@ export function PeriodSelector({ onRefresh, loading }: PeriodSelectorProps) {
<Popover open={customOpen} onOpenChange={setCustomOpen}>
<PopoverAnchor>
<Select value={currentValue} onValueChange={handleSelectChange}>
<SelectTrigger className="w-44" aria-label={t('dashboard.period', 'Period')}>
<SelectTrigger variant="pill" aria-label={t('dashboard.period', 'Period')}>
<CalendarClock aria-hidden="true" className="size-3.5 shrink-0 text-muted-foreground" />
<SelectValue />
</SelectTrigger>
<SelectContent>
@@ -80,7 +81,7 @@ export function PeriodSelector({ onRefresh, loading }: PeriodSelectorProps) {
<PopoverContent className="w-72 p-4" align="end">
<div className="space-y-3">
<h4 className="text-sm font-medium">{t('dashboard.customRange', 'Custom range')}</h4>
<h4 className="section-title text-sm">{t('dashboard.customRange', 'Custom range')}</h4>
<div className="space-y-2">
<Label htmlFor="custom-from" className="text-xs">
{t('dashboard.from', 'From')}
@@ -115,10 +116,10 @@ export function PeriodSelector({ onRefresh, loading }: PeriodSelectorProps) {
size="icon"
onClick={onRefresh}
disabled={loading}
className="h-9 w-9"
className="size-8"
aria-label={t('dashboard.refresh', 'Refresh')}
>
<RefreshCw aria-hidden="true" className={cn('h-4 w-4', loading && 'animate-spin')} />
<RefreshCw aria-hidden="true" className={cn('size-4', loading && 'animate-spin')} />
</Button>
</div>
);
@@ -0,0 +1,62 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: LicenseRef-SEL
*/
import { Card } from '@/components/ui/card';
import { getChartColor } from '@/components/ui/chart';
import { cn } from '@/lib/utils';
import type { Ranking, Placement } from '../types/schema';
import type { Metric } from '../types/metrics';
import { formatValue, rankingEntries } from '../helpers';
import { toneClasses } from './tone';
import { TileHeader } from './TileHeader';
interface RankingTileProps {
ranking: Ranking & Placement;
className?: string;
historySamples: Metric[];
}
export function RankingTile({ ranking, className, historySamples }: RankingTileProps) {
const toneClass = toneClasses(ranking.tone);
const entries = rankingEntries(ranking, historySamples);
const max = entries.reduce((m, e) => Math.max(m, e.value), 0);
const format = ranking.valueFormat ?? 'number';
return (
<Card
role="figure"
aria-label={ranking.title}
className={cn('flex flex-col gap-3.5 px-5 pb-5 pt-[18px]', toneClass.surface, className)}
>
<TileHeader
icon={ranking.icon}
title={ranking.title}
description={ranking.description}
badgeClass={toneClass.badge}
/>
<ul className="grid gap-2.5">
{entries.map((entry, i) => (
<li
key={entry.label}
className="grid grid-cols-[minmax(0,7.5rem)_minmax(0,1fr)_minmax(3.5rem,auto)] items-center gap-3 text-[13px]"
>
<span className="truncate">{entry.label}</span>
<span className={cn('h-2 overflow-hidden rounded-full', toneClass.track)} aria-hidden="true">
<span
className="block h-full rounded-full"
style={{
width: max > 0 ? `${(entry.value / max) * 100}%` : '0%',
backgroundColor: getChartColor(i),
}}
/>
</span>
<span className={cn('text-right tabular-nums', toneClass.muted)}>{formatValue(entry.value, format)}</span>
</li>
))}
</ul>
</Card>
);
}
+76 -41
View File
@@ -6,20 +6,29 @@
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { HelpCircle, Info } from 'lucide-react';
import { ArrowDownRight, ArrowUpRight, HelpCircle, Info, Minus } from 'lucide-react';
import { DynamicIcon } from '@/components/common/DynamicIcon';
import { LineChart, Line } from 'recharts';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Card } from '@/components/ui/card';
import { HelpTooltip } from '@/components/common/HelpTooltip';
import type { Card as CardSchema } from '../types/schema';
import type { Card as CardSchema, Placement } from '../types/schema';
import type { Metric } from '../types/metrics';
import { cardValue, formatValue, sparklineData, computeDelta } from '../helpers';
import { cardValue, deltaSentiment, formatValue, sparklineData, computeDelta } from '../helpers';
import { useLiveMetricsStore } from '../stores/liveMetricsStore';
import { getChartColor } from '@/components/ui/chart';
import { formatPercent } from '@/lib/format';
import { cn } from '@/lib/utils';
import { toneClasses } from './tone';
function DeltaBadge({ pct, direction }: { pct: number; direction: 'up' | 'down' | 'neutral' }) {
function DeltaBadge({
pct,
direction,
className,
}: {
pct: number;
direction: 'up' | 'down' | 'neutral';
className: string;
}) {
const { t } = useTranslation();
const value = formatPercent(Math.abs(pct), Number.isInteger(pct) ? 0 : 1);
const label =
@@ -28,23 +37,30 @@ function DeltaBadge({ pct, direction }: { pct: number; direction: 'up' | 'down'
: direction === 'down'
? t('dashboard.deltaDown', 'Down {{value}}', { value })
: t('dashboard.deltaNone', 'No change');
const Icon = direction === 'up' ? ArrowUpRight : direction === 'down' ? ArrowDownRight : Minus;
return (
<Badge variant="secondary" className="text-xs font-normal text-muted-foreground">
<span
className={cn(
'inline-flex h-[22px] items-center gap-1 rounded-full px-2 text-xs font-semibold tabular-nums',
className,
)}
>
<span className="sr-only">{label}</span>
<span aria-hidden="true">
{direction === 'up' ? `\u2191 ${value}` : direction === 'down' ? `\u2193 ${value}` : '\u2013'}
</span>
</Badge>
<Icon aria-hidden="true" className="size-3" />
{direction !== 'neutral' && <span aria-hidden="true">{value}</span>}
</span>
);
}
interface StatCardProps {
card: CardSchema;
card: CardSchema & Placement;
className?: string;
historySamples: Metric[];
historyWindow: { from: Date; to: Date };
}
export function StatCard({ card, historySamples, historyWindow }: StatCardProps) {
export function StatCard({ card, className, historySamples, historyWindow }: StatCardProps) {
const toneClass = toneClasses(card.tone);
const liveSnapshot = useLiveMetricsStore((s) => s.snapshot);
const value = useMemo(() => {
@@ -73,36 +89,55 @@ export function StatCard({ card, historySamples, historyWindow }: StatCardProps)
}, [card, historySamples, from, to]);
return (
<Card role="group" aria-label={card.title}>
<CardContent className="p-4">
<div className="flex items-center gap-2">
<DynamicIcon name={card.icon} fallback={HelpCircle} className="h-4 w-4 text-muted-foreground" />
<span className="text-sm font-medium text-muted-foreground">{card.title}</span>
{card.description && <HelpTooltip content={card.description} label={card.title} icon={Info} />}
</div>
<Card
role="group"
aria-label={card.title}
className={cn('flex min-h-[148px] flex-col gap-2.5 px-5 pb-4 pt-[18px]', toneClass.surface, className)}
>
<div className={cn('flex min-w-0 items-center gap-2.5 text-[13px] font-medium', toneClass.muted)}>
<span className={cn('grid size-9 shrink-0 place-items-center rounded-[11px]', toneClass.badge)}>
<DynamicIcon name={card.icon} fallback={HelpCircle} className="size-[17px]" />
</span>
<span className="min-w-0 truncate">{card.title}</span>
{card.description && <HelpTooltip content={card.description} label={card.title} icon={Info} />}
</div>
<div data-slot="stat-value" className="mt-2 text-2xl font-bold">
{formattedValue}
</div>
<div
data-slot="stat-value"
className="font-display text-[1.75rem] font-bold leading-none tracking-[-0.03em] tabular-nums"
>
{formattedValue}
</div>
{(delta || sparkline) && (
<div className="mt-1 flex items-center gap-2">
{delta && <DeltaBadge pct={delta.pct} direction={delta.direction} />}
{sparkline && (
<LineChart width={64} height={32} data={sparkline}>
<Line
type="monotone"
dataKey="v"
stroke={getChartColor(0)}
strokeWidth={1.5}
dot={false}
isAnimationActive={false}
/>
</LineChart>
)}
</div>
)}
</CardContent>
{(delta || sparkline) && (
<div className="mt-auto flex items-end justify-between gap-3">
{delta && (
<DeltaBadge
pct={delta.pct}
direction={delta.direction}
className={toneClass.sentiment[deltaSentiment(delta.direction, card.polarity)]}
/>
)}
{sparkline && (
<LineChart
className="ml-auto"
width={120}
height={36}
data={sparkline}
margin={{ top: 2, right: 2, bottom: 2, left: 2 }}
>
<Line
type="monotone"
dataKey="v"
stroke={toneClass.accentColor ?? getChartColor(0)}
strokeWidth={2}
dot={false}
isAnimationActive={false}
/>
</LineChart>
)}
</div>
)}
</Card>
);
}
@@ -0,0 +1,34 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: LicenseRef-SEL
*/
import { HelpCircle, Info } from 'lucide-react';
import { DynamicIcon } from '@/components/common/DynamicIcon';
import { HelpTooltip } from '@/components/common/HelpTooltip';
import { cn } from '@/lib/utils';
export function TileHeader({
icon,
title,
description,
badgeClass,
}: {
icon?: string;
title: string;
description?: string;
badgeClass: string;
}) {
return (
<div className="flex min-w-0 items-center gap-2.5">
{icon && (
<span className={cn('grid size-9 shrink-0 place-items-center rounded-[11px]', badgeClass)}>
<DynamicIcon name={icon} fallback={HelpCircle} className="size-[17px]" />
</span>
)}
<h2 className="section-title truncate">{title}</h2>
{description && <HelpTooltip content={description} label={title} icon={Info} />}
</div>
);
}
+72
View File
@@ -0,0 +1,72 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: LicenseRef-SEL
*/
import type { Tone } from '../types/schema';
import type { DeltaSentiment } from '../helpers';
interface ToneClasses {
surface: string;
badge: string;
muted: string;
track: string;
accentColor: string | undefined;
sentiment: Record<DeltaSentiment, string>;
}
const TONES: Record<Tone | 'default', ToneClasses> = {
default: {
surface: '',
badge: 'bg-highlight text-highlight-foreground',
muted: 'text-muted-foreground',
track: 'bg-muted',
accentColor: undefined,
sentiment: {
good: 'bg-success-soft text-success',
bad: 'bg-destructive-soft text-destructive',
neutral: 'bg-muted text-muted-foreground',
},
},
flat: {
surface: 'bg-muted shadow-none',
badge: 'bg-card text-highlight-foreground',
muted: 'text-muted-foreground',
track: 'bg-card',
accentColor: undefined,
sentiment: {
good: 'bg-card text-success',
bad: 'bg-card text-destructive',
neutral: 'bg-card text-muted-foreground',
},
},
accent: {
surface: 'bg-highlight shadow-none',
badge: 'bg-card text-highlight-foreground',
muted: 'text-foreground/70',
track: 'bg-card',
accentColor: undefined,
sentiment: {
good: 'bg-card text-success',
bad: 'bg-card text-destructive',
neutral: 'bg-card text-muted-foreground',
},
},
ink: {
surface: 'bg-ink text-ink-foreground shadow-ink',
badge: 'bg-ink-2 text-ink-accent',
muted: 'text-ink-muted',
track: 'bg-ink-2',
accentColor: 'var(--ink-accent)',
sentiment: {
good: 'bg-ink-success/15 text-ink-success',
bad: 'bg-ink-danger/15 text-ink-danger',
neutral: 'bg-ink-2 text-ink-muted',
},
},
};
export function toneClasses(tone: Tone | undefined): ToneClasses {
return TONES[tone ?? 'default'];
}
+90 -29
View File
@@ -5,7 +5,17 @@
*/
import type { ClusterNodeInfo, Metric, MetricId, Period, PresetKey } from './types/metrics';
import type { Aggregate, Card, Chart, MetricFormat, MetricScope } from './types/schema';
import type {
Aggregate,
Card,
Dashboard,
DashboardItem,
Headline,
MetricFormat,
MetricScope,
Polarity,
Ranking,
} from './types/schema';
import { PRESET_MS, BUCKET_CONFIG, CUSTOM_BUCKET_COUNT, SPARKLINE_BUCKET_COUNT } from './types/metrics';
import { formatCompactNumber, formatDate, formatElapsed, formatPercent, formatSize, formatTime } from '@/lib/format';
@@ -79,9 +89,27 @@ function pushValue(groups: Map<number, number[]>, nodeId: number, value: number)
else groups.set(nodeId, [value]);
}
const samplesByMetric = new WeakMap<Metric[], Map<MetricId, Metric[]>>();
function indexSamples(samples: Metric[]): Map<MetricId, Metric[]> {
let index = samplesByMetric.get(samples);
if (!index) {
index = new Map();
for (const m of samples) {
const list = index.get(m.metric);
if (list) list.push(m);
else index.set(m.metric, [m]);
}
samplesByMetric.set(samples, index);
}
return index;
}
export function selectSamples(target: MetricTarget, samples: Metric[]): Metric[] {
const ids = new Set(target.metrics);
return samples.filter((m) => ids.has(m.metric));
const index = indexSamples(samples);
const unique = new Set(target.metrics);
if (unique.size === 1) return index.get(target.metrics[0]) ?? [];
return [...unique].flatMap((id) => index.get(id) ?? []);
}
export function latestSamples(samples: Metric[]): Metric[] {
@@ -319,33 +347,66 @@ export function formatTimeTick(date: Date, period: Period): string {
return intraday ? formatTime(date) : formatDate(date, TICK_DATE);
}
export function collectHistoryMetricIds(cards: Card[] | undefined, charts: Chart[] | undefined): Set<MetricId> {
const ids = new Set<MetricId>();
if (cards) {
for (const card of cards) {
if (card.source === 'history') {
for (const id of card.metrics) ids.add(id);
}
}
}
if (charts) {
for (const chart of charts) {
for (const series of chart.series) {
for (const id of series.metrics) ids.add(id);
}
}
}
return ids;
export function dashboardItems(dashboard: Dashboard): DashboardItem[] {
if (dashboard.items && dashboard.items.length > 0) return dashboard.items;
const charts = dashboard.charts ?? [];
return [
...(dashboard.cards ?? []).map((card): DashboardItem => ({ type: 'stat', ...card })),
...charts.map((chart, i): DashboardItem => ({
type: 'chart',
...chart,
...(charts.length % 2 === 1 && i === charts.length - 1 && { span: 12 }),
})),
];
}
export function collectLiveMetricIds(cards: Card[] | undefined): Set<MetricId> {
const ids = new Set<MetricId>();
if (cards) {
for (const card of cards) {
if (card.source === 'live') {
for (const id of card.metrics) ids.add(id);
}
}
function itemHistoryMetrics(item: DashboardItem): MetricId[] {
switch (item.type) {
case 'stat':
return item.source === 'history' ? item.metrics : [];
case 'chart':
case 'ranking':
return item.series.flatMap((series) => series.metrics);
case 'headline':
return [...item.numerator, ...item.denominator];
}
return ids;
}
export function collectHistoryMetricIds(items: readonly DashboardItem[]): Set<MetricId> {
return new Set(items.flatMap(itemHistoryMetrics));
}
export function collectLiveMetricIds(items: readonly DashboardItem[]): Set<MetricId> {
return new Set(items.flatMap((item) => (item.type === 'stat' && item.source === 'live' ? item.metrics : [])));
}
export function headlineRatio(headline: Headline, samples: Metric[]): number | null {
const reduce = (metrics: MetricId[]) => {
const target = { metrics, aggregate: headline.aggregate, scope: headline.scope };
return reduceSamples(target, selectSamples(target, samples)) ?? 0;
};
const denominator = reduce(headline.denominator);
if (denominator <= 0) return null;
return reduce(headline.numerator) / denominator;
}
interface RankingEntry {
label: string;
value: number;
}
export function rankingEntries(ranking: Ranking, samples: Metric[]): RankingEntry[] {
return ranking.series
.map((series) => ({ label: series.label, value: reduceSamples(series, selectSamples(series, samples)) ?? 0 }))
.sort((a, b) => b.value - a.value);
}
export type DeltaSentiment = 'good' | 'bad' | 'neutral';
export function deltaSentiment(
direction: 'up' | 'down' | 'neutral',
polarity: Polarity = 'higherIsBetter',
): DeltaSentiment {
if (direction === 'neutral' || polarity === 'neutral') return 'neutral';
return (direction === 'up') === (polarity === 'higherIsBetter') ? 'good' : 'bad';
}
+37
View File
@@ -9,6 +9,41 @@ export type Dashboard = {
label: string;
cards?: Card[];
charts?: Chart[];
items?: DashboardItem[];
};
export type Tone = 'flat' | 'accent' | 'ink';
export type Placement = {
span?: number;
rows?: number;
tone?: Tone;
};
export type DashboardItem = Placement &
(
| ({ type: 'stat' } & Card)
| ({ type: 'chart' } & Chart)
| ({ type: 'headline' } & Headline)
| ({ type: 'ranking' } & Ranking)
);
export type Headline = {
title: string;
icon?: string;
numerator: string[];
denominator: string[];
aggregate?: Aggregate;
scope?: MetricScope;
description?: string;
};
export type Ranking = {
title: string;
icon?: string;
series: Series[];
valueFormat?: MetricFormat;
description?: string;
};
export type Card = {
@@ -22,6 +57,7 @@ export type Card = {
description?: string;
sparkline?: boolean;
delta?: boolean;
polarity?: Polarity;
};
export type Chart = {
@@ -41,6 +77,7 @@ export type Series = {
};
export type Aggregate = 'sum' | 'avg' | 'last';
export type Polarity = 'higherIsBetter' | 'lowerIsBetter' | 'neutral';
export type MetricScope = 'node' | 'cluster';
export type ChartKind = 'line' | 'area' | 'bar';
export type CardSource = 'live' | 'history';
@@ -39,14 +39,16 @@ export function LiveTracingForm({
const [addingFilter, setAddingFilter] = useState(false);
return (
<div className="mx-auto max-w-2xl space-y-6 pt-8">
<div>
<h1 className="text-2xl font-bold">{t('tracing.liveTitle', 'Live Tracing')}</h1>
<p className="mt-2 text-muted-foreground">{t('tracing.liveSubtitle', 'Stream server events in real time.')}</p>
<div className="mx-auto max-w-2xl space-y-3.5 pt-6">
<div className="space-y-1 px-1 pb-1 pt-3">
<h1 className="page-title">{t('tracing.liveTitle', 'Live Tracing')}</h1>
<p className="text-sm text-muted-foreground">
{t('tracing.liveSubtitle', 'Stream server events in real time.')}
</p>
</div>
<Card>
<CardContent className="space-y-4 p-4">
<CardContent className="space-y-4 p-5">
<div className="space-y-2">
<Label htmlFor={keywordsId}>{t('tracing.keywordsLabel', 'Keywords (optional)')}</Label>
<Input
@@ -64,12 +66,12 @@ export function LiveTracingForm({
<ul className="flex flex-wrap gap-2" aria-label={t('tracing.activeFilters', 'Active filters')}>
{filters.map((f) => (
<li key={f.key}>
<Badge variant="secondary" className="gap-1">
<Badge className="h-7 gap-1 pl-3 pr-1.5 text-[12.5px] font-medium">
{f.label} = {f.value}
<button
type="button"
onClick={() => onFiltersChange(filters.filter((other) => other.key !== f.key))}
className="ml-1 rounded-sm hover:text-destructive focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
className="ml-0.5 grid size-5 place-items-center rounded-full hover:bg-card hover:text-destructive focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
aria-label={t('tracing.removeFilter', 'Remove filter {{label}}', { label: f.label })}
>
<X aria-hidden="true" className="h-3 w-3" />
@@ -90,17 +92,13 @@ export function LiveTracingForm({
/>
) : (
<Button variant="outline" size="sm" onClick={() => setAddingFilter(true)}>
<Plus aria-hidden="true" className="mr-2 h-4 w-4" />
<Plus aria-hidden="true" />
{t('tracing.addFilter', 'Add filter')}
</Button>
)}
<Button className="w-full" onClick={onStart} disabled={starting}>
{starting ? (
<Loader2 aria-hidden="true" className="mr-2 h-4 w-4 animate-spin" />
) : (
<Play aria-hidden="true" className="mr-2 h-4 w-4" />
)}
{starting ? <Loader2 aria-hidden="true" className="animate-spin" /> : <Play aria-hidden="true" />}
{starting ? t('tracing.connecting', 'Connecting...') : t('tracing.startTracing', 'Start tracing')}
</Button>
</CardContent>
@@ -124,7 +122,7 @@ function FilterEditor({ onAdd, onCancel }: { onAdd: (filter: KeyValueFilter) =>
};
return (
<div className="flex items-center gap-2">
<div className="flex items-center gap-2 rounded-xl bg-muted p-2">
<Select value={key} onValueChange={setKey}>
<SelectTrigger className="w-48" aria-label={t('tracing.filterKey', 'Filter key')}>
<SelectValue placeholder={t('field.selectKey', 'Select key...')} />
@@ -24,20 +24,30 @@ function StreamIndicator({ status }: { status: StreamStatus }) {
const { t } = useTranslation();
if (status.kind === 'open') {
return (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<span aria-hidden="true" className="relative flex h-2 w-2">
<span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-400 opacity-75" />
<span className="relative inline-flex h-2 w-2 rounded-full bg-emerald-500" />
<span className="inline-flex h-6 items-center gap-1.5 rounded-full bg-success-soft px-2.5 text-xs font-semibold text-success">
<span aria-hidden="true" className="relative flex size-1.5">
<span className="absolute inline-flex size-full animate-ping rounded-full bg-current opacity-75" />
<span className="relative inline-flex size-1.5 rounded-full bg-current" />
</span>
{t('tracing.streamingEvents', 'Streaming events...')}
</div>
</span>
);
}
if (status.kind === 'reconnecting' || status.kind === 'connecting') {
return <span className="text-sm text-muted-foreground">{t('tracing.reconnecting', 'Reconnecting...')}</span>;
return (
<span className="inline-flex h-6 items-center gap-1.5 rounded-full bg-warning-soft px-2.5 text-xs font-semibold text-warning">
<span aria-hidden="true" className="size-1.5 animate-pulse rounded-full bg-current" />
{t('tracing.reconnecting', 'Reconnecting...')}
</span>
);
}
if (status.kind === 'closed') {
return <span className="text-sm text-muted-foreground">{t('tracing.stopped', 'Stopped')}</span>;
return (
<span className="inline-flex h-6 items-center gap-1.5 rounded-full bg-muted px-2.5 text-xs font-semibold text-muted-foreground">
<span aria-hidden="true" className="size-1.5 rounded-full bg-current" />
{t('tracing.stopped', 'Stopped')}
</span>
);
}
return null;
}
@@ -48,38 +58,35 @@ export function LiveTracingSession({ status, buffer, error, onStop, onRestart }:
const count = buffer.events.length;
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<h1 className="text-lg font-semibold">{t('tracing.liveTitle', 'Live Tracing')}</h1>
<div className="space-y-3.5">
<div className="flex flex-wrap items-end justify-between gap-4 px-1 pb-1 pt-3">
<div className="flex flex-wrap items-center gap-3">
<h1 className="page-title">{t('tracing.liveTitle', 'Live Tracing')}</h1>
<div role="status">
<StreamIndicator status={status} />
</div>
</div>
{active ? (
<Button variant="outline" onClick={onStop}>
<Square aria-hidden="true" className="mr-2 h-4 w-4" />
<Square aria-hidden="true" />
{t('tracing.stopTracing', 'Stop tracing')}
</Button>
) : (
<Button variant="outline" onClick={onRestart}>
<RotateCcw aria-hidden="true" className="mr-2 h-4 w-4" />
<RotateCcw aria-hidden="true" />
{t('tracing.restart', 'Restart')}
</Button>
)}
</div>
{error && (
<div
role="alert"
className="rounded-lg border border-destructive/50 bg-destructive/10 p-3 text-sm text-destructive"
>
<div role="alert" className="rounded-xl bg-destructive-soft p-4 text-sm text-destructive">
{error}
</div>
)}
<Card>
<CardContent className="p-4">
<CardContent className="p-5">
<TraceTimeline
events={buffer.events}
anchorTimestamp={buffer.anchorTimestamp ?? undefined}
@@ -88,7 +95,7 @@ export function LiveTracingSession({ status, buffer, error, onStop, onRestart }:
</CardContent>
</Card>
<p className="text-center text-xs text-muted-foreground">
<p className="text-center text-xs text-dim">
{t('tracing.eventCount', '{{count}} events', { count })}
{count >= MAX_LIVE_EVENTS && ' ' + t('tracing.bufferFull', '(buffer full)')}
</p>
@@ -33,7 +33,7 @@ export function TraceDetailView({ viewName, objectId }: TraceDetailViewProps) {
const backButton = (
<Button variant="outline" size="sm" onClick={() => navigate(-1)}>
<ArrowLeft aria-hidden="true" className="mr-2 h-4 w-4" />
<ArrowLeft aria-hidden="true" />
{t('common.back', 'Back')}
</Button>
);
@@ -60,9 +60,9 @@ export function TraceDetailView({ viewName, objectId }: TraceDetailViewProps) {
if (error) {
return (
<div className="space-y-4">
<div className="space-y-3.5 pt-3">
{backButton}
<div role="alert" className="p-4 text-destructive">
<div role="alert" className="rounded-xl bg-destructive-soft p-4 text-sm text-destructive">
{error}
</div>
</div>
@@ -72,11 +72,11 @@ export function TraceDetailView({ viewName, objectId }: TraceDetailViewProps) {
if (!events) return null;
return (
<div className="space-y-6">
<div className="space-y-3.5 pt-3">
{backButton}
<TraceSummaryCards events={events} />
<Card>
<CardContent className="p-4">
<CardContent className="p-5">
<TraceTimeline events={events} anchorTimestamp={events[0]?.timestamp} />
</CardContent>
</Card>
@@ -7,7 +7,7 @@
import type { ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { Activity, Clock, FileText, Timer, type LucideIcon } from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { Card } from '@/components/ui/card';
import { formatDateTime, formatElapsed, formatNumber } from '@/lib/format';
import { traceDurationMs } from '../format';
import { useTraceLabels } from '../hooks/useTraceLabels';
@@ -15,14 +15,14 @@ import type { TraceEvent } from '../types';
function SummaryCard({ icon: Icon, label, children }: { icon: LucideIcon; label: string; children: ReactNode }) {
return (
<Card>
<CardContent className="p-4">
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Icon aria-hidden="true" className="h-4 w-4" />
{label}
</div>
<p className="mt-1 truncate text-lg font-semibold">{children}</p>
</CardContent>
<Card className="flex min-w-0 items-center gap-3 px-5 py-4">
<span className="grid size-9 shrink-0 place-items-center rounded-[11px] bg-highlight text-highlight-foreground">
<Icon aria-hidden="true" className="size-[17px]" />
</span>
<div className="min-w-0">
<div className="text-[13px] font-medium text-muted-foreground">{label}</div>
<p className="truncate font-display text-lg font-bold tracking-[-0.012em]">{children}</p>
</div>
</Card>
);
}
@@ -35,7 +35,7 @@ export function TraceSummaryCards({ events }: { events: TraceEvent[] }) {
const durationMs = first && last && events.length >= 2 ? traceDurationMs(first.timestamp, last.timestamp) : null;
return (
<div className="grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] gap-4">
<div className="grid grid-cols-[repeat(auto-fit,minmax(200px,1fr))] gap-3.5">
<SummaryCard icon={FileText} label={t('tracing.spanType', 'Span Type')}>
{first ? labels.event(first.event).label : '-'}
</SummaryCard>
@@ -39,7 +39,7 @@ export function TraceTimeline({ events, anchorTimestamp, keyOffset = 0 }: TraceT
if (events.length === 0) {
return (
<div className="flex items-center justify-center p-8 text-muted-foreground">
<div className="rounded-xl bg-muted p-10 text-center text-muted-foreground">
{t('tracing.noEvents', 'No trace events to display.')}
</div>
);
@@ -50,7 +50,7 @@ export function TraceTimeline({ events, anchorTimestamp, keyOffset = 0 }: TraceT
return (
<div className="relative">
<div ref={containerRef} onScroll={handleScroll} className="max-h-[70vh] overflow-y-auto scroll-smooth">
<ol className="space-y-4 p-2">
<ol className="space-y-1 pb-6">
{events.map((event, idx) => (
<TraceEventItem key={keyOffset + idx} event={event} anchorMs={anchorMs} />
))}
@@ -64,11 +64,23 @@ export function TraceTimeline({ events, anchorTimestamp, keyOffset = 0 }: TraceT
function TraceEventIcon({ eventType }: { eventType: string }) {
switch (traceEventKind(eventType)) {
case 'error':
return <CircleX aria-hidden="true" className="h-4 w-4 text-red-500" />;
return (
<span className="grid size-7 place-items-center rounded-full bg-destructive-soft text-destructive">
<CircleX aria-hidden="true" className="size-3.5" />
</span>
);
case 'span':
return <Clock aria-hidden="true" className="h-4 w-4 text-muted-foreground" />;
return (
<span className="grid size-7 place-items-center rounded-full bg-highlight text-highlight-foreground">
<Clock aria-hidden="true" className="size-3.5" />
</span>
);
default:
return <CircleDot aria-hidden="true" className="h-4 w-4 text-muted-foreground" />;
return (
<span className="grid size-7 place-items-center rounded-full bg-muted text-muted-foreground">
<CircleDot aria-hidden="true" className="size-3.5" />
</span>
);
}
}
@@ -78,29 +90,29 @@ function TraceEventItem({ event, anchorMs }: { event: TraceEvent; anchorMs: numb
const offset = new Date(event.timestamp).getTime() - anchorMs;
return (
<li className="flex gap-3">
<div className="mt-1 shrink-0">
<li className="flex gap-3 rounded-xl px-2 py-2.5">
<div className="shrink-0">
<TraceEventIcon eventType={event.event} />
</div>
<div className="min-w-0 flex-1">
<div className="flex items-start justify-between gap-2">
<div>
<div className="flex min-h-7 items-start justify-between gap-2">
<div className="min-w-0 pt-1">
{known ? (
<span className="text-sm font-semibold">{label}</span>
) : (
<span className="rounded bg-muted px-1.5 py-0.5 font-mono text-sm">{label}</span>
<span className="rounded-md bg-muted px-1.5 py-0.5 font-mono text-[13px]">{label}</span>
)}
{explanation && <p className="mt-0.5 text-xs text-muted-foreground">{explanation}</p>}
</div>
<div className="shrink-0 text-right text-xs">
<div className="shrink-0 pt-1 text-right text-xs tabular-nums">
<time dateTime={event.timestamp} className="block text-muted-foreground">
{formatTime(event.timestamp, { milliseconds: true })}
</time>
<div className="text-muted-foreground/60">(+{formatElapsed(offset)})</div>
<div className="text-dim">(+{formatElapsed(offset)})</div>
</div>
</div>
{event.keyValues.length > 0 && (
<div className="mt-2 space-y-1">
<div className="mt-2 space-y-1 rounded-xl bg-muted p-3">
<TraceKeyValueList keyValues={event.keyValues} />
</div>
)}
+11 -6
View File
@@ -23,8 +23,10 @@ function TraceKeyValueRow({ kv, depth }: { kv: TraceKeyValue; depth: number }) {
const labels = useTraceLabels();
return (
<div className="flex gap-2 text-sm" style={{ paddingInlineStart: depth * 16 }}>
<span className="min-w-24 shrink-0 pt-0.5 text-right text-xs text-muted-foreground">{labels.key(kv.key)}</span>
<span className="pt-0.5 text-xs">
<span className="min-w-24 shrink-0 pt-0.5 text-right text-xs font-medium text-muted-foreground">
{labels.key(kv.key)}
</span>
<span className="min-w-0 break-words pt-0.5 text-xs">
<TraceValueDisplay keyName={kv.key} value={kv.value} depth={depth} />
</span>
</div>
@@ -36,7 +38,10 @@ function IdValue({ keyName, raw }: { keyName: string; raw: number | string }) {
const encoded = intToBase32(raw);
if (keyName === 'queueId') {
return (
<Link to={`/${section}/x:QueuedMessage/${encoded}`} className="text-primary underline hover:no-underline">
<Link
to={`/${section}/x:QueuedMessage/${encoded}`}
className="font-mono text-brand-text underline underline-offset-2 hover:no-underline"
>
{encoded}
</Link>
);
@@ -48,14 +53,14 @@ function NestedEvent({ event, value, depth }: { event: string; value: TraceKeyVa
const labels = useTraceLabels();
if (depth >= MAX_EVENT_DEPTH) {
return (
<pre className="whitespace-pre-wrap rounded bg-muted/30 p-2 text-xs">
<pre className="whitespace-pre-wrap rounded-lg bg-muted-strong p-2.5 font-mono text-xs">
{JSON.stringify({ event, values: value }, null, 2)}
</pre>
);
}
const { label, explanation } = labels.event(event);
return (
<div className="mt-1 space-y-1 border-l-2 border-muted pl-3">
<div className="mt-1 space-y-1 border-l-2 border-input pl-3">
<div className="text-xs font-semibold">{label}</div>
{explanation && <div className="text-xs text-muted-foreground">{explanation}</div>}
<TraceKeyValueList keyValues={value} depth={depth + 1} />
@@ -109,7 +114,7 @@ function TraceValueDisplay({ keyName, value, depth }: { keyName: string; value:
case 'Event':
return <NestedEvent event={value.event} value={value.value} depth={depth} />;
case 'Null':
return <span className="text-muted-foreground">&mdash;</span>;
return <span className="text-dim">&mdash;</span>;
default:
return <>{JSON.stringify(value)}</>;
}
@@ -36,10 +36,10 @@ export function DeliveryTraceForm({ target, onTargetChange, starting, onStart }:
};
return (
<div className="mx-auto max-w-2xl space-y-6 pt-8">
<div>
<h1 className="text-2xl font-bold">{t('deliveryTrace.title', 'Delivery Trace')}</h1>
<p className="mt-2 text-muted-foreground">
<div className="mx-auto max-w-2xl space-y-3.5 pt-6">
<div className="space-y-1 px-1 pb-1 pt-3">
<h1 className="page-title">{t('deliveryTrace.title', 'Delivery Trace')}</h1>
<p className="text-sm text-muted-foreground">
{t(
'deliveryTrace.subtitle',
'Run a real outbound SMTP delivery attempt and watch every DNS lookup, TLS handshake, and SMTP command as it happens.',
@@ -47,7 +47,7 @@ export function DeliveryTraceForm({ target, onTargetChange, starting, onStart }:
</p>
</div>
<Card>
<CardContent className="space-y-4 p-4">
<CardContent className="space-y-4 p-5">
<form
className="space-y-2"
onSubmit={(e) => {
@@ -71,12 +71,8 @@ export function DeliveryTraceForm({ target, onTargetChange, starting, onStart }:
className="flex-1"
/>
<Button type="submit" disabled={starting}>
{starting ? (
<Loader2 aria-hidden="true" className="h-4 w-4 animate-spin" />
) : (
<Play aria-hidden="true" className="h-4 w-4" />
)}
<span className="ml-2">{t('deliveryTrace.startTrace', 'Start trace')}</span>
{starting ? <Loader2 aria-hidden="true" className="animate-spin" /> : <Play aria-hidden="true" />}
<span>{t('deliveryTrace.startTrace', 'Start trace')}</span>
</Button>
</div>
{invalid && (
@@ -28,10 +28,7 @@ function Banner({ destructive, children }: { destructive?: boolean; children: Re
return (
<div
role={destructive ? 'alert' : 'status'}
className={cn(
'rounded-lg border p-4',
destructive ? 'border-destructive/50 bg-destructive/10 text-destructive' : 'border-border bg-card',
)}
className={cn(destructive ? 'rounded-xl bg-destructive-soft p-4 text-destructive' : 'tile px-5 py-4')}
>
{children}
</div>
@@ -65,13 +62,18 @@ function CompletionSummary({ run }: { run: DeliveryRun }) {
const { attempts, delivered } = summarizeDelivery(run.stages);
return (
<Banner>
<div className="flex items-center gap-2">
{delivered ? (
<CircleCheck aria-hidden="true" className="h-4 w-4 text-emerald-500" />
) : (
<CircleX aria-hidden="true" className="h-4 w-4 text-red-500" />
)}
<span className="text-sm font-medium">
<div className="flex flex-wrap items-center gap-2.5">
<span
className={cn(
'inline-flex h-6 items-center gap-1.5 rounded-full px-2.5 text-xs font-semibold',
delivered ? 'bg-success-soft text-success' : 'bg-destructive-soft text-destructive',
)}
>
{delivered ? (
<CircleCheck aria-hidden="true" className="size-3.5" />
) : (
<CircleX aria-hidden="true" className="size-3.5" />
)}
{delivered
? t('deliveryTrace.deliverySuccessful', 'Delivery successful')
: t('deliveryTrace.deliveryFailed', 'Delivery failed')}
@@ -92,11 +94,11 @@ function CompletionSummary({ run }: { run: DeliveryRun }) {
function WaitingIndicator() {
const { t } = useTranslation();
return (
<div className="mt-4 flex items-center gap-2 text-sm text-muted-foreground">
<div className="mt-3 flex items-center gap-2.5 rounded-xl bg-muted px-3.5 py-2.5 text-sm text-muted-foreground">
<div aria-hidden="true" className="flex gap-1">
<span className="animate-pulse">.</span>
<span className="animate-pulse [animation-delay:0.2s]">.</span>
<span className="animate-pulse [animation-delay:0.4s]">.</span>
<span className="size-1.5 animate-pulse rounded-full bg-current" />
<span className="size-1.5 animate-pulse rounded-full bg-current [animation-delay:0.2s]" />
<span className="size-1.5 animate-pulse rounded-full bg-current [animation-delay:0.4s]" />
</div>
{t('deliveryTrace.waiting', 'Waiting for more events')}
</div>
@@ -109,10 +111,10 @@ export function DeliveryTraceResult({ run, phase, onCancel, onReset }: DeliveryT
const target = run.target;
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<div>
<h1 className="text-lg font-semibold">
<div className="space-y-3.5">
<div className="flex flex-wrap items-end justify-between gap-4 px-1 pb-1 pt-3">
<div className="min-w-0 space-y-1">
<h1 className="page-title break-words">
{phase.kind === 'running'
? t('deliveryTrace.tracingDelivery', 'Tracing delivery to {{target}}', { target })
: phase.kind === 'completed'
@@ -123,7 +125,7 @@ export function DeliveryTraceResult({ run, phase, onCancel, onReset }: DeliveryT
</div>
{phase.kind === 'running' ? (
<Button variant="outline" onClick={onCancel}>
<StopCircle aria-hidden="true" className="mr-2 h-4 w-4" />
<StopCircle aria-hidden="true" />
{t('deliveryTrace.cancelTrace', 'Cancel trace')}
</Button>
) : (
@@ -141,16 +143,16 @@ export function DeliveryTraceResult({ run, phase, onCancel, onReset }: DeliveryT
)}
<Card>
<CardContent className="p-4">
<CardContent className="p-5">
<div aria-live="polite">
{groups.map((group) => (
<div key={group.key}>
{group.attempt && (
<div className="mb-1 mt-3">
<div className="mb-1 mt-3 first:mt-0">
<StageRow stage={group.attempt.stage} />
</div>
)}
<div className={group.attempt ? 'ml-6 border-l-2 border-muted/40 pl-4' : undefined}>
<div className={group.attempt ? 'ml-3 border-l-2 border-input pl-5' : undefined}>
{group.stages.map((item) => (
<StageRow key={item.key} stage={item.stage} />
))}
@@ -13,36 +13,44 @@ import { formatElapsed } from '@/lib/format';
import { phaseLabel, stageBody } from '../stageText';
import { stageSeverity, type DeliveryStage, type MX, type ReportUri, type StageSeverity } from '../types';
const SEVERITY_BADGE: Record<StageSeverity, string> = {
pending: 'bg-info-soft text-info',
ok: 'bg-success-soft text-success',
warn: 'bg-warning-soft text-warning',
error: 'bg-destructive-soft text-destructive',
};
function SeverityIcon({ severity }: { severity: StageSeverity }) {
const { t } = useTranslation();
const badge = cn('grid size-6 place-items-center rounded-full', SEVERITY_BADGE[severity]);
switch (severity) {
case 'pending':
return (
<Loader2
role="img"
aria-label={t('deliveryTrace.severity.pending', 'In progress')}
className="h-4 w-4 animate-spin text-muted-foreground"
/>
<span className={badge}>
<Loader2
role="img"
aria-label={t('deliveryTrace.severity.pending', 'In progress')}
className="size-3.5 animate-spin"
/>
</span>
);
case 'ok':
return (
<CircleCheck
role="img"
aria-label={t('deliveryTrace.severity.ok', 'Succeeded')}
className="h-4 w-4 text-emerald-500"
/>
<span className={badge}>
<CircleCheck role="img" aria-label={t('deliveryTrace.severity.ok', 'Succeeded')} className="size-3.5" />
</span>
);
case 'warn':
return (
<TriangleAlert
role="img"
aria-label={t('deliveryTrace.severity.warn', 'Warning')}
className="h-4 w-4 text-amber-500"
/>
<span className={badge}>
<TriangleAlert role="img" aria-label={t('deliveryTrace.severity.warn', 'Warning')} className="size-3.5" />
</span>
);
case 'error':
return (
<CircleX role="img" aria-label={t('deliveryTrace.severity.error', 'Failed')} className="h-4 w-4 text-red-500" />
<span className={badge}>
<CircleX role="img" aria-label={t('deliveryTrace.severity.error', 'Failed')} className="size-3.5" />
</span>
);
}
}
@@ -52,11 +60,11 @@ function MxTable({ mxs }: { mxs: MX[] }) {
.sort((a, b) => a.preference - b.preference)
.flatMap((mx) => mx.exchanges.map((exchange) => ({ preference: mx.preference, exchange })));
return (
<div className="mt-1 rounded border text-xs">
<div className="mt-1.5 divide-y divide-border rounded-xl bg-muted px-1 py-0.5 text-xs">
{rows.map(({ preference, exchange }) => (
<div key={`${preference}-${exchange}`} className="flex gap-3 border-b px-3 py-1 last:border-b-0">
<span className="w-8 text-right text-muted-foreground">{preference}</span>
<span>{exchange}</span>
<div key={`${preference}-${exchange}`} className="flex gap-3 px-3 py-1.5">
<span className="w-8 text-right tabular-nums text-muted-foreground">{preference}</span>
<span className="font-mono">{exchange}</span>
</div>
))}
</div>
@@ -65,14 +73,14 @@ function MxTable({ mxs }: { mxs: MX[] }) {
function ReportUris({ rua }: { rua: ReportUri[] }) {
return (
<ul className="mt-1 space-y-1">
<ul className="mt-1.5 space-y-1 rounded-xl bg-muted p-3">
{rua.map((uri) => {
const value = uri.type === 'mail' ? uri.email : uri.url;
const Icon = uri.type === 'mail' ? Mail : Globe;
return (
<li key={`${uri.type}:${value}`} className="flex items-center gap-2 text-xs">
<Icon aria-hidden="true" className="h-3 w-3 text-muted-foreground" />
<span>{value}</span>
<Icon aria-hidden="true" className="size-3 text-muted-foreground" />
<span className="break-all font-mono">{value}</span>
</li>
);
})}
@@ -82,14 +90,14 @@ function ReportUris({ rua }: { rua: ReportUri[] }) {
function OpaqueObject({ data }: { data: Record<string, unknown> }) {
return (
<div className="mt-1 rounded border bg-muted/30 p-2">
<div className="mt-1.5 rounded-xl bg-muted p-3">
<dl className="space-y-1 text-xs">
{Object.entries(data).map(([k, v]) => (
<div key={k} className="flex gap-2">
<dt className="min-w-24 font-medium text-muted-foreground">{k}</dt>
<dd className="break-all">
{typeof v === 'object' && v !== null ? (
<pre className="whitespace-pre-wrap text-xs">{JSON.stringify(v, null, 2)}</pre>
<pre className="whitespace-pre-wrap font-mono text-xs">{JSON.stringify(v, null, 2)}</pre>
) : (
String(v)
)}
@@ -133,20 +141,20 @@ export function StageRow({ stage }: { stage: DeliveryStage }) {
const content = (
<div className="flex items-start gap-3 py-2">
<div className="mt-0.5 shrink-0">
<div className="shrink-0">
<SeverityIcon severity={severity} />
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<div className="flex min-h-6 flex-wrap items-center gap-2">
<span className="text-sm font-medium">{phaseLabel(t, stage)}</span>
{elapsed !== null && (
<Badge variant="secondary" className="text-xs">
<Badge variant="secondary" className="text-xs tabular-nums">
{formatElapsed(elapsed)}
</Badge>
)}
</div>
{body && (
<p className={cn('mt-0.5 text-xs', severity === 'error' ? 'text-red-500' : 'text-muted-foreground')}>
<p className={cn('mt-0.5 text-xs', severity === 'error' ? 'text-destructive' : 'text-muted-foreground')}>
{body}
</p>
)}
@@ -162,13 +170,13 @@ export function StageRow({ stage }: { stage: DeliveryStage }) {
<CollapsibleTrigger asChild>
<button
type="button"
className="group ml-7 flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
className="group ml-9 flex items-center gap-1 rounded-full text-xs font-medium text-brand-text hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<ChevronRight aria-hidden="true" className="h-3 w-3 transition-transform group-data-[state=open]:rotate-90" />
<ChevronRight aria-hidden="true" className="size-3 transition-transform group-data-[state=open]:rotate-90" />
{t('deliveryTrace.viewDetails', 'View details')}
</button>
</CollapsibleTrigger>
<CollapsibleContent className="ml-7">
<CollapsibleContent className="ml-9">
<StageDetails stage={stage} />
</CollapsibleContent>
</Collapsible>
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff. Show more