init commit

This commit is contained in:
2026-11-14 08:49:19 +01:00
parent d16a94324b
commit f94d10e8e9
75 changed files with 5662 additions and 3731 deletions
+54 -17
View File
@@ -1,6 +1,6 @@
# @collabry/components # @collabry/components
React + Tailwind CSS component library for the Collabry UI, built on [shadcn/ui](https://ui.shadcn.com) (Radix UI, cmdk, Sonner), with a Storybook catalogue. React 19 + Tailwind CSS component library for the Collabry UI, built on [shadcn/ui](https://ui.shadcn.com) (Radix UI, cmdk, Sonner), with a Storybook catalogue.
```sh ```sh
npm install npm install
@@ -25,32 +25,69 @@ import '@fontsource/lato/900.css';
</ThemeProvider>; </ThemeProvider>;
``` ```
`react`, `react-dom` are peer dependencies; `radix-ui`, `cmdk`, `sonner`, `class-variance-authority`, `lucide-react`, `clsx` and `tailwind-merge` are installed with the package. `react` and `react-dom` (19) are peer dependencies; `radix-ui`, `cmdk`, `sonner`, `class-variance-authority`, `lucide-react`, `clsx` and `tailwind-merge` come with the package.
Dialogs, menus and popovers portal into the nearest `ThemeProvider` element, so they keep its theme, accent and tint. Dialogs, menus and popovers portal into the nearest `ThemeProvider` element, so they keep its theme, accent and tint.
## Composition
Components are small parts you assemble, like shadcn/ui. They don't take data objects or config props; each part renders one element, takes `className` and `ref`, and has a `data-slot` (`card-title`, `nav-item`, …) to target it from outside. Parts that are often links or headings accept `asChild`. The design (spacing, colors, states) lives in the parts; structure and data live in your code.
```tsx
<CardFrame>
<Card asChild>
<section aria-labelledby="h-tasks">
<CardHeader>
<CardTitle id="h-tasks">
Meine Aufgaben <CountBadge>6</CountBadge>
</CardTitle>
<CardAction>…</CardAction>
</CardHeader>
<TaskTable aria-label="Meine Aufgaben">
<TaskRow done={task.status === 'done'}>
<TaskCell>
<TaskCheckbox checked={…} onCheckedChange={…} aria-label="…" />
</TaskCell>
<TaskCell>
<TaskTitle>{task.title}</TaskTitle>
<TaskMeta>…</TaskMeta>
</TaskCell>
…
</TaskRow>
</TaskTable>
</section>
</Card>
</CardFrame>
```
Conventions:
- State flows down through context where it's shared: `Field` wires label, control and messages (`id`, `aria-describedby`, `aria-invalid`); `Sidebar` tells its parts whether it's collapsed; `TaskTable` sets the column grid of its rows.
- Overlays use the Radix pattern: `Dialog` + `DialogTrigger` + `DialogContent`, `Menu` + `MenuTrigger` + `MenuContent`, `Popover` + `PopoverTrigger` + `PopoverContent`. Controlled (`open` / `onOpenChange`) or not.
- Text the user sees is German by default (labels like "Schließen"); pass your own children or `aria-label` to change it.
- The stories are the reference compositions; `src/stories/examples.tsx` holds the bigger ones (notification panel, account menu).
## Structure ## Structure
- `src/styles/tokens.css`: design tokens (`--cl-*`) for dark and light, with accent and tint derived via `color-mix` - `src/styles/tokens.css`: design tokens (`--cl-*`) for dark and light, with accent and tint derived via `color-mix`
- `src/styles/index.css`: Tailwind v4 theme mapping tokens to utilities (`bg-surface`, `text-fg-muted`, `border-line`, …) - `src/styles/index.css`: Tailwind v4 theme mapping tokens to utilities (`bg-surface`, `text-fg-muted`, `border-line`, …) and to shadcn's token names
- `src/components/ui/`: shadcn/ui primitives (`components.json`), restyled to the Collabry tokens. Accessibility, focus and keyboard handling come from Radix / cmdk. - `src/components/ui/`: shadcn/ui primitives (`components.json`), restyled to the Collabry tokens
- `src/components/<Name>/<Name>.tsx` + `<Name>.stories.tsx`: Collabry components composed from `ui/` - `src/components/<Name>/<Name>.tsx` + `<Name>.stories.tsx`: Collabry parts built from `ui/`
- `src/stories/`: introduction, token overview and sample data from the design
## Components ## Components
| Area | Components | | Area | Parts |
| --- | --- | | --- | --- |
| Grundlagen | `ThemeProvider`, `Button`, `ButtonLink`, `Card`, `CardHeader`, `CardFooter`, `PageHeader`, `EmptyState`, `Spinner`, `Logo` | | Foundations | `ThemeProvider`, `Button`, `CardFrame`, `Card`, `CardHeader`, `CardHeading`, `CardTitle`, `CardDescription`, `CardAction`, `CardFooter`, `PageHeader`, `PageHeading`, `PageEyebrow`, `PageTitle`, `PageDescription`, `PageActions`, `Empty*`, `SectionLabel`, `MetaSeparator`, `Spinner`, `Logo` |
| Formulare | `Field`, `Input`, `PasswordInput`, `Textarea`, `Select`, `Checkbox`, `TaskCheckbox`, `SegmentedControl` | | Forms | `Field`, `FieldHeader`, `FieldLabel`, `FieldNote`, `FieldDescription`, `FieldError`, `Input`, `InputGroup`, `InputGroupAddon`, `InputGroupButton`, `PasswordInput`, `Textarea`, `Select`, `SelectOption`, `Checkbox`, `TaskCheckbox`, `SegmentedControl`, `SegmentedControlItem`, `SegmentedControlCount` |
| Anzeige | `StatusBadge`, `CountBadge`, `RoleBadge`, `Swatch`, `Kbd`, `Avatar`, `AvatarStack`, `ProgressBar`, `StatusProgress` | | Display | `StatusBadge`, `CountBadge`, `RoleBadge`, `Swatch`, `Kbd`, `KbdGroup`, `IndicatorDot`, `Avatar`, `AvatarImage`, `AvatarFallback`, `PersonAvatar`, `AvatarGroup`, `ProgressBar`, `StatusProgress`, `StatusBar`, `StatusLegend` |
| Overlays | `Menu`, `Dialog`, `Drawer`, `Toast`, `Toaster`, `toast()`, `CommandPalette`, `SearchTrigger`, `NotificationPanel`, `NotificationItem` | | Overlays | `Dialog*`, `AlertDialog*`, `Drawer*`, `Menu*`, `Popover*`, `Command*`, `SearchTrigger`, `Toast`, `ToastAction`, `ToastClose`, `Toaster`, `toast()`, `Notification*` |
| Navigation | `Sidebar`, `NavItem`, `UserMenu`, `MobileHeader`, `MobileTabBar`, `SettingsNav` | | Navigation | `Sidebar`, `SidebarHeader`, `SidebarLogo`, `SidebarActions`, `SidebarButton`, `SidebarToggle`, `SidebarNav`, `NavItem`, `NavItemLabel`, `SidebarFooter`, `SidebarUserButton`, `SidebarUserName`, `MobileHeader*`, `MobileTabBar`, `MobileTab` |
| Aufgaben | `TaskTable`, `TaskRow`, `TaskSectionHeader`, `PriorityLabel`, `DeadlineItem`, `DateTile`, `CommentItem`, `CommentComposer` | | Tasks | `TaskTable`, `TaskTableHeader`, `TaskTableHead`, `TaskRow`, `TaskCell`, `TaskOpenButton`, `TaskTitle`, `TaskMeta`, `TaskCommentCount`, `TaskAssignee`, `TaskDue`, `TaskTableEmpty`, `TaskSection*`, `PriorityLabel`, `Deadline*`, `DateTile`, `Comment*` |
| Gruppen | `GroupCard`, `GroupRow`, `NewGroupTile`, `InviteBanner` | | Groups | `GroupRow*`, `GroupCard*`, `NewGroupTile*`, `InviteBanner*` |
| Kalender | `CalendarMonth`, `CalendarToolbar`, `CalendarLegend`, `GroupFilterChip`, `DayEventItem` | | Calendar | `CalendarGrid`, `CalendarWeekday`, `CalendarDay*`, `CalendarChip`, `CalendarMarker`, `CalendarLegend*`, `CalendarToolbar`, `CalendarNav`, `CalendarRangeLabel`, `FilterChip`, `FilterChipSwatch`, `DayEvent*` |
| Einstellungen | `SettingsSection`, `SettingsRow`, `ThemePicker`, `ColorSchemePicker`, `SaveStatus` | | Settings | `SettingsNav*`, `SettingsSection*`, `SettingsRow*`, `ThemePicker`, `ThemeOption`, `ThemePreview`, `ThemeOptionLabel`, `ColorSchemePicker`, `ColorSchemeOption`, `SaveStatus` |
| Anmeldung | `AuthBrandPanel`, `FeatureItem`, `PasswordRules` | | Auth | `AuthBrandPanel`, `AuthBrandContent`, `AuthHeadline`, `Feature*`, `PasswordRules`, `PasswordRule`, `passwordRules()` |
## Adding shadcn/ui components ## Adding shadcn/ui components
+24 -50
View File
@@ -27,11 +27,11 @@
"@storybook/test": "8.6.14", "@storybook/test": "8.6.14",
"@tailwindcss/vite": "4.1.11", "@tailwindcss/vite": "4.1.11",
"@types/node": "22.10.5", "@types/node": "22.10.5",
"@types/react": "18.3.18", "@types/react": "19.2.2",
"@types/react-dom": "18.3.5", "@types/react-dom": "19.2.2",
"@vitejs/plugin-react": "4.3.4", "@vitejs/plugin-react": "4.3.4",
"react": "18.3.1", "react": "19.2.0",
"react-dom": "18.3.1", "react-dom": "19.2.0",
"storybook": "8.6.14", "storybook": "8.6.14",
"tailwindcss": "4.1.11", "tailwindcss": "4.1.11",
"typescript": "5.7.3", "typescript": "5.7.3",
@@ -4192,32 +4192,24 @@
"undici-types": "~6.20.0" "undici-types": "~6.20.0"
} }
}, },
"node_modules/@types/prop-types": {
"version": "15.7.15",
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",
"integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==",
"devOptional": true,
"license": "MIT"
},
"node_modules/@types/react": { "node_modules/@types/react": {
"version": "18.3.18", "version": "19.2.2",
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.18.tgz", "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.2.tgz",
"integrity": "sha512-t4yC+vtgnkYjNSKlFx1jkAhH8LgTo2N/7Qvi83kdEaUtMDiwpbLAktKDaAMlRcJ5eSxZkH74eEGt1ky31d7kfQ==", "integrity": "sha512-6mDvHUFSjyT2B2yeNx2nUgMxh9LtOWvkhIU3uePn2I2oyNymUAX1NIsdgviM4CH+JSrp2D2hsMvJOkxY+0wNRA==",
"devOptional": true, "devOptional": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@types/prop-types": "*",
"csstype": "^3.0.2" "csstype": "^3.0.2"
} }
}, },
"node_modules/@types/react-dom": { "node_modules/@types/react-dom": {
"version": "18.3.5", "version": "19.2.2",
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.5.tgz", "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.2.tgz",
"integrity": "sha512-P4t6saawp+b/dFrUr2cvkVsfvPguwsxtH6dNIYRllMsefqFzkZk5UIjzyDOv5g1dXIPdG4Sp1yCR4Z6RCUsG/Q==", "integrity": "sha512-9KQPoO6mZCi7jcIStSnlOWn2nEF3mNmyr3rIAsGnAbQKYbRLyqmeSc39EVgtxXVia+LMT8j3knZLAZAh+xLmrw==",
"devOptional": true, "devOptional": true,
"license": "MIT", "license": "MIT",
"peerDependencies": { "peerDependencies": {
"@types/react": "^18.0.0" "@types/react": "^19.2.0"
} }
}, },
"node_modules/@types/resolve": { "node_modules/@types/resolve": {
@@ -5790,6 +5782,7 @@
"version": "4.0.0", "version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
"dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/jsdoc-type-pratt-parser": { "node_modules/jsdoc-type-pratt-parser": {
@@ -6146,18 +6139,6 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/loose-envify": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
"integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
"license": "MIT",
"dependencies": {
"js-tokens": "^3.0.0 || ^4.0.0"
},
"bin": {
"loose-envify": "cli.js"
}
},
"node_modules/loupe": { "node_modules/loupe": {
"version": "3.2.1", "version": "3.2.1",
"resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz", "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",
@@ -6678,13 +6659,10 @@
} }
}, },
"node_modules/react": { "node_modules/react": {
"version": "18.3.1", "version": "19.2.0",
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", "resolved": "https://registry.npmjs.org/react/-/react-19.2.0.tgz",
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", "integrity": "sha512-tmbWg6W31tQLeB5cdIBOicJDJRR2KzXsV7uSK9iNfLWQ5bIZfxuPEHp7M8wiHyHnn0DD1i7w3Zmin0FtkrwoCQ==",
"license": "MIT", "license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0"
},
"engines": { "engines": {
"node": ">=0.10.0" "node": ">=0.10.0"
} }
@@ -6722,16 +6700,15 @@
} }
}, },
"node_modules/react-dom": { "node_modules/react-dom": {
"version": "18.3.1", "version": "19.2.0",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz", "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.0.tgz",
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", "integrity": "sha512-UlbRu4cAiGaIewkPyiRGJk0imDN2T3JjieT6spoL2UeSf5od4n5LB/mQ4ejmxhCFT1tYe8IvaFulzynWovsEFQ==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"loose-envify": "^1.1.0", "scheduler": "^0.27.0"
"scheduler": "^0.23.2"
}, },
"peerDependencies": { "peerDependencies": {
"react": "^18.3.1" "react": "^19.2.0"
} }
}, },
"node_modules/react-is": { "node_modules/react-is": {
@@ -6962,13 +6939,10 @@
} }
}, },
"node_modules/scheduler": { "node_modules/scheduler": {
"version": "0.23.2", "version": "0.27.0",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz", "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",
"integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==", "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==",
"license": "MIT", "license": "MIT"
"dependencies": {
"loose-envify": "^1.1.0"
}
}, },
"node_modules/semver": { "node_modules/semver": {
"version": "6.3.2", "version": "6.3.2",
+6 -6
View File
@@ -29,8 +29,8 @@
"typecheck": "tsc --noEmit" "typecheck": "tsc --noEmit"
}, },
"peerDependencies": { "peerDependencies": {
"react": "^18.2.0 || ^19.0.0", "react": "^19.0.0",
"react-dom": "^18.2.0 || ^19.0.0" "react-dom": "^19.0.0"
}, },
"dependencies": { "dependencies": {
"class-variance-authority": "0.7.1", "class-variance-authority": "0.7.1",
@@ -51,11 +51,11 @@
"@storybook/test": "8.6.14", "@storybook/test": "8.6.14",
"@tailwindcss/vite": "4.1.11", "@tailwindcss/vite": "4.1.11",
"@types/node": "22.10.5", "@types/node": "22.10.5",
"@types/react": "18.3.18", "@types/react": "19.2.2",
"@types/react-dom": "18.3.5", "@types/react-dom": "19.2.2",
"@vitejs/plugin-react": "4.3.4", "@vitejs/plugin-react": "4.3.4",
"react": "18.3.1", "react": "19.2.0",
"react-dom": "18.3.1", "react-dom": "19.2.0",
"storybook": "8.6.14", "storybook": "8.6.14",
"tailwindcss": "4.1.11", "tailwindcss": "4.1.11",
"typescript": "5.7.3", "typescript": "5.7.3",
+138 -73
View File
@@ -1,12 +1,29 @@
import type { Meta, StoryObj } from '@storybook/react'; import type { Meta, StoryObj } from '@storybook/react';
import { ListChecks, Target, Users } from 'lucide-react';
import { useState, type FormEvent, type ReactNode } from 'react'; import { useState, type FormEvent, type ReactNode } from 'react';
import { Button, type ButtonState } from '../Button/Button'; import { Button, type ButtonState } from '../Button/Button';
import { Card, CardFrame } from '../Card/Card';
import { Checkbox } from '../Checkbox/Checkbox'; import { Checkbox } from '../Checkbox/Checkbox';
import { Field, Input, PasswordInput } from '../Field/Field'; import { Field, FieldError, FieldHeader, FieldLabel, Input, PasswordInput } from '../Field/Field';
import { AuthBrandPanel, PasswordRules, passwordRules } from './Auth'; import { PageDescription, PageTitle } from '../Layout/Layout';
import { Logo } from '../Logo/Logo';
import {
AuthBrandContent,
AuthBrandPanel,
AuthHeadline,
FeatureContent,
FeatureDescription,
FeatureIcon,
FeatureItem,
FeatureList,
FeatureTitle,
PasswordRule,
PasswordRules,
passwordRules,
} from './Auth';
const meta: Meta<typeof AuthBrandPanel> = { const meta: Meta<typeof AuthBrandPanel> = {
title: 'Anmeldung/Anmeldung', title: 'Auth/Auth',
component: AuthBrandPanel, component: AuthBrandPanel,
parameters: { layout: 'fullscreen' }, parameters: { layout: 'fullscreen' },
}; };
@@ -14,18 +31,56 @@ export default meta;
type Story = StoryObj<typeof AuthBrandPanel>; type Story = StoryObj<typeof AuthBrandPanel>;
function FormCard({ label, onSubmit, children }: { label: string; onSubmit: (e: FormEvent) => void; children: ReactNode }) { const fi = { size: 18, strokeWidth: 1.75, 'aria-hidden': true } as const;
const features = [
{
icon: <Users {...fi} />,
title: 'Alles an einem Ort',
description: 'Team, Aufgaben und Deadlines. Endlich gebündelt!',
},
{ icon: <ListChecks {...fi} />, title: 'Immer im Bild', description: 'Wer macht was bis wann? Ein Blick genügt!' },
{ icon: <Target {...fi} />, title: 'Mehr Fokus', description: 'Weniger Chaos, mehr Zeit fürs Wesentliche.' },
];
function Brand() {
return ( return (
<div className="rounded-[18px] border border-line-frame bg-frame p-[5px]"> <AuthBrandPanel>
<form <Logo variant="stacked" />
aria-label={label} <AuthBrandContent>
noValidate <AuthHeadline>Gruppenarbeit, die einfach funktioniert!</AuthHeadline>
onSubmit={onSubmit} <FeatureList>
className="m-0 box-border flex flex-col gap-[18px] rounded-[13px] border border-line bg-surface p-[22px]" {features.map((f) => (
> <FeatureItem key={f.title}>
{children} <FeatureIcon>{f.icon}</FeatureIcon>
</form> <FeatureContent>
</div> <FeatureTitle>{f.title}</FeatureTitle>
<FeatureDescription>{f.description}</FeatureDescription>
</FeatureContent>
</FeatureItem>
))}
</FeatureList>
</AuthBrandContent>
</AuthBrandPanel>
);
}
function FormCard({
label,
onSubmit,
children,
}: {
label: string;
onSubmit: (e: FormEvent) => void;
children: ReactNode;
}) {
return (
<CardFrame>
<Card asChild padding="none" className="m-0 gap-[18px] p-[22px]">
<form aria-label={label} noValidate onSubmit={onSubmit}>
{children}
</form>
</Card>
</CardFrame>
); );
} }
@@ -47,46 +102,42 @@ export const Login: Story = {
}; };
return ( return (
<div className="flex min-h-[860px] flex-wrap"> <div className="flex min-h-[860px] flex-wrap">
<AuthBrandPanel /> <Brand />
<main className="box-border flex min-w-0 flex-[1_1_440px] items-center justify-center px-4 py-12"> <main className="box-border flex min-w-0 flex-[1_1_440px] items-center justify-center px-4 py-12">
<div className="flex w-full max-w-[400px] flex-col gap-6"> <div className="flex w-full max-w-[400px] flex-col gap-6">
<div> <div>
<h1 className="m-0 text-display font-black tracking-[-0.01em]">Willkommen zurück</h1> <PageTitle>Willkommen zurück</PageTitle>
<p className="mt-1.5 mb-0 text-fg-muted">Melde dich an, um mit deinem Team weiterzuarbeiten.</p> <PageDescription>Melde dich an, um mit deinem Team weiterzuarbeiten.</PageDescription>
</div> </div>
<FormCard label="Anmelden" onSubmit={submit}> <FormCard label="Anmelden" onSubmit={submit}>
<Field label="E-Mail" error={emailBad ? 'Bitte gib eine gültige E-Mail-Adresse ein.' : undefined}> <Field>
{({ id, invalid, describedBy }) => ( <FieldLabel>E-Mail</FieldLabel>
<Input <Input
id={id} size="lg"
size="lg" autoComplete="email"
autoComplete="email" placeholder="du@beispiel.at"
placeholder="du@beispiel.at" value={email}
value={email} onChange={(e) => setEmail(e.target.value)}
onChange={(e) => setEmail(e.target.value)} />
invalid={invalid} {emailBad && <FieldError>Bitte gib eine gültige E-Mail-Adresse ein.</FieldError>}
aria-describedby={describedBy}
/>
)}
</Field> </Field>
<Field <Field>
label="Passwort" <FieldHeader>
labelAside={<a href="#">Passwort vergessen?</a>} <FieldLabel>Passwort</FieldLabel>
error={pwBad ? 'Bitte gib dein Passwort ein.' : undefined} <a href="#">Passwort vergessen?</a>
> </FieldHeader>
{({ id, invalid, describedBy }) => ( <PasswordInput
<PasswordInput size="lg"
id={id} autoComplete="current-password"
size="lg" value={pw}
autoComplete="current-password" onChange={(e) => setPw(e.target.value)}
value={pw} />
onChange={(e) => setPw(e.target.value)} {pwBad && <FieldError>Bitte gib dein Passwort ein.</FieldError>}
invalid={invalid} </Field>
aria-describedby={describedBy} <Field orientation="horizontal">
/> <Checkbox />
)} <FieldLabel>Angemeldet bleiben</FieldLabel>
</Field> </Field>
<Checkbox label="Angemeldet bleiben" />
<Button type="submit" variant="primary" size="xl" fullWidth state={state}> <Button type="submit" variant="primary" size="xl" fullWidth state={state}>
Anmelden Anmelden
</Button> </Button>
@@ -104,19 +155,18 @@ export const Login: Story = {
}, },
}; };
export const Registrierung: Story = { export const Register: Story = {
render: function Render() { render: function Render() {
const [pw, setPw] = useState('Collabry'); const [pw, setPw] = useState('Collabry');
const [tried, setTried] = useState(false); const [tried, setTried] = useState(false);
const rules = passwordRules(pw);
return ( return (
<div className="flex min-h-[900px] flex-wrap"> <div className="flex min-h-[900px] flex-wrap">
<AuthBrandPanel /> <Brand />
<main className="box-border flex min-w-0 flex-[1_1_440px] items-center justify-center px-4 py-12"> <main className="box-border flex min-w-0 flex-[1_1_440px] items-center justify-center px-4 py-12">
<div className="flex w-full max-w-[400px] flex-col gap-6"> <div className="flex w-full max-w-[400px] flex-col gap-6">
<div> <div>
<h1 className="m-0 text-display font-black tracking-[-0.01em]">Konto erstellen</h1> <PageTitle>Konto erstellen</PageTitle>
<p className="mt-1.5 mb-0 text-fg-muted">Sicher registrieren und direkt mit deinem Team loslegen.</p> <PageDescription>Sicher registrieren und direkt mit deinem Team loslegen.</PageDescription>
</div> </div>
<FormCard <FormCard
label="Registrieren" label="Registrieren"
@@ -126,27 +176,36 @@ export const Registrierung: Story = {
}} }}
> >
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<Field label="Vorname">{({ id }) => <Input id={id} size="lg" autoComplete="given-name" />}</Field> <Field>
<Field label="Nachname">{({ id }) => <Input id={id} size="lg" autoComplete="family-name" />}</Field> <FieldLabel>Vorname</FieldLabel>
</div> <Input size="lg" autoComplete="given-name" />
<Field label="E-Mail"> </Field>
{({ id }) => <Input id={id} size="lg" autoComplete="email" placeholder="du@beispiel.at" />} <Field>
</Field> <FieldLabel>Nachname</FieldLabel>
<div className="flex flex-col gap-1.5"> <Input size="lg" autoComplete="family-name" />
<Field label="Passwort">
{({ id }) => (
<PasswordInput
id={id}
size="lg"
autoComplete="new-password"
value={pw}
onChange={(e) => setPw(e.target.value)}
aria-describedby="reg-pw-rules"
/>
)}
</Field> </Field>
<PasswordRules id="reg-pw-rules" rules={rules} showErrors={tried} />
</div> </div>
<Field>
<FieldLabel>E-Mail</FieldLabel>
<Input size="lg" autoComplete="email" placeholder="du@beispiel.at" />
</Field>
<Field>
<FieldLabel>Passwort</FieldLabel>
<PasswordInput
size="lg"
autoComplete="new-password"
value={pw}
onChange={(e) => setPw(e.target.value)}
aria-describedby="reg-pw-rules"
/>
<PasswordRules id="reg-pw-rules">
{passwordRules(pw).map((r) => (
<PasswordRule key={r.label} met={r.met} showError={tried}>
{r.label}
</PasswordRule>
))}
</PasswordRules>
</Field>
<Button type="submit" variant="primary" size="xl" fullWidth> <Button type="submit" variant="primary" size="xl" fullWidth>
Konto erstellen Konto erstellen
</Button> </Button>
@@ -164,14 +223,20 @@ export const Registrierung: Story = {
}, },
}; };
export const Passwortregeln: Story = { export const Rules: Story = {
parameters: { layout: 'padded' }, parameters: { layout: 'padded' },
render: function Render() { render: function Render() {
const [pw, setPw] = useState('abc'); const [pw, setPw] = useState('abc');
return ( return (
<div className="flex max-w-[400px] flex-col gap-1.5"> <div className="flex max-w-[400px] flex-col gap-1.5">
<PasswordInput aria-label="Passwort" value={pw} onChange={(e) => setPw(e.target.value)} /> <PasswordInput aria-label="Passwort" value={pw} onChange={(e) => setPw(e.target.value)} />
<PasswordRules rules={passwordRules(pw)} /> <PasswordRules>
{passwordRules(pw).map((r) => (
<PasswordRule key={r.label} met={r.met}>
{r.label}
</PasswordRule>
))}
</PasswordRules>
</div> </div>
); );
}, },
+115 -91
View File
@@ -1,76 +1,93 @@
import type { ReactNode } from 'react'; import type { ComponentProps } from 'react';
import { Check, ListChecks, Target, Users } from 'lucide-react'; import { Check } from 'lucide-react';
import { cn } from '../../lib/cn'; import { cn } from '../../lib/cn';
import { Logo } from '../Logo/Logo';
export interface FeatureItemProps { /**
icon: ReactNode; * Left half of the login and register screens.
title: string; *
description: string; * <AuthBrandPanel>
} * <Logo variant="stacked" />
* <AuthBrandContent>
/** Icon tile + title + one line, used on the login brand panel. */ * <AuthHeadline>Gruppenarbeit, die einfach funktioniert!</AuthHeadline>
export function FeatureItem({ icon, title, description }: FeatureItemProps) { * <FeatureList><FeatureItem><FeatureIcon><Users /></FeatureIcon><FeatureContent>…</FeatureContent></FeatureItem></FeatureList>
return ( * </AuthBrandContent>
<li className="flex list-none items-start gap-3.5"> * </AuthBrandPanel>
<span className="flex h-9 w-9 flex-none items-center justify-center rounded-[10px] border border-line-divider bg-feature text-accent-fg"> */
{icon} export function AuthBrandPanel({ className, ...props }: ComponentProps<'div'>) {
</span>
<div>
<div className="leading-tight font-bold">{title}</div>
<div className="mt-0.5 leading-snug text-fg-muted">{description}</div>
</div>
</li>
);
}
const featureIcon = { size: 18, strokeWidth: 1.75, 'aria-hidden': true } as const;
export const defaultFeatures: FeatureItemProps[] = [
{ icon: <Users {...featureIcon} />, title: 'Alles an einem Ort', description: 'Team, Aufgaben und Deadlines. Endlich gebündelt!' },
{ icon: <ListChecks {...featureIcon} />, title: 'Immer im Bild', description: 'Wer macht was bis wann? Ein Blick genügt!' },
{ icon: <Target {...featureIcon} />, title: 'Mehr Fokus', description: 'Weniger Chaos, mehr Zeit fürs Wesentliche.' },
];
export interface AuthBrandPanelProps {
headline?: string;
features?: FeatureItemProps[];
className?: string;
}
/** Left half of the login and register screens. */
export function AuthBrandPanel({
headline = 'Gruppenarbeit, die einfach funktioniert!',
features = defaultFeatures,
className,
}: AuthBrandPanelProps) {
return ( return (
<div <div
data-slot="auth-brand-panel"
className={cn( className={cn(
'box-border flex min-w-0 flex-[1_1_520px] flex-col items-center justify-center gap-9 border-r border-line-shell bg-brand px-[clamp(24px,5vw,72px)] py-12', 'box-border flex min-w-0 flex-[1_1_520px] flex-col items-center justify-center gap-9 border-r border-line-shell bg-brand px-[clamp(24px,5vw,72px)] py-12',
className, className,
)} )}
> {...props}
<Logo variant="stacked" /> />
<div className="flex w-full max-w-[420px] flex-col gap-7">
<p className="m-0 text-center text-[30px] leading-tight font-black tracking-[-0.01em] text-balance">{headline}</p>
<ul className="m-0 flex flex-col gap-[18px] p-0">
{features.map((f) => (
<FeatureItem key={f.title} {...f} />
))}
</ul>
</div>
</div>
); );
} }
export interface PasswordRule { export function AuthBrandContent({ className, ...props }: ComponentProps<'div'>) {
return (
<div
data-slot="auth-brand-content"
className={cn('flex w-full max-w-[420px] flex-col gap-7', className)}
{...props}
/>
);
}
export function AuthHeadline({ className, ...props }: ComponentProps<'p'>) {
return (
<p
data-slot="auth-headline"
className={cn('m-0 text-center text-[30px] leading-tight font-black tracking-[-0.01em] text-balance', className)}
{...props}
/>
);
}
export function FeatureList({ className, ...props }: ComponentProps<'ul'>) {
return <ul data-slot="feature-list" className={cn('m-0 flex flex-col gap-[18px] p-0', className)} {...props} />;
}
export function FeatureItem({ className, ...props }: ComponentProps<'li'>) {
return <li data-slot="feature-item" className={cn('flex list-none items-start gap-3.5', className)} {...props} />;
}
export function FeatureIcon({ className, ...props }: ComponentProps<'span'>) {
return (
<span
data-slot="feature-icon"
className={cn(
'flex h-9 w-9 flex-none items-center justify-center rounded-[10px] border border-line-divider bg-feature text-accent-fg',
className,
)}
{...props}
/>
);
}
export function FeatureContent(props: ComponentProps<'div'>) {
return <div data-slot="feature-content" {...props} />;
}
export function FeatureTitle({ className, ...props }: ComponentProps<'div'>) {
return <div data-slot="feature-title" className={cn('leading-tight font-bold', className)} {...props} />;
}
export function FeatureDescription({ className, ...props }: ComponentProps<'div'>) {
return (
<div data-slot="feature-description" className={cn('mt-0.5 leading-snug text-fg-muted', className)} {...props} />
);
}
export interface PasswordRuleCheck {
label: string; label: string;
met: boolean; met: boolean;
} }
/** Checks a password against the design's three rules. */ /** Checks a password against the design's three rules. */
export function passwordRules(pw: string): PasswordRule[] { export function passwordRules(pw: string): PasswordRuleCheck[] {
return [ return [
{ label: 'Mindestens 8 Zeichen', met: pw.length >= 8 }, { label: 'Mindestens 8 Zeichen', met: pw.length >= 8 },
{ label: 'Groß- und Kleinbuchstaben', met: /[a-zäöü]/.test(pw) && /[A-ZÄÖÜ]/.test(pw) }, { label: 'Groß- und Kleinbuchstaben', met: /[a-zäöü]/.test(pw) && /[A-ZÄÖÜ]/.test(pw) },
@@ -78,42 +95,49 @@ export function passwordRules(pw: string): PasswordRule[] {
]; ];
} }
export interface PasswordRulesProps { /** Live checklist under a password field: `PasswordRule`s. Link it with `aria-describedby`. */
rules: PasswordRule[]; export function PasswordRules({ className, ...props }: ComponentProps<'ul'>) {
id?: string;
/** Show unmet rules in red (after a submit attempt). */
showErrors?: boolean;
className?: string;
}
/** Live checklist under the password field. */
export function PasswordRules({ rules, id, showErrors, className }: PasswordRulesProps) {
return ( return (
<ul id={id} aria-label="Passwort-Anforderungen" className={cn('m-0 mt-1 flex flex-col gap-1.5 p-0', className)}> <ul
{rules.map((r) => ( aria-label="Passwort-Anforderungen"
<li data-slot="password-rules"
key={r.label} className={cn('m-0 mt-1 flex flex-col gap-1.5 p-0', className)}
{...props}
/>
);
}
export interface PasswordRuleProps extends ComponentProps<'li'> {
met: boolean;
/** Show it in red while unmet (after a submit attempt). */
showError?: boolean;
}
export function PasswordRule({ met, showError, className, children, ...props }: PasswordRuleProps) {
return (
<li
data-slot="password-rule"
className={cn(
'flex list-none items-center gap-2 text-xs',
met ? 'text-fg-muted' : showError ? 'text-danger-fg' : 'text-fg-subtle',
className,
)}
{...props}
>
{met ? (
<span className="flex h-4 w-4 flex-none items-center justify-center rounded-full bg-success text-on-color">
<Check size={10} strokeWidth={4} aria-hidden="true" />
</span>
) : (
<span
className={cn( className={cn(
'flex list-none items-center gap-2 text-xs', 'box-border h-4 w-4 flex-none rounded-full border-[1.5px]',
r.met ? 'text-fg-muted' : showErrors ? 'text-danger-fg' : 'text-fg-subtle', showError ? 'border-danger-fg' : 'border-line-control',
)} )}
> />
{r.met ? ( )}
<span className="flex h-4 w-4 flex-none items-center justify-center rounded-full bg-success text-on-color"> {children}
<Check size={10} strokeWidth={4} aria-hidden="true" /> <span className="sr-only">{met ? 'erfüllt' : 'nicht erfüllt'}</span>
</span> </li>
) : (
<span
className={cn(
'box-border h-4 w-4 flex-none rounded-full border-[1.5px]',
showErrors ? 'border-danger-fg' : 'border-line-control',
)}
/>
)}
{r.label}
<span className="sr-only">{r.met ? 'erfüllt' : 'nicht erfüllt'}</span>
</li>
))}
</ul>
); );
} }
+35 -14
View File
@@ -1,40 +1,61 @@
import type { Meta, StoryObj } from '@storybook/react'; import type { Meta, StoryObj } from '@storybook/react';
import { me, people } from '../../stories/fixtures'; import { me, people } from '../../stories/fixtures';
import { Avatar, AvatarStack } from './Avatar'; import { Avatar, AvatarFallback, AvatarGroup, AvatarImage, PersonAvatar } from './Avatar';
const meta: Meta<typeof Avatar> = { const meta: Meta<typeof PersonAvatar> = {
title: 'Anzeige/Avatar', title: 'Display/Avatar',
component: Avatar, component: PersonAvatar,
args: { person: people.LB, size: 36 }, args: { person: people.LB, size: 36 },
argTypes: { person: { control: false } }, argTypes: { person: { control: false } },
}; };
export default meta; export default meta;
type Story = StoryObj<typeof Avatar>; type Story = StoryObj<typeof PersonAvatar>;
export const Initialen: Story = {}; export const Initials: Story = {};
export const MitFoto: Story = { export const Photo: Story = {
name: 'Mit Foto',
args: { person: me, size: 64 }, args: { person: me, size: 64 },
}; };
export const Groessen: Story = { export const Sizes: Story = {
name: 'Größen',
render: () => ( render: () => (
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
{[22, 24, 26, 30, 32, 36].map((s) => ( {[22, 24, 26, 30, 32, 36].map((s) => (
<Avatar key={s} person={people.PM} size={s} /> <PersonAvatar key={s} person={people.PM} size={s} />
))} ))}
</div> </div>
), ),
}; };
export const Stapel: Story = { export const Group: Story = {
render: () => ( render: () => (
<div className="flex flex-col gap-4"> <div className="flex flex-col gap-4">
<AvatarStack people={Object.values(people)} /> <AvatarGroup>
<AvatarStack people={Object.values(people)} size={26} max={4} /> {Object.values(people).map((p) => (
<PersonAvatar key={p.name} person={p} size={22} />
))}
</AvatarGroup>
<AvatarGroup max={4} size={26}>
{Object.values(people).map((p) => (
<PersonAvatar key={p.name} person={p} size={26} />
))}
</AvatarGroup>
</div>
),
};
/** The parts `PersonAvatar` is made of. */
export const Parts: Story = {
render: () => (
<div className="flex items-center gap-3">
<Avatar size={40}>
<AvatarImage src={me.image} alt="" />
<AvatarFallback color={me.color}>NH</AvatarFallback>
</Avatar>
<Avatar size={40}>
<AvatarFallback color={people.KB.color}>KB</AvatarFallback>
</Avatar>
</div> </div>
), ),
}; };
+88 -45
View File
@@ -1,6 +1,6 @@
import type { HTMLAttributes } from 'react'; import { Children, isValidElement, type ComponentProps, type CSSProperties } from 'react';
import { cn } from '../../lib/cn'; import { cn } from '../../lib/cn';
import { Avatar as UiAvatar, AvatarFallback, AvatarImage } from '../ui/avatar'; import { Avatar as UiAvatar, AvatarFallback as UiAvatarFallback, AvatarImage } from '../ui/avatar';
export interface Person { export interface Person {
name: string; name: string;
@@ -11,14 +11,6 @@ export interface Person {
image?: string; image?: string;
} }
export interface AvatarProps extends HTMLAttributes<HTMLSpanElement> {
person: Person;
/** Diameter in px. The design uses 22, 24, 26, 30, 32 and 36. */
size?: number;
/** Ring that separates stacked avatars. */
ring?: boolean;
}
function fontSizeFor(size: number) { function fontSizeFor(size: number) {
if (size <= 22) return 8; if (size <= 22) return 8;
if (size <= 26) return 10; if (size <= 26) return 10;
@@ -26,51 +18,102 @@ function fontSizeFor(size: number) {
return 12; return 12;
} }
export function Avatar({ person, size = 32, ring = false, className, style, ...props }: AvatarProps) { const sizeStyle = (size: number) =>
({ width: size, height: size, '--avatar-font-size': `${fontSizeFor(size)}px` }) as CSSProperties;
export interface AvatarProps extends ComponentProps<typeof UiAvatar> {
/** Diameter in px. The design uses 22, 24, 26, 30, 32 and 36. */
size?: number;
}
/** Round avatar: put an `AvatarImage` and an `AvatarFallback` inside. Photos get a hairline ring. */
export function Avatar({ size = 32, className, style, ...props }: AvatarProps) {
return ( return (
<UiAvatar <UiAvatar
role="img" className={cn('has-[img]:shadow-[0_0_0_1px_var(--cl-line-heavy)]', className)}
aria-label={person.name} style={{ ...sizeStyle(size), ...style }}
title={person.name}
className={cn(
ring ? 'shadow-[0_0_0_2px_var(--cl-surface)]' : person.image && 'shadow-[0_0_0_1px_var(--cl-line-heavy)]',
className,
)}
style={{ width: size, height: size, ...style }}
{...props} {...props}
> />
{person.image && <AvatarImage src={person.image} alt="" />}
<AvatarFallback style={{ background: person.color, fontSize: fontSizeFor(size) }}>
<span aria-hidden="true">{person.initials}</span>
</AvatarFallback>
</UiAvatar>
); );
} }
export interface AvatarStackProps extends HTMLAttributes<HTMLSpanElement> { export { AvatarImage };
people: Person[];
size?: number; export interface AvatarFallbackProps extends ComponentProps<typeof UiAvatarFallback> {
/** Show at most this many, then "+n". */ /** Background color, usually the person's color. */
max?: number; color?: string;
} }
/** Overlapping avatars for group members. */ /** Initials shown until (or instead of) the image. */
export function AvatarStack({ people, size = 22, max = 5, className, ...props }: AvatarStackProps) { export function AvatarFallback({ color, className, style, ...props }: AvatarFallbackProps) {
const shown = people.slice(0, max);
const rest = people.length - shown.length;
return ( return (
<span className={cn('flex flex-none pl-1.5', className)} {...props}> <UiAvatarFallback
{shown.map((p) => ( className={cn('text-[length:var(--avatar-font-size)]', className)}
<Avatar key={p.name} person={p} size={size} ring className="-ml-1.5" /> style={{ background: color, ...style }}
))} {...props}
{rest > 0 && ( />
<span );
className="-ml-1.5 inline-flex flex-none items-center justify-center rounded-full bg-chip font-bold text-fg-3 shadow-[0_0_0_2px_var(--cl-surface)]" }
style={{ width: size, height: size, fontSize: fontSizeFor(size) }}
> export interface PersonAvatarProps extends Omit<AvatarProps, 'children'> {
+{rest} person: Person;
</span> }
/** `Avatar` for a `Person`: photo if there is one, else initials on their color. Labelled with the name. */
export function PersonAvatar({ person, ...props }: PersonAvatarProps) {
return (
<Avatar role="img" aria-label={person.name} title={person.name} {...props}>
{person.image && <AvatarImage src={person.image} alt="" />}
<AvatarFallback color={person.color}>
<span aria-hidden="true">{person.initials}</span>
</AvatarFallback>
</Avatar>
);
}
export interface AvatarGroupProps extends ComponentProps<'span'> {
/** Show at most this many avatars, then an `AvatarGroupCount` with the rest. */
max?: number;
/** Size of the "+n" bubble; match the avatars. */
size?: number;
}
/** Overlapping avatars with a ring that separates them. */
export function AvatarGroup({ max, size = 22, className, children, ...props }: AvatarGroupProps) {
const items = Children.toArray(children).filter(isValidElement);
const shown = max === undefined ? items : items.slice(0, max);
const rest = items.length - shown.length;
return (
<span
data-slot="avatar-group"
className={cn(
// `!` beats the photo ring of `Avatar`.
'flex flex-none pl-1.5 *:-ml-1.5 *:shadow-[0_0_0_2px_var(--cl-surface)]!',
className,
)} )}
{...props}
>
{shown}
{rest > 0 && <AvatarGroupCount size={size}>+{rest}</AvatarGroupCount>}
</span> </span>
); );
} }
export interface AvatarGroupCountProps extends ComponentProps<'span'> {
size?: number;
}
/** "+n" bubble at the end of an `AvatarGroup`. */
export function AvatarGroupCount({ size = 22, className, style, ...props }: AvatarGroupCountProps) {
return (
<span
data-slot="avatar-group-count"
className={cn(
'inline-flex flex-none items-center justify-center rounded-full bg-chip text-[length:var(--avatar-font-size)] font-bold text-fg-3',
className,
)}
style={{ ...sizeStyle(size), ...style }}
{...props}
/>
);
}
+9 -10
View File
@@ -1,9 +1,9 @@
import type { Meta, StoryObj } from '@storybook/react'; import type { Meta, StoryObj } from '@storybook/react';
import { swatches } from '../../lib/tokens'; import { swatches } from '../../lib/tokens';
import { CountBadge, Kbd, RoleBadge, StatusBadge, Swatch } from './Badge'; import { CountBadge, Kbd, KbdGroup, RoleBadge, StatusBadge, Swatch } from './Badge';
const meta: Meta<typeof StatusBadge> = { const meta: Meta<typeof StatusBadge> = {
title: 'Anzeige/Badges', title: 'Display/Badge',
component: StatusBadge, component: StatusBadge,
args: { status: 'doing' }, args: { status: 'doing' },
argTypes: { status: { control: 'inline-radio', options: ['done', 'review', 'doing', 'open'] } }, argTypes: { status: { control: 'inline-radio', options: ['done', 'review', 'doing', 'open'] } },
@@ -14,8 +14,7 @@ type Story = StoryObj<typeof StatusBadge>;
export const Status: Story = {}; export const Status: Story = {};
export const AlleStatus: Story = { export const AllStatuses: Story = {
name: 'Alle Status',
render: () => ( render: () => (
<div className="flex flex-wrap gap-2"> <div className="flex flex-wrap gap-2">
<StatusBadge status="done" /> <StatusBadge status="done" />
@@ -26,8 +25,7 @@ export const AlleStatus: Story = {
), ),
}; };
export const Zaehler: Story = { export const CountsAndRoles: Story = {
name: 'Zähler & Rollen',
render: () => ( render: () => (
<div className="flex flex-wrap items-center gap-3"> <div className="flex flex-wrap items-center gap-3">
<span className="flex items-center gap-2"> <span className="flex items-center gap-2">
@@ -44,8 +42,7 @@ export const Zaehler: Story = {
), ),
}; };
export const Farbfelder: Story = { export const SwatchesAndKeys: Story = {
name: 'Farbfelder & Tasten',
render: () => ( render: () => (
<div className="flex flex-col gap-4"> <div className="flex flex-col gap-4">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
@@ -58,8 +55,10 @@ export const Farbfelder: Story = {
</span> </span>
</div> </div>
<div className="flex items-center gap-1"> <div className="flex items-center gap-1">
<Kbd>⌘</Kbd> <KbdGroup>
<Kbd>K</Kbd> <Kbd>⌘</Kbd>
<Kbd>K</Kbd>
</KbdGroup>
<span className="ml-3 flex items-center gap-1.5 text-xs text-fg-subtle"> <span className="ml-3 flex items-center gap-1.5 text-xs text-fg-subtle">
<Kbd size="sm">↵</Kbd> <Kbd size="sm">↵</Kbd>
Öffnen Öffnen
+48 -23
View File
@@ -1,8 +1,8 @@
import type { HTMLAttributes, ReactNode } from 'react'; import type { ComponentProps } from 'react';
import { cn } from '../../lib/cn'; import { cn } from '../../lib/cn';
import { taskStatusLabel, type TaskStatus } from '../../lib/tokens';
import { Badge } from '../ui/badge'; import { Badge } from '../ui/badge';
import { Kbd as UiKbd } from '../ui/kbd'; import { Kbd as UiKbd } from '../ui/kbd';
import { taskStatusLabel, type TaskStatus } from '../../lib/tokens';
const statusStyles: Record<TaskStatus, string> = { const statusStyles: Record<TaskStatus, string> = {
done: 'text-success-fg bg-[rgba(74,222,128,0.08)] border-[rgba(74,222,128,0.22)]', done: 'text-success-fg bg-[rgba(74,222,128,0.08)] border-[rgba(74,222,128,0.22)]',
@@ -11,46 +11,45 @@ const statusStyles: Record<TaskStatus, string> = {
open: 'text-fg-open bg-status-open border-line-strong', open: 'text-fg-open bg-status-open border-line-strong',
}; };
export interface StatusBadgeProps extends HTMLAttributes<HTMLSpanElement> { type BadgeProps = Omit<ComponentProps<typeof Badge>, 'variant'>;
export interface StatusBadgeProps extends BadgeProps {
status: TaskStatus; status: TaskStatus;
/** Overrides the default German label. */
label?: string;
} }
/** Task status tag: Erledigt, Review, In Arbeit, Offen. */ /** Task status tag. Defaults to the German label (Erledigt, Review, In Arbeit, Offen); `children` override it. */
export function StatusBadge({ status, label, className, ...props }: StatusBadgeProps) { export function StatusBadge({ status, className, children, ...props }: StatusBadgeProps) {
return ( return (
<Badge variant="status" className={cn(statusStyles[status], className)} {...props}> <Badge variant="status" data-status={status} className={cn(statusStyles[status], className)} {...props}>
{label ?? taskStatusLabel[status]} {children ?? taskStatusLabel[status]}
</Badge> </Badge>
); );
} }
export interface CountBadgeProps extends HTMLAttributes<HTMLSpanElement> { export interface CountBadgeProps extends BadgeProps {
children: ReactNode;
/** `accent` is used for unread counts. */ /** `accent` is used for unread counts. */
tone?: 'neutral' | 'accent'; tone?: 'neutral' | 'accent';
} }
/** Small pill showing a count next to a heading. */ /** Small pill showing a count next to a heading. */
export function CountBadge({ tone = 'neutral', className, children, ...props }: CountBadgeProps) { export function CountBadge({ tone = 'neutral', className, ...props }: CountBadgeProps) {
return ( return (
<Badge <Badge
variant="count" variant="count"
className={cn(tone === 'accent' ? 'bg-accent font-bold text-on-accent' : 'bg-chip font-normal text-fg-3', className)} className={cn(
tone === 'accent' ? 'bg-accent font-bold text-on-accent' : 'bg-chip font-normal text-fg-3',
className,
)}
{...props} {...props}
> />
{children}
</Badge>
); );
} }
export interface RoleBadgeProps extends HTMLAttributes<HTMLSpanElement> { export interface RoleBadgeProps extends BadgeProps {
role?: 'admin' | 'member'; role?: 'admin' | 'member';
children?: ReactNode;
} }
/** "Admin" / "Mitglied" tag on group cards and member lists. */ /** "Admin" / "Mitglied" tag on group cards and member lists; `children` override the label. */
export function RoleBadge({ role = 'member', className, children, ...props }: RoleBadgeProps) { export function RoleBadge({ role = 'member', className, children, ...props }: RoleBadgeProps) {
return ( return (
<Badge <Badge
@@ -63,7 +62,7 @@ export function RoleBadge({ role = 'member', className, children, ...props }: Ro
); );
} }
export interface SwatchProps extends HTMLAttributes<HTMLSpanElement> { export interface SwatchProps extends ComponentProps<'span'> {
color: string; color: string;
/** 8px in meta lines, 10px next to headings. */ /** 8px in meta lines, 10px next to headings. */
size?: 8 | 10; size?: 8 | 10;
@@ -74,20 +73,46 @@ export function Swatch({ color, size = 8, className, style, ...props }: SwatchPr
return ( return (
<span <span
aria-hidden="true" aria-hidden="true"
className={cn('inline-block flex-none', size === 8 ? 'h-2 w-2 rounded-[2px]' : 'h-2.5 w-2.5 rounded-[3px]', className)} data-slot="swatch"
className={cn(
'inline-block flex-none',
size === 8 ? 'h-2 w-2 rounded-[2px]' : 'h-2.5 w-2.5 rounded-[3px]',
className,
)}
style={{ background: color, ...style }} style={{ background: color, ...style }}
{...props} {...props}
/> />
); );
} }
export interface KbdProps extends HTMLAttributes<HTMLElement> { export interface KbdProps extends ComponentProps<'kbd'> {
size?: 'sm' | 'md'; size?: 'sm' | 'md';
} }
/** Keyboard key hint, e.g. ⌘ K. */ /** Keyboard key hint, e.g. ⌘ K. */
export function Kbd({ size = 'md', className, ...props }: KbdProps) { export function Kbd({ size = 'md', className, ...props }: KbdProps) {
return <UiKbd className={cn(size === 'sm' && 'h-5 min-w-5 border-line-strong text-2xs', className)} {...props} />;
}
/** Keys that belong together, e.g. ⌘ K. */
export function KbdGroup({ className, ...props }: ComponentProps<'span'>) {
return <span data-slot="kbd-group" className={cn('inline-flex items-center gap-1', className)} {...props} />;
}
/**
* Small red dot for unread items. `SidebarButton` and `MobileHeaderButton` position it;
* mention the unread state in the button's label too.
*/
export function IndicatorDot({ className, ...props }: ComponentProps<'span'>) {
return ( return (
<UiKbd className={cn(size === 'sm' && 'h-5 min-w-5 border-line-strong text-2xs', className)} {...props} /> <span
data-slot="indicator-dot"
aria-hidden="true"
className={cn(
'pointer-events-none absolute top-1.5 right-1.5 h-[7px] w-[7px] rounded-full bg-danger shadow-[0_0_0_2px_var(--indicator-ring,var(--cl-surface))]',
className,
)}
{...props}
/>
); );
} }
+23 -19
View File
@@ -2,18 +2,16 @@ import type { Meta, StoryObj } from '@storybook/react';
import { fn } from '@storybook/test'; import { fn } from '@storybook/test';
import { ChevronRight, MoreHorizontal, Plus, Trash2 } from 'lucide-react'; import { ChevronRight, MoreHorizontal, Plus, Trash2 } from 'lucide-react';
import { useState } from 'react'; import { useState } from 'react';
import { Button, ButtonLink, type ButtonState } from './Button'; import { Button, type ButtonState } from './Button';
const meta: Meta<typeof Button> = { const meta: Meta<typeof Button> = {
title: 'Grundlagen/Button', title: 'Foundations/Button',
component: Button, component: Button,
args: { children: 'Neue Aufgabe', variant: 'primary', size: 'lg', onClick: fn() }, args: { children: 'Neue Aufgabe', variant: 'primary', size: 'lg', onClick: fn() },
argTypes: { argTypes: {
variant: { control: 'inline-radio', options: ['primary', 'secondary', 'ghost', 'danger', 'danger-outline'] }, variant: { control: 'inline-radio', options: ['primary', 'secondary', 'ghost', 'danger', 'danger-outline'] },
size: { control: 'inline-radio', options: ['xs', 'sm', 'md', 'lg', 'xl'] }, size: { control: 'inline-radio', options: ['xs', 'sm', 'md', 'lg', 'xl'] },
state: { control: 'inline-radio', options: ['idle', 'loading', 'success'] }, state: { control: 'inline-radio', options: ['idle', 'loading', 'success'] },
icon: { control: false },
iconEnd: { control: false },
}, },
}; };
export default meta; export default meta;
@@ -21,27 +19,33 @@ export default meta;
type Story = StoryObj<typeof Button>; type Story = StoryObj<typeof Button>;
export const Primary: Story = { export const Primary: Story = {
args: { icon: <Plus size={16} strokeWidth={2.25} /> }, render: (args) => (
<Button {...args}>
<Plus size={16} strokeWidth={2.25} />
{args.children}
</Button>
),
}; };
export const Varianten: Story = { export const Variants: Story = {
render: () => ( render: () => (
<div className="flex flex-wrap items-center gap-3"> <div className="flex flex-wrap items-center gap-3">
<Button variant="primary" size="lg" icon={<Plus size={16} strokeWidth={2.25} />}> <Button variant="primary" size="lg">
<Plus size={16} strokeWidth={2.25} />
Neue Aufgabe Neue Aufgabe
</Button> </Button>
<Button variant="secondary">Abbrechen</Button> <Button variant="secondary">Abbrechen</Button>
<Button variant="ghost">Filter zurücksetzen</Button> <Button variant="ghost">Filter zurücksetzen</Button>
<Button variant="danger">Löschen</Button> <Button variant="danger">Löschen</Button>
<Button variant="danger-outline" icon={<Trash2 size={16} strokeWidth={1.75} />}> <Button variant="danger-outline">
<Trash2 size={16} strokeWidth={1.75} />
Konto löschen Konto löschen
</Button> </Button>
</div> </div>
), ),
}; };
export const Groessen: Story = { export const Sizes: Story = {
name: 'Größen',
render: () => ( render: () => (
<div className="flex flex-wrap items-center gap-3"> <div className="flex flex-wrap items-center gap-3">
{(['xs', 'sm', 'md', 'lg', 'xl'] as const).map((s) => ( {(['xs', 'sm', 'md', 'lg', 'xl'] as const).map((s) => (
@@ -53,8 +57,7 @@ export const Groessen: Story = {
), ),
}; };
export const NurIcon: Story = { export const IconOnly: Story = {
name: 'Nur Icon',
render: () => ( render: () => (
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<Button variant="ghost" size="xs" iconOnly aria-label="Mehr Optionen" className="text-fg-subtle"> <Button variant="ghost" size="xs" iconOnly aria-label="Mehr Optionen" className="text-fg-subtle">
@@ -70,8 +73,7 @@ export const NurIcon: Story = {
), ),
}; };
export const Ladezustand: Story = { export const LoadingAndSuccess: Story = {
name: 'Laden & Erfolg',
render: function Render() { render: function Render() {
const [state, setState] = useState<ButtonState>('idle'); const [state, setState] = useState<ButtonState>('idle');
const run = () => { const run = () => {
@@ -98,11 +100,13 @@ export const Ladezustand: Story = {
}, },
}; };
export const AlsLink: Story = { export const AsLink: Story = {
name: 'Als Link',
render: () => ( render: () => (
<ButtonLink href="#" variant="secondary" size="sm" className="h-[34px]" iconEnd={<ChevronRight size={14} strokeWidth={1.75} />}> <Button asChild variant="secondary" size="sm" className="h-[34px]">
Alle Aufgaben <a href="#">
</ButtonLink> Alle Aufgaben
<ChevronRight size={14} strokeWidth={1.75} />
</a>
</Button>
), ),
}; };
+25 -40
View File
@@ -1,5 +1,4 @@
import { forwardRef, type AnchorHTMLAttributes, type ButtonHTMLAttributes, type ReactNode } from 'react'; import type { ComponentProps } from 'react';
import type { VariantProps } from 'class-variance-authority';
import { cn } from '../../lib/cn'; import { cn } from '../../lib/cn';
import { Button as UiButton, buttonVariants } from '../ui/button'; import { Button as UiButton, buttonVariants } from '../ui/button';
import { Spinner, SuccessCheck } from '../Spinner/Spinner'; import { Spinner, SuccessCheck } from '../Spinner/Spinner';
@@ -10,29 +9,38 @@ export type ButtonVariant = 'primary' | 'secondary' | 'ghost' | 'danger' | 'dang
export type ButtonSize = 'xs' | 'sm' | 'md' | 'lg' | 'xl'; export type ButtonSize = 'xs' | 'sm' | 'md' | 'lg' | 'xl';
export type ButtonState = 'idle' | 'loading' | 'success'; export type ButtonState = 'idle' | 'loading' | 'success';
/** Options of `buttonVariants`, for anything that should look like a button. */
export type ButtonStyleOptions = VariantProps<typeof buttonVariants>;
const spinnerSize: Record<ButtonSize, number> = { xs: 12, sm: 14, md: 14, lg: 16, xl: 18 }; const spinnerSize: Record<ButtonSize, number> = { xs: 12, sm: 14, md: 14, lg: 16, xl: 18 };
export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement>, ButtonStyleOptions { export interface ButtonProps extends ComponentProps<typeof UiButton> {
/** Icon before the label. */ /** Async feedback: the label hides behind a spinner, then a checkmark. Ignored with `asChild`. */
icon?: ReactNode;
/** Icon after the label. */
iconEnd?: ReactNode;
/** Async feedback: the label hides behind a spinner, then a checkmark. */
state?: ButtonState; state?: ButtonState;
} }
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button( /**
{ size = 'md', icon, iconEnd, state = 'idle', disabled, type = 'button', className, children, ...props }, * Put icons in `children` next to the label. Use `asChild` to render a link as a button:
ref, * `<Button asChild><a href="…">Alle Aufgaben</a></Button>`.
) { */
export function Button({
size = 'md',
state = 'idle',
disabled,
type = 'button',
asChild,
className,
children,
...props
}: ButtonProps) {
if (asChild) {
return (
<UiButton asChild size={size} className={className} {...props}>
{children}
</UiButton>
);
}
const busy = state !== 'idle'; const busy = state !== 'idle';
const spinner = spinnerSize[size ?? 'md']; const spinner = spinnerSize[size ?? 'md'];
return ( return (
<UiButton <UiButton
ref={ref}
type={type} type={type}
size={size} size={size}
disabled={disabled || busy} disabled={disabled || busy}
@@ -41,11 +49,9 @@ export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button
{...props} {...props}
> >
<span className={cn('inline-flex items-center justify-center gap-[inherit]', busy && 'invisible')}> <span className={cn('inline-flex items-center justify-center gap-[inherit]', busy && 'invisible')}>
{icon}
{children} {children}
{iconEnd}
</span> </span>
{state !== 'idle' && ( {busy && (
<span className="pointer-events-none absolute inset-0 flex items-center justify-center"> <span className="pointer-events-none absolute inset-0 flex items-center justify-center">
{state === 'loading' ? <Spinner size={spinner} /> : <SuccessCheck size={spinner} />} {state === 'loading' ? <Spinner size={spinner} /> : <SuccessCheck size={spinner} />}
</span> </span>
@@ -55,25 +61,4 @@ export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button
</span> </span>
</UiButton> </UiButton>
); );
});
export interface ButtonLinkProps extends AnchorHTMLAttributes<HTMLAnchorElement>, ButtonStyleOptions {
icon?: ReactNode;
iconEnd?: ReactNode;
} }
/** A link styled as a button, e.g. "Alle Aufgaben ›". */
export const ButtonLink = forwardRef<HTMLAnchorElement, ButtonLinkProps>(function ButtonLink(
{ variant, size, iconOnly, fullWidth, icon, iconEnd, className, children, ...props },
ref,
) {
return (
<UiButton asChild variant={variant} size={size} iconOnly={iconOnly} fullWidth={fullWidth} className={className}>
<a ref={ref} {...props}>
{icon}
{children}
{iconEnd}
</a>
</UiButton>
);
});
+195 -60
View File
@@ -1,28 +1,79 @@
import type { Meta, StoryObj } from '@storybook/react'; import type { Meta, StoryObj } from '@storybook/react';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { useMemo, useState } from 'react'; import { useMemo, useState } from 'react';
import { groupRefs, people } from '../../stories/fixtures'; import { groupRefs, people } from '../../stories/fixtures';
import { Card } from '../Card/Card'; import type { Person } from '../Avatar/Avatar';
import { SegmentedControl } from '../SegmentedControl/SegmentedControl'; import { PersonAvatar } from '../Avatar/Avatar';
import { Button } from '../Button/Button';
import { Card, CardFrame } from '../Card/Card';
import { PageTitle } from '../Layout/Layout';
import { SegmentedControl, SegmentedControlItem } from '../SegmentedControl/SegmentedControl';
import { import {
CalendarChip,
CalendarDay,
CalendarDayEvents,
CalendarDayHeader,
CalendarDayMore,
CalendarDayNumber,
CalendarGrid,
CalendarLegend, CalendarLegend,
CalendarMonth, CalendarNav,
CalendarRangeLabel,
CalendarToolbar, CalendarToolbar,
DayEventItem, CalendarWeekday,
GroupFilterChip, DayEvent,
type CalendarDay, DayEventContent,
type CalendarEvent, DayEventIcon,
DayEventList,
DayEventMeta,
DayEventTitle,
FilterChip,
FilterChipSwatch,
type CalendarEventKind,
} from './Calendar'; } from './Calendar';
const meta: Meta<typeof CalendarMonth> = { const meta: Meta<typeof CalendarGrid> = {
title: 'Kalender/Kalender', title: 'Calendar/Calendar',
component: CalendarMonth, component: CalendarGrid,
}; };
export default meta; export default meta;
type Story = StoryObj<typeof CalendarMonth>; type Story = StoryObj<typeof CalendarGrid>;
interface EventData {
id: string;
title: string;
color: string;
group: string;
kind: CalendarEventKind;
done?: boolean;
overdue?: boolean;
status?: string;
statusColor?: string;
assignee?: Person;
}
interface DayData {
date: string;
day: number;
inMonth: boolean;
weekend: boolean;
today: boolean;
events: EventData[];
}
const weekdays = ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'];
const kindLabel = { milestone: 'Abgabe', task: 'Aufgabe' } as const;
const MAX_PER_CELL = 3;
type GroupKey = keyof typeof groupRefs; type GroupKey = keyof typeof groupRefs;
const ev = (id: string, title: string, g: GroupKey, kind: CalendarEvent['kind'], extra: Partial<CalendarEvent> = {}): CalendarEvent & { g: GroupKey } => ({ const ev = (
id: string,
title: string,
g: GroupKey,
kind: EventData['kind'],
extra: Partial<EventData> = {},
): EventData & { g: GroupKey } => ({
id, id,
title, title,
color: groupRefs[g].color, color: groupRefs[g].color,
@@ -33,12 +84,28 @@ const ev = (id: string, title: string, g: GroupKey, kind: CalendarEvent['kind'],
}); });
/** Events in November 2026, keyed by day of month. */ /** Events in November 2026, keyed by day of month. */
const EVENTS: Record<number, (CalendarEvent & { g: GroupKey })[]> = { const EVENTS: Record<number, (EventData & { g: GroupKey })[]> = {
2: [ev('e1', 'ER-Diagramm finalisieren', 'db', 'task', { status: 'Offen', statusColor: 'var(--cl-fg-open)', assignee: people.PM })], 2: [
4: [ev('e2', 'Login & Registrierung umsetzen', 'swe', 'task', { status: 'In Arbeit', statusColor: 'var(--cl-info-fg)', assignee: people.NH })], ev('e1', 'ER-Diagramm finalisieren', 'db', 'task', {
status: 'Offen',
statusColor: 'var(--cl-fg-open)',
assignee: people.PM,
}),
],
4: [
ev('e2', 'Login & Registrierung umsetzen', 'swe', 'task', {
status: 'In Arbeit',
statusColor: 'var(--cl-info-fg)',
assignee: people.NH,
}),
],
5: [ 5: [
ev('e3', 'Präsentation Marktanalyse', 'mk', 'milestone'), ev('e3', 'Präsentation Marktanalyse', 'mk', 'milestone'),
ev('e4', 'Dashboard-UI entwerfen', 'swe', 'task', { status: 'Review', statusColor: 'var(--cl-warning-fg)', assignee: people.KB }), ev('e4', 'Dashboard-UI entwerfen', 'swe', 'task', {
status: 'Review',
statusColor: 'var(--cl-warning-fg)',
assignee: people.KB,
}),
], ],
6: [ev('e5', 'Kanban-Board: API-Endpunkte', 'swe', 'task', { assignee: people.LK })], 6: [ev('e5', 'Kanban-Board: API-Endpunkte', 'swe', 'task', { assignee: people.LK })],
9: [ev('e6', 'Git-Branching-Regeln dokumentieren', 'swe', 'task', { assignee: people.LK })], 9: [ev('e6', 'Git-Branching-Regeln dokumentieren', 'swe', 'task', { assignee: people.LK })],
@@ -51,14 +118,14 @@ const EVENTS: Record<number, (CalendarEvent & { g: GroupKey })[]> = {
], ],
27: [ev('e12', 'Abgabe Iteration 2', 'swe', 'milestone')], 27: [ev('e12', 'Abgabe Iteration 2', 'swe', 'milestone')],
}; };
const OCT_EVENTS: Record<number, (CalendarEvent & { g: GroupKey })[]> = { const OCT_EVENTS: Record<number, (EventData & { g: GroupKey })[]> = {
30: [ev('e0', 'Gruppen-Einladung per Link', 'swe', 'task', { overdue: true, assignee: people.NH })], 30: [ev('e0', 'Gruppen-Einladung per Link', 'swe', 'task', { overdue: true, assignee: people.NH })],
31: [ev('e00', 'Review Iteration 1 schreiben', 'swe', 'task', { done: true, assignee: people.LB })], 31: [ev('e00', 'Review Iteration 1 schreiben', 'swe', 'task', { done: true, assignee: people.LB })],
}; };
/** November 2026 starts on a Sunday; Monday-first grid from 26 Oct to 6 Dec. */ /** November 2026 starts on a Sunday; Monday-first grid from 26 Oct to 6 Dec. */
function buildNovember(active: Record<GroupKey, boolean>): CalendarDay[] { function buildNovember(active: Record<GroupKey, boolean>): DayData[] {
const days: CalendarDay[] = []; const days: DayData[] = [];
const start = new Date(2026, 9, 26); const start = new Date(2026, 9, 26);
for (let i = 0; i < 42; i++) { for (let i = 0; i < 42; i++) {
const d = new Date(start); const d = new Date(start);
@@ -78,7 +145,7 @@ function buildNovember(active: Record<GroupKey, boolean>): CalendarDay[] {
return days; return days;
} }
export const Monat: Story = { export const Month: Story = {
render: function Render() { render: function Render() {
const [active, setActive] = useState<Record<GroupKey, boolean>>({ swe: true, db: true, mk: true }); const [active, setActive] = useState<Record<GroupKey, boolean>>({ swe: true, db: true, mk: true });
const days = useMemo(() => buildNovember(active), [active]); const days = useMemo(() => buildNovember(active), [active]);
@@ -88,60 +155,128 @@ export const Monat: Story = {
return ( return (
<div className="flex flex-col gap-5"> <div className="flex flex-col gap-5">
<div className="flex flex-wrap items-center gap-4"> <div className="flex flex-wrap items-center gap-4">
<h1 className="m-0 text-display font-black tracking-[-0.01em]">Kalender</h1> <PageTitle>Kalender</PageTitle>
<CalendarToolbar rangeLabel="November 2026" /> <CalendarToolbar>
<SegmentedControl <CalendarNav>
label="Ansicht" <Button iconOnly aria-label="Vorheriger Monat">
className="ml-auto" <ChevronLeft size={16} strokeWidth={1.75} />
value={view} </Button>
onChange={setView} <Button iconOnly aria-label="Nächster Monat">
options={[ <ChevronRight size={16} strokeWidth={1.75} />
{ value: 'month', label: 'Monat' }, </Button>
{ value: 'week', label: 'Woche' }, <CalendarRangeLabel>November 2026</CalendarRangeLabel>
]} </CalendarNav>
/> <Button>Heute</Button>
</CalendarToolbar>
<SegmentedControl aria-label="Ansicht" className="ml-auto" value={view} onValueChange={setView}>
<SegmentedControlItem value="month">Monat</SegmentedControlItem>
<SegmentedControlItem value="week">Woche</SegmentedControlItem>
</SegmentedControl>
</div> </div>
<div role="group" aria-label="Gruppen filtern" className="flex flex-wrap gap-1.5"> <div role="group" aria-label="Gruppen filtern" className="flex flex-wrap gap-1.5">
{(Object.keys(groupRefs) as GroupKey[]).map((k) => ( {(Object.keys(groupRefs) as GroupKey[]).map((k) => (
<GroupFilterChip <FilterChip key={k} pressed={active[k]} onPressedChange={(on) => setActive((a) => ({ ...a, [k]: on }))}>
key={k} <FilterChipSwatch color={groupRefs[k].color} />
name={groupRefs[k].name} {groupRefs[k].name}
color={groupRefs[k].color} </FilterChip>
on={active[k]}
onToggle={() => setActive((a) => ({ ...a, [k]: !a[k] }))}
/>
))} ))}
</div> </div>
<div className="flex flex-wrap items-start gap-5"> <div className="flex flex-wrap items-start gap-5">
<Card padding="none" className="min-w-0 flex-[999_1_640px]" innerClassName="overflow-hidden" aria-label="November 2026"> <CardFrame className="min-w-0 flex-[999_1_640px]">
<CalendarMonth days={days} selected={selected} onSelect={setSelected} label="November 2026" /> <Card padding="none" className="overflow-hidden">
<CalendarLegend /> <CalendarGrid aria-label="November 2026">
</Card> {weekdays.map((w) => (
<Card as="aside" padding="none" aria-label="Tagesansicht" className="min-w-0 max-w-[380px] flex-[1_1_300px]"> <CalendarWeekday key={w}>{w}</CalendarWeekday>
<div className="px-[18px] pt-4 pb-3.5"> ))}
<div className="text-xs font-bold text-fg-subtle">{day?.today ? 'Heute' : 'Ausgewählter Tag'}</div> {days.map((d) => {
<h2 className="mt-0.5 mb-0 text-lg font-bold">{day ? `${day.day}. November` : ''}</h2> const more = d.events.length - MAX_PER_CELL;
</div> return (
<ul className="m-0 p-0"> <CalendarDay
{day?.events.map((e) => ( key={d.date}
<DayEventItem key={e.id} event={e} /> outside={!d.inMonth}
))} weekend={d.weekend}
</ul> today={d.today}
{day && day.events.length === 0 && ( selected={d.date === selected}
<div className="border-t border-line-subtle px-[18px] py-4 text-sm text-fg-subtle">Keine Deadlines</div> aria-label={`${d.day}., ${d.events.length} Einträge`}
)} onClick={() => setSelected(d.date)}
</Card> >
<CalendarDayHeader>
<CalendarDayNumber>{d.day}</CalendarDayNumber>
{more > 0 && <CalendarDayMore>+{more}</CalendarDayMore>}
</CalendarDayHeader>
<CalendarDayEvents>
{d.events.slice(0, MAX_PER_CELL).map((e) => (
<CalendarChip key={e.id} color={e.color} kind={e.kind} done={e.done} overdue={e.overdue}>
{e.title}
</CalendarChip>
))}
</CalendarDayEvents>
</CalendarDay>
);
})}
</CalendarGrid>
<CalendarLegend />
</Card>
</CardFrame>
<CardFrame className="min-w-0 max-w-[380px] flex-[1_1_300px]">
<Card asChild padding="none">
<aside aria-label="Tagesansicht">
<div className="px-[18px] pt-4 pb-3.5">
<div className="text-xs font-bold text-fg-subtle">{day?.today ? 'Heute' : 'Ausgewählter Tag'}</div>
<h2 className="mt-0.5 mb-0 text-lg font-bold">{day ? `${day.day}. November` : ''}</h2>
</div>
<DayEventList>
{day?.events.map((e) => (
<DayEvent key={e.id} done={e.done}>
<DayEventIcon color={e.color} kind={e.kind} />
<DayEventContent>
<DayEventTitle>{e.title}</DayEventTitle>
<DayEventMeta>
<span className="flex items-center gap-1.5">
<span className="h-2 w-2 rounded-[2px]" style={{ background: e.color }} />
{e.group}
</span>
<span>·</span>
<span>{kindLabel[e.kind]}</span>
{e.status && (
<>
<span>·</span>
<span className="font-bold" style={{ color: e.statusColor }}>
{e.status}
</span>
</>
)}
</DayEventMeta>
</DayEventContent>
{e.assignee && <PersonAvatar person={e.assignee} size={26} />}
</DayEvent>
))}
</DayEventList>
{day && day.events.length === 0 && (
<div className="border-t border-line-subtle px-[18px] py-4 text-sm text-fg-subtle">
Keine Deadlines
</div>
)}
</aside>
</Card>
</CardFrame>
</div> </div>
</div> </div>
); );
}, },
}; };
export const Filterchips: Story = { export const FilterChips: Story = {
render: () => ( render: () => (
<div className="flex gap-1.5"> <div className="flex gap-1.5">
<GroupFilterChip name="SWE · Collabry" color={groupRefs.swe.color} on /> <FilterChip defaultPressed>
<GroupFilterChip name="Datenbanken Übung" color={groupRefs.db.color} on={false} /> <FilterChipSwatch color={groupRefs.swe.color} />
SWE · Collabry
</FilterChip>
<FilterChip>
<FilterChipSwatch color={groupRefs.db.color} />
Datenbanken Übung
</FilterChip>
</div> </div>
), ),
}; };
+292 -210
View File
@@ -1,262 +1,344 @@
import { ChevronLeft, ChevronRight, Flag, SquareCheck } from 'lucide-react'; import type { ComponentProps, CSSProperties } from 'react';
import { Flag, SquareCheck } from 'lucide-react';
import { cn } from '../../lib/cn'; import { cn } from '../../lib/cn';
import { Avatar, type Person } from '../Avatar/Avatar';
import { Button } from '../Button/Button';
import { Toggle } from '../ui/toggle'; import { Toggle } from '../ui/toggle';
export interface CalendarEvent { export type CalendarEventKind = 'milestone' | 'task';
id: string;
title: string; /* ---------------------------------------------------------------- Markers */
/** Group color. */
color: string; export interface CalendarMarkerProps extends ComponentProps<'span'> {
group: string; /** `milestone` = Abgabe der Gruppe (flag), `task` = Aufgaben-Deadline (dot). */
/** `milestone` = Abgabe der Gruppe, `task` = Aufgaben-Deadline. */ kind: CalendarEventKind;
kind: 'milestone' | 'task'; /** Flag color. Defaults to the current text color. */
done?: boolean; color?: string;
/** Red dot for overdue tasks. */
overdue?: boolean; overdue?: boolean;
/** Status label for the day list, e.g. "In Arbeit". */ /** Flag size in px. */
status?: string; size?: number;
statusColor?: string;
assignee?: Person;
} }
export interface CalendarDay { /** Flag or dot that marks an event kind; used in chips and the legend. */
/** ISO date, used as key and for callbacks. */ export function CalendarMarker({ kind, color, overdue, size = 11, className, style, ...props }: CalendarMarkerProps) {
date: string; if (kind === 'milestone') {
day: number; return (
inMonth: boolean; <span
weekend?: boolean; data-slot="calendar-marker"
today?: boolean; className={cn('flex flex-none', className)}
events: CalendarEvent[]; style={{ color, ...style }}
} {...props}
>
const kindLabel = { milestone: 'Abgabe', task: 'Aufgabe' } as const; <Flag size={size} strokeWidth={1.75} aria-hidden="true" className="fill-current" />
</span>
/** Event pill inside a month cell. */ );
export function CalendarChip({ event: e }: { event: CalendarEvent }) { }
return ( return (
<span <span
data-slot="calendar-marker"
aria-hidden="true"
className={cn('h-1.5 w-1.5 flex-none rounded-full', overdue ? 'bg-danger' : 'bg-fg-muted', className)}
style={style}
{...props}
/>
);
}
export interface CalendarChipProps extends ComponentProps<'span'> {
/** Group color. */
color: string;
kind: CalendarEventKind;
done?: boolean;
overdue?: boolean;
}
/** Event pill inside a month cell; `children` is the title. */
export function CalendarChip({ color, kind, done, overdue, className, style, children, ...props }: CalendarChipProps) {
return (
<span
data-slot="calendar-chip"
className={cn( className={cn(
'box-border flex h-[22px] min-w-0 items-center gap-[5px] rounded-md px-1.5 text-xs leading-none', 'box-border flex h-[22px] min-w-0 items-center gap-[5px] rounded-md px-1.5 text-xs leading-none',
e.done ? 'text-fg-subtle line-through' : 'text-fg', done ? 'text-fg-subtle line-through' : 'text-fg',
e.kind === 'milestone' ? 'font-bold' : 'font-normal', kind === 'milestone' ? 'font-bold' : 'font-normal',
className,
)} )}
style={{ background: `color-mix(in srgb, ${e.color} 16%, transparent)` }} style={{ background: `color-mix(in srgb, ${color} 16%, transparent)`, ...style }}
{...props}
> >
{e.kind === 'milestone' ? ( <CalendarMarker kind={kind} color={color} overdue={overdue} />
<Flag size={11} strokeWidth={1.75} aria-hidden="true" className="flex-none fill-current" style={{ color: e.color }} /> <span className="truncate">{children}</span>
) : (
<span
className="h-1.5 w-1.5 flex-none rounded-full"
style={{ background: e.overdue ? 'var(--cl-danger)' : 'var(--cl-fg-muted)' }}
/>
)}
<span className="truncate">{e.title}</span>
</span> </span>
); );
} }
export interface CalendarMonthProps { /* ---------------------------------------------------------------- Month grid */
/** 35 or 42 days, Monday first. */
days: CalendarDay[];
weekdays?: string[];
selected?: string;
onSelect?: (date: string) => void;
/** Accessible name, e.g. "November 2026". */
label: string;
/** Events shown per cell before "+n". */
maxPerCell?: number;
className?: string;
}
const defaultWeekdays = ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So']; /**
* Month grid, Monday first; scrolls horizontally on narrow screens. `className` goes to
/** Month grid with event chips; the selected day gets an accent ring. */ * the scroll wrapper, other props to the grid. Give it an `aria-label` ("November 2026").
export function CalendarMonth({ *
days, * <CalendarGrid aria-label="November 2026">
weekdays = defaultWeekdays, * <CalendarWeekday>Mo</CalendarWeekday>…
selected, * <CalendarDay today selected onClick={…}>
onSelect, * <CalendarDayHeader><CalendarDayNumber>5</CalendarDayNumber><CalendarDayMore>+1</CalendarDayMore></CalendarDayHeader>
label, * <CalendarDayEvents><CalendarChip …>…</CalendarChip></CalendarDayEvents>
maxPerCell = 3, * </CalendarDay>
className, * </CalendarGrid>
}: CalendarMonthProps) { */
export function CalendarGrid({ className, ...props }: ComponentProps<'div'>) {
return ( return (
<div className={cn('overflow-x-auto', className)}> <div data-slot="calendar-grid" className={cn('overflow-x-auto', className)}>
<div <div
role="grid" role="grid"
aria-label={label}
className="grid min-w-[640px] grid-cols-7 gap-px border-t border-line-subtle bg-grid" className="grid min-w-[640px] grid-cols-7 gap-px border-t border-line-subtle bg-grid"
> {...props}
{weekdays.map((w) => ( />
<div key={w} role="columnheader" className="bg-surface px-2.5 pt-2.5 pb-2 text-xs font-bold text-fg-subtle">
{w}
</div>
))}
{days.map((d) => {
const isSel = d.date === selected;
const shown = d.events.slice(0, maxPerCell);
const more = d.events.length - shown.length;
return (
<button
key={d.date}
type="button"
role="gridcell"
aria-selected={isSel}
aria-label={`${d.day}., ${d.events.length} Einträge`}
onClick={() => onSelect?.(d.date)}
className={cn(
'box-border flex min-h-[116px] min-w-0 flex-col gap-1.5 border-0 p-2 text-left text-inherit hover:brightness-[1.18]',
!d.inMonth ? 'bg-outside' : d.weekend ? 'bg-weekend' : 'bg-surface',
isSel && 'shadow-[inset_0_0_0_2px_var(--cl-accent)]',
)}
>
<span className="flex items-center justify-between gap-1.5">
<span
className={cn(
'box-border inline-flex h-[26px] min-w-[26px] items-center justify-center rounded-full px-1.5 text-sm tabular-nums',
d.today ? 'bg-accent font-bold text-on-accent' : d.inMonth ? 'text-fg' : 'text-fg-faint',
)}
>
{d.day}
</span>
{more > 0 && <span className="text-2xs text-fg-subtle">+{more}</span>}
</span>
<span className="flex min-w-0 flex-col gap-[3px]">
{shown.map((e) => (
<CalendarChip key={e.id} event={e} />
))}
</span>
</button>
);
})}
</div>
</div> </div>
); );
} }
/** Legend under the calendar grid. */ export function CalendarWeekday({ className, ...props }: ComponentProps<'div'>) {
export function CalendarLegend({ className }: { className?: string }) {
return ( return (
<div <div
role="columnheader"
data-slot="calendar-weekday"
className={cn('bg-surface px-2.5 pt-2.5 pb-2 text-xs font-bold text-fg-subtle', className)}
{...props}
/>
);
}
export interface CalendarDayProps extends ComponentProps<'button'> {
/** Day of the previous or next month. */
outside?: boolean;
weekend?: boolean;
today?: boolean;
selected?: boolean;
}
/** Day cell (a button); the selected one gets an accent ring. Label it, e.g. "5., 2 Einträge". */
export function CalendarDay({
outside,
weekend,
today,
selected,
className,
type = 'button',
...props
}: CalendarDayProps) {
return (
<button
type={type}
role="gridcell"
aria-selected={selected ?? false}
data-slot="calendar-day"
data-outside={outside || undefined}
data-today={today || undefined}
className={cn(
'group/day box-border flex min-h-[116px] min-w-0 flex-col gap-1.5 border-0 p-2 text-left text-inherit hover:brightness-[1.18]',
outside ? 'bg-outside' : weekend ? 'bg-weekend' : 'bg-surface',
'aria-selected:shadow-[inset_0_0_0_2px_var(--cl-accent)]',
className,
)}
{...props}
/>
);
}
export function CalendarDayHeader({ className, ...props }: ComponentProps<'span'>) {
return (
<span
data-slot="calendar-day-header"
className={cn('flex items-center justify-between gap-1.5', className)}
{...props}
/>
);
}
/** Date number; filled with the accent on today, faint outside the month. */
export function CalendarDayNumber({ className, ...props }: ComponentProps<'span'>) {
return (
<span
data-slot="calendar-day-number"
className={cn(
'box-border inline-flex h-[26px] min-w-[26px] items-center justify-center rounded-full px-1.5 text-sm text-fg tabular-nums',
'group-data-outside/day:text-fg-faint group-data-today/day:bg-accent group-data-today/day:font-bold group-data-today/day:text-on-accent',
className,
)}
{...props}
/>
);
}
/** "+n" for events that don't fit. */
export function CalendarDayMore({ className, ...props }: ComponentProps<'span'>) {
return <span data-slot="calendar-day-more" className={cn('text-2xs text-fg-subtle', className)} {...props} />;
}
export function CalendarDayEvents({ className, ...props }: ComponentProps<'span'>) {
return (
<span data-slot="calendar-day-events" className={cn('flex min-w-0 flex-col gap-[3px]', className)} {...props} />
);
}
/** Legend under the grid. Without children it shows the standard three entries. */
export function CalendarLegend({ className, children, ...props }: ComponentProps<'div'>) {
return (
<div
data-slot="calendar-legend"
className={cn( className={cn(
'flex flex-wrap items-center gap-x-[18px] gap-y-2 border-t border-line-subtle px-4 py-3 text-xs text-fg-subtle', 'flex flex-wrap items-center gap-x-[18px] gap-y-2 border-t border-line-subtle px-4 py-3 text-xs text-fg-subtle',
className, className,
)} )}
{...props}
> >
<span className="flex items-center gap-1.5"> {children ?? (
<Flag size={12} strokeWidth={1.75} aria-hidden="true" className="fill-current text-fg-muted" /> <>
Abgabe der Gruppe <CalendarLegendItem>
</span> <CalendarMarker kind="milestone" size={12} className="text-fg-muted" />
<span className="flex items-center gap-1.5"> Abgabe der Gruppe
<span className="h-1.5 w-1.5 rounded-full bg-fg-muted" /> </CalendarLegendItem>
Aufgaben-Deadline <CalendarLegendItem>
</span> <CalendarMarker kind="task" />
<span className="flex items-center gap-1.5"> Aufgaben-Deadline
<span className="h-1.5 w-1.5 rounded-full bg-danger" /> </CalendarLegendItem>
Überfällig <CalendarLegendItem>
</span> <CalendarMarker kind="task" overdue />
Überfällig
</CalendarLegendItem>
</>
)}
</div> </div>
); );
} }
export interface CalendarToolbarProps { export function CalendarLegendItem({ className, ...props }: ComponentProps<'span'>) {
/** e.g. "November 2026" or "2. – 8. Nov". */ return <span data-slot="calendar-legend-item" className={cn('flex items-center gap-1.5', className)} {...props} />;
rangeLabel: string;
onPrev?: () => void;
onNext?: () => void;
onToday?: () => void;
prevLabel?: string;
nextLabel?: string;
} }
/** ‹ › range switcher and "Heute" button. */ /* ---------------------------------------------------------------- Toolbar */
export function CalendarToolbar({
rangeLabel, /** ‹ › range switcher, range label and "Heute": `CalendarNav` + `Button`s. */
onPrev, export function CalendarToolbar({ className, ...props }: ComponentProps<'div'>) {
onNext, return <div data-slot="calendar-toolbar" className={cn('flex flex-wrap items-center gap-4', className)} {...props} />;
onToday, }
prevLabel = 'Vorheriger Monat',
nextLabel = 'Nächster Monat', export function CalendarNav({ className, ...props }: ComponentProps<'div'>) {
}: CalendarToolbarProps) { return <div data-slot="calendar-nav" className={cn('flex items-center gap-1.5', className)} {...props} />;
}
/** e.g. "November 2026"; announced when it changes. */
export function CalendarRangeLabel({ className, ...props }: ComponentProps<'span'>) {
return ( return (
<div className="flex flex-wrap items-center gap-4"> <span
<div className="flex items-center gap-1.5"> aria-live="polite"
<Button iconOnly onClick={onPrev} aria-label={prevLabel}> data-slot="calendar-range-label"
<ChevronLeft size={16} strokeWidth={1.75} /> className={cn('min-w-[190px] pl-1.5 text-[18px] font-bold', className)}
</Button> {...props}
<Button iconOnly onClick={onNext} aria-label={nextLabel}> />
<ChevronRight size={16} strokeWidth={1.75} />
</Button>
<span aria-live="polite" className="min-w-[190px] pl-1.5 text-[18px] font-bold">
{rangeLabel}
</span>
</div>
<Button onClick={onToday}>Heute</Button>
</div>
); );
} }
export interface GroupFilterChipProps { /* ---------------------------------------------------------------- Filter chip */
name: string;
/** Toggleable pill, e.g. a group filter above the calendar. Use `pressed` / `onPressedChange`. */
export function FilterChip({ className, ...props }: Omit<ComponentProps<typeof Toggle>, 'variant' | 'size'>) {
return <Toggle variant="chip" className={cn('group/chip', className)} {...props} />;
}
export interface FilterChipSwatchProps extends ComponentProps<'span'> {
color: string; color: string;
on: boolean;
onToggle?: () => void;
} }
/** Toggleable group pill above the calendar. */ /** Outlined square that fills in while the chip is pressed. */
export function GroupFilterChip({ name, color, on, onToggle }: GroupFilterChipProps) { export function FilterChipSwatch({ color, className, style, ...props }: FilterChipSwatchProps) {
return ( return (
<Toggle variant="chip" pressed={on} onPressedChange={() => onToggle?.()}> <span
<span aria-hidden="true"
className="h-2.5 w-2.5 rounded-[3px]" data-slot="filter-chip-swatch"
style={{ background: on ? color : 'transparent', boxShadow: `inset 0 0 0 1.5px ${color}` }} className={cn(
/> 'h-2.5 w-2.5 rounded-[3px] shadow-[inset_0_0_0_1.5px_var(--chip-color)] group-data-[state=on]/chip:bg-[var(--chip-color)]',
{name} className,
</Toggle> )}
style={{ '--chip-color': color, ...style } as CSSProperties}
{...props}
/>
); );
} }
/** Row in the day panel next to the calendar. */ /* ---------------------------------------------------------------- Day list */
export function DayEventItem({ event: e }: { event: CalendarEvent }) {
export function DayEventList({ className, ...props }: ComponentProps<'ul'>) {
return <ul data-slot="day-event-list" className={cn('m-0 p-0', className)} {...props} />;
}
export interface DayEventProps extends ComponentProps<'li'> {
done?: boolean;
}
/** Row in the day panel next to the calendar: `DayEventIcon`, `DayEventContent`, optional avatar. */
export function DayEvent({ done, className, ...props }: DayEventProps) {
return ( return (
<li className="flex list-none gap-3 border-t border-line-subtle px-[18px] py-3.5"> <li
<span data-slot="day-event"
className="box-border flex h-8 w-8 flex-none items-center justify-center rounded-[9px] border" data-done={done || undefined}
style={{ className={cn('group/event flex list-none gap-3 border-t border-line-subtle px-[18px] py-3.5', className)}
borderColor: `color-mix(in srgb, ${e.color} 40%, transparent)`, {...props}
background: `color-mix(in srgb, ${e.color} 16%, transparent)`, />
color: e.color, );
}} }
>
{e.kind === 'milestone' ? ( export interface DayEventIconProps extends ComponentProps<'span'> {
<Flag size={15} strokeWidth={1.75} aria-hidden="true" className="fill-current" /> color: string;
) : ( kind: CalendarEventKind;
<SquareCheck size={15} strokeWidth={1.75} aria-hidden="true" /> }
)}
</span> export function DayEventIcon({ color, kind, className, style, ...props }: DayEventIconProps) {
<span className="min-w-0 flex-auto"> return (
<span className={cn('block leading-snug font-bold', e.done ? 'text-fg-subtle line-through' : 'text-fg')}> <span
{e.title} data-slot="day-event-icon"
</span> className={cn('box-border flex h-8 w-8 flex-none items-center justify-center rounded-[9px] border', className)}
<span className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-fg-subtle"> style={{
<span className="flex items-center gap-1.5"> borderColor: `color-mix(in srgb, ${color} 40%, transparent)`,
<span className="h-2 w-2 rounded-[2px]" style={{ background: e.color }} /> background: `color-mix(in srgb, ${color} 16%, transparent)`,
{e.group} color,
</span> ...style,
<span>·</span> }}
<span>{kindLabel[e.kind]}</span> {...props}
{e.status && ( >
<> {kind === 'milestone' ? (
<span>·</span> <Flag size={15} strokeWidth={1.75} aria-hidden="true" className="fill-current" />
<span className="font-bold" style={{ color: e.statusColor }}> ) : (
{e.status} <SquareCheck size={15} strokeWidth={1.75} aria-hidden="true" />
</span> )}
</> </span>
)} );
</span> }
</span>
{e.assignee && <Avatar person={e.assignee} size={26} />} export function DayEventContent({ className, ...props }: ComponentProps<'span'>) {
</li> return <span data-slot="day-event-content" className={cn('min-w-0 flex-auto', className)} {...props} />;
}
export function DayEventTitle({ className, ...props }: ComponentProps<'span'>) {
return (
<span
data-slot="day-event-title"
className={cn(
'block leading-snug font-bold text-fg group-data-done/event:text-fg-subtle group-data-done/event:line-through',
className,
)}
{...props}
/>
);
}
/** Group, kind and status, separated by "·". */
export function DayEventMeta({ className, ...props }: ComponentProps<'span'>) {
return (
<span
data-slot="day-event-meta"
className={cn('mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-fg-subtle', className)}
{...props}
/>
); );
} }
+69 -47
View File
@@ -1,13 +1,13 @@
import type { Meta, StoryObj } from '@storybook/react'; import type { Meta, StoryObj } from '@storybook/react';
import { ChevronRight, MoreHorizontal } from 'lucide-react'; import { ChevronRight, MoreHorizontal } from 'lucide-react';
import { swatches } from '../../lib/tokens'; import { swatches } from '../../lib/tokens';
import { Swatch } from '../Badge/Badge'; import { CountBadge, Swatch } from '../Badge/Badge';
import { Button, ButtonLink } from '../Button/Button'; import { Button } from '../Button/Button';
import { StatusProgress } from '../Progress/Progress'; import { StatusBar, StatusLegend, StatusProgress } from '../Progress/Progress';
import { Card, CardFooter, CardHeader } from './Card'; import { Card, CardAction, CardDescription, CardFooter, CardFrame, CardHeader, CardHeading, CardTitle } from './Card';
const meta: Meta<typeof Card> = { const meta: Meta<typeof Card> = {
title: 'Grundlagen/Card', title: 'Foundations/Card',
component: Card, component: Card,
argTypes: { padding: { control: 'inline-radio', options: ['none', 'sm', 'md'] } }, argTypes: { padding: { control: 'inline-radio', options: ['none', 'sm', 'md'] } },
}; };
@@ -21,57 +21,79 @@ const more = (
</Button> </Button>
); );
export const Leer: Story = { export const Basic: Story = {
args: { padding: 'md', children: 'Inhalt' }, args: { padding: 'md', children: 'Inhalt' },
decorators: [(Story) => <div className="max-w-[420px]">{Story()}</div>], render: (args) => (
<CardFrame className="max-w-[420px]">
<Card {...args} />
</CardFrame>
),
}; };
export const Projektfortschritt: Story = { const counts = { done: 9, review: 2, doing: 3, open: 2 };
export const ProjectProgress: Story = {
render: () => ( render: () => (
<Card aria-labelledby="h-progress" innerClassName="gap-5"> <CardFrame>
<CardHeader <Card asChild className="gap-5">
titleId="h-progress" <section aria-labelledby="h-progress">
title="Projektfortschritt" <CardHeader className="items-start">
subtitle={ <CardHeading>
<span className="flex items-center gap-2 text-fg-muted"> <CardTitle id="h-progress">Projektfortschritt</CardTitle>
<Swatch color={swatches.violet} size={10} /> <CardDescription>
SWE · Collabry <span className="text-fg-subtle">Iteration 2</span> <span className="flex items-center gap-2 text-fg-muted">
</span> <Swatch color={swatches.violet} size={10} />
} SWE · Collabry <span className="text-fg-subtle">Iteration 2</span>
actions={more} </span>
className="items-start" </CardDescription>
/> </CardHeading>
<div className="flex flex-wrap items-center gap-x-12 gap-y-5"> <CardAction>{more}</CardAction>
<div className="flex-none"> </CardHeader>
<div className="text-hero font-bold tracking-[-0.03em] tabular-nums">56%</div> <div className="flex flex-wrap items-center gap-x-12 gap-y-5">
<div className="mt-2 text-fg-muted"> <div className="flex-none">
<strong className="text-fg">9 von 16</strong> Aufgaben erledigt <div className="text-hero font-bold tracking-[-0.03em] tabular-nums">56%</div>
<div className="mt-2 text-fg-muted">
<strong className="text-fg">9 von 16</strong> Aufgaben erledigt
</div>
</div>
<StatusProgress className="flex-[1_1_320px]">
<StatusBar counts={counts} />
<StatusLegend counts={counts} />
</StatusProgress>
<div className="flex-none">
<div className="text-sm text-fg-subtle">Abgabe Iteration 2</div>
<div className="mt-0.5 text-[17px] font-bold">Fr, 27. November</div>
<div className="mt-0.5 font-bold text-accent-fg">noch 26 Tage</div>
</div>
</div> </div>
</div> </section>
<StatusProgress counts={{ done: 9, review: 2, doing: 3, open: 2 }} className="flex-[1_1_320px]" /> </Card>
<div className="flex-none"> </CardFrame>
<div className="text-sm text-fg-subtle">Abgabe Iteration 2</div>
<div className="mt-0.5 text-[17px] font-bold">Fr, 27. November</div>
<div className="mt-0.5 font-bold text-accent-fg">noch 26 Tage</div>
</div>
</div>
</Card>
), ),
}; };
export const MitFusszeile: Story = { export const WithFooter: Story = {
name: 'Mit Fußzeile',
render: () => ( render: () => (
<div className="max-w-[420px]"> <CardFrame className="max-w-[420px]">
<Card aria-labelledby="h-dl" innerClassName="min-h-[220px]"> <Card asChild className="min-h-[220px]">
<CardHeader titleId="h-dl" title="Anstehende Deadlines" count={6} actions={more} /> <section aria-labelledby="h-dl">
<p className="m-0 text-fg-muted">Listeninhalt …</p> <CardHeader>
<CardFooter> <CardTitle id="h-dl">
<ButtonLink href="#" size="sm" className="h-[34px]" iconEnd={<ChevronRight size={14} strokeWidth={1.75} />}> Anstehende Deadlines <CountBadge>6</CountBadge>
Zum Kalender </CardTitle>
</ButtonLink> <CardAction>{more}</CardAction>
</CardFooter> </CardHeader>
<p className="m-0 text-fg-muted">Listeninhalt …</p>
<CardFooter>
<Button asChild size="sm" className="h-[34px]">
<a href="#">
Zum Kalender
<ChevronRight size={14} strokeWidth={1.75} />
</a>
</Button>
</CardFooter>
</section>
</Card> </Card>
</div> </CardFrame>
), ),
}; };
+25 -67
View File
@@ -1,81 +1,39 @@
import { forwardRef, type HTMLAttributes, type ReactNode } from 'react'; import type { ComponentProps } from 'react';
import { cn } from '../../lib/cn'; import { cn } from '../../lib/cn';
import { import { Card as UiCard } from '../ui/card';
Card as UiCard,
CardAction,
CardDescription,
CardFooter as UiCardFooter,
CardHeader as UiCardHeader,
CardTitle,
} from '../ui/card';
import { CountBadge } from '../Badge/Badge';
export interface CardProps extends HTMLAttributes<HTMLElement> { export { CardAction, CardDescription, CardFooter, CardHeader, CardHeading, CardTitle } from '../ui/card';
/** Element to render as; `section` for dashboard panels, `article` for group cards. */
as?: 'div' | 'section' | 'article' | 'form' | 'aside';
/** Inner padding. `none` lets rows run edge to edge (settings, task list). */
padding?: 'none' | 'sm' | 'md';
/** Classes for the inner surface. */
innerClassName?: string;
}
/** /**
* The design's signature double frame: a dark 5px rim around a raised surface. * The dark 5px rim of the design's signature double frame. Wrap a `Card` in it:
* Use it for dashboard panels, settings sections, auth forms and group cards. * `<CardFrame><Card>…</Card></CardFrame>`. Place and size the pair through the frame.
*/ */
export const Card = forwardRef<HTMLElement, CardProps>(function Card( export function CardFrame({ className, ...props }: ComponentProps<'div'>) {
{ as: Tag = 'section', padding = 'md', className, innerClassName, children, ...props },
ref,
) {
return ( return (
<Tag <div
ref={ref as never} data-slot="card-frame"
className={cn('flex min-w-0 rounded-[18px] border border-line-frame bg-frame p-[5px]', className)} className={cn('flex min-w-0 rounded-[18px] border border-line-frame bg-frame p-[5px]', className)}
{...props} {...props}
> />
<UiCard
className={cn(
padding === 'md' && 'gap-3.5 px-[22px] py-5',
padding === 'sm' && 'gap-4 px-[18px] pt-[18px] pb-4',
innerClassName,
)}
>
{children}
</UiCard>
</Tag>
); );
});
export interface CardHeaderProps extends Omit<HTMLAttributes<HTMLDivElement>, 'title'> {
title: ReactNode;
/** id for the heading, so the card can be `aria-labelledby` it. */
titleId?: string;
count?: ReactNode;
/** Secondary line under the title. */
subtitle?: ReactNode;
/** Right side: filters, "more" button, add button. */
actions?: ReactNode;
/** Heading level. */
level?: 2 | 3;
} }
export function CardHeader({ title, titleId, count, subtitle, actions, level = 2, ...props }: CardHeaderProps) { export interface CardProps extends ComponentProps<typeof UiCard> {
const H = level === 2 ? 'h2' : 'h3'; /** Inner padding. `none` lets rows run edge to edge (settings, task list). */
padding?: 'none' | 'sm' | 'md';
}
/** The raised surface. Use `asChild` for `section`, `article` or `form`. */
export function Card({ padding = 'md', className, ...props }: CardProps) {
return ( return (
<UiCardHeader {...props}> <UiCard
<div className="min-w-0"> data-padding={padding}
<div className="flex items-center gap-2"> className={cn(
<CardTitle asChild> padding === 'md' && 'gap-3.5 px-[22px] py-5',
<H id={titleId}>{title}</H> padding === 'sm' && 'gap-4 px-[18px] pt-[18px] pb-4',
</CardTitle> className,
{count !== undefined && <CountBadge>{count}</CountBadge>} )}
</div> {...props}
{subtitle && <CardDescription className="mt-1">{subtitle}</CardDescription>} />
</div>
{actions && <CardAction>{actions}</CardAction>}
</UiCardHeader>
); );
} }
/** Footer row that pins its content to the bottom of a card. */
export const CardFooter = UiCardFooter;
+19 -11
View File
@@ -1,17 +1,18 @@
import type { Meta, StoryObj } from '@storybook/react'; import type { Meta, StoryObj } from '@storybook/react';
import { useState } from 'react'; import { useState } from 'react';
import { Field, FieldLabel } from '../Field/Field';
import { Checkbox, TaskCheckbox } from './Checkbox'; import { Checkbox, TaskCheckbox } from './Checkbox';
const meta: Meta<typeof TaskCheckbox> = { const meta: Meta<typeof TaskCheckbox> = {
title: 'Formulare/Checkbox', title: 'Forms/Checkbox',
component: TaskCheckbox, component: TaskCheckbox,
args: { checked: false, taskTitle: 'ER-Diagramm finalisieren', loading: false }, args: { checked: false, loading: false, 'aria-label': 'ER-Diagramm finalisieren als erledigt markieren' },
}; };
export default meta; export default meta;
type Story = StoryObj<typeof TaskCheckbox>; type Story = StoryObj<typeof TaskCheckbox>;
export const Aufgabe: Story = { export const TaskToggle: Story = {
render: function Render(args) { render: function Render(args) {
const [checked, setChecked] = useState(args.checked); const [checked, setChecked] = useState(args.checked);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@@ -20,7 +21,10 @@ export const Aufgabe: Story = {
{...args} {...args}
checked={checked} checked={checked}
loading={loading || args.loading} loading={loading || args.loading}
onToggle={() => { aria-label={
checked ? 'ER-Diagramm finalisieren wieder öffnen' : 'ER-Diagramm finalisieren als erledigt markieren'
}
onCheckedChange={() => {
setLoading(true); setLoading(true);
setTimeout(() => { setTimeout(() => {
setChecked((c) => !c); setChecked((c) => !c);
@@ -32,17 +36,21 @@ export const Aufgabe: Story = {
}, },
}; };
export const Zustaende: Story = { export const States: Story = {
name: 'Zustände',
render: () => ( render: () => (
<div className="flex items-center gap-4"> <div className="flex items-center gap-4">
<TaskCheckbox checked={false} taskTitle="Offen" /> <TaskCheckbox checked={false} aria-label="Offen" />
<TaskCheckbox checked taskTitle="Erledigt" /> <TaskCheckbox checked aria-label="Erledigt" />
<TaskCheckbox checked={false} loading taskTitle="Lädt" /> <TaskCheckbox checked={false} loading aria-label="Lädt" />
</div> </div>
), ),
}; };
export const Formular: Story = { export const FormCheckbox: Story = {
render: () => <Checkbox label="Angemeldet bleiben" defaultChecked />, render: () => (
<Field orientation="horizontal">
<Checkbox defaultChecked />
<FieldLabel>Angemeldet bleiben</FieldLabel>
</Field>
),
}; };
+17 -26
View File
@@ -1,50 +1,41 @@
import { forwardRef, type ComponentPropsWithoutRef, type ReactNode } from 'react'; import type { ComponentProps } from 'react';
import { Check } from 'lucide-react'; import { Check } from 'lucide-react';
import { cn } from '../../lib/cn'; import { cn } from '../../lib/cn';
import { Checkbox as UiCheckbox } from '../ui/checkbox'; import { Checkbox as UiCheckbox } from '../ui/checkbox';
import { Label } from '../ui/label';
import { Toggle } from '../ui/toggle'; import { Toggle } from '../ui/toggle';
import { useFieldControl } from '../Field/Field';
import { Spinner } from '../Spinner/Spinner'; import { Spinner } from '../Spinner/Spinner';
export interface CheckboxProps extends ComponentPropsWithoutRef<typeof UiCheckbox> { /**
label: ReactNode; * Form checkbox. Put it in a `<Field orientation="horizontal">` next to a `FieldLabel`.
* Use `checked` / `onCheckedChange`.
*/
export function Checkbox(props: ComponentProps<typeof UiCheckbox>) {
return <UiCheckbox {...useFieldControl(props)} />;
} }
/** Plain form checkbox, e.g. "Angemeldet bleiben". Use `checked` / `onCheckedChange`. */ export interface TaskCheckboxProps extends Omit<
export const Checkbox = forwardRef<HTMLButtonElement, CheckboxProps>(function Checkbox( ComponentProps<typeof Toggle>,
{ label, className, ...props }, 'pressed' | 'onPressedChange' | 'size' | 'variant'
ref, > {
) {
return (
<Label className={cn('flex cursor-pointer items-center gap-2.5 text-fg-4', className)}>
<UiCheckbox ref={ref} {...props} />
{label}
</Label>
);
});
export interface TaskCheckboxProps {
checked: boolean; checked: boolean;
onToggle?: () => void; onCheckedChange?: (checked: boolean) => void;
loading?: boolean; loading?: boolean;
/** Title of the task, used for the accessible label. */
taskTitle: string;
/** Hit area: 36px in the dashboard, 40px in the task list. */ /** Hit area: 36px in the dashboard, 40px in the task list. */
size?: 36 | 40; size?: 36 | 40;
className?: string;
} }
/** The rounded-square toggle that completes or reopens a task. */ /** The rounded-square toggle that completes or reopens a task. Give it an `aria-label`. */
export function TaskCheckbox({ checked, onToggle, loading, taskTitle, size = 36, className }: TaskCheckboxProps) { export function TaskCheckbox({ checked, onCheckedChange, loading, size = 36, className, ...props }: TaskCheckboxProps) {
return ( return (
<Toggle <Toggle
variant="bare" variant="bare"
pressed={checked} pressed={checked}
onPressedChange={() => onToggle?.()} onPressedChange={onCheckedChange}
aria-busy={loading || undefined} aria-busy={loading || undefined}
aria-label={checked ? `${taskTitle} wieder öffnen` : `${taskTitle} als erledigt markieren`}
disabled={loading} disabled={loading}
className={cn('group flex-none rounded-lg', size === 36 ? 'h-9 w-9' : 'h-10 w-10', className)} className={cn('group flex-none rounded-lg', size === 36 ? 'h-9 w-9' : 'h-10 w-10', className)}
{...props}
> >
<span <span
className={cn( className={cn(
@@ -1,27 +1,61 @@
import type { Meta, StoryObj } from '@storybook/react'; import type { Meta, StoryObj } from '@storybook/react';
import { Clock, FileText, LogOut, Moon, Plus, Settings, SquareCheck, Users } from 'lucide-react'; import { Clock, FileText, LogOut, Moon, Plus, Settings, SquareCheck, Users } from 'lucide-react';
import { useState } from 'react'; import { useState, type ReactNode } from 'react';
import { Stage, groups, tasks } from '../../stories/fixtures'; import { Stage, groups, tasks } from '../../stories/fixtures';
import { CommandPalette, SearchTrigger, type CommandSection } from './CommandPalette'; import { Swatch } from '../Badge/Badge';
import { Dialog, DialogTrigger } from '../Dialog/Dialog';
import {
CommandClose,
CommandDialog,
CommandDialogContent,
CommandEmpty,
CommandFooter,
CommandGroup,
CommandInput,
CommandItem,
CommandItemIcon,
CommandItemLabel,
CommandItemMeta,
CommandList,
SearchTrigger,
} from './CommandPalette';
const meta: Meta<typeof CommandPalette> = { const meta: Meta<typeof CommandDialog> = {
title: 'Overlays/CommandPalette', title: 'Overlays/CommandPalette',
component: CommandPalette, component: CommandDialog,
}; };
export default meta; export default meta;
type Story = StoryObj<typeof CommandPalette>; type Story = StoryObj<typeof CommandDialog>;
const i = { size: 16, strokeWidth: 1.75 } as const; const i = { size: 16, strokeWidth: 1.75 } as const;
const taskItems = tasks.map((t) => ({ id: t.id, label: t.title, meta: `${t.group.name} · ${t.due}`, icon: <SquareCheck {...i} /> })); interface Entry {
const actions = [ id: string;
label: string;
meta: string;
icon: ReactNode;
}
const taskEntries: Entry[] = tasks.map((t) => ({
id: t.id,
label: t.title,
meta: `${t.group.name} · ${t.due}`,
icon: <SquareCheck {...i} />,
}));
const groupEntries: Entry[] = groups.map((g) => ({
id: g.id,
label: g.name,
meta: `${g.members.length} Mitglieder`,
icon: <Swatch color={g.color} size={10} />,
}));
const actions: Entry[] = [
{ id: 'a-new', label: 'Neue Aufgabe erstellen', meta: 'Aktion', icon: <Plus {...i} /> }, { id: 'a-new', label: 'Neue Aufgabe erstellen', meta: 'Aktion', icon: <Plus {...i} /> },
{ id: 'a-group', label: 'Gruppe erstellen', meta: 'Aktion', icon: <Users {...i} /> }, { id: 'a-group', label: 'Gruppe erstellen', meta: 'Aktion', icon: <Users {...i} /> },
{ id: 'a-theme', label: 'Zu hellem Design wechseln', meta: 'Aktion', icon: <Moon {...i} /> }, { id: 'a-theme', label: 'Zu hellem Design wechseln', meta: 'Aktion', icon: <Moon {...i} /> },
{ id: 'a-logout', label: 'Abmelden', meta: 'Aktion', icon: <LogOut {...i} /> }, { id: 'a-logout', label: 'Abmelden', meta: 'Aktion', icon: <LogOut {...i} /> },
]; ];
const pages = [ const pages: Entry[] = [
{ id: 'p-dash', label: 'Dashboard', meta: 'Seite', icon: <FileText {...i} /> }, { id: 'p-dash', label: 'Dashboard', meta: 'Seite', icon: <FileText {...i} /> },
{ id: 'p-tasks', label: 'Aufgaben', meta: 'Seite', icon: <FileText {...i} /> }, { id: 'p-tasks', label: 'Aufgaben', meta: 'Seite', icon: <FileText {...i} /> },
{ id: 'p-kanban', label: 'Kanban', meta: 'Seite', icon: <FileText {...i} /> }, { id: 'p-kanban', label: 'Kanban', meta: 'Seite', icon: <FileText {...i} /> },
@@ -29,39 +63,74 @@ const pages = [
{ id: 'p-acc', label: 'Einstellungen: Konto', meta: 'Seite', icon: <Settings {...i} /> }, { id: 'p-acc', label: 'Einstellungen: Konto', meta: 'Seite', icon: <Settings {...i} /> },
{ id: 'p-gen', label: 'Einstellungen: Allgemein', meta: 'Seite', icon: <Settings {...i} /> }, { id: 'p-gen', label: 'Einstellungen: Allgemein', meta: 'Seite', icon: <Settings {...i} /> },
]; ];
const recent: Entry[] = taskEntries.slice(0, 3).map((t) => ({ ...t, id: `r-${t.id}`, icon: <Clock {...i} /> }));
const initial: CommandSection[] = [ function Group({ heading, entries, onSelect }: { heading: string; entries: Entry[]; onSelect: () => void }) {
{ title: 'Zuletzt geöffnet', items: taskItems.slice(0, 3).map((t) => ({ ...t, id: `r-${t.id}`, icon: <Clock {...i} /> })) }, return (
{ title: 'Aktionen', items: actions }, <CommandGroup heading={heading}>
{ title: 'Seiten', items: pages.slice(0, 5) }, {entries.map((e) => (
]; <CommandItem key={e.id} value={`${e.label} ${e.meta}`} onSelect={onSelect}>
const search: CommandSection[] = [ <CommandItemIcon>{e.icon}</CommandItemIcon>
{ title: 'Aufgaben', items: taskItems }, <CommandItemLabel>{e.label}</CommandItemLabel>
{ title: 'Gruppen', items: groups.map((g) => ({ id: g.id, label: g.name, meta: `${g.members.length} Mitglieder`, color: g.color })) }, <CommandItemMeta>{e.meta}</CommandItemMeta>
{ title: 'Seiten', items: pages }, </CommandItem>
{ title: 'Aktionen', items: actions }, ))}
]; </CommandGroup>
);
}
export const Suche: Story = { /** Recent items and shortcuts while empty; everything searchable once you type (cmdk filters). */
export const Search: Story = {
render: function Render() { render: function Render() {
const [open, setOpen] = useState(true); const [open, setOpen] = useState(true);
const [query, setQuery] = useState('');
const close = () => setOpen(false);
return ( return (
<Stage height={680}> <Stage height={680}>
<div className="p-6"> <Dialog
<SearchTrigger onClick={() => setOpen(true)} className="max-w-[520px]" />
</div>
<CommandPalette
open={open} open={open}
onClose={() => setOpen(false)} onOpenChange={(o) => {
sections={initial} setOpen(o);
searchSections={search} setQuery('');
/> }}
>
<div className="p-6">
<DialogTrigger asChild>
<SearchTrigger wrapperClassName="max-w-[520px]" />
</DialogTrigger>
</div>
<CommandDialogContent loop>
<CommandInput placeholder="Suche nach Aufgaben, Gruppen, Seiten …" value={query} onValueChange={setQuery}>
<CommandClose />
</CommandInput>
<CommandList>
{query ? (
<>
<Group heading="Aufgaben" entries={taskEntries} onSelect={close} />
<Group heading="Gruppen" entries={groupEntries} onSelect={close} />
<Group heading="Seiten" entries={pages} onSelect={close} />
<Group heading="Aktionen" entries={actions} onSelect={close} />
</>
) : (
<>
<Group heading="Zuletzt geöffnet" entries={recent} onSelect={close} />
<Group heading="Aktionen" entries={actions} onSelect={close} />
<Group heading="Seiten" entries={pages.slice(0, 5)} onSelect={close} />
</>
)}
<CommandEmpty>
<div className="font-bold text-fg">Keine Ergebnisse</div>
<div className="mt-1 text-sm">Nichts gefunden für „{query}“.</div>
</CommandEmpty>
</CommandList>
<CommandFooter />
</CommandDialogContent>
</Dialog>
</Stage> </Stage>
); );
}, },
}; };
export const Ausloeser: Story = { export const Trigger: Story = {
name: 'Auslöser (⌘K)', render: () => <SearchTrigger wrapperClassName="max-w-[520px]" />,
render: () => <SearchTrigger className="max-w-[520px]" />,
}; };
+140 -133
View File
@@ -1,146 +1,149 @@
import { useEffect, useMemo, useState, type ReactNode } from 'react'; import type { ComponentProps } from 'react';
import { CornerDownLeft, Search } from 'lucide-react'; import { CornerDownLeft, Search } from 'lucide-react';
import { cn } from '../../lib/cn'; import { cn } from '../../lib/cn';
import { import { DialogClose } from '../ui/dialog';
import { Kbd, KbdGroup } from '../Badge/Badge';
/**
* ⌘K search (cmdk): filtering, arrow keys and Enter come built in.
*
* <Dialog open={open} onOpenChange={setOpen}>
* <DialogTrigger asChild><SearchTrigger /></DialogTrigger>
* <CommandDialogContent>
* <CommandInput placeholder="…"><CommandClose /></CommandInput>
* <CommandList>
* <CommandGroup heading="Aufgaben">
* <CommandItem onSelect={…}>
* <CommandItemIcon><SquareCheck /></CommandItemIcon>
* <CommandItemLabel>…</CommandItemLabel>
* <CommandItemMeta>SWE · Collabry</CommandItemMeta>
* </CommandItem>
* </CommandGroup>
* <CommandEmpty>Keine Ergebnisse</CommandEmpty>
* </CommandList>
* <CommandFooter />
* </CommandDialogContent>
* </Dialog>
*
* `CommandDialog` is the shorthand without a trigger.
*/
export {
Command,
CommandDialog, CommandDialog,
CommandDialogContent,
CommandInput,
CommandList,
CommandEmpty, CommandEmpty,
CommandGroup, CommandGroup,
CommandInput, CommandItem,
CommandItem as CommandEntry,
CommandList,
} from '../ui/command'; } from '../ui/command';
import { DialogClose } from '../ui/dialog';
import { Kbd } from '../Badge/Badge';
export interface CommandItem {
id: string;
label: string;
/** Right-aligned context, e.g. "SWE · Collabry · Mi, 4. Nov" or "Aktion". */
meta?: string;
/** Icon in the 30px tile. */
icon?: ReactNode;
/** Group color; renders a swatch instead of an icon. */
color?: string;
/** Extra words to match against. */
keywords?: string;
href?: string;
onSelect?: () => void;
}
export interface CommandSection {
title: string;
items: CommandItem[];
}
export interface CommandPaletteProps {
open: boolean;
onClose?: () => void;
/** Sections shown while the query is empty, e.g. "Zuletzt geöffnet". */
sections: CommandSection[];
/** Sections searched when the user types. Defaults to `sections`. */
searchSections?: CommandSection[];
placeholder?: string;
}
/** ⌘K search across tasks, groups, pages and actions, with keyboard navigation. */
export function CommandPalette({
open,
onClose,
sections,
searchSections,
placeholder = 'Suche nach Aufgaben, Gruppen, Seiten …',
}: CommandPaletteProps) {
const [query, setQuery] = useState('');
useEffect(() => {
if (open) setQuery('');
}, [open]);
const visible = useMemo(() => {
const q = query.trim().toLowerCase();
if (!q) return sections.filter((s) => s.items.length > 0);
return (searchSections ?? sections)
.map((s) => ({
...s,
items: s.items.filter((it) => `${it.label} ${it.meta ?? ''} ${it.keywords ?? ''}`.toLowerCase().includes(q)),
}))
.filter((s) => s.items.length > 0);
}, [query, sections, searchSections]);
const run = (it: CommandItem) => {
it.onSelect?.();
if (it.href) window.location.assign(it.href);
onClose?.();
};
/** "Esc" key button that closes the dialog; place it in `CommandInput`. */
export function CommandClose({ className, children, ...props }: ComponentProps<typeof DialogClose>) {
return ( return (
// Filtering stays ours (empty query shows other sections); cmdk handles keyboard and selection. <DialogClose
<CommandDialog aria-label="Schließen"
open={open} className={cn(
onOpenChange={(next) => !next && onClose?.()} 'h-[26px] flex-none rounded-md border border-line-strong bg-elevated px-[7px] text-2xs font-bold text-fg-muted',
commandProps={{ shouldFilter: false, loop: true, label: 'Suche' }} className,
)}
{...props}
> >
<CommandInput aria-label="Suche" placeholder={placeholder} value={query} onValueChange={setQuery}> {children ?? 'Esc'}
<DialogClose aria-label="Schließen" className="h-[26px] flex-none rounded-md border border-line-strong bg-elevated px-[7px] text-2xs font-bold text-fg-muted"> </DialogClose>
Esc
</DialogClose>
</CommandInput>
<CommandList aria-label="Ergebnisse">
{visible.map((sec) => (
<CommandGroup key={sec.title} heading={sec.title}>
{sec.items.map((it) => (
<CommandEntry key={it.id} value={`${sec.title}-${it.id}`} onSelect={() => run(it)}>
<span className="box-border flex h-[30px] w-[30px] flex-none items-center justify-center rounded-lg border border-line-strong bg-elevated text-fg-muted">
{it.color ? <span className="h-2.5 w-2.5 rounded-[3px]" style={{ background: it.color }} /> : it.icon}
</span>
<span className="min-w-0 flex-auto truncate text-fg">{it.label}</span>
<span className="flex flex-none items-center gap-1.5 text-xs text-fg-subtle">
{it.meta}
<CornerDownLeft
size={14}
strokeWidth={1.75}
aria-hidden="true"
className="hidden text-fg-muted group-data-[selected=true]/item:block"
/>
</span>
</CommandEntry>
))}
</CommandGroup>
))}
<CommandEmpty>
<div className="font-bold text-fg">Keine Ergebnisse</div>
<div className="mt-1 text-sm">Nichts gefunden für „{query}“.</div>
</CommandEmpty>
</CommandList>
<div className="flex flex-wrap items-center gap-x-4 gap-y-2 border-t border-line-divider px-4 py-2.5 text-xs text-fg-subtle">
<span className="flex items-center gap-1.5">
<Kbd size="sm">↑</Kbd>
<Kbd size="sm">↓</Kbd>
Navigieren
</span>
<span className="flex items-center gap-1.5">
<Kbd size="sm">↵</Kbd>
Öffnen
</span>
<span className="flex items-center gap-1.5">
<Kbd size="sm">Esc</Kbd>
Schließen
</span>
</div>
</CommandDialog>
); );
} }
export interface SearchTriggerProps { /** 30px tile for an icon, or a `Swatch` for groups. */
onClick?: () => void; export function CommandItemIcon({ className, ...props }: ComponentProps<'span'>) {
placeholder?: string; return (
className?: string; <span
data-slot="command-item-icon"
className={cn(
'box-border flex h-[30px] w-[30px] flex-none items-center justify-center rounded-lg border border-line-strong bg-elevated text-fg-muted',
className,
)}
{...props}
/>
);
} }
/** Fake search field that opens the command palette; shows the ⌘K hint. */ export function CommandItemLabel({ className, ...props }: ComponentProps<'span'>) {
export function SearchTrigger({ onClick, placeholder = 'Aufgaben oder Gruppen suchen', className }: SearchTriggerProps) {
return ( return (
<div className={cn('box-border min-w-0 rounded-[14px] border border-line-frame bg-frame p-1', className)}> <span data-slot="command-item-label" className={cn('min-w-0 flex-auto truncate text-fg', className)} {...props} />
);
}
/** Right-aligned context; shows ↵ while the item is selected. */
export function CommandItemMeta({ className, children, ...props }: ComponentProps<'span'>) {
return (
<span
data-slot="command-item-meta"
className={cn('flex flex-none items-center gap-1.5 text-xs text-fg-subtle', className)}
{...props}
>
{children}
<CornerDownLeft
size={14}
strokeWidth={1.75}
aria-hidden="true"
className="hidden text-fg-muted group-data-[selected=true]/item:block"
/>
</span>
);
}
/** Bottom bar with keyboard hints. Without children it shows the standard ones. */
export function CommandFooter({ className, children, ...props }: ComponentProps<'div'>) {
return (
<div
data-slot="command-footer"
className={cn(
'flex flex-wrap items-center gap-x-4 gap-y-2 border-t border-line-divider px-4 py-2.5 text-xs text-fg-subtle',
className,
)}
{...props}
>
{children ?? (
<>
<CommandHint>
<Kbd size="sm">↑</Kbd>
<Kbd size="sm">↓</Kbd>
Navigieren
</CommandHint>
<CommandHint>
<Kbd size="sm">↵</Kbd>
Öffnen
</CommandHint>
<CommandHint>
<Kbd size="sm">Esc</Kbd>
Schließen
</CommandHint>
</>
)}
</div>
);
}
/** Key + description in the `CommandFooter`. */
export function CommandHint({ className, ...props }: ComponentProps<'span'>) {
return <span data-slot="command-hint" className={cn('flex items-center gap-1.5', className)} {...props} />;
}
export interface SearchTriggerProps extends ComponentProps<'button'> {
/** Classes for the framed wrapper. */
wrapperClassName?: string;
}
/** Fake search field that opens the command palette; shows the ⌘K hint. Use it inside `DialogTrigger asChild` or with `onClick`. */
export function SearchTrigger({
wrapperClassName,
className,
children = 'Aufgaben oder Gruppen suchen',
...props
}: SearchTriggerProps) {
return (
<div className={cn('box-border min-w-0 rounded-[14px] border border-line-frame bg-frame p-1', wrapperClassName)}>
<span className="relative flex items-center"> <span className="relative flex items-center">
<Search <Search
size={16} size={16}
@@ -150,17 +153,21 @@ export function SearchTrigger({ onClick, placeholder = 'Aufgaben oder Gruppen su
/> />
<button <button
type="button" type="button"
onClick={onClick}
aria-haspopup="dialog" aria-haspopup="dialog"
aria-label="Suche öffnen (⌘K)" aria-label="Suche öffnen (⌘K)"
className="box-border block h-[38px] w-full cursor-text rounded-[10px] border border-line bg-surface pr-[76px] pl-[38px] text-left text-fg-subtle outline-none hover:border-line-hover focus-visible:shadow-focus" data-slot="search-trigger"
className={cn(
'box-border block h-[38px] w-full cursor-text rounded-[10px] border border-line bg-surface pr-[76px] pl-[38px] text-left text-fg-subtle outline-none hover:border-line-hover focus-visible:shadow-focus',
className,
)}
{...props}
> >
{placeholder} {children}
</button> </button>
<span aria-hidden="true" className="pointer-events-none absolute right-2 flex gap-1"> <KbdGroup aria-hidden="true" className="pointer-events-none absolute right-2">
<Kbd>⌘</Kbd> <Kbd>⌘</Kbd>
<Kbd>K</Kbd> <Kbd>K</Kbd>
</span> </KbdGroup>
</span> </span>
</div> </div>
); );
+91 -20
View File
@@ -1,41 +1,112 @@
import type { Meta, StoryObj } from '@storybook/react'; import type { Meta, StoryObj } from '@storybook/react';
import { SendHorizontal } from 'lucide-react';
import { useState } from 'react'; import { useState } from 'react';
import { me, people } from '../../stories/fixtures'; import { me, people } from '../../stories/fixtures';
import { CommentComposer, CommentItem, type CommentData } from './Comment'; import { PersonAvatar, type Person } from '../Avatar/Avatar';
import { Button } from '../Button/Button';
import {
Comment,
CommentAuthor,
CommentBody,
CommentBubble,
CommentComposer,
CommentComposerHint,
CommentComposerRow,
CommentHeader,
CommentInput,
CommentList,
CommentTime,
} from './Comment';
const meta: Meta<typeof CommentItem> = { const meta: Meta<typeof Comment> = {
title: 'Aufgaben/Kommentare', title: 'Tasks/Comment',
component: CommentItem, component: Comment,
}; };
export default meta; export default meta;
type Story = StoryObj<typeof CommentItem>; type Story = StoryObj<typeof Comment>;
interface CommentData {
id: string;
author: Person;
when: string;
text: string;
mine?: boolean;
}
const initial: CommentData[] = [ const initial: CommentData[] = [
{ id: 'c1', author: people.PM, when: 'vor 1 Std.', text: 'Kannst du die n:m-Beziehung zwischen Gruppe und Mitglied noch auflösen?' }, {
{ id: 'c2', author: me, when: 'vor 40 Min.', text: 'Ja, ich lege eine Zwischentabelle „Mitgliedschaft“ an.', mine: true }, id: 'c1',
author: people.PM,
when: 'vor 1 Std.',
text: 'Kannst du die n:m-Beziehung zwischen Gruppe und Mitglied noch auflösen?',
},
{
id: 'c2',
author: me,
when: 'vor 40 Min.',
text: 'Ja, ich lege eine Zwischentabelle „Mitgliedschaft“ an.',
mine: true,
},
]; ];
export const Verlauf: Story = { export const Thread: Story = {
render: function Render() { render: function Render() {
const [comments, setComments] = useState(initial); const [comments, setComments] = useState(initial);
const [draft, setDraft] = useState(''); const [draft, setDraft] = useState('');
const empty = !draft.trim();
const send = () => {
if (empty) return;
setComments((cs) => [
...cs,
{ id: `c${cs.length + 1}`, author: me, when: 'gerade eben', text: draft, mine: true },
]);
setDraft('');
};
return ( return (
<div className="flex max-w-[460px] flex-col gap-4"> <div className="flex max-w-[460px] flex-col gap-4">
<ol aria-label="Kommentarverlauf" className="m-0 flex flex-col gap-3.5 p-0"> <CommentList aria-label="Kommentarverlauf">
{comments.map((c) => ( {comments.map((c) => (
<CommentItem key={c.id} comment={c} onDelete={(id) => setComments((cs) => cs.filter((x) => x.id !== id))} /> <Comment key={c.id}>
<PersonAvatar person={c.author} size={30} aria-hidden="true" />
<CommentBody>
<CommentHeader>
<CommentAuthor>{c.author.name}</CommentAuthor>
<CommentTime>{c.when}</CommentTime>
{c.mine && (
<Button
variant="ghost"
size="xs"
className="ml-auto h-6 px-1.5 text-xs text-fg-subtle"
aria-label="Kommentar löschen"
onClick={() => setComments((cs) => cs.filter((x) => x.id !== c.id))}
>
Löschen
</Button>
)}
</CommentHeader>
<CommentBubble>{c.text}</CommentBubble>
</CommentBody>
</Comment>
))} ))}
</ol> </CommentList>
<CommentComposer <CommentComposer>
me={me} <CommentComposerRow>
value={draft} <PersonAvatar person={me} size={30} aria-hidden="true" />
onChange={setDraft} <CommentInput value={draft} onChange={(e) => setDraft(e.target.value)} onSubmit={send} />
onSend={() => { <Button
setComments((cs) => [...cs, { id: `c${cs.length + 1}`, author: me, when: 'gerade eben', text: draft, mine: true }]); variant="primary"
setDraft(''); iconOnly
}} aria-label="Kommentar senden"
/> aria-disabled={empty}
className={empty ? 'h-[38px] w-[38px] opacity-50' : 'h-[38px] w-[38px]'}
onClick={send}
>
<SendHorizontal size={16} strokeWidth={2} />
</Button>
</CommentComposerRow>
<CommentComposerHint />
</CommentComposer>
</div> </div>
); );
}, },
+93 -86
View File
@@ -1,102 +1,109 @@
import { useId, type KeyboardEvent } from 'react'; import type { ComponentProps, KeyboardEvent } from 'react';
import { SendHorizontal } from 'lucide-react'; import { cn } from '../../lib/cn';
import { Avatar, type Person } from '../Avatar/Avatar';
import { Button, type ButtonState } from '../Button/Button';
import { Textarea } from '../Field/Field'; import { Textarea } from '../Field/Field';
export interface CommentData { /**
id: string; * Chat-style comments.
author: Person; *
/** e.g. "vor 2 Std." */ * <CommentList>
when: string; * <Comment>
text: string; * <PersonAvatar size={30} …/>
mine?: boolean; * <CommentBody>
* <CommentHeader><CommentAuthor>…</CommentAuthor><CommentTime>vor 2 Std.</CommentTime>…</CommentHeader>
* <CommentBubble>…</CommentBubble>
* </CommentBody>
* </Comment>
* </CommentList>
*/
export function CommentList({ className, ...props }: ComponentProps<'ol'>) {
return <ol data-slot="comment-list" className={cn('m-0 flex flex-col gap-3.5 p-0', className)} {...props} />;
} }
export interface CommentItemProps { export function Comment({ className, ...props }: ComponentProps<'li'>) {
comment: CommentData; return <li data-slot="comment" className={cn('flex list-none gap-2.5', className)} {...props} />;
onDelete?: (id: string) => void;
deleteState?: ButtonState;
} }
/** Chat-style comment with avatar, name, time and a bubble. */ export function CommentBody({ className, ...props }: ComponentProps<'div'>) {
export function CommentItem({ comment: c, onDelete, deleteState }: CommentItemProps) { return <div data-slot="comment-body" className={cn('min-w-0 flex-auto', className)} {...props} />;
}
/** Author, time and actions (pushed right with `ml-auto`). */
export function CommentHeader({ className, ...props }: ComponentProps<'div'>) {
return <div data-slot="comment-header" className={cn('flex items-baseline gap-2', className)} {...props} />;
}
export function CommentAuthor({ className, ...props }: ComponentProps<'span'>) {
return <span data-slot="comment-author" className={cn('text-sm font-bold', className)} {...props} />;
}
export function CommentTime({ className, ...props }: ComponentProps<'span'>) {
return <span data-slot="comment-time" className={cn('text-xs text-fg-subtle', className)} {...props} />;
}
export function CommentBubble({ className, ...props }: ComponentProps<'div'>) {
return ( return (
<li className="flex list-none gap-2.5"> <div
<Avatar person={c.author} size={30} aria-hidden="true" /> data-slot="comment-bubble"
<div className="min-w-0 flex-auto"> className={cn(
<div className="flex items-baseline gap-2"> 'mt-1 rounded-[4px_12px_12px_12px] bg-soft px-3 py-[9px] text-base leading-normal [overflow-wrap:anywhere] whitespace-pre-wrap text-fg-2',
<span className="text-sm font-bold">{c.author.name}</span> className,
<span className="text-xs text-fg-subtle">{c.when}</span> )}
{c.mine && onDelete && ( {...props}
<Button />
variant="ghost"
size="xs"
className="ml-auto h-6 px-1.5 text-xs text-fg-subtle"
aria-label="Kommentar löschen"
state={deleteState}
onClick={() => onDelete(c.id)}
>
Löschen
</Button>
)}
</div>
<div className="mt-1 rounded-[4px_12px_12px_12px] bg-soft px-3 py-[9px] text-base leading-normal [overflow-wrap:anywhere] whitespace-pre-wrap text-fg-2">
{c.text}
</div>
</div>
</li>
); );
} }
export interface CommentComposerProps { /**
me: Person; * Comment input row: avatar, `CommentInput`, send `Button`, then a `CommentComposerHint`.
value: string; *
onChange?: (value: string) => void; * <CommentComposer>
onSend?: () => void; * <CommentComposerRow><PersonAvatar …/><CommentInput onSubmit={send} …/><Button …/></CommentComposerRow>
sendState?: ButtonState; * <CommentComposerHint />
* </CommentComposer>
*/
export function CommentComposer(props: ComponentProps<'div'>) {
return <div data-slot="comment-composer" {...props} />;
} }
/** Comment input with ⌘ + Enter to send. */ export function CommentComposerRow({ className, ...props }: ComponentProps<'div'>) {
export function CommentComposer({ me, value, onChange, onSend, sendState }: CommentComposerProps) {
const id = useId();
const empty = value.trim() === '';
const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey) && !empty) {
e.preventDefault();
onSend?.();
}
};
return ( return (
<div> <div
<div className="flex items-end gap-2.5"> data-slot="comment-composer-row"
<Avatar person={me} size={30} className="mb-1" aria-hidden="true" /> className={cn('flex items-end gap-2.5 *:data-[slot=avatar]:mb-1', className)}
<label htmlFor={id} className="sr-only"> {...props}
Kommentar schreiben />
</label> );
<Textarea }
id={id}
rows={2} export interface CommentInputProps extends Omit<ComponentProps<'textarea'>, 'onSubmit'> {
placeholder="Kommentar schreiben …" /** Called on ⌘/Ctrl + Enter when the text isn't empty. */
value={value} onSubmit?: () => void;
onChange={(e) => onChange?.(e.target.value)} }
onKeyDown={onKeyDown}
className="min-w-0 flex-auto resize-none py-[9px]" /** Two-line textarea that submits on ⌘/Ctrl + Enter. */
/> export function CommentInput({ onSubmit, onKeyDown, className, ...props }: CommentInputProps) {
<Button return (
variant="primary" <Textarea
size="md" rows={2}
iconOnly aria-label="Kommentar schreiben"
aria-label="Kommentar senden" placeholder="Kommentar schreiben …"
className={empty ? 'h-[38px] w-[38px] opacity-50' : 'h-[38px] w-[38px]'} onKeyDown={(e: KeyboardEvent<HTMLTextAreaElement>) => {
aria-disabled={empty} onKeyDown?.(e);
state={sendState} if (e.key === 'Enter' && (e.metaKey || e.ctrlKey) && e.currentTarget.value.trim()) {
onClick={() => !empty && onSend?.()} e.preventDefault();
> onSubmit?.();
<SendHorizontal size={16} strokeWidth={2} /> }
</Button> }}
</div> className={cn('min-w-0 flex-auto resize-none py-[9px]', className)}
<div className="mt-1.5 pl-10 text-2xs text-fg-subtle">Mit ⌘ + Enter senden</div> {...props}
/>
);
}
export function CommentComposerHint({ className, children = 'Mit ⌘ + Enter senden', ...props }: ComponentProps<'div'>) {
return (
<div data-slot="comment-composer-hint" className={cn('mt-1.5 pl-10 text-2xs text-fg-subtle', className)} {...props}>
{children}
</div> </div>
); );
} }
+270 -160
View File
@@ -1,40 +1,102 @@
import type { Meta, StoryObj } from '@storybook/react'; import type { Meta, StoryObj } from '@storybook/react';
import { Trash2 } from 'lucide-react'; import { SendHorizontal, Trash2 } from 'lucide-react';
import { useState } from 'react'; import { useState } from 'react';
import { Stage, me, people, tasks } from '../../stories/fixtures'; import { Stage, me, people, tasks } from '../../stories/fixtures';
import { priorityLabel, type Priority } from '../../lib/tokens';
import { PersonAvatar } from '../Avatar/Avatar';
import { StatusBadge, Swatch } from '../Badge/Badge'; import { StatusBadge, Swatch } from '../Badge/Badge';
import { Button, type ButtonState } from '../Button/Button'; import { Button, type ButtonState } from '../Button/Button';
import { CommentComposer, CommentItem } from '../Comment/Comment'; import {
import { Field, Input, Select, Textarea } from '../Field/Field'; Comment,
import { SegmentedControl } from '../SegmentedControl/SegmentedControl'; CommentAuthor,
import { Dialog, Drawer } from './Dialog'; CommentBody,
CommentBubble,
CommentComposer,
CommentComposerHint,
CommentComposerRow,
CommentHeader,
CommentInput,
CommentList,
CommentTime,
} from '../Comment/Comment';
import { Field, FieldError, FieldLabel, FieldNote, Input, Select, SelectOption, Textarea } from '../Field/Field';
import { SegmentedControl, SegmentedControlItem } from '../SegmentedControl/SegmentedControl';
import {
AlertDialog,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
Dialog,
DialogBody,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
Drawer,
DrawerActions,
DrawerBody,
DrawerContent,
DrawerFooter,
DrawerHeader,
DrawerTitle,
DrawerTrigger,
} from './Dialog';
const meta: Meta<typeof Dialog> = { const meta: Meta<typeof Dialog> = {
title: 'Overlays/Dialog', title: 'Overlays/Dialog',
component: Dialog, component: Dialog,
parameters: { layout: 'padded' },
}; };
export default meta; export default meta;
type Story = StoryObj<typeof Dialog>; type Story = StoryObj<typeof Dialog>;
const groupOptions = [ const priorities: Priority[] = ['high', 'medium', 'low'];
{ value: 'swe', label: 'SWE · Collabry' },
{ value: 'db', label: 'Datenbanken Übung' },
{ value: 'mk', label: 'Marketing Seminar' },
];
const peopleOptions = Object.entries(people).map(([k, p]) => ({ value: k, label: p.name }));
const prioOptions = [
{ value: 'Hoch', label: 'Hoch' },
{ value: 'Mittel', label: 'Mittel' },
{ value: 'Niedrig', label: 'Niedrig' },
];
export const NeueAufgabe: Story = { function PrioritySelect({ value, onValueChange }: { value: string; onValueChange: (v: string) => void }) {
name: 'Neue Aufgabe', return (
<SegmentedControl aria-label="Priorität" size="md" value={value} onValueChange={onValueChange}>
{priorities.map((p) => (
<SegmentedControlItem key={p} value={p}>
{priorityLabel[p]}
</SegmentedControlItem>
))}
</SegmentedControl>
);
}
function GroupOptions() {
return (
<>
<SelectOption value="swe">SWE · Collabry</SelectOption>
<SelectOption value="db">Datenbanken Übung</SelectOption>
<SelectOption value="mk">Marketing Seminar</SelectOption>
</>
);
}
function PeopleOptions() {
return (
<>
{Object.entries(people).map(([k, p]) => (
<SelectOption key={k} value={k}>
{p.name}
</SelectOption>
))}
</>
);
}
export const NewTask: Story = {
render: function Render() { render: function Render() {
const [open, setOpen] = useState(true); const [open, setOpen] = useState(true);
const [prio, setPrio] = useState('Mittel'); const [prio, setPrio] = useState('medium');
const [title, setTitle] = useState(''); const [title, setTitle] = useState('');
const [tried, setTried] = useState(false); const [tried, setTried] = useState(false);
const [state, setState] = useState<ButtonState>('idle'); const [state, setState] = useState<ButtonState>('idle');
@@ -50,165 +112,213 @@ export const NeueAufgabe: Story = {
}; };
return ( return (
<Stage height={640}> <Stage height={640}>
<div className="p-6"> <Dialog open={open} onOpenChange={setOpen}>
<Button variant="primary" onClick={() => setOpen(true)}> <div className="p-6">
Neue Aufgabe <DialogTrigger asChild>
</Button> <Button variant="primary">Neue Aufgabe</Button>
</div> </DialogTrigger>
<Dialog </div>
open={open} <DialogContent>
onClose={() => setOpen(false)} <DialogHeader>
title="Neue Aufgabe" <DialogTitle>Neue Aufgabe</DialogTitle>
description="Die zuständige Person wird benachrichtigt." <DialogDescription>Die zuständige Person wird benachrichtigt.</DialogDescription>
footer={ </DialogHeader>
<> <DialogBody>
<Button onClick={() => setOpen(false)}>Abbrechen</Button> <Field>
<FieldLabel>Titel</FieldLabel>
<Input placeholder="Was ist zu tun?" value={title} onChange={(e) => setTitle(e.target.value)} />
{tried && !title.trim() && <FieldError>Bitte gib einen Titel ein.</FieldError>}
</Field>
<div className="grid grid-cols-[repeat(auto-fit,minmax(200px,1fr))] gap-4">
<Field>
<FieldLabel>Gruppe</FieldLabel>
<Select>
<GroupOptions />
</Select>
</Field>
<Field>
<FieldLabel>Zuständig</FieldLabel>
<Select>
<PeopleOptions />
</Select>
</Field>
<Field>
<FieldLabel>Fällig am</FieldLabel>
<Input type="date" defaultValue="2026-11-09" />
</Field>
<div className="flex min-w-0 flex-col gap-1.5">
<span className="text-sm font-bold">Priorität</span>
<PrioritySelect value={prio} onValueChange={setPrio} />
</div>
</div>
<Field>
<FieldLabel>
Beschreibung <FieldNote>(optional)</FieldNote>
</FieldLabel>
<Textarea rows={3} />
</Field>
</DialogBody>
<DialogFooter>
<DialogClose asChild>
<Button>Abbrechen</Button>
</DialogClose>
<Button variant="primary" state={state} onClick={submit}> <Button variant="primary" state={state} onClick={submit}>
Aufgabe erstellen Aufgabe erstellen
</Button> </Button>
</> </DialogFooter>
} </DialogContent>
>
<Field label="Titel" error={tried && !title.trim() ? 'Bitte gib einen Titel ein.' : undefined}>
{({ id, invalid, describedBy }) => (
<Input
id={id}
placeholder="Was ist zu tun?"
value={title}
onChange={(e) => setTitle(e.target.value)}
invalid={invalid}
aria-describedby={describedBy}
/>
)}
</Field>
<div className="grid grid-cols-[repeat(auto-fit,minmax(200px,1fr))] gap-4">
<Field label="Gruppe">{({ id }) => <Select id={id} options={groupOptions} />}</Field>
<Field label="Zuständig">{({ id }) => <Select id={id} options={peopleOptions} />}</Field>
<Field label="Fällig am">{({ id }) => <Input id={id} type="date" defaultValue="2026-11-09" />}</Field>
<div className="flex min-w-0 flex-col gap-1.5">
<span className="text-sm font-bold">Priorität</span>
<SegmentedControl label="Priorität" size="md" value={prio} onChange={setPrio} options={prioOptions} />
</div>
</div>
<Field label="Beschreibung" labelNote="(optional)">
{({ id }) => <Textarea id={id} rows={3} />}
</Field>
</Dialog> </Dialog>
</Stage> </Stage>
); );
}, },
}; };
export const Bestaetigung: Story = { export const Confirmation: Story = {
name: 'Bestätigung', render: () => (
render: function Render() { <Stage height={360}>
const [open, setOpen] = useState(true); <AlertDialog defaultOpen>
return (
<Stage height={360}>
<div className="p-6"> <div className="p-6">
<Button variant="danger-outline" onClick={() => setOpen(true)}> <AlertDialogTrigger asChild>
Aufgabe löschen <Button variant="danger-outline">Aufgabe löschen</Button>
</Button> </AlertDialogTrigger>
</div> </div>
<Dialog <AlertDialogContent>
open={open} <AlertDialogHeader>
onClose={() => setOpen(false)} <AlertDialogTitle>Aufgabe löschen?</AlertDialogTitle>
kind="alert" <AlertDialogDescription>
width={420} „ER-Diagramm finalisieren“ wird für alle Gruppenmitglieder entfernt.
title="Aufgabe löschen?" </AlertDialogDescription>
description="„ER-Diagramm finalisieren“ wird für alle Gruppenmitglieder entfernt." </AlertDialogHeader>
footer={ <AlertDialogFooter>
<> <AlertDialogCancel>Abbrechen</AlertDialogCancel>
<Button onClick={() => setOpen(false)}>Abbrechen</Button> <Button variant="danger">Löschen</Button>
<Button variant="danger" onClick={() => setOpen(false)}> </AlertDialogFooter>
Löschen </AlertDialogContent>
</Button> </AlertDialog>
</> </Stage>
} ),
/>
</Stage>
);
},
}; };
export const Aufgabendetails: Story = { export const TaskDetails: Story = {
render: function Render() { render: function Render() {
const [open, setOpen] = useState(true);
const [draft, setDraft] = useState(''); const [draft, setDraft] = useState('');
const [prio, setPrio] = useState('Hoch'); const [prio, setPrio] = useState('high');
const t = tasks[1]; const t = tasks[1];
return ( return (
<Stage height={760}> <Stage height={760}>
<div className="p-6"> <Drawer defaultOpen>
<Button onClick={() => setOpen(true)}>Details öffnen</Button> <div className="p-6">
</div> <DrawerTrigger asChild>
<Drawer <Button>Details öffnen</Button>
open={open} </DrawerTrigger>
onClose={() => setOpen(false)}
label={t.title}
header={
<span className="flex items-center gap-[7px] text-sm text-fg-muted">
<Swatch color={t.group.color} />
{t.group.name}
</span>
}
actions={
<Button variant="ghost" size="sm" iconOnly aria-label="Aufgabe löschen" title="Löschen" className="text-fg-subtle">
<Trash2 size={16} strokeWidth={1.75} />
</Button>
}
footer={<CommentComposer me={me} value={draft} onChange={setDraft} onSend={() => setDraft('')} />}
>
<div>
<input
aria-label="Titel"
defaultValue={t.title}
className="-mx-2 box-border w-[calc(100%+16px)] rounded-lg border border-transparent bg-transparent px-2 py-1.5 text-xl leading-tight font-black text-fg hover:border-line focus:border-accent-focus focus:shadow-focus focus:outline-none"
/>
<div className="mt-1.5 flex gap-2">
<StatusBadge status={t.status} />
</div>
</div> </div>
<div className="grid grid-cols-[110px_minmax(0,1fr)] items-center gap-x-3.5 gap-y-3"> <DrawerContent aria-describedby={undefined}>
<label htmlFor="td-status" className="text-sm text-fg-subtle"> <DrawerTitle className="sr-only">{t.title}</DrawerTitle>
Status <DrawerHeader>
</label> <span className="flex min-w-0 items-center gap-[7px] text-sm text-fg-muted">
<Select <Swatch color={t.group.color} />
id="td-status" {t.group.name}
defaultValue="doing" </span>
options={[ <DrawerActions>
{ value: 'open', label: 'Offen' }, <Button
{ value: 'doing', label: 'In Arbeit' }, variant="ghost"
{ value: 'review', label: 'Review' }, size="sm"
{ value: 'done', label: 'Erledigt' }, iconOnly
]} aria-label="Aufgabe löschen"
/> title="Löschen"
<label htmlFor="td-who" className="text-sm text-fg-subtle"> className="text-fg-subtle"
Zuständig >
</label> <Trash2 size={16} strokeWidth={1.75} />
<Select id="td-who" options={peopleOptions} /> </Button>
<label htmlFor="td-due" className="text-sm text-fg-subtle"> </DrawerActions>
Fällig am </DrawerHeader>
</label> <DrawerBody>
<Input id="td-due" type="date" defaultValue="2026-11-04" /> <div>
<span className="text-sm text-fg-subtle">Priorität</span> <input
<SegmentedControl label="Priorität" size="md" value={prio} onChange={setPrio} options={prioOptions} /> aria-label="Titel"
</div> defaultValue={t.title}
<Field label="Beschreibung"> className="-mx-2 box-border w-[calc(100%+16px)] rounded-lg border border-transparent bg-transparent px-2 py-1.5 text-xl leading-tight font-black text-fg hover:border-line focus:border-accent-focus focus:shadow-focus focus:outline-none"
{({ id }) => <Textarea id={id} rows={4} placeholder="Details, Links oder Akzeptanzkriterien …" />} />
</Field> <div className="mt-1.5 flex gap-2">
<section className="flex flex-col gap-1 border-t border-line-divider pt-4"> <StatusBadge status={t.status} />
<h3 className="m-0 mb-2 text-base font-bold">Kommentare</h3> </div>
<ol className="m-0 flex flex-col gap-3.5 p-0"> </div>
<CommentItem <div className="grid grid-cols-[110px_minmax(0,1fr)] items-center gap-x-3.5 gap-y-3">
comment={{ id: 'c1', author: people.LB, when: 'vor 2 Std.', text: 'Bitte auch die Validierung der E-Mail-Adresse einbauen.' }} <label htmlFor="td-status" className="text-sm text-fg-subtle">
/> Status
<CommentItem </label>
comment={{ id: 'c2', author: me, when: 'vor 1 Std.', text: 'Mache ich, kommt heute noch.', mine: true }} <Select id="td-status" defaultValue="doing">
onDelete={() => undefined} <SelectOption value="open">Offen</SelectOption>
/> <SelectOption value="doing">In Arbeit</SelectOption>
</ol> <SelectOption value="review">Review</SelectOption>
</section> <SelectOption value="done">Erledigt</SelectOption>
</Select>
<label htmlFor="td-who" className="text-sm text-fg-subtle">
Zuständig
</label>
<Select id="td-who">
<PeopleOptions />
</Select>
<label htmlFor="td-due" className="text-sm text-fg-subtle">
Fällig am
</label>
<Input id="td-due" type="date" defaultValue="2026-11-04" />
<span className="text-sm text-fg-subtle">Priorität</span>
<PrioritySelect value={prio} onValueChange={setPrio} />
</div>
<Field>
<FieldLabel>Beschreibung</FieldLabel>
<Textarea rows={4} placeholder="Details, Links oder Akzeptanzkriterien …" />
</Field>
<section className="flex flex-col gap-1 border-t border-line-divider pt-4">
<h3 className="m-0 mb-2 text-base font-bold">Kommentare</h3>
<CommentList>
<Comment>
<PersonAvatar person={people.LB} size={30} aria-hidden="true" />
<CommentBody>
<CommentHeader>
<CommentAuthor>{people.LB.name}</CommentAuthor>
<CommentTime>vor 2 Std.</CommentTime>
</CommentHeader>
<CommentBubble>Bitte auch die Validierung der E-Mail-Adresse einbauen.</CommentBubble>
</CommentBody>
</Comment>
<Comment>
<PersonAvatar person={me} size={30} aria-hidden="true" />
<CommentBody>
<CommentHeader>
<CommentAuthor>{me.name}</CommentAuthor>
<CommentTime>vor 1 Std.</CommentTime>
</CommentHeader>
<CommentBubble>Mache ich, kommt heute noch.</CommentBubble>
</CommentBody>
</Comment>
</CommentList>
</section>
</DrawerBody>
<DrawerFooter>
<CommentComposer>
<CommentComposerRow>
<PersonAvatar person={me} size={30} aria-hidden="true" />
<CommentInput
value={draft}
onChange={(e) => setDraft(e.target.value)}
onSubmit={() => setDraft('')}
/>
<Button
variant="primary"
iconOnly
aria-label="Kommentar senden"
className="h-[38px] w-[38px]"
disabled={!draft.trim()}
>
<SendHorizontal size={16} strokeWidth={2} />
</Button>
</CommentComposerRow>
<CommentComposerHint />
</CommentComposer>
</DrawerFooter>
</DrawerContent>
</Drawer> </Drawer>
</Stage> </Stage>
); );
+47 -141
View File
@@ -1,147 +1,53 @@
import type { ReactNode } from 'react'; /**
import { X } from 'lucide-react'; * Modal dialogs (Radix). The first form field gets focus on open; focus returns on close.
import { *
* <Dialog open={open} onOpenChange={setOpen}>
* <DialogTrigger asChild><Button>Neue Aufgabe</Button></DialogTrigger>
* <DialogContent>
* <DialogHeader><DialogTitle>…</DialogTitle><DialogDescription>…</DialogDescription></DialogHeader>
* <DialogBody>…</DialogBody>
* <DialogFooter><DialogClose asChild><Button>Abbrechen</Button></DialogClose>…</DialogFooter>
* </DialogContent>
* </Dialog>
*
* `AlertDialog*` is the same for confirmations (no close button, backdrop clicks are ignored).
* `Drawer*` is a side sheet from the right, e.g. task details.
* Without a description, pass `aria-describedby={undefined}` to the content.
*/
export {
Dialog,
DialogTrigger,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogBody,
DialogFooter,
DialogClose,
} from '../ui/dialog';
export {
AlertDialog, AlertDialog,
AlertDialogTrigger,
AlertDialogContent, AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader, AlertDialogHeader,
AlertDialogTitle, AlertDialogTitle,
AlertDialogDescription,
AlertDialogBody,
AlertDialogFooter,
AlertDialogAction,
AlertDialogCancel,
} from '../ui/alert-dialog'; } from '../ui/alert-dialog';
import {
Dialog as UiDialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogTitle,
} from '../ui/dialog';
import { Sheet, SheetClose, SheetContent, SheetFooter, SheetHeader, SheetTitle } from '../ui/sheet';
import { Button } from '../Button/Button';
/** Focus the first form field when a dialog opens (instead of the close button); Radix returns focus on close. */ export {
function focusFirstField(e: Event) { Sheet as Drawer,
const field = (e.currentTarget as HTMLElement).querySelector<HTMLElement>('[autofocus], input, textarea, select'); SheetTrigger as DrawerTrigger,
if (!field) return; SheetContent as DrawerContent,
e.preventDefault(); SheetHeader as DrawerHeader,
field.focus({ preventScroll: true }); SheetActions as DrawerActions,
} SheetTitle as DrawerTitle,
SheetDescription as DrawerDescription,
/** Radix warns about a missing description unless `aria-describedby` is explicitly unset. */ SheetBody as DrawerBody,
const noDescription = (description: ReactNode) => (description ? {} : { 'aria-describedby': undefined }); SheetFooter as DrawerFooter,
SheetClose as DrawerClose,
const closeButton = ( } from '../ui/sheet';
<Button variant="ghost" size="sm" iconOnly aria-label="Schließen" className="text-fg-subtle">
<X size={16} strokeWidth={1.75} />
</Button>
);
export interface DialogProps {
open: boolean;
onClose?: () => void;
title: ReactNode;
description?: ReactNode;
children?: ReactNode;
/** Footer actions, right-aligned. */
footer?: ReactNode;
/** Panel width in px. */
width?: number;
/** `alert` is a confirmation without a close button (role="alertdialog"); it ignores clicks on the backdrop. */
kind?: 'dialog' | 'alert';
className?: string;
}
/** Centered modal panel, e.g. "Neue Aufgabe" or "Aufgabe löschen?". */
export function Dialog({
open,
onClose,
title,
description,
children,
footer,
width = 560,
kind = 'dialog',
className,
}: DialogProps) {
const onOpenChange = (next: boolean) => !next && onClose?.();
const body = children && <div className="flex flex-col gap-4 px-[22px] pt-4 pb-5">{children}</div>;
if (kind === 'alert') {
return (
<AlertDialog open={open} onOpenChange={onOpenChange}>
<AlertDialogContent className={className} style={{ width }} {...noDescription(description)}>
<AlertDialogHeader>
<AlertDialogTitle>{title}</AlertDialogTitle>
{description && <AlertDialogDescription>{description}</AlertDialogDescription>}
</AlertDialogHeader>
{body}
{footer && <AlertDialogFooter>{footer}</AlertDialogFooter>}
</AlertDialogContent>
</AlertDialog>
);
}
return (
<UiDialog open={open} onOpenChange={onOpenChange}>
<DialogContent
showCloseButton={false}
onOpenAutoFocus={focusFirstField}
className={className}
style={{ width }}
{...noDescription(description)}
>
<div className="flex items-start gap-3 pt-5 pr-4 pb-1 pl-[22px]">
<div className="flex-auto">
<DialogTitle>{title}</DialogTitle>
{description && <DialogDescription className="mt-1">{description}</DialogDescription>}
</div>
<DialogClose asChild>{closeButton}</DialogClose>
</div>
{body}
{footer && <DialogFooter>{footer}</DialogFooter>}
</DialogContent>
</UiDialog>
);
}
export interface DrawerProps {
open: boolean;
onClose?: () => void;
/** Accessible name of the drawer. */
label: string;
/** Header content left of the actions, e.g. the group of a task. */
header?: ReactNode;
/** Extra header buttons before the close button. */
actions?: ReactNode;
children: ReactNode;
/** Sticky footer, e.g. a comment composer. */
footer?: ReactNode;
width?: number;
className?: string;
}
/** Side sheet that slides in from the right, e.g. task details. */
export function Drawer({ open, onClose, label, header, actions, children, footer, width = 460, className }: DrawerProps) {
return (
<Sheet open={open} onOpenChange={(next) => !next && onClose?.()}>
<SheetContent
showCloseButton={false}
onOpenAutoFocus={focusFirstField}
aria-describedby={undefined}
className={className}
style={{ width }}
>
<SheetTitle className="sr-only">{label}</SheetTitle>
<SheetHeader>
<div className="min-w-0 flex-auto">{header}</div>
<div className="ml-auto flex gap-0.5">
{actions}
<SheetClose asChild>{closeButton}</SheetClose>
</div>
</SheetHeader>
<div className="flex flex-auto flex-col gap-[18px] overflow-y-auto px-5 pt-[18px] pb-6">{children}</div>
{footer && <SheetFooter>{footer}</SheetFooter>}
</SheetContent>
</Sheet>
);
}
+69 -50
View File
@@ -1,10 +1,24 @@
import type { Meta, StoryObj } from '@storybook/react'; import type { Meta, StoryObj } from '@storybook/react';
import { Search } from 'lucide-react'; import { Search } from 'lucide-react';
import { useState } from 'react'; import { useState } from 'react';
import { Field, Input, PasswordInput, Select, Textarea } from './Field'; import {
Field,
FieldDescription,
FieldError,
FieldHeader,
FieldLabel,
FieldNote,
Input,
InputGroup,
InputGroupAddon,
PasswordInput,
Select,
SelectOption,
Textarea,
} from './Field';
const meta: Meta<typeof Input> = { const meta: Meta<typeof Input> = {
title: 'Formulare/Felder', title: 'Forms/Field',
component: Input, component: Input,
args: { placeholder: 'du@beispiel.at', size: 'lg' }, args: { placeholder: 'du@beispiel.at', size: 'lg' },
argTypes: { size: { control: 'inline-radio', options: ['md', 'lg'] } }, argTypes: { size: { control: 'inline-radio', options: ['md', 'lg'] } },
@@ -14,82 +28,87 @@ export default meta;
type Story = StoryObj<typeof Input>; type Story = StoryObj<typeof Input>;
export const Eingabe: Story = {}; export const Basic: Story = {};
export const MitLabel: Story = { export const WithLabelAndError: Story = {
name: 'Mit Label & Fehler',
render: function Render() { render: function Render() {
const [email, setEmail] = useState('niklas@'); const [email, setEmail] = useState('niklas@');
const invalid = !/^\S+@\S+\.\S+$/.test(email); const invalid = !/^\S+@\S+\.\S+$/.test(email);
return ( return (
<div className="flex flex-col gap-[18px]"> <div className="flex flex-col gap-[18px]">
<Field label="E-Mail" error={invalid ? 'Bitte gib eine gültige E-Mail-Adresse ein.' : undefined}> <Field>
{({ id, describedBy, invalid: inv }) => ( <FieldLabel>E-Mail</FieldLabel>
<Input <Input
id={id} size="lg"
size="lg" type="text"
type="text" autoComplete="email"
autoComplete="email" placeholder="du@beispiel.at"
placeholder="du@beispiel.at" value={email}
value={email} onChange={(e) => setEmail(e.target.value)}
onChange={(e) => setEmail(e.target.value)} />
invalid={inv} {invalid && <FieldError>Bitte gib eine gültige E-Mail-Adresse ein.</FieldError>}
aria-describedby={describedBy}
/>
)}
</Field> </Field>
<Field label="Passwort" labelAside={<a href="#">Passwort vergessen?</a>}> <Field>
{({ id }) => <PasswordInput id={id} size="lg" autoComplete="current-password" defaultValue="geheim123" />} <FieldHeader>
<FieldLabel>Passwort</FieldLabel>
<a href="#">Passwort vergessen?</a>
</FieldHeader>
<PasswordInput size="lg" autoComplete="current-password" defaultValue="geheim123" />
</Field> </Field>
<Field label="E-Mail" hint="Wird für die Anmeldung und Benachrichtigungen verwendet."> <Field>
{({ id, describedBy }) => <Input id={id} defaultValue="niklas@beispiel.at" aria-describedby={describedBy} />} <FieldLabel>E-Mail</FieldLabel>
<Input defaultValue="niklas@beispiel.at" />
<FieldDescription>Wird für die Anmeldung und Benachrichtigungen verwendet.</FieldDescription>
</Field> </Field>
</div> </div>
); );
}, },
}; };
export const Suche: Story = { export const WithIcon: Story = {
render: () => <Input placeholder="Filtern …" leadingIcon={<Search size={16} strokeWidth={1.75} />} aria-label="Aufgaben filtern" />, render: () => (
<InputGroup>
<InputGroupAddon>
<Search size={16} strokeWidth={1.75} />
</InputGroupAddon>
<Input placeholder="Filtern …" aria-label="Aufgaben filtern" />
</InputGroup>
),
}; };
export const Auswahl: Story = { export const SelectBox: Story = {
render: () => ( render: () => (
<div className="flex flex-col gap-4"> <div className="flex flex-col gap-4">
<Select <Select aria-label="Gruppe">
aria-label="Gruppe" <SelectOption value="all">Alle Gruppen</SelectOption>
options={[ <SelectOption value="swe">SWE · Collabry</SelectOption>
{ value: 'all', label: 'Alle Gruppen' }, <SelectOption value="db">Datenbanken Übung</SelectOption>
{ value: 'swe', label: 'SWE · Collabry' }, <SelectOption value="mk">Marketing Seminar</SelectOption>
{ value: 'db', label: 'Datenbanken Übung' }, </Select>
{ value: 'mk', label: 'Marketing Seminar' }, <Select aria-label="Sprache" size="settings" className="w-[220px]">
]} <SelectOption value="de">Deutsch</SelectOption>
/> <SelectOption value="en">English</SelectOption>
<Select </Select>
aria-label="Sprache"
size="settings"
className="w-[220px]"
options={[
{ value: 'de', label: 'Deutsch' },
{ value: 'en', label: 'English' },
]}
/>
</div> </div>
), ),
}; };
export const Textfeld: Story = { export const TextArea: Story = {
render: () => ( render: () => (
<Field label="Beschreibung" labelNote="(optional)"> <Field>
{({ id }) => <Textarea id={id} rows={4} placeholder="Details, Links oder Akzeptanzkriterien …" />} <FieldLabel>
Beschreibung <FieldNote>(optional)</FieldNote>
</FieldLabel>
<Textarea rows={4} placeholder="Details, Links oder Akzeptanzkriterien …" />
</Field> </Field>
), ),
}; };
export const Datum: Story = { export const DateInput: Story = {
render: () => ( render: () => (
<Field label="Fällig am"> <Field>
{({ id }) => <Input id={id} type="date" defaultValue="2026-11-04" />} <FieldLabel>Fällig am</FieldLabel>
<Input type="date" defaultValue="2026-11-04" />
</Field> </Field>
), ),
}; };
+221 -140
View File
@@ -1,11 +1,12 @@
import { import {
forwardRef, createContext,
useCallback,
useContext,
useId, useId,
useLayoutEffect,
useMemo,
useState, useState,
type InputHTMLAttributes, type ComponentProps,
type ReactNode,
type SelectHTMLAttributes,
type TextareaHTMLAttributes,
} from 'react'; } from 'react';
import { AlertCircle, Eye, EyeOff } from 'lucide-react'; import { AlertCircle, Eye, EyeOff } from 'lucide-react';
import { cn } from '../../lib/cn'; import { cn } from '../../lib/cn';
@@ -14,156 +15,236 @@ import { Label } from '../ui/label';
import { NativeSelect, NativeSelectOption } from '../ui/native-select'; import { NativeSelect, NativeSelectOption } from '../ui/native-select';
import { Textarea as UiTextarea } from '../ui/textarea'; import { Textarea as UiTextarea } from '../ui/textarea';
export type FieldSize = 'md' | 'lg'; /* ---------------------------------------------------------------- Field */
const heights: Record<FieldSize, string> = { md: 'h-[38px]', lg: 'h-[42px]' };
export interface InputProps extends Omit<InputHTMLAttributes<HTMLInputElement>, 'size'> { interface FieldContextValue {
invalid?: boolean; id: string;
/** 38px (filters, dialogs) or 42px (auth forms). */ invalid: boolean;
size?: FieldSize; describedBy?: string;
/** Icon inside the field on the left, e.g. a search glass. */ register: (messageId: string, isError: boolean) => () => void;
leadingIcon?: ReactNode;
/** Element inside the field on the right, e.g. a reveal button. */
trailing?: ReactNode;
} }
export const Input = forwardRef<HTMLInputElement, InputProps>(function Input( const FieldContext = createContext<FieldContextValue | null>(null);
{ invalid, size = 'md', leadingIcon, trailing, className, ...props },
ref, /**
) { * Props a control needs to join the surrounding `Field`: `id`, `aria-describedby`
const input = ( * and `aria-invalid`. Explicit props win. Use it to make your own controls field-aware.
<UiInput */
ref={ref} export function useFieldControl<P extends { id?: string; 'aria-describedby'?: string; 'aria-invalid'?: unknown }>(
aria-invalid={invalid || undefined} props: P,
): P {
const field = useContext(FieldContext);
if (!field) return props;
return {
...props,
id: props.id ?? field.id,
'aria-describedby': props['aria-describedby'] ?? field.describedBy,
'aria-invalid': props['aria-invalid'] ?? (field.invalid || undefined),
};
}
export interface FieldProps extends ComponentProps<'div'> {
/** Marks the control invalid. Rendering a `FieldError` does this too. */
invalid?: boolean;
/** `horizontal` puts control and label side by side (checkboxes). */
orientation?: 'vertical' | 'horizontal';
}
/**
* Groups a label, one control and its messages, and wires ids and ARIA between them.
*
* <Field>
* <FieldLabel>E-Mail</FieldLabel>
* <Input />
* {error && <FieldError>{error}</FieldError>}
* </Field>
*/
export function Field({ invalid, orientation = 'vertical', className, ...props }: FieldProps) {
const id = useId();
const [messages, setMessages] = useState<{ id: string; error: boolean }[]>([]);
const register = useCallback((messageId: string, error: boolean) => {
setMessages((m) => [...m, { id: messageId, error }]);
return () => setMessages((m) => m.filter((x) => x.id !== messageId));
}, []);
const value = useMemo<FieldContextValue>(
() => ({
id,
invalid: invalid ?? messages.some((m) => m.error),
describedBy: messages.map((m) => m.id).join(' ') || undefined,
register,
}),
[id, invalid, messages, register],
);
return (
<FieldContext value={value}>
<div
role="group"
data-slot="field"
data-orientation={orientation}
data-invalid={value.invalid || undefined}
className={cn(
'group/field flex min-w-0 gap-1.5',
orientation === 'vertical' ? 'flex-col' : 'flex-row items-center gap-2.5',
className,
)}
{...props}
/>
</FieldContext>
);
}
/** Row above the control: the label and something aligned right, e.g. "Passwort vergessen?". */
export function FieldHeader({ className, ...props }: ComponentProps<'div'>) {
return (
<div
data-slot="field-header"
className={cn('flex items-baseline justify-between gap-3 text-sm', className)}
{...props}
/>
);
}
export function FieldLabel({ className, ...props }: ComponentProps<typeof Label>) {
const field = useContext(FieldContext);
return (
<Label
htmlFor={field?.id}
className={cn( className={cn(
heights[size], 'text-sm font-bold group-data-[orientation=horizontal]/field:cursor-pointer group-data-[orientation=horizontal]/field:text-base group-data-[orientation=horizontal]/field:font-normal group-data-[orientation=horizontal]/field:text-fg-4',
leadingIcon && 'pl-[34px]', className,
trailing && 'pr-12',
!leadingIcon && !trailing && className,
)} )}
{...props} {...props}
/> />
); );
if (!leadingIcon && !trailing) return input; }
/** Small, muted text inside a label, e.g. "(optional)". */
export function FieldNote({ className, ...props }: ComponentProps<'span'>) {
return <span data-slot="field-note" className={cn('font-normal text-fg-subtle', className)} {...props} />;
}
function useMessageId(id: string | undefined, error: boolean) {
const field = useContext(FieldContext);
const ownId = useId();
const messageId = id ?? `${field?.id ?? ownId}-${error ? 'error' : 'description'}`;
const register = field?.register;
useLayoutEffect(() => register?.(messageId, error), [register, messageId, error]);
return messageId;
}
/** Hint under the control; linked to it with `aria-describedby`. */
export function FieldDescription({ id, className, ...props }: ComponentProps<'div'>) {
return ( return (
<span className={cn('relative flex items-center', className)}> <div
{leadingIcon && ( id={useMessageId(id, false)}
<span className="pointer-events-none absolute left-[11px] flex text-fg-subtle">{leadingIcon}</span> data-slot="field-description"
)} className={cn('text-xs text-fg-subtle', className)}
{input} {...props}
{trailing && <span className="absolute right-[5px] flex">{trailing}</span>} />
</span>
);
});
export const PasswordInput = forwardRef<HTMLInputElement, Omit<InputProps, 'type' | 'trailing'>>(
function PasswordInput(props, ref) {
const [visible, setVisible] = useState(false);
const label = visible ? 'Passwort verbergen' : 'Passwort anzeigen';
return (
<Input
ref={ref}
type={visible ? 'text' : 'password'}
trailing={
<button
type="button"
onClick={() => setVisible((v) => !v)}
aria-pressed={visible}
aria-label={label}
title={label}
className="flex h-8 w-8 items-center justify-center rounded-[7px] text-fg-subtle hover:bg-hover hover:text-fg"
>
{visible ? <EyeOff size={18} strokeWidth={1.75} /> : <Eye size={18} strokeWidth={1.75} />}
</button>
}
{...props}
/>
);
},
);
export interface TextareaProps extends TextareaHTMLAttributes<HTMLTextAreaElement> {
invalid?: boolean;
}
export const Textarea = forwardRef<HTMLTextAreaElement, TextareaProps>(function Textarea(
{ invalid, rows = 3, ...props },
ref,
) {
return <UiTextarea ref={ref} rows={rows} aria-invalid={invalid || undefined} {...props} />;
});
export interface SelectOption {
value: string;
label: string;
}
export interface SelectProps extends Omit<SelectHTMLAttributes<HTMLSelectElement>, 'size'> {
options: SelectOption[];
invalid?: boolean;
size?: FieldSize | 'settings';
}
/** Native select with the design's chevron. */
export const Select = forwardRef<HTMLSelectElement, SelectProps>(function Select(
{ options, invalid, size = 'md', ...props },
ref,
) {
return (
<NativeSelect ref={ref} size={size} aria-invalid={invalid || undefined} {...props}>
{options.map((o) => (
<NativeSelectOption key={o.value} value={o.value}>
{o.label}
</NativeSelectOption>
))}
</NativeSelect>
);
});
export interface FieldProps {
label: ReactNode;
/** Small, muted text after the label, e.g. "(optional)". */
labelNote?: ReactNode;
/** Element aligned right of the label, e.g. "Passwort vergessen?". */
labelAside?: ReactNode;
hint?: ReactNode;
error?: ReactNode;
className?: string;
/** Receives the generated ids so the control can wire up label and messages. */
children: (ids: { id: string; describedBy?: string; invalid: boolean }) => ReactNode;
}
/** Label, control and message stacked with the design's 6px rhythm. */
export function Field({ label, labelNote, labelAside, hint, error, className, children }: FieldProps) {
const id = useId();
const msgId = `${id}-msg`;
const hasMsg = Boolean(error || hint);
return (
<div className={cn('flex min-w-0 flex-col gap-1.5', className)}>
<div className="flex items-baseline justify-between gap-3">
<Label htmlFor={id} className="text-sm font-bold">
{label}
{labelNote && <span className="font-normal text-fg-subtle"> {labelNote}</span>}
</Label>
{labelAside && <span className="text-sm">{labelAside}</span>}
</div>
{children({ id, describedBy: hasMsg ? msgId : undefined, invalid: Boolean(error) })}
{error ? (
<FieldError id={msgId}>{error}</FieldError>
) : hint ? (
<div id={msgId} className="text-xs text-fg-subtle">
{hint}
</div>
) : null}
</div>
); );
} }
export function FieldError({ id, children }: { id?: string; children: ReactNode }) { /** Error under the control; marks the field invalid while rendered. */
export function FieldError({ id, className, children, ...props }: ComponentProps<'div'>) {
return ( return (
<div id={id} className="flex items-center gap-1.5 text-xs text-danger-fg"> <div
id={useMessageId(id, true)}
data-slot="field-error"
className={cn('flex items-center gap-1.5 text-xs text-danger-fg', className)}
{...props}
>
<AlertCircle size={14} strokeWidth={1.75} aria-hidden="true" className="flex-none" /> <AlertCircle size={14} strokeWidth={1.75} aria-hidden="true" className="flex-none" />
{children} {children}
</div> </div>
); );
} }
/* ---------------------------------------------------------------- Controls */
export type FieldSize = 'md' | 'lg';
const heights: Record<FieldSize, string> = { md: 'h-[38px]', lg: 'h-[42px]' };
export interface InputProps extends Omit<ComponentProps<'input'>, 'size'> {
/** 38px (filters, dialogs) or 42px (auth forms). */
size?: FieldSize;
}
export function Input({ size = 'md', className, ...props }: InputProps) {
return <UiInput className={cn(heights[size], className)} {...useFieldControl(props)} />;
}
/** Wraps an `Input` with addons inside the field: icons on the left, buttons on the right. */
export function InputGroup({ className, ...props }: ComponentProps<'div'>) {
return (
<div
data-slot="input-group"
className={cn(
'relative flex items-center has-[>[data-align=start]]:[&>input]:pl-[34px] has-[>[data-align=end]]:[&>input]:pr-12',
className,
)}
{...props}
/>
);
}
export interface InputGroupAddonProps extends ComponentProps<'span'> {
/** `start`: decorative icon on the left. `end`: interactive element on the right. */
align?: 'start' | 'end';
}
export function InputGroupAddon({ align = 'start', className, ...props }: InputGroupAddonProps) {
return (
<span
data-slot="input-group-addon"
data-align={align}
className={cn(
'absolute flex',
align === 'start' ? 'pointer-events-none left-[11px] text-fg-subtle' : 'right-[5px]',
className,
)}
{...props}
/>
);
}
/** Small square button for an `InputGroupAddon align="end"`. */
export function InputGroupButton({ className, type = 'button', ...props }: ComponentProps<'button'>) {
return (
<button
type={type}
data-slot="input-group-button"
className={cn(
'flex h-8 w-8 items-center justify-center rounded-[7px] text-fg-subtle hover:bg-hover hover:text-fg focus-visible:shadow-focus focus-visible:outline-none',
className,
)}
{...props}
/>
);
}
/** Password input with a show/hide button. `className` goes to the wrapping `InputGroup`. */
export function PasswordInput({ className, ...props }: Omit<InputProps, 'type'>) {
const [visible, setVisible] = useState(false);
const label = visible ? 'Passwort verbergen' : 'Passwort anzeigen';
return (
<InputGroup className={className}>
<Input type={visible ? 'text' : 'password'} {...props} />
<InputGroupAddon align="end">
<InputGroupButton onClick={() => setVisible((v) => !v)} aria-pressed={visible} aria-label={label} title={label}>
{visible ? <EyeOff size={18} strokeWidth={1.75} /> : <Eye size={18} strokeWidth={1.75} />}
</InputGroupButton>
</InputGroupAddon>
</InputGroup>
);
}
export function Textarea({ rows = 3, ...props }: ComponentProps<'textarea'>) {
return <UiTextarea rows={rows} {...useFieldControl(props)} />;
}
/** Native select with the design's chevron. Children are `SelectOption`s; `className` sizes the wrapper. */
export function Select(props: ComponentProps<typeof NativeSelect>) {
return <NativeSelect {...useFieldControl(props)} />;
}
export const SelectOption = NativeSelectOption;
+207 -64
View File
@@ -1,98 +1,241 @@
import type { Meta, StoryObj } from '@storybook/react'; import type { Meta, StoryObj } from '@storybook/react';
import { LogOut, Pencil, Plus, SquareArrowOutUpRight, Users } from 'lucide-react'; import {
CalendarClock,
ChevronRight,
LogOut,
MoreHorizontal,
Pencil,
Plus,
SquareArrowOutUpRight,
Users,
} from 'lucide-react';
import { useState } from 'react'; import { useState } from 'react';
import { groups, people } from '../../stories/fixtures'; import { groups, people, type GroupData } from '../../stories/fixtures';
import { AvatarGroup, PersonAvatar } from '../Avatar/Avatar';
import { CountBadge, RoleBadge, Swatch } from '../Badge/Badge';
import { Button, type ButtonState } from '../Button/Button'; import { Button, type ButtonState } from '../Button/Button';
import { Card, CardHeader } from '../Card/Card'; import { Card, CardAction, CardFrame, CardHeader, CardTitle } from '../Card/Card';
import { MenuItem, MenuLink, MenuSeparator } from '../Menu/Menu'; import { Menu, MenuContent, MenuItem, MenuSeparator, MenuTrigger } from '../Menu/Menu';
import { GroupCard, GroupRow, InviteBanner, NewGroupTile } from './Group'; import { ProgressBar } from '../Progress/Progress';
import {
GroupCard,
GroupCardDescription,
GroupCardFooter,
GroupCardHeader,
GroupCardHeading,
GroupCardIcon,
GroupCardMeta,
GroupCardProgress,
GroupCardProgressLabel,
GroupCardTitle,
GroupRow,
GroupRowHeader,
GroupRowLink,
GroupRowName,
GroupRowProgress,
GroupRowStats,
InviteBanner,
InviteBannerActions,
InviteBannerText,
NewGroupTile,
NewGroupTileDescription,
NewGroupTileIcon,
NewGroupTileTitle,
} from './Group';
const meta: Meta<typeof GroupCard> = { const meta: Meta<typeof GroupCard> = {
title: 'Gruppen/Gruppen', title: 'Groups/Group',
component: GroupCard, component: GroupCard,
args: { group: groups[0] },
argTypes: { group: { control: false }, menu: { control: false } },
}; };
export default meta; export default meta;
type Story = StoryObj<typeof GroupCard>; type Story = StoryObj<typeof GroupCard>;
const i = { size: 16, strokeWidth: 1.75 } as const; const i = { size: 16, strokeWidth: 1.75 } as const;
const pct = (g: GroupData) => (g.total ? Math.round((g.done / g.total) * 100) : 0);
const groupMenu = ( function GroupMenu({ name }: { name: string }) {
<> return (
<MenuLink href="#" icon={<SquareArrowOutUpRight {...i} />}> <Menu>
Gruppe öffnen <MenuTrigger asChild>
</MenuLink> <Button
<MenuItem icon={<Pencil {...i} />}>Bearbeiten</MenuItem> variant="ghost"
<MenuLink href="#" icon={<Users {...i} />}> size="sm"
Mitglieder verwalten iconOnly
</MenuLink> aria-label={`Aktionen für ${name}`}
<MenuSeparator /> className="text-fg-subtle data-[state=open]:bg-hover"
<MenuItem danger icon={<LogOut {...i} />}> >
Gruppe verlassen <MoreHorizontal size={16} strokeWidth={2.5} />
</MenuItem> </Button>
</> </MenuTrigger>
); <MenuContent aria-label={`Aktionen für ${name}`}>
<MenuItem asChild>
<a href="#">
<SquareArrowOutUpRight {...i} />
Gruppe öffnen
</a>
</MenuItem>
<MenuItem>
<Pencil {...i} />
Bearbeiten
</MenuItem>
<MenuItem asChild>
<a href="#">
<Users {...i} />
Mitglieder verwalten
</a>
</MenuItem>
<MenuSeparator />
<MenuItem variant="destructive">
<LogOut {...i} />
Gruppe verlassen
</MenuItem>
</MenuContent>
</Menu>
);
}
export const Karte: Story = { /** One `GroupData` as a `GroupCard`. */
args: { menu: groupMenu }, function ExampleGroupCard({ g }: { g: GroupData }) {
render: (args) => ( const p = pct(g);
<div className="max-w-[380px]"> return (
<GroupCard {...args} /> <GroupCard>
</div> <GroupCardHeader>
), <GroupCardIcon color={g.color} />
<GroupCardHeading>
<GroupCardTitle>
<a href="#">{g.name}</a>
</GroupCardTitle>
<RoleBadge role={g.role} />
</GroupCardHeading>
<GroupMenu name={g.name} />
</GroupCardHeader>
<GroupCardDescription>{g.description}</GroupCardDescription>
<GroupCardProgress>
<GroupCardProgressLabel>
<span>Fortschritt</span>
<span>
<strong>{p}%</strong> · {g.done}/{g.total} Aufgaben
</span>
</GroupCardProgressLabel>
<ProgressBar value={p} color={g.color} aria-label={`${p} % erledigt`} />
</GroupCardProgress>
<GroupCardFooter>
<GroupCardMeta className="flex-none gap-2">
<AvatarGroup max={4} size={26}>
{g.members.map((m) => (
<PersonAvatar key={m.name} person={m} size={26} />
))}
</AvatarGroup>
{g.members.length} Mitglieder
</GroupCardMeta>
{g.next && (
<GroupCardMeta>
<CalendarClock size={14} strokeWidth={1.75} aria-hidden="true" />
<span className="truncate">{g.next}</span>
</GroupCardMeta>
)}
</GroupCardFooter>
</GroupCard>
);
}
export const Single: Story = {
render: () => <ExampleGroupCard g={groups[0]} />,
decorators: [(Story) => <div className="max-w-[380px]">{Story()}</div>],
}; };
export const Uebersicht: Story = { export const Overview: Story = {
name: 'Übersicht',
render: () => ( render: () => (
<div className="grid grid-cols-[repeat(auto-fill,minmax(min(320px,100%),1fr))] items-stretch gap-5"> <div className="grid grid-cols-[repeat(auto-fill,minmax(min(320px,100%),1fr))] items-stretch gap-5">
{groups.map((g) => ( {groups.map((g) => (
<GroupCard key={g.id} group={g} menu={groupMenu} /> <ExampleGroupCard key={g.id} g={g} />
))} ))}
<NewGroupTile /> <NewGroupTile>
<NewGroupTileIcon />
<NewGroupTileTitle>Neue Gruppe erstellen</NewGroupTileTitle>
<NewGroupTileDescription>
Lade dein Team ein und behaltet Aufgaben und Deadlines gemeinsam im Blick.
</NewGroupTileDescription>
</NewGroupTile>
</div> </div>
), ),
}; };
export const Dashboardliste: Story = { export const DashboardList: Story = {
name: 'Dashboard: Meine Gruppen',
render: () => ( render: () => (
<Card aria-labelledby="h-groups" innerClassName="gap-2"> <CardFrame>
<CardHeader <Card asChild className="gap-2">
titleId="h-groups" <section aria-labelledby="h-groups">
title="Meine Gruppen" <CardHeader>
count={groups.length} <CardTitle id="h-groups">
actions={ Meine Gruppen <CountBadge>{groups.length}</CountBadge>
<Button variant="ghost" size="xs" iconOnly aria-label="Gruppe erstellen" className="text-fg-subtle"> </CardTitle>
<Plus size={16} strokeWidth={2} /> <CardAction>
</Button> <Button variant="ghost" size="xs" iconOnly aria-label="Gruppe erstellen" className="text-fg-subtle">
} <Plus size={16} strokeWidth={2} />
/> </Button>
<ul className="m-0 grid grid-cols-[repeat(auto-fit,minmax(min(280px,100%),1fr))] gap-x-10 p-0"> </CardAction>
{groups.map((g) => ( </CardHeader>
<GroupRow key={g.id} group={g} /> <ul className="m-0 grid grid-cols-[repeat(auto-fit,minmax(min(280px,100%),1fr))] gap-x-10 p-0">
))} {groups.map((g) => {
</ul> const p = pct(g);
</Card> return (
<GroupRow key={g.id}>
<GroupRowLink href="#">
<GroupRowHeader>
<Swatch color={g.color} size={10} />
<GroupRowName>{g.name}</GroupRowName>
<AvatarGroup>
{g.members.map((m) => (
<PersonAvatar key={m.name} person={m} size={22} />
))}
</AvatarGroup>
<ChevronRight size={16} strokeWidth={1.75} aria-hidden="true" />
</GroupRowHeader>
<GroupRowProgress>
<ProgressBar value={p} color={g.color} aria-label={`${g.name}: ${p} % erledigt`} />
<GroupRowStats>
<strong>{p}%</strong> · {g.done}/{g.total}
</GroupRowStats>
</GroupRowProgress>
</GroupRowLink>
</GroupRow>
);
})}
</ul>
</section>
</Card>
</CardFrame>
), ),
}; };
export const Einladung: Story = { export const Invite: Story = {
render: function Render() { render: function Render() {
const [state, setState] = useState<ButtonState>('idle'); const [state, setState] = useState<ButtonState>('idle');
return ( return (
<InviteBanner <InviteBanner>
from={people.KB} <PersonAvatar person={people.KB} size={36} aria-hidden="true" />
groupName="Statistik Projekt" <InviteBannerText>
acceptState={state} <strong>{people.KB.name}</strong> hat dich in die Gruppe <strong>„Statistik Projekt“</strong> eingeladen.
onAccept={() => { </InviteBannerText>
setState('loading'); <InviteBannerActions>
setTimeout(() => setState('success'), 900); <Button variant="secondary" disabled={state === 'loading'}>
setTimeout(() => setState('idle'), 1700); Ablehnen
}} </Button>
/> <Button
variant="primary"
state={state}
onClick={() => {
setState('loading');
setTimeout(() => setState('success'), 900);
setTimeout(() => setState('idle'), 1700);
}}
>
Beitreten
</Button>
</InviteBannerActions>
</InviteBanner>
); );
}, },
}; };
+260 -162
View File
@@ -1,188 +1,286 @@
import type { ReactNode } from 'react'; import { createContext, useContext, useId, type ComponentProps, type CSSProperties } from 'react';
import { CalendarClock, ChevronRight, MoreHorizontal, Plus, Users } from 'lucide-react'; import { Plus, Users } from 'lucide-react';
import { Avatar, AvatarStack, type Person } from '../Avatar/Avatar'; import { Slot } from 'radix-ui';
import { RoleBadge } from '../Badge/Badge'; import { cn } from '../../lib/cn';
import { Button } from '../Button/Button'; import { Card, CardFrame } from '../Card/Card';
import { Card } from '../Card/Card';
import { Menu } from '../Menu/Menu';
import { ProgressBar } from '../Progress/Progress';
export interface GroupData { /* ---------------------------------------------------------------- Row */
id: string;
name: string; /**
* Compact group entry on the dashboard.
*
* <GroupRow>
* <GroupRowLink href="…">
* <GroupRowHeader><Swatch size={10} …/><GroupRowName>…</GroupRowName><AvatarGroup>…</AvatarGroup><ChevronRight /></GroupRowHeader>
* <GroupRowProgress><ProgressBar …/><GroupRowStats><strong>56%</strong> · 9/16</GroupRowStats></GroupRowProgress>
* </GroupRowLink>
* </GroupRow>
*/
export function GroupRow({ className, ...props }: ComponentProps<'li'>) {
return <li data-slot="group-row" className={cn('list-none', className)} {...props} />;
}
export interface GroupRowLinkProps extends ComponentProps<'a'> {
asChild?: boolean;
}
export function GroupRowLink({ asChild, className, ...props }: GroupRowLinkProps) {
const Comp = asChild ? Slot.Root : 'a';
return (
<Comp
data-slot="group-row-link"
className={cn('-mx-2.5 block rounded-lg px-2.5 py-4 text-fg hover:bg-hover-row hover:text-fg', className)}
{...props}
/>
);
}
export function GroupRowHeader({ className, ...props }: ComponentProps<'div'>) {
return (
<div
data-slot="group-row-header"
className={cn('flex items-center gap-2.5 [&>svg]:flex-none [&>svg]:text-fg-faint', className)}
{...props}
/>
);
}
export function GroupRowName({ className, ...props }: ComponentProps<'span'>) {
return (
<span data-slot="group-row-name" className={cn('min-w-0 flex-auto truncate font-bold', className)} {...props} />
);
}
/** Bar and stats, indented under the name. */
export function GroupRowProgress({ className, ...props }: ComponentProps<'div'>) {
return (
<div
data-slot="group-row-progress"
className={cn('mt-3 flex items-center gap-3 pl-5 *:data-[slot=progress]:flex-auto', className)}
{...props}
/>
);
}
/** e.g. "<strong>56%</strong> · 9/16". */
export function GroupRowStats({ className, ...props }: ComponentProps<'div'>) {
return (
<div
data-slot="group-row-stats"
className={cn('w-[84px] flex-none text-right text-xs text-fg-muted tabular-nums [&_strong]:text-fg', className)}
{...props}
/>
);
}
/* ---------------------------------------------------------------- Card */
const GroupCardContext = createContext<string | undefined>(undefined);
/**
* Group overview card. Labelled by its `GroupCardTitle`. `className` goes to the frame.
*
* <GroupCard>
* <GroupCardHeader>
* <GroupCardIcon color={…} />
* <GroupCardHeading><GroupCardTitle><a href="…">…</a></GroupCardTitle><RoleBadge … /></GroupCardHeading>
* <Menu>…</Menu>
* </GroupCardHeader>
* <GroupCardDescription>…</GroupCardDescription>
* <GroupCardProgress>…</GroupCardProgress>
* <GroupCardFooter><GroupCardMeta>…</GroupCardMeta>…</GroupCardFooter>
* </GroupCard>
*/
export function GroupCard({ className, ...props }: ComponentProps<'article'>) {
const titleId = useId();
return (
<GroupCardContext value={titleId}>
<CardFrame className={className}>
<Card asChild padding="sm">
<article aria-labelledby={titleId} data-slot="group-card" {...props} />
</Card>
</CardFrame>
</GroupCardContext>
);
}
export function GroupCardHeader({ className, ...props }: ComponentProps<'div'>) {
return <div data-slot="group-card-header" className={cn('flex items-start gap-3', className)} {...props} />;
}
export interface GroupCardIconProps extends ComponentProps<'span'> {
color: string; color: string;
members: Person[];
done: number;
total: number;
description?: string;
role?: 'admin' | 'member';
/** Next deadline, e.g. "Nächste: Fr, 27. Nov". */
next?: string;
} }
const pct = (g: Pick<GroupData, 'done' | 'total'>) => (g.total ? Math.round((g.done / g.total) * 100) : 0); /** 40px tile tinted with the group color; shows a people icon unless you pass children. */
export function GroupCardIcon({ color, className, style, children, ...props }: GroupCardIconProps) {
export interface GroupRowProps {
group: GroupData;
href?: string;
}
/** Compact group entry with members and progress, used on the dashboard. */
export function GroupRow({ group: g, href = '#' }: GroupRowProps) {
const p = pct(g);
return ( return (
<li className="list-none"> <span
<a href={href} className="-mx-2.5 block rounded-lg px-2.5 py-4 text-fg hover:bg-hover-row hover:text-fg"> data-slot="group-card-icon"
<div className="flex items-center gap-2.5"> className={cn('box-border flex h-10 w-10 flex-none items-center justify-center rounded-[11px] border', className)}
<span className="h-2.5 w-2.5 flex-none rounded-[3px]" style={{ background: g.color }} /> style={
<span className="min-w-0 flex-auto truncate font-bold">{g.name}</span> {
<AvatarStack people={g.members} size={22} /> borderColor: `color-mix(in srgb, ${color} 45%, transparent)`,
<ChevronRight size={16} strokeWidth={1.75} aria-hidden="true" className="text-fg-faint" /> background: `color-mix(in srgb, ${color} 18%, transparent)`,
</div> color,
<div className="mt-3 flex items-center gap-3 pl-5"> ...style,
<ProgressBar value={p} color={g.color} label={`${g.name}: ${p} % erledigt`} className="flex-auto" /> } as CSSProperties
<div className="w-[84px] flex-none text-right text-xs text-fg-muted tabular-nums"> }
<strong className="text-fg">{p}%</strong> · {g.done}/{g.total} {...props}
</div> >
</div> {children ?? <Users size={18} strokeWidth={1.75} aria-hidden="true" />}
</a> </span>
</li>
); );
} }
export interface GroupCardProps { /** Title and role badge. */
group: GroupData; export function GroupCardHeading({ className, ...props }: ComponentProps<'div'>) {
href?: string; return (
/** Items of the "…" menu at the top right (`MenuItem`, `MenuLink`, `MenuSeparator`). */ <div
menu?: ReactNode; data-slot="group-card-heading"
className={cn('min-w-0 flex-auto [&>[data-slot=badge]]:mt-[5px]', className)}
{...props}
/>
);
} }
/** Group overview card on the Gruppen page. */ /** `h2`; put the group link inside. */
export function GroupCard({ group: g, href = '#', menu }: GroupCardProps) { export function GroupCardTitle({ className, ...props }: ComponentProps<'h2'>) {
const p = pct(g);
const headingId = `gc-${g.id}`;
return ( return (
<Card as="article" aria-labelledby={headingId} padding="sm"> <h2
<div className="flex items-start gap-3"> id={useContext(GroupCardContext)}
<span data-slot="group-card-title"
className="box-border flex h-10 w-10 flex-none items-center justify-center rounded-[11px] border" className={cn(
style={{ 'm-0 truncate text-[16px] leading-tight font-bold [&_a]:text-inherit [&_a:hover]:text-inherit',
borderColor: `color-mix(in srgb, ${g.color} 45%, transparent)`, className,
background: `color-mix(in srgb, ${g.color} 18%, transparent)`,
color: g.color,
}}
>
<Users size={18} strokeWidth={1.75} aria-hidden="true" />
</span>
<div className="min-w-0 flex-auto">
<h2 id={headingId} className="m-0 truncate text-[16px] leading-tight font-bold">
<a href={href} className="text-inherit hover:text-inherit">
{g.name}
</a>
</h2>
<RoleBadge role={g.role} className="mt-[5px]" />
</div>
{menu && (
<Menu
label={`Aktionen für ${g.name}`}
trigger={
<Button
variant="ghost"
size="sm"
iconOnly
aria-label={`Aktionen für ${g.name}`}
className="text-fg-subtle data-[state=open]:bg-hover"
>
<MoreHorizontal size={16} strokeWidth={2.5} />
</Button>
}
>
{menu}
</Menu>
)}
</div>
{g.description !== undefined && (
<p className="m-0 min-h-[39px] text-sm leading-normal text-fg-muted">{g.description}</p>
)} )}
<div> {...props}
<div className="flex items-baseline justify-between gap-2 text-xs text-fg-subtle"> />
<span>Fortschritt</span>
<span>
<strong className="text-sm text-fg">{p}%</strong> · {g.done}/{g.total} Aufgaben
</span>
</div>
<ProgressBar value={p} color={g.color} label={`${p} % erledigt`} className="mt-2" />
</div>
<div className="mt-auto flex items-center justify-between gap-3 border-t border-line-subtle pt-3.5">
<span className="flex items-center gap-2 text-xs text-fg-subtle">
<AvatarStack people={g.members} size={26} max={4} />
{g.members.length} Mitglieder
</span>
{g.next && (
<span className="flex min-w-0 items-center gap-1.5 text-xs text-fg-subtle">
<CalendarClock size={14} strokeWidth={1.75} aria-hidden="true" className="flex-none" />
<span className="truncate">{g.next}</span>
</span>
)}
</div>
</Card>
); );
} }
export interface NewGroupTileProps { export function GroupCardDescription({ className, ...props }: ComponentProps<'p'>) {
onClick?: () => void; return (
title?: string; <p
description?: string; data-slot="group-card-description"
className={cn('m-0 min-h-[39px] text-sm leading-normal text-fg-muted', className)}
{...props}
/>
);
} }
/** A `GroupCardProgressLabel` above a `ProgressBar`. */
export function GroupCardProgress({ className, ...props }: ComponentProps<'div'>) {
return <div data-slot="group-card-progress" className={cn('flex flex-col gap-2', className)} {...props} />;
}
/** "Fortschritt" on the left, "<strong>56%</strong> · 9/16 Aufgaben" on the right. */
export function GroupCardProgressLabel({ className, ...props }: ComponentProps<'div'>) {
return (
<div
data-slot="group-card-progress-label"
className={cn(
'flex items-baseline justify-between gap-2 text-xs text-fg-subtle [&_strong]:text-sm [&_strong]:text-fg',
className,
)}
{...props}
/>
);
}
export function GroupCardFooter({ className, ...props }: ComponentProps<'div'>) {
return (
<div
data-slot="group-card-footer"
className={cn('mt-auto flex items-center justify-between gap-3 border-t border-line-subtle pt-3.5', className)}
{...props}
/>
);
}
/** Small muted item in the footer: members, next deadline. Wrap long text in `<span className="truncate">`. */
export function GroupCardMeta({ className, ...props }: ComponentProps<'span'>) {
return (
<span
data-slot="group-card-meta"
className={cn('flex min-w-0 items-center gap-1.5 text-xs text-fg-subtle [&>svg]:flex-none', className)}
{...props}
/>
);
}
/* ---------------------------------------------------------------- Others */
/** Dashed tile that starts creating a group. */ /** Dashed tile that starts creating a group. */
export function NewGroupTile({ export function NewGroupTile({ className, type = 'button', ...props }: ComponentProps<'button'>) {
onClick,
title = 'Neue Gruppe erstellen',
description = 'Lade dein Team ein und behaltet Aufgaben und Deadlines gemeinsam im Blick.',
}: NewGroupTileProps) {
return ( return (
<button <button
type="button" type={type}
onClick={onClick} data-slot="new-group-tile"
className="flex min-h-[260px] flex-col items-center justify-center gap-2.5 rounded-[18px] border-[1.5px] border-dashed border-line-heavy bg-transparent p-6 text-center text-fg-muted hover:border-line-hover hover:bg-hover-row" className={cn(
> 'flex min-h-[260px] flex-col items-center justify-center gap-2.5 rounded-[18px] border-[1.5px] border-dashed border-line-heavy bg-transparent p-6 text-center text-fg-muted hover:border-line-hover hover:bg-hover-row',
<span className="flex h-11 w-11 items-center justify-center rounded-xl border border-line-strong bg-surface text-fg"> className,
<Plus size={20} strokeWidth={1.75} aria-hidden="true" /> )}
</span> {...props}
<span className="font-bold text-fg">{title}</span> />
<span className="max-w-[240px] text-sm leading-normal">{description}</span>
</button>
); );
} }
export interface InviteBannerProps { /** Plus in a tile, unless you pass children. */
from: Person; export function NewGroupTileIcon({ className, children, ...props }: ComponentProps<'span'>) {
groupName: string;
onAccept?: () => void;
onDecline?: () => void;
acceptState?: 'idle' | 'loading' | 'success';
declineState?: 'idle' | 'loading' | 'success';
}
/** Pending group invitation, shown above the group grid. */
export function InviteBanner({ from, groupName, onAccept, onDecline, acceptState, declineState }: InviteBannerProps) {
const busy = acceptState === 'loading' || declineState === 'loading';
return ( return (
<Card as="div" padding="none" innerClassName="flex-row flex-wrap items-center gap-3.5 px-4 py-3.5"> <span
<Avatar person={from} size={36} aria-hidden="true" /> data-slot="new-group-tile-icon"
<div className="min-w-0 flex-[1_1_280px] text-base text-fg-muted"> className={cn(
<strong className="text-fg">{from.name}</strong> hat dich in die Gruppe <strong className="text-fg">„{groupName}“</strong>{' '} 'flex h-11 w-11 items-center justify-center rounded-xl border border-line-strong bg-surface text-fg',
eingeladen. className,
</div> )}
<div className="flex gap-2"> {...props}
<Button variant="secondary" onClick={onDecline} state={declineState} disabled={busy}> >
Ablehnen {children ?? <Plus size={20} strokeWidth={1.75} aria-hidden="true" />}
</Button> </span>
<Button variant="primary" onClick={onAccept} state={acceptState} disabled={busy}>
Beitreten
</Button>
</div>
</Card>
); );
} }
export function NewGroupTileTitle({ className, ...props }: ComponentProps<'span'>) {
return <span data-slot="new-group-tile-title" className={cn('font-bold text-fg', className)} {...props} />;
}
export function NewGroupTileDescription({ className, ...props }: ComponentProps<'span'>) {
return (
<span
data-slot="new-group-tile-description"
className={cn('max-w-[240px] text-sm leading-normal', className)}
{...props}
/>
);
}
/** Pending group invitation above the group grid: avatar, `InviteBannerText`, `InviteBannerActions`. */
export function InviteBanner({ className, ...props }: ComponentProps<'div'>) {
return (
<CardFrame className={className}>
<Card
padding="none"
data-slot="invite-banner"
className="flex-row flex-wrap items-center gap-3.5 px-4 py-3.5"
{...props}
/>
</CardFrame>
);
}
/** `<strong>` marks the person and group. */
export function InviteBannerText({ className, ...props }: ComponentProps<'div'>) {
return (
<div
data-slot="invite-banner-text"
className={cn('min-w-0 flex-[1_1_280px] text-base text-fg-muted [&_strong]:text-fg', className)}
{...props}
/>
);
}
export function InviteBannerActions({ className, ...props }: ComponentProps<'div'>) {
return <div data-slot="invite-banner-actions" className={cn('flex gap-2', className)} {...props} />;
}
+56 -29
View File
@@ -1,43 +1,70 @@
import type { Meta, StoryObj } from '@storybook/react'; import type { Meta, StoryObj } from '@storybook/react';
import { Plus, SquareCheck } from 'lucide-react'; import { Plus, SquareCheck } from 'lucide-react';
import { Button } from '../Button/Button'; import { Button } from '../Button/Button';
import { EmptyState, PageHeader } from './Layout'; import {
Empty,
EmptyAction,
EmptyDescription,
EmptyMedia,
EmptyTitle,
PageActions,
PageDescription,
PageEyebrow,
PageHeader,
PageHeading,
PageTitle,
} from './Layout';
const meta: Meta<typeof PageHeader> = { const meta: Meta<typeof PageHeader> = {
title: 'Grundlagen/Seitenkopf', title: 'Foundations/PageHeader',
component: PageHeader, component: PageHeader,
args: {
title: 'Aufgaben',
description: '7 Aufgaben in 3 Gruppen · 1 überfällig',
},
}; };
export default meta; export default meta;
type Story = StoryObj<typeof PageHeader>; type Story = StoryObj<typeof PageHeader>;
export const MitAktion: Story = { export const WithAction: Story = {
name: 'Mit Aktion',
args: {
actions: (
<Button variant="primary" size="lg" className="text-sm" icon={<Plus size={16} strokeWidth={2.25} />}>
Neue Aufgabe
</Button>
),
},
};
export const MitUeberzeile: Story = {
name: 'Mit Überzeile',
args: { eyebrow: 'Einstellungen', title: 'Allgemein', description: 'Darstellung, Sprache und wo Collabry für dich startet.' },
};
export const Leerzustand: Story = {
render: () => ( render: () => (
<EmptyState <PageHeader>
icon={<SquareCheck size={28} strokeWidth={1.75} />} <PageHeading>
title="Keine Aufgaben gefunden" <PageTitle>Aufgaben</PageTitle>
description="Passe die Filter an oder lege eine neue Aufgabe an." <PageDescription>7 Aufgaben in 3 Gruppen · 1 überfällig</PageDescription>
action={<Button variant="ghost" size="sm">Filter zurücksetzen</Button>} </PageHeading>
/> <PageActions>
<Button variant="primary" size="lg" className="text-sm">
<Plus size={16} strokeWidth={2.25} />
Neue Aufgabe
</Button>
</PageActions>
</PageHeader>
),
};
export const WithEyebrow: Story = {
render: () => (
<PageHeader>
<PageHeading>
<PageEyebrow>Einstellungen</PageEyebrow>
<PageTitle>Allgemein</PageTitle>
<PageDescription>Darstellung, Sprache und wo Collabry für dich startet.</PageDescription>
</PageHeading>
</PageHeader>
),
};
export const EmptyState: Story = {
render: () => (
<Empty>
<EmptyMedia>
<SquareCheck size={28} strokeWidth={1.75} />
</EmptyMedia>
<EmptyTitle>Keine Aufgaben gefunden</EmptyTitle>
<EmptyDescription>Passe die Filter an oder lege eine neue Aufgabe an.</EmptyDescription>
<EmptyAction>
<Button variant="ghost" size="sm">
Filter zurücksetzen
</Button>
</EmptyAction>
</Empty>
), ),
}; };
+71 -35
View File
@@ -1,50 +1,86 @@
import type { HTMLAttributes, ReactNode } from 'react'; import type { ComponentProps } from 'react';
import { cn } from '../../lib/cn'; import { cn } from '../../lib/cn';
export interface PageHeaderProps extends Omit<HTMLAttributes<HTMLElement>, 'title'> { /** Page title block: `PageHeading` on the left, `PageActions` on the right. */
title: ReactNode; export function PageHeader({ className, ...props }: ComponentProps<'header'>) {
/** Small label above the title, e.g. "Einstellungen". */
eyebrow?: ReactNode;
description?: ReactNode;
/** Right side, e.g. the primary page action. */
actions?: ReactNode;
}
/** Page title block: 28px black heading with optional eyebrow, description and actions. */
export function PageHeader({ title, eyebrow, description, actions, className, ...props }: PageHeaderProps) {
return ( return (
<header className={cn('flex flex-wrap items-end justify-between gap-x-6 gap-y-3', className)} {...props}> <header
<div> data-slot="page-header"
{eyebrow && <div className="text-sm font-bold text-fg-subtle">{eyebrow}</div>} className={cn('flex flex-wrap items-end justify-between gap-x-6 gap-y-3', className)}
<h1 className={cn('m-0 text-display font-black tracking-[-0.01em]', eyebrow && 'mt-1')}>{title}</h1> {...props}
{description && <p className="mt-1.5 mb-0 text-fg-muted">{description}</p>} />
</div>
{actions && <div className="flex items-center gap-2.5">{actions}</div>}
</header>
); );
} }
export interface EmptyStateProps { /** Eyebrow, title and description, stacked. */
icon?: ReactNode; export function PageHeading(props: ComponentProps<'div'>) {
title: ReactNode; return <div data-slot="page-heading" {...props} />;
description?: ReactNode; }
action?: ReactNode;
className?: string; /** Small label above the title, e.g. "Einstellungen". */
export function PageEyebrow({ className, ...props }: ComponentProps<'div'>) {
return <div data-slot="page-eyebrow" className={cn('mb-1 text-sm font-bold text-fg-subtle', className)} {...props} />;
}
/** 28px black page heading. */
export function PageTitle({ className, ...props }: ComponentProps<'h1'>) {
return (
<h1 data-slot="page-title" className={cn('m-0 text-display font-black tracking-[-0.01em]', className)} {...props} />
);
}
export function PageDescription({ className, ...props }: ComponentProps<'p'>) {
return <p data-slot="page-description" className={cn('mt-1.5 mb-0 text-fg-muted', className)} {...props} />;
}
export function PageActions({ className, ...props }: ComponentProps<'div'>) {
return <div data-slot="page-actions" className={cn('flex items-center gap-2.5', className)} {...props} />;
} }
/** Centered placeholder for empty lists and searches. */ /** Centered placeholder for empty lists and searches. */
export function EmptyState({ icon, title, description, action, className }: EmptyStateProps) { export function Empty({ className, ...props }: ComponentProps<'div'>) {
return ( return (
<div className={cn('flex flex-col items-center gap-2 px-4 py-12 text-center text-fg-subtle', className)}> <div
{icon && <span className="flex text-fg-faint">{icon}</span>} data-slot="empty"
<div className="font-bold text-fg">{title}</div> className={cn('flex flex-col items-center gap-2 px-4 py-12 text-center text-fg-subtle', className)}
{description && <div className="text-sm">{description}</div>} {...props}
{action && <div className="mt-1.5">{action}</div>} />
</div>
); );
} }
/** Icon above the title. */
export function EmptyMedia({ className, ...props }: ComponentProps<'span'>) {
return <span data-slot="empty-media" className={cn('flex text-fg-faint', className)} {...props} />;
}
export function EmptyTitle({ className, ...props }: ComponentProps<'div'>) {
return <div data-slot="empty-title" className={cn('font-bold text-fg', className)} {...props} />;
}
export function EmptyDescription({ className, ...props }: ComponentProps<'div'>) {
return <div data-slot="empty-description" className={cn('text-sm', className)} {...props} />;
}
export function EmptyAction({ className, ...props }: ComponentProps<'div'>) {
return <div data-slot="empty-action" className={cn('mt-1.5', className)} {...props} />;
}
/** Small section label inside lists ("Heute", "Früher"). */ /** Small section label inside lists ("Heute", "Früher"). */
export function SectionLabel({ className, ...props }: HTMLAttributes<HTMLDivElement>) { export function SectionLabel({ className, ...props }: ComponentProps<'div'>) {
return <div className={cn('px-2.5 pt-2.5 pb-1.5 text-xs font-bold text-fg-subtle', className)} {...props} />; return (
<div
data-slot="section-label"
className={cn('px-2.5 pt-2.5 pb-1.5 text-xs font-bold text-fg-subtle', className)}
{...props}
/>
);
}
/** "·" between items of a meta line. */
export function MetaSeparator({ className, children = '·', ...props }: ComponentProps<'span'>) {
return (
<span data-slot="meta-separator" aria-hidden="true" className={cn('text-fg-dim', className)} {...props}>
{children}
</span>
);
} }
+5 -1
View File
@@ -13,6 +13,10 @@ export interface LogoProps extends Omit<ImgHTMLAttributes<HTMLImageElement>, 'sr
export function Logo({ variant = 'wordmark', alt = 'Collabry', className, ...props }: LogoProps) { export function Logo({ variant = 'wordmark', alt = 'Collabry', className, ...props }: LogoProps) {
const size = const size =
variant === 'wordmark' ? 'h-[26px] w-auto' : variant === 'mark' ? 'h-[34px] w-[34px]' : 'h-auto w-[min(260px,100%)]'; variant === 'wordmark'
? 'h-[26px] w-auto'
: variant === 'mark'
? 'h-[34px] w-[34px]'
: 'h-auto w-[min(260px,100%)]';
return <img src={sources[variant]} alt={alt} className={cn('block flex-none', size, className)} {...props} />; return <img src={sources[variant]} alt={alt} className={cn('block flex-none', size, className)} {...props} />;
} }
+35 -21
View File
@@ -1,7 +1,7 @@
import type { Meta, StoryObj } from '@storybook/react'; import type { Meta, StoryObj } from '@storybook/react';
import { LogOut, MoreHorizontal, Pencil, SquareArrowOutUpRight, Users } from 'lucide-react'; import { LogOut, MoreHorizontal, Pencil, SquareArrowOutUpRight, Users } from 'lucide-react';
import { Button } from '../Button/Button'; import { Button } from '../Button/Button';
import { Menu, MenuItem, MenuLink, MenuSeparator } from './Menu'; import { Menu, MenuContent, MenuItem, MenuSeparator, MenuTrigger } from './Menu';
const icon = { size: 16, strokeWidth: 1.75 } as const; const icon = { size: 16, strokeWidth: 1.75 } as const;
@@ -13,30 +13,44 @@ export default meta;
type Story = StoryObj<typeof Menu>; type Story = StoryObj<typeof Menu>;
export const Gruppenmenue: Story = { export const GroupMenu: Story = {
name: 'Gruppenmenü',
render: () => ( render: () => (
<div className="flex h-[280px] justify-center"> <div className="flex h-[280px] justify-center">
<Menu <Menu defaultOpen>
label="Aktionen für SWE · Collabry" <MenuTrigger asChild>
defaultOpen <Button
trigger={ variant="ghost"
<Button variant="ghost" size="sm" iconOnly aria-label="Aktionen für SWE · Collabry" className="text-fg-subtle"> size="sm"
iconOnly
aria-label="Aktionen für SWE · Collabry"
className="text-fg-subtle"
>
<MoreHorizontal size={16} strokeWidth={2.5} /> <MoreHorizontal size={16} strokeWidth={2.5} />
</Button> </Button>
} </MenuTrigger>
> <MenuContent aria-label="Aktionen für SWE · Collabry">
<MenuLink href="#" icon={<SquareArrowOutUpRight {...icon} />}> <MenuItem asChild>
Gruppe öffnen <a href="#">
</MenuLink> <SquareArrowOutUpRight {...icon} />
<MenuItem icon={<Pencil {...icon} />}>Bearbeiten</MenuItem> Gruppe öffnen
<MenuLink href="#" icon={<Users {...icon} />}> </a>
Mitglieder verwalten </MenuItem>
</MenuLink> <MenuItem>
<MenuSeparator /> <Pencil {...icon} />
<MenuItem danger icon={<LogOut {...icon} />}> Bearbeiten
Gruppe verlassen </MenuItem>
</MenuItem> <MenuItem asChild>
<a href="#">
<Users {...icon} />
Mitglieder verwalten
</a>
</MenuItem>
<MenuSeparator />
<MenuItem variant="destructive">
<LogOut {...icon} />
Gruppe verlassen
</MenuItem>
</MenuContent>
</Menu> </Menu>
</div> </div>
), ),
+23 -115
View File
@@ -1,116 +1,24 @@
import { forwardRef, type AnchorHTMLAttributes, type ComponentProps, type HTMLAttributes, type ReactNode } from 'react'; /**
import { cn } from '../../lib/cn'; * Dropdown menu (Radix): keyboard navigation, typeahead, focus return.
import { *
DropdownMenu, * <Menu>
DropdownMenuContent, * <MenuTrigger asChild><Button …/></MenuTrigger>
DropdownMenuItem, * <MenuContent aria-label="Konto" size="lg">
DropdownMenuLabel, * <MenuLabel>…</MenuLabel>
DropdownMenuSeparator, * <MenuItem asChild><a href="…"><Settings />Einstellungen</a></MenuItem>
DropdownMenuTrigger, * <MenuItem onSelect={…}><Moon />Darstellung<MenuItemDetail>Dunkel</MenuItemDetail></MenuItem>
* <MenuSeparator />
* <MenuItem variant="destructive"><LogOut />Gruppe verlassen</MenuItem>
* </MenuContent>
* </Menu>
*/
export {
DropdownMenu as Menu,
DropdownMenuTrigger as MenuTrigger,
DropdownMenuContent as MenuContent,
DropdownMenuGroup as MenuGroup,
DropdownMenuItem as MenuItem,
DropdownMenuDetail as MenuItemDetail,
DropdownMenuLabel as MenuLabel,
DropdownMenuSeparator as MenuSeparator,
} from '../ui/dropdown-menu'; } from '../ui/dropdown-menu';
export interface MenuProps
extends Pick<ComponentProps<typeof DropdownMenu>, 'open' | 'defaultOpen' | 'onOpenChange' | 'modal'>,
Pick<ComponentProps<typeof DropdownMenuContent>, 'side' | 'align' | 'sideOffset' | 'alignOffset'> {
/** The element that opens the menu, usually a `Button`. Must forward its ref. */
trigger: ReactNode;
/** Accessible name, e.g. "Konto". */
label: string;
/** `lg` for the account menu (40px items), `md` for card menus (38px). */
size?: 'md' | 'lg';
/** Classes for the menu surface. */
className?: string;
children: ReactNode;
}
/** Dropdown menu with keyboard navigation, anchored to its trigger. */
export function Menu({
trigger,
label,
size = 'md',
className,
children,
open,
defaultOpen,
onOpenChange,
modal,
align = 'end',
...position
}: MenuProps) {
return (
<DropdownMenu open={open} defaultOpen={defaultOpen} onOpenChange={onOpenChange} modal={modal}>
<DropdownMenuTrigger asChild>{trigger}</DropdownMenuTrigger>
<DropdownMenuContent
aria-label={label}
data-size={size}
align={align}
className={cn('group/menu', size === 'lg' ? 'w-72 rounded-[14px] shadow-menu' : 'w-[220px]', className)}
{...position}
>
{children}
</DropdownMenuContent>
</DropdownMenu>
);
}
const itemClass =
'group-data-[size=lg]/menu:h-10 group-data-[size=lg]/menu:gap-3 group-data-[size=lg]/menu:rounded-[9px]';
interface ItemContentProps {
icon?: ReactNode;
/** Right-aligned detail, e.g. the current theme "Dunkel ›". */
detail?: ReactNode;
danger?: boolean;
children: ReactNode;
}
function ItemContent({ icon, detail, danger, children }: ItemContentProps) {
return (
<>
{icon && <span className={cn('flex', danger ? 'text-danger-fg' : 'text-fg-muted')}>{icon}</span>}
<span className="flex-auto">{children}</span>
{detail && <span className="flex items-center gap-1 text-sm text-fg-subtle">{detail}</span>}
</>
);
}
export interface MenuItemProps
extends Omit<ComponentProps<typeof DropdownMenuItem>, 'variant' | 'children'>,
Omit<ItemContentProps, 'children'> {
children: ReactNode;
}
/** Menu action. Use `onSelect` (or `onClick`); the menu closes afterwards. */
export function MenuItem({ icon, detail, danger, className, children, ...props }: MenuItemProps) {
return (
<DropdownMenuItem variant={danger ? 'destructive' : 'default'} className={cn(itemClass, className)} {...props}>
<ItemContent icon={icon} detail={detail} danger={danger}>
{children}
</ItemContent>
</DropdownMenuItem>
);
}
export interface MenuLinkProps extends AnchorHTMLAttributes<HTMLAnchorElement>, Omit<ItemContentProps, 'children'> {}
export const MenuLink = forwardRef<HTMLAnchorElement, MenuLinkProps>(function MenuLink(
{ icon, detail, danger, className, children, ...props },
ref,
) {
return (
<DropdownMenuItem asChild variant={danger ? 'destructive' : 'default'} className={cn(itemClass, className)}>
<a ref={ref} {...props}>
<ItemContent icon={icon} detail={detail} danger={danger}>
{children}
</ItemContent>
</a>
</DropdownMenuItem>
);
});
export const MenuSeparator = DropdownMenuSeparator;
/** Non-interactive header block, e.g. the signed-in user. */
export function MenuHeader(props: HTMLAttributes<HTMLDivElement>) {
return <DropdownMenuLabel {...props} />;
}
+66 -16
View File
@@ -1,9 +1,14 @@
import type { Meta, StoryObj } from '@storybook/react'; import type { Meta, StoryObj } from '@storybook/react';
import { Bell, Calendar, Kanban, LayoutDashboard, Search, SquareCheck, Sun, Users } from 'lucide-react';
import { me } from '../../stories/fixtures'; import { me } from '../../stories/fixtures';
import { MobileHeader, MobileTabBar } from './MobileNav'; import { PersonAvatar } from '../Avatar/Avatar';
import { IndicatorDot } from '../Badge/Badge';
import { Card, CardFrame } from '../Card/Card';
import { Logo } from '../Logo/Logo';
import { MobileHeader, MobileHeaderActions, MobileHeaderButton, MobileTab, MobileTabBar } from './MobileNav';
const meta: Meta<typeof MobileTabBar> = { const meta: Meta<typeof MobileTabBar> = {
title: 'Navigation/Mobil', title: 'Navigation/MobileNav',
component: MobileTabBar, component: MobileTabBar,
parameters: { layout: 'fullscreen', viewport: { defaultViewport: 'mobile2' } }, parameters: { layout: 'fullscreen', viewport: { defaultViewport: 'mobile2' } },
}; };
@@ -11,37 +16,82 @@ export default meta;
type Story = StoryObj<typeof MobileTabBar>; type Story = StoryObj<typeof MobileTabBar>;
export const Bildschirm: Story = { const tab = { size: 22, strokeWidth: 1.75, 'aria-hidden': true } as const;
render: (args) => ( const tabs = [
{ id: 'dashboard', label: 'Dashboard', icon: <LayoutDashboard {...tab} /> },
{ id: 'tasks', label: 'Aufgaben', icon: <SquareCheck {...tab} /> },
{ id: 'kanban', label: 'Kanban', icon: <Kanban {...tab} /> },
{ id: 'calendar', label: 'Kalender', icon: <Calendar {...tab} /> },
{ id: 'groups', label: 'Gruppen', icon: <Users {...tab} /> },
];
function Tabs({ active = 'dashboard' }: { active?: string }) {
return (
<MobileTabBar>
{tabs.map((t) => (
<MobileTab key={t.id} href="#" active={t.id === active}>
{t.icon}
{t.label}
</MobileTab>
))}
</MobileTabBar>
);
}
function ExampleHeader() {
return (
<MobileHeader>
<Logo className="h-6" />
<MobileHeaderActions>
<MobileHeaderButton aria-label="Helles Design aktivieren" title="Helles Design aktivieren">
<Sun size={18} strokeWidth={1.75} />
</MobileHeaderButton>
<MobileHeaderButton aria-label="Suchen">
<Search size={20} strokeWidth={1.75} />
</MobileHeaderButton>
<MobileHeaderButton asChild>
<a href="#" aria-label="Benachrichtigungen, 4 ungelesen">
<Bell size={20} strokeWidth={1.75} />
<IndicatorDot />
</a>
</MobileHeaderButton>
<MobileHeaderButton aria-label="Profil und Einstellungen" className="hover:bg-transparent">
<PersonAvatar person={me} size={30} aria-hidden="true" />
</MobileHeaderButton>
</MobileHeaderActions>
</MobileHeader>
);
}
export const Screen: Story = {
render: () => (
<div className="mx-auto flex h-[720px] w-full max-w-[390px] flex-col border-x border-line-subtle bg-app"> <div className="mx-auto flex h-[720px] w-full max-w-[390px] flex-col border-x border-line-subtle bg-app">
<MobileHeader user={me} unreadCount={4} /> <ExampleHeader />
<main className="flex flex-auto flex-col gap-4 overflow-y-auto px-4 pt-5 pb-7"> <main className="flex flex-auto flex-col gap-4 overflow-y-auto px-4 pt-5 pb-7">
<h1 className="m-0 text-display font-black">Hallo Niklas</h1> <h1 className="m-0 text-display font-black">Hallo Niklas</h1>
{Array.from({ length: 6 }, (_, i) => ( {Array.from({ length: 6 }, (_, i) => (
<div key={i} className="h-24 flex-none rounded-[18px] border border-line-frame bg-frame p-[5px]"> <CardFrame key={i} className="h-24 flex-none">
<div className="h-full rounded-[13px] border border-line bg-surface" /> <Card padding="none" />
</div> </CardFrame>
))} ))}
</main> </main>
<MobileTabBar {...args} /> <Tabs />
</div> </div>
), ),
}; };
export const Kopfzeile: Story = { export const Header: Story = {
render: () => ( render: () => (
<div className="max-w-[390px]"> <div className="max-w-[390px]">
<MobileHeader user={me} unreadCount={4} /> <ExampleHeader />
</div> </div>
), ),
}; };
export const Tableiste: Story = { export const TabBar: Story = {
name: 'Tab-Leiste', render: () => (
args: { activeId: 'kalender' },
render: (args) => (
<div className="max-w-[390px]"> <div className="max-w-[390px]">
<MobileTabBar {...args} /> <Tabs active="calendar" />
</div> </div>
), ),
}; };
+57 -92
View File
@@ -1,114 +1,79 @@
import type { ReactNode } from 'react'; import type { ComponentProps } from 'react';
import { Bell, Calendar, Kanban, LayoutDashboard, Moon, Search, SquareCheck, Sun, Users } from 'lucide-react'; import { Slot } from 'radix-ui';
import { cn } from '../../lib/cn'; import { cn } from '../../lib/cn';
import { Avatar, type Person } from '../Avatar/Avatar';
import { Logo } from '../Logo/Logo';
import type { NavItemData } from '../Sidebar/Sidebar';
const tabIcon = { size: 22, strokeWidth: 1.75, 'aria-hidden': true } as const; /** Sticky bottom navigation on phones. Children are `MobileTab`s. */
export function MobileTabBar({ className, ...props }: ComponentProps<'nav'>) {
export const defaultMobileTabs: NavItemData[] = [
{ id: 'dashboard', label: 'Dashboard', href: '#', icon: <LayoutDashboard {...tabIcon} /> },
{ id: 'aufgaben', label: 'Aufgaben', href: '#', icon: <SquareCheck {...tabIcon} /> },
{ id: 'kanban', label: 'Kanban', href: '#', icon: <Kanban {...tabIcon} /> },
{ id: 'kalender', label: 'Kalender', href: '#', icon: <Calendar {...tabIcon} /> },
{ id: 'gruppen', label: 'Gruppen', href: '#', icon: <Users {...tabIcon} /> },
];
export interface MobileTabBarProps {
items?: NavItemData[];
activeId?: string;
className?: string;
}
/** Sticky bottom navigation on phones. */
export function MobileTabBar({ items = defaultMobileTabs, activeId = 'dashboard', className }: MobileTabBarProps) {
return ( return (
<nav <nav
aria-label="Hauptnavigation" aria-label="Hauptnavigation"
data-slot="mobile-tab-bar"
className={cn( className={cn(
'sticky bottom-0 z-[5] box-border flex border-t border-line-shell bg-glass-2 px-1.5 pt-1.5 pb-[calc(8px+env(safe-area-inset-bottom))] backdrop-blur-md', 'sticky bottom-0 z-[5] box-border flex border-t border-line-shell bg-glass-2 px-1.5 pt-1.5 pb-[calc(8px+env(safe-area-inset-bottom))] backdrop-blur-md',
className, className,
)} )}
> {...props}
{items.map((it) => { />
const active = it.id === activeId;
return (
<a
key={it.id}
href={it.href}
aria-current={active ? 'page' : undefined}
className={cn(
'flex h-[52px] min-w-0 flex-1 basis-0 flex-col items-center justify-center gap-1 rounded-[10px] text-2xs font-bold',
active ? 'text-accent-fg hover:text-accent-fg' : 'text-fg-subtle hover:text-fg',
)}
>
{it.icon}
{it.label}
</a>
);
})}
</nav>
); );
} }
export interface MobileHeaderProps { export interface MobileTabProps extends ComponentProps<'a'> {
user: Person; active?: boolean;
theme?: 'dark' | 'light'; asChild?: boolean;
onToggleTheme?: () => void;
onSearch?: () => void;
unreadCount?: number;
notificationsHref?: string;
onProfile?: () => void;
/** Replaces the logo, e.g. a back button and page title. */
leading?: ReactNode;
className?: string;
} }
/** Sticky glass header on phones: logo, theme, search, notifications, profile. */ /** Icon over a label. */
export function MobileHeader({ export function MobileTab({ active, asChild, className, ...props }: MobileTabProps) {
user, const Comp = asChild ? Slot.Root : 'a';
theme = 'dark', return (
onToggleTheme, <Comp
onSearch, aria-current={active ? 'page' : undefined}
unreadCount = 0, data-slot="mobile-tab"
notificationsHref = '#', className={cn(
onProfile, 'flex h-[52px] min-w-0 flex-1 basis-0 flex-col items-center justify-center gap-1 rounded-[10px] text-2xs font-bold text-fg-subtle hover:text-fg',
leading, 'aria-[current=page]:text-accent-fg aria-[current=page]:hover:text-accent-fg',
className, className,
}: MobileHeaderProps) { )}
const btn = 'flex h-11 w-11 flex-none items-center justify-center rounded-[10px] text-fg-4 hover:bg-hover hover:text-fg'; {...props}
const themeLabel = theme === 'dark' ? 'Helles Design aktivieren' : 'Dunkles Design aktivieren'; />
);
}
/** Sticky glass header on phones: logo (or a back button and title), then `MobileHeaderActions`. */
export function MobileHeader({ className, ...props }: ComponentProps<'header'>) {
return ( return (
<header <header
data-slot="mobile-header"
className={cn( className={cn(
'sticky top-0 z-[5] box-border flex h-14 items-center gap-2.5 border-b border-line-shell bg-glass pr-2 pl-4 backdrop-blur-md', 'sticky top-0 z-[5] box-border flex h-14 items-center gap-2.5 border-b border-line-shell bg-glass pr-2 pl-4 backdrop-blur-md',
className, className,
)} )}
> {...props}
{leading ?? <Logo className="h-6" />} />
<div className="ml-auto flex items-center"> );
<button type="button" onClick={onToggleTheme} aria-label={themeLabel} title={themeLabel} className={btn}> }
{theme === 'dark' ? <Sun size={18} strokeWidth={1.75} /> : <Moon size={18} strokeWidth={1.75} />}
</button> export function MobileHeaderActions({ className, ...props }: ComponentProps<'div'>) {
<button type="button" onClick={onSearch} aria-label="Suchen" className={btn}> return <div data-slot="mobile-header-actions" className={cn('ml-auto flex items-center', className)} {...props} />;
<Search size={20} strokeWidth={1.75} /> }
</button>
<a href={notificationsHref} aria-label={`Benachrichtigungen, ${unreadCount} ungelesen`} className={cn(btn, 'relative')}> export interface MobileHeaderButtonProps extends ComponentProps<'button'> {
<Bell size={20} strokeWidth={1.75} /> asChild?: boolean;
{unreadCount > 0 && ( }
<span className="absolute top-[11px] right-3 h-[7px] w-[7px] rounded-full bg-danger shadow-[0_0_0_2px_var(--cl-app)]" />
)} /** 44px touch target for icons or the profile avatar. Holds an `IndicatorDot`. Give it an `aria-label`. */
</a> export function MobileHeaderButton({ asChild, className, ...props }: MobileHeaderButtonProps) {
<button const Comp = asChild ? Slot.Root : 'button';
type="button" return (
onClick={onProfile} <Comp
aria-label="Profil und Einstellungen" type={asChild ? undefined : 'button'}
className="flex h-11 w-11 items-center justify-center p-0" data-slot="mobile-header-button"
> className={cn(
<Avatar person={user} size={30} aria-hidden="true" /> 'relative flex h-11 w-11 flex-none items-center justify-center rounded-[10px] text-fg-4 hover:bg-hover hover:text-fg',
</button> '[--indicator-ring:var(--cl-app)] *:data-[slot=indicator-dot]:top-[11px] *:data-[slot=indicator-dot]:right-3',
</div> className,
</header> )}
{...props}
/>
); );
} }
@@ -1,69 +1,32 @@
import type { Meta, StoryObj } from '@storybook/react'; import type { Meta, StoryObj } from '@storybook/react';
import { useState } from 'react';
import { notificationsEarlier, notificationsToday } from '../../stories/fixtures'; import { notificationsEarlier, notificationsToday } from '../../stories/fixtures';
import type { ButtonState } from '../Button/Button'; import { NotificationEntry, NotificationsDemo } from '../../stories/examples';
import { NotificationItem, NotificationPanel, type NotificationData } from './Notifications'; import { NotificationList, NotificationPanel } from './Notifications';
const meta: Meta<typeof NotificationPanel> = { const meta: Meta<typeof NotificationPanel> = {
title: 'Overlays/Benachrichtigungen', title: 'Overlays/Notifications',
component: NotificationPanel, component: NotificationPanel,
}; };
export default meta; export default meta;
type Story = StoryObj<typeof NotificationPanel>; type Story = StoryObj<typeof NotificationPanel>;
/** Composition in `src/stories/examples.tsx`. */
export const Panel: Story = { export const Panel: Story = {
render: function Render() { render: () => <NotificationsDemo onClose={() => undefined} />,
const [today, setToday] = useState(notificationsToday);
const [earlier, setEarlier] = useState(notificationsEarlier);
const [markAll, setMarkAll] = useState<ButtonState>('idle');
const [accept, setAccept] = useState<ButtonState>('idle');
const read = (list: NotificationData[], id?: string) => list.map((n) => (!id || n.id === id ? { ...n, unread: false } : n));
return (
<NotificationPanel
today={today}
earlier={earlier}
onClose={() => undefined}
markAllState={markAll}
onMarkAllRead={() => {
setMarkAll('loading');
setTimeout(() => {
setToday((l) => read(l));
setEarlier((l) => read(l));
setMarkAll('idle');
}, 900);
}}
onOpen={(id) => {
setToday((l) => read(l, id));
setEarlier((l) => read(l, id));
}}
onAccept={(id) => {
setAccept('loading');
setTimeout(() => {
setToday((l) => l.map((n) => (n.id === id ? { ...n, unread: false, inviteResult: 'joined' } : n)));
setAccept('idle');
}, 900);
}}
onDecline={(id) => setToday((l) => l.map((n) => (n.id === id ? { ...n, unread: false, inviteResult: 'declined' } : n)))}
inviteStates={{ n3: { accept } }}
/>
);
},
}; };
export const AllesGelesen: Story = { export const AllRead: Story = {
name: 'Alles gelesen', render: () => <NotificationsDemo initialToday={[]} initialEarlier={[]} />,
args: { today: [], earlier: [] },
}; };
export const Eintraege: Story = { export const Items: Story = {
name: 'Einträge',
render: () => ( render: () => (
<ul className="m-0 flex w-[400px] flex-col gap-0.5 p-0"> <NotificationList className="w-[400px]">
{[...notificationsToday, ...notificationsEarlier].map((n) => ( {[...notificationsToday, ...notificationsEarlier].map((n) => (
<NotificationItem key={n.id} notification={n} /> <NotificationEntry key={n.id} n={n} />
))} ))}
<NotificationItem notification={{ ...notificationsToday[2], inviteResult: 'joined', unread: false }} /> <NotificationEntry n={{ ...notificationsToday[2], id: 'n3-joined', inviteResult: 'joined', unread: false }} />
</ul> </NotificationList>
), ),
}; };
+245 -267
View File
@@ -1,282 +1,260 @@
import { useState, type MouseEvent, type ReactNode } from 'react'; import { createContext, useContext, type ComponentProps } from 'react';
import { AlertCircle, CheckCircle2, Clock, X } from 'lucide-react'; import { Slot } from 'radix-ui';
import { cn } from '../../lib/cn'; import { cn } from '../../lib/cn';
import { Avatar, type Person } from '../Avatar/Avatar';
import { CountBadge, Swatch } from '../Badge/Badge';
import { Button, type ButtonState } from '../Button/Button';
import { SegmentedControl } from '../SegmentedControl/SegmentedControl';
export type NotificationKind = 'person' | 'deadline' | 'overdue'; /* ---------------------------------------------------------------- Panel */
export interface NotificationData { export interface NotificationPanelProps extends ComponentProps<'section'> {
id: string; /** Without the popover frame (full-screen page on mobile). */
kind: NotificationKind;
/** Who triggered it (for `person`). */
person?: Person;
/** Bold lead, e.g. "Lena Berger" or "Deadline morgen:". */
actor: string;
verb?: string;
/** Bold object, e.g. „Login & Registrierung umsetzen“. */
object?: string;
tail?: string;
/** Quoted comment text. */
quote?: string;
group?: { name: string; color: string };
time: string;
unread?: boolean;
/** Group invitation with Beitreten / Ablehnen. */
invite?: boolean;
/** Result after accepting or declining an invite. */
inviteResult?: 'joined' | 'declined';
}
export interface NotificationItemProps {
notification: NotificationData;
onOpen?: (id: string) => void;
onAccept?: (id: string) => void;
onDecline?: (id: string) => void;
acceptState?: ButtonState;
declineState?: ButtonState;
href?: string;
}
function KindIcon({ kind, person }: Pick<NotificationData, 'kind' | 'person'>) {
if (kind === 'person' && person) return <Avatar person={person} size={36} aria-hidden="true" />;
return (
<span
className={cn(
'box-border flex h-9 w-9 flex-none items-center justify-center rounded-[10px] border border-line-strong bg-elevated',
kind === 'deadline' ? 'text-warning-fg' : 'text-danger-fg',
)}
>
{kind === 'deadline' ? (
<Clock size={18} strokeWidth={1.75} aria-hidden="true" />
) : (
<AlertCircle size={18} strokeWidth={1.75} aria-hidden="true" />
)}
</span>
);
}
export function NotificationItem({
notification: n,
onOpen,
onAccept,
onDecline,
acceptState,
declineState,
href = '#',
}: NotificationItemProps) {
const busy = acceptState === 'loading' || declineState === 'loading';
return (
<li className={cn('list-none rounded-xl', n.unread ? 'bg-accent-soft' : 'bg-transparent')}>
<a
href={href}
onClick={(e: MouseEvent) => {
if (href === '#') e.preventDefault();
onOpen?.(n.id);
}}
className="flex items-start gap-3 rounded-xl py-3 pr-3 pl-2.5 text-fg hover:bg-hover-menu hover:text-fg"
>
<KindIcon kind={n.kind} person={n.person} />
<div className="min-w-0 flex-auto">
<div className="text-base leading-normal text-fg-muted">
<strong className="font-bold text-fg">{n.actor}</strong>
{n.verb && ` ${n.verb}`} {n.object && <strong className="font-bold text-fg">{n.object}</strong>}
{n.tail}
</div>
{n.quote && (
<div className="mt-2 rounded-lg bg-elevated px-2.5 py-2 text-sm leading-normal text-fg-4">{n.quote}</div>
)}
<div className="mt-1.5 flex flex-wrap items-center gap-x-[7px] gap-y-1 text-xs text-fg-subtle">
{n.group && (
<>
<Swatch color={n.group.color} />
<span>{n.group.name}</span>
<span className="text-fg-dim">·</span>
</>
)}
<span>{n.time}</span>
</div>
</div>
<span
aria-hidden="true"
className={cn('mt-1.5 h-2 w-2 flex-none rounded-full', n.unread ? 'bg-accent' : 'bg-transparent')}
/>
{n.unread && <span className="sr-only">Ungelesen</span>}
</a>
{n.invite && !n.inviteResult && (
<div className="flex gap-2 pr-3 pb-3 pl-[58px]">
<Button
variant="primary"
size="sm"
className="h-[34px] px-3.5 shadow-primary-flat"
state={acceptState}
disabled={busy}
onClick={() => onAccept?.(n.id)}
>
Beitreten
</Button>
<Button
variant="secondary"
size="sm"
className="h-[34px] px-3.5"
state={declineState}
disabled={busy}
onClick={() => onDecline?.(n.id)}
>
Ablehnen
</Button>
</div>
)}
{n.invite && n.inviteResult && (
<div
className={cn(
'flex items-center gap-1.5 pr-3 pb-3 pl-[58px] text-sm font-bold',
n.inviteResult === 'joined' ? 'text-success-fg' : 'text-fg-subtle',
)}
>
{n.inviteResult === 'joined' ? '✓ Du bist der Gruppe beigetreten' : 'Einladung abgelehnt'}
</div>
)}
</li>
);
}
export interface NotificationPanelProps {
today: NotificationData[];
earlier: NotificationData[];
onClose?: () => void;
onMarkAllRead?: () => void;
markAllState?: ButtonState;
onOpen?: (id: string) => void;
onAccept?: (id: string) => void;
onDecline?: (id: string) => void;
/** Loading/success feedback for invite buttons, by notification id. */
inviteStates?: Record<string, { accept?: ButtonState; decline?: ButtonState }>;
settingsHref?: string;
/** Extra classes; position the panel from the outside. */
className?: string;
/** Rendered without the popover frame (mobile full-screen page). */
bare?: boolean; bare?: boolean;
/** Footer slot replaces the default settings link. */
footer?: ReactNode;
} }
/** Notification popover: Alle / Ungelesen tabs, "Heute" and "Früher" sections. */ /**
export function NotificationPanel({ * Notification popover surface.
today, *
earlier, * <NotificationPanel>
onClose, * <NotificationPanelHeader>
onMarkAllRead, * <NotificationPanelBar><NotificationPanelTitle>…</NotificationPanelTitle><NotificationPanelActions>…</NotificationPanelActions></NotificationPanelBar>
markAllState, * <SegmentedControl …/>
onOpen, * </NotificationPanelHeader>
onAccept, * <NotificationPanelBody><SectionLabel>Heute</SectionLabel><NotificationList>…</NotificationList></NotificationPanelBody>
onDecline, * <NotificationPanelFooter>…</NotificationPanelFooter>
inviteStates = {}, * </NotificationPanel>
settingsHref = '#', */
className, export function NotificationPanel({ bare = false, className, ...props }: NotificationPanelProps) {
bare = false,
footer,
}: NotificationPanelProps) {
const [tab, setTab] = useState<'all' | 'unread'>('all');
const all = [...today, ...earlier];
const unread = all.filter((n) => n.unread).length;
const filter = (list: NotificationData[]) => (tab === 'unread' ? list.filter((n) => n.unread) : list);
const t = filter(today);
const e = filter(earlier);
const itemProps = { onOpen, onAccept, onDecline };
return ( return (
<section <section
aria-label="Benachrichtigungen" aria-label="Benachrichtigungen"
data-slot="notification-panel"
className={cn( className={cn(
'box-border flex flex-col overflow-hidden', 'box-border flex flex-col overflow-hidden',
!bare && 'max-h-[min(700px,calc(100vh-24px))] w-[400px] max-w-full rounded-2xl border border-line-strong bg-raised shadow-popover', !bare &&
'max-h-[min(700px,calc(100vh-24px))] w-[400px] max-w-full rounded-2xl border border-line-strong bg-raised shadow-popover',
className, className,
)} )}
> {...props}
<div className="flex flex-col gap-3 border-b border-line-divider pt-3.5 pr-2.5 pb-3 pl-4"> />
<div className="flex items-center gap-2"> );
<h2 className="m-0 text-md font-bold">Benachrichtigungen</h2> }
{unread > 0 && <CountBadge tone="accent">{unread}</CountBadge>}
<div className="ml-auto flex items-center gap-0.5"> export function NotificationPanelHeader({ className, ...props }: ComponentProps<'div'>) {
{onMarkAllRead && ( return (
<Button variant="ghost" size="sm" className="px-2.5" state={markAllState} onClick={onMarkAllRead}> <div
Alle gelesen data-slot="notification-panel-header"
</Button> className={cn('flex flex-col gap-3 border-b border-line-divider pt-3.5 pr-2.5 pb-3 pl-4', className)}
)} {...props}
{onClose && ( />
<Button variant="ghost" size="sm" iconOnly aria-label="Schließen" onClick={onClose} className="text-fg-subtle"> );
<X size={16} strokeWidth={1.75} /> }
</Button>
)} /** Title row: title, count, actions on the right. */
</div> export function NotificationPanelBar({ className, ...props }: ComponentProps<'div'>) {
</div> return <div data-slot="notification-panel-bar" className={cn('flex items-center gap-2', className)} {...props} />;
<div className="pr-1.5"> }
<SegmentedControl
label="Filter" export function NotificationPanelTitle({ className, ...props }: ComponentProps<'h2'>) {
fullWidth return <h2 data-slot="notification-panel-title" className={cn('m-0 text-md font-bold', className)} {...props} />;
value={tab} }
onChange={setTab}
options={[ export function NotificationPanelActions({ className, ...props }: ComponentProps<'div'>) {
{ value: 'all', label: 'Alle', count: all.length }, return (
{ value: 'unread', label: 'Ungelesen', count: unread }, <div
]} data-slot="notification-panel-actions"
/> className={cn('ml-auto flex items-center gap-0.5', className)}
</div> {...props}
</div> />
<div className="min-h-0 flex-auto overflow-y-auto px-1.5 pt-1 pb-2"> );
{t.length > 0 && ( }
<>
<div className="px-2.5 pt-2.5 pb-1.5 text-xs font-bold text-fg-subtle">Heute</div> /** Scrolling list area. */
<ul className="m-0 flex flex-col gap-0.5 p-0"> export function NotificationPanelBody({ className, ...props }: ComponentProps<'div'>) {
{t.map((n) => ( return (
<NotificationItem <div
key={n.id} data-slot="notification-panel-body"
notification={n} className={cn('min-h-0 flex-auto overflow-y-auto px-1.5 pt-1 pb-2', className)}
acceptState={inviteStates[n.id]?.accept} {...props}
declineState={inviteStates[n.id]?.decline} />
{...itemProps} );
/> }
))}
</ul> export function NotificationPanelFooter({ className, ...props }: ComponentProps<'div'>) {
</> return (
)} <div
{e.length > 0 && ( data-slot="notification-panel-footer"
<> className={cn('flex border-t border-line-divider px-3 py-2.5', className)}
<div className="px-2.5 pt-2.5 pb-1.5 text-xs font-bold text-fg-subtle">Früher</div> {...props}
<ul className="m-0 flex flex-col gap-0.5 p-0"> />
{e.map((n) => ( );
<NotificationItem }
key={n.id}
notification={n} /** Quiet link for the footer, e.g. "Benachrichtigungs-Einstellungen". */
acceptState={inviteStates[n.id]?.accept} export function NotificationPanelLink({ className, ...props }: ComponentProps<'a'>) {
declineState={inviteStates[n.id]?.decline} return (
{...itemProps} <a
/> data-slot="notification-panel-link"
))} className={cn(
</ul> 'flex h-8 items-center gap-2 rounded-lg px-2 text-sm font-bold text-fg-muted hover:bg-hover hover:text-fg',
</> className,
)} )}
{t.length + e.length === 0 && ( {...props}
<div className="flex flex-col items-center gap-2 px-4 py-12 text-center text-fg-subtle"> />
<CheckCircle2 size={28} strokeWidth={1.75} aria-hidden="true" className="text-success-fg" /> );
<div className="font-bold text-fg">Alles gelesen</div> }
<div className="text-sm">Neue Benachrichtigungen erscheinen hier.</div>
</div> /* ---------------------------------------------------------------- Items */
)}
</div> export function NotificationList({ className, ...props }: ComponentProps<'ul'>) {
<div className="flex border-t border-line-divider px-3 py-2.5"> return <ul data-slot="notification-list" className={cn('m-0 flex flex-col gap-0.5 p-0', className)} {...props} />;
{footer ?? ( }
<a
href={settingsHref} const NotificationContext = createContext({ unread: false });
className="flex h-8 items-center gap-2 rounded-lg px-2 text-sm font-bold text-fg-muted hover:bg-hover hover:text-fg"
> export interface NotificationItemProps extends ComponentProps<'li'> {
Benachrichtigungs-Einstellungen unread?: boolean;
</a> }
)}
</div> /**
</section> * One notification. Unread ones get a tint and a dot (`NotificationUnreadDot`).
*
* <NotificationItem unread>
* <NotificationLink href="…">
* <PersonAvatar …/> or <NotificationIcon tone="warning"><Clock /></NotificationIcon>
* <NotificationContent>
* <NotificationText><strong>Lena Berger</strong> hat dir … zugewiesen.</NotificationText>
* <NotificationQuote>…</NotificationQuote>
* <NotificationMeta><Swatch …/>SWE · Collabry<MetaSeparator />vor 12 Min.</NotificationMeta>
* </NotificationContent>
* <NotificationUnreadDot />
* </NotificationLink>
* <NotificationActions>…</NotificationActions>
* </NotificationItem>
*/
export function NotificationItem({ unread = false, className, ...props }: NotificationItemProps) {
return (
<NotificationContext value={{ unread }}>
<li
data-slot="notification-item"
data-unread={unread || undefined}
className={cn('list-none rounded-xl data-unread:bg-accent-soft', className)}
{...props}
/>
</NotificationContext>
);
}
export interface NotificationLinkProps extends ComponentProps<'a'> {
asChild?: boolean;
}
/** The clickable row: media, content, unread dot. */
export function NotificationLink({ asChild, className, ...props }: NotificationLinkProps) {
const Comp = asChild ? Slot.Root : 'a';
return (
<Comp
data-slot="notification-link"
className={cn(
'flex items-start gap-3 rounded-xl py-3 pr-3 pl-2.5 text-fg hover:bg-hover-menu hover:text-fg',
className,
)}
{...props}
/>
);
}
export interface NotificationIconProps extends ComponentProps<'span'> {
tone?: 'warning' | 'danger';
}
/** 36px tile for system notifications (deadline, overdue). For people use a 36px `PersonAvatar`. */
export function NotificationIcon({ tone = 'warning', className, ...props }: NotificationIconProps) {
return (
<span
data-slot="notification-icon"
className={cn(
'box-border flex h-9 w-9 flex-none items-center justify-center rounded-[10px] border border-line-strong bg-elevated',
tone === 'warning' ? 'text-warning-fg' : 'text-danger-fg',
className,
)}
{...props}
/>
);
}
export function NotificationContent({ className, ...props }: ComponentProps<'div'>) {
return <div data-slot="notification-content" className={cn('min-w-0 flex-auto', className)} {...props} />;
}
/** The sentence. `<strong>` marks the actor and object. */
export function NotificationText({ className, ...props }: ComponentProps<'div'>) {
return (
<div
data-slot="notification-text"
className={cn('text-base leading-normal text-fg-muted [&_strong]:font-bold [&_strong]:text-fg', className)}
{...props}
/>
);
}
/** Quoted comment text. */
export function NotificationQuote({ className, ...props }: ComponentProps<'div'>) {
return (
<div
data-slot="notification-quote"
className={cn('mt-2 rounded-lg bg-elevated px-2.5 py-2 text-sm leading-normal text-fg-4', className)}
{...props}
/>
);
}
/** Group and time, e.g. "■ SWE · Collabry · vor 12 Min.". */
export function NotificationMeta({ className, ...props }: ComponentProps<'div'>) {
return (
<div
data-slot="notification-meta"
className={cn('mt-1.5 flex flex-wrap items-center gap-x-[7px] gap-y-1 text-xs text-fg-subtle', className)}
{...props}
/>
);
}
/** Accent dot (and "Ungelesen" for screen readers) while the item is unread. Keeps its space when read. */
export function NotificationUnreadDot({ className, ...props }: ComponentProps<'span'>) {
const { unread } = useContext(NotificationContext);
return (
<>
<span
aria-hidden="true"
data-slot="notification-unread-dot"
className={cn('mt-1.5 h-2 w-2 flex-none rounded-full', unread ? 'bg-accent' : 'bg-transparent', className)}
{...props}
/>
{unread && <span className="sr-only">Ungelesen</span>}
</>
);
}
/** Buttons under the text, e.g. Beitreten / Ablehnen; aligned with the text. */
export function NotificationActions({ className, ...props }: ComponentProps<'div'>) {
return (
<div data-slot="notification-actions" className={cn('flex gap-2 pr-3 pb-3 pl-[58px]', className)} {...props} />
);
}
export interface NotificationResultProps extends ComponentProps<'div'> {
tone?: 'success' | 'muted';
}
/** Outcome that replaces the actions, e.g. "✓ Du bist der Gruppe beigetreten". */
export function NotificationResult({ tone = 'success', className, ...props }: NotificationResultProps) {
return (
<div
data-slot="notification-result"
className={cn(
'flex items-center gap-1.5 pr-3 pb-3 pl-[58px] text-sm font-bold',
tone === 'success' ? 'text-success-fg' : 'text-fg-subtle',
className,
)}
{...props}
/>
); );
} }
+18 -14
View File
@@ -1,28 +1,32 @@
import type { Meta, StoryObj } from '@storybook/react'; import type { Meta, StoryObj } from '@storybook/react';
import { swatches } from '../../lib/tokens'; import { swatches } from '../../lib/tokens';
import { ProgressBar, StatusProgress } from './Progress'; import { ProgressBar, StatusBar, StatusLegend, StatusProgress } from './Progress';
const meta: Meta<typeof StatusProgress> = { const meta: Meta<typeof StatusBar> = {
title: 'Anzeige/Fortschritt', title: 'Display/Progress',
component: StatusProgress, component: StatusBar,
args: { counts: { done: 9, review: 2, doing: 3, open: 2 }, legend: true }, args: { counts: { done: 9, review: 2, doing: 3, open: 2 } },
}; };
export default meta; export default meta;
type Story = StoryObj<typeof StatusProgress>; type Story = StoryObj<typeof StatusBar>;
export const NachStatus: Story = { export const ByStatus: Story = {
name: 'Nach Status', render: (args) => (
decorators: [(Story) => <div className="max-w-[640px]">{Story()}</div>], <StatusProgress className="max-w-[640px]">
<StatusBar counts={args.counts} />
<StatusLegend counts={args.counts} />
</StatusProgress>
),
}; };
export const Balken: Story = { export const Bar: Story = {
render: () => ( render: () => (
<div className="flex max-w-[480px] flex-col gap-4"> <div className="flex max-w-[480px] flex-col gap-4">
<ProgressBar value={56} color={swatches.violet} label="SWE · Collabry: 56 % erledigt" /> <ProgressBar value={56} color={swatches.violet} aria-label="SWE · Collabry: 56 % erledigt" />
<ProgressBar value={40} color={swatches.cyan} label="Datenbanken Übung: 40 % erledigt" /> <ProgressBar value={40} color={swatches.cyan} aria-label="Datenbanken Übung: 40 % erledigt" />
<ProgressBar value={86} color={swatches.pink} label="Marketing Seminar: 86 % erledigt" /> <ProgressBar value={86} color={swatches.pink} aria-label="Marketing Seminar: 86 % erledigt" />
<ProgressBar value={30} label="Akzentfarbe" /> <ProgressBar value={30} aria-label="Akzentfarbe" />
</div> </div>
), ),
}; };
+50 -42
View File
@@ -1,25 +1,20 @@
import type { CSSProperties, HTMLAttributes } from 'react'; import type { ComponentProps, CSSProperties } from 'react';
import { cn } from '../../lib/cn'; import { cn } from '../../lib/cn';
import { Progress } from '../ui/progress';
import { taskStatusBar, taskStatusLabel, taskStatusOrder, type TaskStatus } from '../../lib/tokens'; import { taskStatusBar, taskStatusLabel, taskStatusOrder, type TaskStatus } from '../../lib/tokens';
import { Progress } from '../ui/progress';
export interface ProgressBarProps extends Omit<HTMLAttributes<HTMLDivElement>, 'dir'> { export interface ProgressBarProps extends ComponentProps<typeof Progress> {
/** 0–100. */ /** 0–100. */
value: number; value: number;
/** Fill color, usually the group color. Defaults to the accent. */ /** Fill color, usually the group color. Defaults to the accent. */
color?: string; color?: string;
/** Accessible label, e.g. "SWE · Collabry: 62 % erledigt". */
label?: string;
} }
/** Thin 6px track used for group progress. */ /** Thin 6px track used for group progress. Give it an `aria-label`. */
export function ProgressBar({ value, color, label, className, style, ...props }: ProgressBarProps) { export function ProgressBar({ value, color, style, ...props }: ProgressBarProps) {
const pct = Math.max(0, Math.min(100, value));
return ( return (
<Progress <Progress
value={pct} value={Math.max(0, Math.min(100, value))}
aria-label={label}
className={className}
style={{ '--progress-fill': color, ...style } as CSSProperties} style={{ '--progress-fill': color, ...style } as CSSProperties}
{...props} {...props}
/> />
@@ -28,41 +23,54 @@ export function ProgressBar({ value, color, label, className, style, ...props }:
export type StatusCounts = Partial<Record<TaskStatus, number>>; export type StatusCounts = Partial<Record<TaskStatus, number>>;
export interface StatusProgressProps extends HTMLAttributes<HTMLDivElement> { const segmentsOf = (counts: StatusCounts) => {
const total = taskStatusOrder.reduce((n, k) => n + (counts[k] ?? 0), 0);
return taskStatusOrder
.filter((k) => (counts[k] ?? 0) > 0)
.map((k) => ({ key: k, count: counts[k] ?? 0, width: ((counts[k] ?? 0) / total) * 100 }));
};
export interface StatusCountsProps extends ComponentProps<'div'> {
counts: StatusCounts; counts: StatusCounts;
/** Show the colored legend with counts below the bar. */
legend?: boolean;
} }
/** Segmented bar that splits a project's tasks by status, with a legend. */ /** Segmented bar that splits a project's tasks by status. */
export function StatusProgress({ counts, legend = true, className, ...props }: StatusProgressProps) { export function StatusBar({ counts, className, ...props }: StatusCountsProps) {
const total = taskStatusOrder.reduce((n, k) => n + (counts[k] ?? 0), 0);
const segments = taskStatusOrder
.filter((k) => (counts[k] ?? 0) > 0)
.map((k) => ({ key: k, count: counts[k] ?? 0, w: total ? ((counts[k] ?? 0) / total) * 100 : 0 }));
const barLabel = taskStatusOrder.map((k) => `${taskStatusLabel[k]}: ${counts[k] ?? 0}`).join(', ');
return ( return (
<div className={cn('min-w-0', className)} {...props}> <div
<div role="img" aria-label={barLabel} className="flex h-2.5 gap-[3px]"> role="img"
{segments.map((s) => ( aria-label={taskStatusOrder.map((k) => `${taskStatusLabel[k]}: ${counts[k] ?? 0}`).join(', ')}
<div key={s.key} className="rounded-full" style={{ width: `${s.w}%`, background: taskStatusBar[s.key] }} /> data-slot="status-bar"
))} className={cn('flex h-2.5 gap-[3px]', className)}
</div> {...props}
{legend && ( >
<div className="mt-3.5 flex flex-wrap gap-x-[22px] gap-y-2"> {segmentsOf(counts).map((s) => (
{segments.map((s) => ( <div key={s.key} className="rounded-full" style={{ width: `${s.width}%`, background: taskStatusBar[s.key] }} />
<div key={s.key} className="flex items-center gap-2 text-fg-muted"> ))}
<span
aria-hidden="true"
className="h-2 w-2 flex-none rounded-[2px]"
style={{ background: taskStatusBar[s.key] }}
/>
{taskStatusLabel[s.key]}
<strong className="text-fg tabular-nums">{s.count}</strong>
</div>
))}
</div>
)}
</div> </div>
); );
} }
/** Colored legend with counts per status, for under a `StatusBar`. */
export function StatusLegend({ counts, className, ...props }: StatusCountsProps) {
return (
<div data-slot="status-legend" className={cn('flex flex-wrap gap-x-[22px] gap-y-2', className)} {...props}>
{segmentsOf(counts).map((s) => (
<div key={s.key} className="flex items-center gap-2 text-fg-muted">
<span
aria-hidden="true"
className="h-2 w-2 flex-none rounded-[2px]"
style={{ background: taskStatusBar[s.key] }}
/>
{taskStatusLabel[s.key]}
<strong className="text-fg tabular-nums">{s.count}</strong>
</div>
))}
</div>
);
}
/** Stacks a `StatusBar` and a `StatusLegend` with the design's spacing. */
export function StatusProgress({ className, ...props }: ComponentProps<'div'>) {
return <div data-slot="status-progress" className={cn('flex min-w-0 flex-col gap-3.5', className)} {...props} />;
}
@@ -1,9 +1,9 @@
import type { Meta, StoryObj } from '@storybook/react'; import type { Meta, StoryObj } from '@storybook/react';
import { useState } from 'react'; import { useState } from 'react';
import { SegmentedControl } from './SegmentedControl'; import { SegmentedControl, SegmentedControlCount, SegmentedControlItem } from './SegmentedControl';
const meta: Meta<typeof SegmentedControl> = { const meta: Meta<typeof SegmentedControl> = {
title: 'Formulare/SegmentedControl', title: 'Forms/SegmentedControl',
component: SegmentedControl, component: SegmentedControl,
}; };
export default meta; export default meta;
@@ -14,75 +14,54 @@ export const Filter: Story = {
render: function Render() { render: function Render() {
const [value, setValue] = useState('all'); const [value, setValue] = useState('all');
return ( return (
<SegmentedControl <SegmentedControl aria-label="Filter" value={value} onValueChange={setValue}>
label="Filter" <SegmentedControlItem value="all">
value={value} Alle <SegmentedControlCount>7</SegmentedControlCount>
onChange={setValue} </SegmentedControlItem>
options={[ <SegmentedControlItem value="open">
{ value: 'all', label: 'Alle', count: 7 }, Offen <SegmentedControlCount>6</SegmentedControlCount>
{ value: 'open', label: 'Offen', count: 6 }, </SegmentedControlItem>
{ value: 'late', label: 'Überfällig', count: 1 }, <SegmentedControlItem value="late">
{ value: 'done', label: 'Erledigt', count: 1 }, Überfällig <SegmentedControlCount>1</SegmentedControlCount>
]} </SegmentedControlItem>
/> <SegmentedControlItem value="done">
Erledigt <SegmentedControlCount>1</SegmentedControlCount>
</SegmentedControlItem>
</SegmentedControl>
); );
}, },
}; };
export const Ansicht: Story = { export const View: Story = {
render: function Render() { render: () => (
const [value, setValue] = useState('month'); <SegmentedControl aria-label="Ansicht" defaultValue="month">
return ( <SegmentedControlItem value="month">Monat</SegmentedControlItem>
<SegmentedControl <SegmentedControlItem value="week">Woche</SegmentedControlItem>
label="Ansicht" </SegmentedControl>
value={value} ),
onChange={setValue}
options={[
{ value: 'month', label: 'Monat' },
{ value: 'week', label: 'Woche' },
]}
/>
);
},
}; };
export const Einstellung: Story = { export const Setting: Story = {
render: function Render() { render: () => (
const [value, setValue] = useState('off'); <SegmentedControl aria-label="Neutraltöne einfärben" size="md" defaultValue="off" className="*:min-w-[84px]">
return ( <SegmentedControlItem value="off">Aus</SegmentedControlItem>
<SegmentedControl <SegmentedControlItem value="subtle">Leicht</SegmentedControlItem>
label="Neutraltöne einfärben" <SegmentedControlItem value="strong">Kräftig</SegmentedControlItem>
size="md" </SegmentedControl>
minSegmentWidth={84} ),
value={value}
onChange={setValue}
options={[
{ value: 'off', label: 'Aus' },
{ value: 'subtle', label: 'Leicht' },
{ value: 'strong', label: 'Kräftig' },
]}
/>
);
},
}; };
export const Volle_Breite: Story = { export const FullWidth: Story = {
name: 'Volle Breite', render: () => (
render: function Render() { <div className="w-[380px]">
const [value, setValue] = useState('all'); <SegmentedControl aria-label="Filter" defaultValue="all" className="*:flex-1 *:basis-0">
return ( <SegmentedControlItem value="all">
<div className="w-[380px]"> Alle <SegmentedControlCount>7</SegmentedControlCount>
<SegmentedControl </SegmentedControlItem>
label="Filter" <SegmentedControlItem value="unread">
fullWidth Ungelesen <SegmentedControlCount>4</SegmentedControlCount>
value={value} </SegmentedControlItem>
onChange={setValue} </SegmentedControl>
options={[ </div>
{ value: 'all', label: 'Alle', count: 7 }, ),
{ value: 'unread', label: 'Ungelesen', count: 4 },
]}
/>
</div>
);
},
}; };
@@ -1,60 +1,42 @@
import type { ComponentProps } from 'react';
import { cn } from '../../lib/cn'; import { cn } from '../../lib/cn';
import { ToggleGroup, ToggleGroupItem } from '../ui/toggle-group'; import { ToggleGroup, ToggleGroupItem } from '../ui/toggle-group';
export interface SegmentedOption<T extends string = string> { export interface SegmentedControlProps extends Omit<ComponentProps<'div'>, 'defaultValue' | 'dir'> {
value: T; value?: string;
label: string; defaultValue?: string;
/** Optional count shown after the label, e.g. "Offen 6". */ onValueChange?: (value: string) => void;
count?: number;
}
export interface SegmentedControlProps<T extends string = string> {
options: SegmentedOption<T>[];
value: T;
onChange?: (value: T) => void;
/** Accessible name of the group, e.g. "Filter". */
label: string;
/** 30px for filters, 32px in settings rows and forms. */ /** 30px for filters, 32px in settings rows and forms. */
size?: 'sm' | 'md'; size?: 'sm' | 'md';
/** Stretch segments to fill the width (notification tabs). */ disabled?: boolean;
fullWidth?: boolean;
/** Minimum segment width in px, used in settings rows. */
minSegmentWidth?: number;
className?: string;
} }
/** Pill-group of toggle buttons used for filters, views and options. Arrow keys move between segments. */ /**
export function SegmentedControl<T extends string = string>({ * Pill group of mutually exclusive segments for filters, views and options; arrow keys
options, * move between them. Give it an `aria-label`. Stretch segments with `className="*:flex-1"`.
value, */
onChange, export function SegmentedControl({ size = 'sm', onValueChange, className, ...props }: SegmentedControlProps) {
label,
size = 'sm',
fullWidth = false,
minSegmentWidth,
className,
}: SegmentedControlProps<T>) {
return ( return (
<ToggleGroup <ToggleGroup
type="single" type="single"
aria-label={label}
size={size} size={size}
value={value} // Radix lets you deselect the active item; a segmented control always keeps one.
// Radix allows deselecting the active item; a segmented control always has one. onValueChange={(v: string) => v && onValueChange?.(v)}
onValueChange={(v) => v && onChange?.(v as T)}
className={cn('gap-0.5 rounded-[10px] border border-line-subtle bg-inset p-[3px]', className)} className={cn('gap-0.5 rounded-[10px] border border-line-subtle bg-inset p-[3px]', className)}
> {...props}
{options.map((o) => ( />
<ToggleGroupItem );
key={o.value} }
value={o.value}
style={minSegmentWidth ? { minWidth: minSegmentWidth } : undefined} export const SegmentedControlItem = ToggleGroupItem;
className={cn(fullWidth && 'flex-1 basis-0')}
> /** Count after a segment label, e.g. "Offen 6". */
{o.label} export function SegmentedControlCount({ className, ...props }: ComponentProps<'span'>) {
{o.count !== undefined && <span className="text-xs font-normal text-fg-subtle tabular-nums">{o.count}</span>} return (
</ToggleGroupItem> <span
))} data-slot="segmented-control-count"
</ToggleGroup> className={cn('text-xs font-normal text-fg-subtle tabular-nums', className)}
{...props}
/>
); );
} }
+246 -161
View File
@@ -3,23 +3,37 @@ import { Camera, CircleUser, Info, SlidersHorizontal, Trash2 } from 'lucide-reac
import { useId, useRef, useState } from 'react'; import { useId, useRef, useState } from 'react';
import { me } from '../../stories/fixtures'; import { me } from '../../stories/fixtures';
import { colorSchemes } from '../../lib/tokens'; import { colorSchemes } from '../../lib/tokens';
import { Avatar } from '../Avatar/Avatar'; import { PersonAvatar } from '../Avatar/Avatar';
import { Button } from '../Button/Button'; import { Button } from '../Button/Button';
import { Field, Input, Select } from '../Field/Field'; import { Field, FieldDescription, FieldLabel, Input, Select, SelectOption } from '../Field/Field';
import { PageHeader } from '../Layout/Layout'; import { PageActions, PageDescription, PageEyebrow, PageHeader, PageHeading, PageTitle } from '../Layout/Layout';
import { SegmentedControl } from '../SegmentedControl/SegmentedControl'; import { SegmentedControl, SegmentedControlItem } from '../SegmentedControl/SegmentedControl';
import { import {
ColorSchemeOption,
ColorSchemePicker, ColorSchemePicker,
SaveStatus, SaveStatus,
SettingsNav, SettingsNav,
SettingsNavItem,
SettingsNavLabel,
SettingsRow, SettingsRow,
SettingsRowControl,
SettingsRowDescription,
SettingsRowLabel,
SettingsRowText,
SettingsSection, SettingsSection,
SettingsSectionDescription,
SettingsSectionFooter,
SettingsSectionHeader,
SettingsSectionTitle,
ThemeOption,
ThemeOptionLabel,
ThemePicker, ThemePicker,
ThemePreview,
type ThemeChoice, type ThemeChoice,
} from './Settings'; } from './Settings';
const meta: Meta<typeof SettingsSection> = { const meta: Meta<typeof SettingsSection> = {
title: 'Einstellungen/Einstellungen', title: 'Settings/Settings',
component: SettingsSection, component: SettingsSection,
}; };
export default meta; export default meta;
@@ -27,15 +41,10 @@ export default meta;
type Story = StoryObj<typeof SettingsSection>; type Story = StoryObj<typeof SettingsSection>;
const ni = { size: 18, strokeWidth: 1.75 } as const; const ni = { size: 18, strokeWidth: 1.75 } as const;
const navGroups = [ const themes: { value: ThemeChoice; label: string }[] = [
{ { value: 'light', label: 'Hell' },
title: 'Persönlich', { value: 'dark', label: 'Dunkel' },
items: [ { value: 'system', label: 'System' },
{ id: 'konto', label: 'Konto', href: '#', icon: <CircleUser {...ni} /> },
{ id: 'allgemein', label: 'Allgemein', href: '#', icon: <SlidersHorizontal {...ni} /> },
],
},
{ title: 'App', items: [{ id: 'info', label: 'Info', href: '#', icon: <Info {...ni} /> }] },
]; ];
function useAutosave() { function useAutosave() {
@@ -44,108 +53,175 @@ function useAutosave() {
const save = () => { const save = () => {
timers.current.forEach(clearTimeout); timers.current.forEach(clearTimeout);
setState('saving'); setState('saving');
timers.current = [ timers.current = [window.setTimeout(() => setState('saved'), 900), window.setTimeout(() => setState('idle'), 3100)];
window.setTimeout(() => setState('saved'), 900),
window.setTimeout(() => setState('idle'), 3100),
];
}; };
return { state, save }; return { state, save };
} }
export const Allgemein: Story = { function ExampleThemePicker(props: { value: string; onValueChange: (v: string) => void; className?: string }) {
return (
<ThemePicker {...props}>
{themes.map((t) => (
<ThemeOption key={t.value} value={t.value}>
<ThemePreview theme={t.value} />
<ThemeOptionLabel>{t.label}</ThemeOptionLabel>
</ThemeOption>
))}
</ThemePicker>
);
}
function ExampleColorSchemePicker(props: {
value: string;
onValueChange: (v: string) => void;
'aria-labelledby'?: string;
}) {
return (
<ColorSchemePicker aria-label={props['aria-labelledby'] ? undefined : 'Farbschema'} {...props}>
{colorSchemes.map((s) => (
<ColorSchemeOption key={s.id} value={s.id} color={s.color}>
{s.name}
</ColorSchemeOption>
))}
</ColorSchemePicker>
);
}
export const General: Story = {
render: function Render() { render: function Render() {
const { state, save } = useAutosave(); const { state, save } = useAutosave();
const [theme, setTheme] = useState<ThemeChoice>('dark'); const [theme, setTheme] = useState<string>('dark');
const [scheme, setScheme] = useState('violett'); const [scheme, setScheme] = useState('violet');
const [tint, setTint] = useState('off'); const [tint, setTint] = useState('off');
const [week, setWeek] = useState('mo'); const [week, setWeek] = useState('mo');
const schemeLabelId = useId(); const schemeLabelId = useId();
const pick = <T,>(set: (v: T) => void) => (v: T) => { const pick = (set: (v: string) => void) => (v: string) => {
set(v); set(v);
save(); save();
}; };
return ( return (
<div className="mx-auto flex max-w-[1040px] flex-col gap-7"> <div className="mx-auto flex max-w-[1040px] flex-col gap-7">
<PageHeader <PageHeader>
eyebrow="Einstellungen" <PageHeading>
title="Allgemein" <PageEyebrow>Einstellungen</PageEyebrow>
description="Darstellung, Sprache und wo Collabry für dich startet." <PageTitle>Allgemein</PageTitle>
actions={ <PageDescription>Darstellung, Sprache und wo Collabry für dich startet.</PageDescription>
<div className="flex min-h-5 items-center"> </PageHeading>
<SaveStatus state={state} /> <PageActions className="min-h-5">
</div> <SaveStatus state={state} />
} </PageActions>
/> </PageHeader>
<div className="flex flex-wrap items-start gap-x-10 gap-y-6"> <div className="flex flex-wrap items-start gap-x-10 gap-y-6">
<SettingsNav groups={navGroups} activeId="allgemein" /> <SettingsNav>
<SettingsNavLabel>Persönlich</SettingsNavLabel>
<SettingsNavItem href="#">
<CircleUser {...ni} />
Konto
</SettingsNavItem>
<SettingsNavItem href="#" active>
<SlidersHorizontal {...ni} />
Allgemein
</SettingsNavItem>
<SettingsNavLabel>App</SettingsNavLabel>
<SettingsNavItem href="#">
<Info {...ni} />
Info
</SettingsNavItem>
</SettingsNav>
<div className="flex min-w-0 max-w-[760px] flex-[999_1_520px] flex-col gap-5"> <div className="flex min-w-0 max-w-[760px] flex-[999_1_520px] flex-col gap-5">
<SettingsSection title="Darstellung" description="Wähle, wie Collabry für dich aussieht."> <SettingsSection>
<ThemePicker value={theme} onChange={pick(setTheme)} className="px-[22px] pt-1 pb-5" /> <SettingsSectionHeader>
<SettingsRow <SettingsSectionTitle>Darstellung</SettingsSectionTitle>
stacked <SettingsSectionDescription>Wähle, wie Collabry für dich aussieht.</SettingsSectionDescription>
label={ </SettingsSectionHeader>
<span className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1.5"> <ExampleThemePicker value={theme} onValueChange={pick(setTheme)} className="px-[22px] pt-1 pb-5" />
<SettingsRow stacked>
<SettingsRowText>
<span className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1.5 leading-tight font-bold">
<span id={schemeLabelId}>Farbschema</span> <span id={schemeLabelId}>Farbschema</span>
<span className="text-sm text-accent-fg">{colorSchemes.find((s) => s.id === scheme)?.name}</span> <span className="text-sm text-accent-fg">{colorSchemes.find((s) => s.id === scheme)?.name}</span>
</span> </span>
} <SettingsRowDescription>
description="Akzentfarbe für Buttons, Links und Markierungen. Gilt für die ganze App." Akzentfarbe für Buttons, Links und Markierungen. Gilt für die ganze App.
> </SettingsRowDescription>
<ColorSchemePicker options={colorSchemes} value={scheme} onChange={pick(setScheme)} labelledBy={schemeLabelId} /> </SettingsRowText>
<SettingsRowControl>
<ExampleColorSchemePicker
value={scheme}
onValueChange={pick(setScheme)}
aria-labelledby={schemeLabelId}
/>
</SettingsRowControl>
</SettingsRow> </SettingsRow>
<SettingsRow label="Neutraltöne einfärben" description="Schwarz, Grau und Weiß bekommen einen Hauch der Akzentfarbe."> <SettingsRow>
<SegmentedControl <SettingsRowText>
label="Neutraltöne einfärben" <SettingsRowLabel>Neutraltöne einfärben</SettingsRowLabel>
size="md" <SettingsRowDescription>
minSegmentWidth={84} Schwarz, Grau und Weiß bekommen einen Hauch der Akzentfarbe.
value={tint} </SettingsRowDescription>
onChange={pick(setTint)} </SettingsRowText>
options={[ <SettingsRowControl>
{ value: 'off', label: 'Aus' }, <SegmentedControl
{ value: 'subtle', label: 'Leicht' }, aria-label="Neutraltöne einfärben"
{ value: 'strong', label: 'Kräftig' }, size="md"
]} value={tint}
/> onValueChange={pick(setTint)}
className="*:min-w-[84px]"
>
<SegmentedControlItem value="off">Aus</SegmentedControlItem>
<SegmentedControlItem value="subtle">Leicht</SegmentedControlItem>
<SegmentedControlItem value="strong">Kräftig</SegmentedControlItem>
</SegmentedControl>
</SettingsRowControl>
</SettingsRow> </SettingsRow>
</SettingsSection> </SettingsSection>
<SettingsSection title="Sprache & Region" description="Wie Texte, Daten und Kalender angezeigt werden."> <SettingsSection>
<SettingsRow label="Sprache" description="Sprache der Oberfläche." htmlFor="gen-lang"> <SettingsSectionHeader>
<Select <SettingsSectionTitle>Sprache & Region</SettingsSectionTitle>
id="gen-lang" <SettingsSectionDescription>Wie Texte, Daten und Kalender angezeigt werden.</SettingsSectionDescription>
size="settings" </SettingsSectionHeader>
className="w-[220px] max-w-full" <SettingsRow>
onChange={save} <SettingsRowText>
options={[ <SettingsRowLabel htmlFor="gen-lang">Sprache</SettingsRowLabel>
{ value: 'de', label: 'Deutsch' }, <SettingsRowDescription>Sprache der Oberfläche.</SettingsRowDescription>
{ value: 'en', label: 'English' }, </SettingsRowText>
]} <SettingsRowControl>
/> <Select id="gen-lang" size="settings" className="w-[220px] max-w-full" onChange={save}>
<SelectOption value="de">Deutsch</SelectOption>
<SelectOption value="en">English</SelectOption>
</Select>
</SettingsRowControl>
</SettingsRow> </SettingsRow>
<SettingsRow label="Datumsformat" description="Zum Beispiel bei Deadlines." htmlFor="gen-date"> <SettingsRow>
<Select <SettingsRowText>
id="gen-date" <SettingsRowLabel htmlFor="gen-date">Datumsformat</SettingsRowLabel>
size="settings" <SettingsRowDescription>Zum Beispiel bei Deadlines.</SettingsRowDescription>
className="w-[220px] max-w-full" </SettingsRowText>
onChange={save} <SettingsRowControl>
options={[ <Select id="gen-date" size="settings" className="w-[220px] max-w-full" onChange={save}>
{ value: 'de', label: '01.11.2026' }, <SelectOption value="de">01.11.2026</SelectOption>
{ value: 'iso', label: '2026-11-01' }, <SelectOption value="iso">2026-11-01</SelectOption>
{ value: 'us', label: '11/01/2026' }, <SelectOption value="us">11/01/2026</SelectOption>
]} </Select>
/> </SettingsRowControl>
</SettingsRow> </SettingsRow>
<SettingsRow label="Woche beginnt am" description="Gilt für den Kalender und die Wochenansicht."> <SettingsRow>
<SegmentedControl <SettingsRowText>
label="Wochenbeginn" <SettingsRowLabel>Woche beginnt am</SettingsRowLabel>
size="md" <SettingsRowDescription>Gilt für den Kalender und die Wochenansicht.</SettingsRowDescription>
minSegmentWidth={92} </SettingsRowText>
value={week} <SettingsRowControl>
onChange={pick(setWeek)} <SegmentedControl
options={[ aria-label="Wochenbeginn"
{ value: 'mo', label: 'Montag' }, size="md"
{ value: 'so', label: 'Sonntag' }, value={week}
]} onValueChange={pick(setWeek)}
/> className="*:min-w-[92px]"
>
<SegmentedControlItem value="mo">Montag</SegmentedControlItem>
<SegmentedControlItem value="so">Sonntag</SegmentedControlItem>
</SegmentedControl>
</SettingsRowControl>
</SettingsRow> </SettingsRow>
</SettingsSection> </SettingsSection>
</div> </div>
@@ -155,78 +231,92 @@ export const Allgemein: Story = {
}, },
}; };
export const Konto: Story = { export const Account: Story = {
render: function Render() { render: function Render() {
const [first, setFirst] = useState('Niklas'); const [first, setFirst] = useState('Niklas');
const [saved, setSaved] = useState(false); const [saved, setSaved] = useState(false);
const dirty = first !== 'Niklas'; const dirty = first !== 'Niklas';
return ( return (
<div className="flex max-w-[760px] flex-col gap-5"> <div className="flex max-w-[760px] flex-col gap-5">
<SettingsSection <SettingsSection>
title="Profil" <SettingsSectionHeader>
description="So sehen dich die anderen in deinen Gruppen." <SettingsSectionTitle>Profil</SettingsSectionTitle>
footer={ <SettingsSectionDescription>So sehen dich die anderen in deinen Gruppen.</SettingsSectionDescription>
<> </SettingsSectionHeader>
{saved && <SaveStatus state="saved" className="mr-auto text-sm" />} <SettingsRow className="justify-start gap-4">
{dirty && ( <PersonAvatar person={me} size={64} />
<Button variant="ghost" className="rounded-[9px]" onClick={() => setFirst('Niklas')}> <SettingsRowText className="flex-[1_1_200px]">
Verwerfen
</Button>
)}
<Button
variant="primary"
className="rounded-[9px] px-4 shadow-primary-flat"
disabled={!dirty}
onClick={() => setSaved(true)}
>
Änderungen speichern
</Button>
</>
}
>
<div className="flex flex-wrap items-center gap-4 border-t border-line-subtle px-[22px] py-4">
<Avatar person={me} size={64} />
<div className="min-w-0 flex-[1_1_200px]">
<div className="font-bold">Profilfoto</div> <div className="font-bold">Profilfoto</div>
<div className="mt-[3px] text-sm text-fg-subtle">JPG oder PNG, quadratisch wirkt am besten.</div> <SettingsRowDescription>JPG oder PNG, quadratisch wirkt am besten.</SettingsRowDescription>
</div> </SettingsRowText>
<div className="flex flex-none gap-2"> <SettingsRowControl className="flex gap-2">
<Button className="rounded-[9px] px-3" icon={<Camera size={16} strokeWidth={1.75} />}> <Button className="rounded-[9px] px-3">
<Camera size={16} strokeWidth={1.75} />
Foto ändern Foto ändern
</Button> </Button>
<Button variant="ghost" className="rounded-[9px] px-3"> <Button variant="ghost" className="rounded-[9px] px-3">
Entfernen Entfernen
</Button> </Button>
</div> </SettingsRowControl>
</div> </SettingsRow>
<div className="grid grid-cols-[repeat(auto-fit,minmax(220px,1fr))] gap-4 border-t border-line-subtle px-[22px] py-[18px]"> <SettingsRow stacked className="grid grid-cols-[repeat(auto-fit,minmax(220px,1fr))] gap-4 py-[18px]">
<Field label="Vorname"> <Field>
{({ id }) => ( <FieldLabel>Vorname</FieldLabel>
<Input <Input
id={id} className="h-10"
className="h-10" autoComplete="given-name"
autoComplete="given-name" value={first}
value={first} onChange={(e) => {
onChange={(e) => { setFirst(e.target.value);
setFirst(e.target.value); setSaved(false);
setSaved(false); }}
}} />
/>
)}
</Field> </Field>
<Field label="Nachname">{({ id }) => <Input id={id} className="h-10" defaultValue="Haiden" />}</Field> <Field>
<Field label="E-Mail" hint="Wird für die Anmeldung und Benachrichtigungen verwendet." className="col-span-full"> <FieldLabel>Nachname</FieldLabel>
{({ id, describedBy }) => ( <Input className="h-10" defaultValue="Haiden" />
<Input id={id} className="h-10" type="email" defaultValue={me.email} aria-describedby={describedBy} />
)}
</Field> </Field>
</div> <Field className="col-span-full">
</SettingsSection> <FieldLabel>E-Mail</FieldLabel>
<SettingsSection title="Gefahrenbereich" description="Aktionen, die sich nicht rückgängig machen lassen."> <Input className="h-10" type="email" defaultValue={me.email} />
<SettingsRow label="Konto löschen" description="Löscht dein Konto dauerhaft. Das kann nicht rückgängig gemacht werden."> <FieldDescription>Wird für die Anmeldung und Benachrichtigungen verwendet.</FieldDescription>
<Button variant="danger-outline" className="rounded-[9px]" icon={<Trash2 size={16} strokeWidth={1.75} />}> </Field>
Konto löschen </SettingsRow>
<SettingsSectionFooter>
{saved && <SaveStatus state="saved" className="mr-auto text-sm" />}
{dirty && (
<Button variant="ghost" className="rounded-[9px]" onClick={() => setFirst('Niklas')}>
Verwerfen
</Button>
)}
<Button
variant="primary"
className="rounded-[9px] px-4 shadow-primary-flat"
disabled={!dirty}
onClick={() => setSaved(true)}
>
Änderungen speichern
</Button> </Button>
</SettingsSectionFooter>
</SettingsSection>
<SettingsSection>
<SettingsSectionHeader>
<SettingsSectionTitle>Gefahrenbereich</SettingsSectionTitle>
<SettingsSectionDescription>Aktionen, die sich nicht rückgängig machen lassen.</SettingsSectionDescription>
</SettingsSectionHeader>
<SettingsRow>
<SettingsRowText>
<SettingsRowLabel>Konto löschen</SettingsRowLabel>
<SettingsRowDescription>
Löscht dein Konto dauerhaft. Das kann nicht rückgängig gemacht werden.
</SettingsRowDescription>
</SettingsRowText>
<SettingsRowControl>
<Button variant="danger-outline" className="rounded-[9px]">
<Trash2 size={16} strokeWidth={1.75} />
Konto löschen
</Button>
</SettingsRowControl>
</SettingsRow> </SettingsRow>
</SettingsSection> </SettingsSection>
</div> </div>
@@ -234,30 +324,25 @@ export const Konto: Story = {
}, },
}; };
export const Designauswahl: Story = { export const Themes: Story = {
name: 'Designauswahl',
render: function Render() { render: function Render() {
const [v, setV] = useState<ThemeChoice>('system'); const [v, setV] = useState('system');
return ( return <ExampleThemePicker value={v} onValueChange={setV} className="max-w-[560px]" />;
<div className="max-w-[560px]">
<ThemePicker value={v} onChange={setV} />
</div>
);
}, },
}; };
export const Farbschema: Story = { export const ColorScheme: Story = {
render: function Render() { render: function Render() {
const [v, setV] = useState('petrol'); const [v, setV] = useState('teal');
return ( return (
<div className="max-w-[720px]"> <div className="max-w-[720px]">
<ColorSchemePicker options={colorSchemes} value={v} onChange={setV} /> <ExampleColorSchemePicker value={v} onValueChange={setV} />
</div> </div>
); );
}, },
}; };
export const Speicherstatus: Story = { export const Saving: Story = {
render: () => ( render: () => (
<div className="flex gap-6"> <div className="flex gap-6">
<SaveStatus state="saving" /> <SaveStatus state="saving" />
+252 -187
View File
@@ -1,131 +1,223 @@
import { useId, type ReactNode } from 'react'; import { createContext, useContext, useId, type ComponentProps } from 'react';
import { Check } from 'lucide-react'; import { Check } from 'lucide-react';
import { Slot } from 'radix-ui';
import { cn } from '../../lib/cn'; import { cn } from '../../lib/cn';
import { Card } from '../Card/Card'; import { Card, CardFrame } from '../Card/Card';
import { CardDescription, CardTitle } from '../ui/card';
import { Label } from '../ui/label'; import { Label } from '../ui/label';
import { RadioGroup, RadioGroupItem } from '../ui/radio-group'; import { RadioGroup, RadioGroupItem } from '../ui/radio-group';
import { Spinner } from '../Spinner/Spinner'; import { Spinner } from '../Spinner/Spinner';
import type { NavItemData } from '../Sidebar/Sidebar';
export interface SettingsNavGroup { /* ---------------------------------------------------------------- Nav */
title: string;
items: NavItemData[];
}
export interface SettingsNavProps { /** Left-hand navigation between settings pages: `SettingsNavLabel`s and `SettingsNavItem`s. */
groups: SettingsNavGroup[]; export function SettingsNav({ className, ...props }: ComponentProps<'nav'>) {
activeId: string;
className?: string;
}
/** Left-hand navigation between settings pages (Konto, Allgemein, Info). */
export function SettingsNav({ groups, activeId, className }: SettingsNavProps) {
return ( return (
<nav aria-label="Einstellungen" className={cn('flex max-w-[240px] flex-[1_1_200px] flex-col gap-0.5', className)}> <nav
{groups.map((g, gi) => ( aria-label="Einstellungen"
<div key={g.title} className="contents"> data-slot="settings-nav"
<div className={cn('px-3 pb-2 text-xs font-bold text-fg-subtle', gi > 0 && 'pt-[18px]')}>{g.title}</div> className={cn('flex max-w-[240px] flex-[1_1_200px] flex-col gap-0.5', className)}
{g.items.map((it) => { {...props}
const active = it.id === activeId; />
return (
<a
key={it.id}
href={it.href}
aria-current={active ? 'page' : undefined}
className={cn(
'flex h-[38px] items-center gap-2.5 rounded-lg px-3 font-bold',
active
? 'bg-side-active text-fg shadow-[inset_0_0_0_1px_var(--cl-side-active-line)] hover:text-fg'
: 'text-fg-muted hover:text-fg',
)}
>
<span className={cn('flex', active ? 'text-accent-fg' : 'text-fg-subtle')}>{it.icon}</span>
{it.label}
</a>
);
})}
</div>
))}
</nav>
); );
} }
export interface SettingsSectionProps { /** Group title, e.g. "Persönlich". */
title: string; export function SettingsNavLabel({ className, ...props }: ComponentProps<'div'>) {
description?: ReactNode;
children: ReactNode;
/** Footer row, right-aligned (e.g. Verwerfen / Speichern). */
footer?: ReactNode;
className?: string;
}
/** A settings card: heading block, then rows separated by hairlines. */
export function SettingsSection({ title, description, children, footer, className }: SettingsSectionProps) {
const id = useId();
return (
<Card aria-labelledby={id} padding="none" className={className}>
<div className="px-[22px] pt-[18px] pb-4">
<CardTitle asChild>
<h2 id={id}>{title}</h2>
</CardTitle>
{description && <CardDescription className="mt-1 leading-normal">{description}</CardDescription>}
</div>
{children}
{footer && (
<div className="flex flex-wrap items-center justify-end gap-2.5 border-t border-line-subtle px-[22px] py-3.5">
{footer}
</div>
)}
</Card>
);
}
export interface SettingsRowProps {
label: ReactNode;
description?: ReactNode;
/** id of the control, so the label is a real <label>. */
htmlFor?: string;
/** The control on the right. Put it on its own line by using `stacked`. */
children?: ReactNode;
stacked?: boolean;
className?: string;
}
/** Label + description on the left, control on the right; wraps on narrow screens. */
export function SettingsRow({ label, description, htmlFor, children, stacked, className }: SettingsRowProps) {
const L = htmlFor ? Label : 'div';
return ( return (
<div <div
data-slot="settings-nav-label"
className={cn('px-3 pb-2 text-xs font-bold text-fg-subtle not-first:pt-[18px]', className)}
{...props}
/>
);
}
export interface SettingsNavItemProps extends ComponentProps<'a'> {
active?: boolean;
asChild?: boolean;
}
/** Icon and label; the active one is framed with an accent icon. */
export function SettingsNavItem({ active, asChild, className, ...props }: SettingsNavItemProps) {
const Comp = asChild ? Slot.Root : 'a';
return (
<Comp
aria-current={active ? 'page' : undefined}
data-slot="settings-nav-item"
className={cn( className={cn(
'border-t border-line-subtle px-[22px] py-4', 'flex h-[38px] items-center gap-2.5 rounded-lg px-3 font-bold text-fg-muted hover:text-fg [&>svg]:text-fg-subtle',
'aria-[current=page]:bg-side-active aria-[current=page]:text-fg aria-[current=page]:shadow-[inset_0_0_0_1px_var(--cl-side-active-line)] aria-[current=page]:[&>svg]:text-accent-fg',
className,
)}
{...props}
/>
);
}
/* ---------------------------------------------------------------- Section */
const SectionContext = createContext<string | undefined>(undefined);
/**
* A settings card: header, then `SettingsRow`s separated by hairlines, then an optional footer.
* Labelled by its `SettingsSectionTitle`. `className` goes to the frame.
*/
export function SettingsSection({ className, ...props }: ComponentProps<'section'>) {
const titleId = useId();
return (
<SectionContext value={titleId}>
<CardFrame className={className}>
<Card asChild padding="none">
<section aria-labelledby={titleId} data-slot="settings-section" {...props} />
</Card>
</CardFrame>
</SectionContext>
);
}
export function SettingsSectionHeader({ className, ...props }: ComponentProps<'div'>) {
return <div data-slot="settings-section-header" className={cn('px-[22px] pt-[18px] pb-4', className)} {...props} />;
}
export function SettingsSectionTitle({ className, ...props }: ComponentProps<'h2'>) {
return (
<h2
id={useContext(SectionContext)}
data-slot="settings-section-title"
className={cn('m-0 text-md font-bold', className)}
{...props}
/>
);
}
export function SettingsSectionDescription({ className, ...props }: ComponentProps<'p'>) {
return (
<p
data-slot="settings-section-description"
className={cn('mt-1 mb-0 text-sm leading-normal text-fg-subtle', className)}
{...props}
/>
);
}
/** Right-aligned actions, e.g. Verwerfen / Speichern. */
export function SettingsSectionFooter({ className, ...props }: ComponentProps<'div'>) {
return (
<div
data-slot="settings-section-footer"
className={cn(
'flex flex-wrap items-center justify-end gap-2.5 border-t border-line-subtle px-[22px] py-3.5',
className,
)}
{...props}
/>
);
}
export interface SettingsRowProps extends ComponentProps<'div'> {
/** Put the control on its own line under the text. */
stacked?: boolean;
}
/** `SettingsRowText` on the left, `SettingsRowControl` on the right; wraps on narrow screens. Also fits free content. */
export function SettingsRow({ stacked, className, ...props }: SettingsRowProps) {
return (
<div
data-slot="settings-row"
data-stacked={stacked || undefined}
className={cn(
'group/row border-t border-line-subtle px-[22px] py-4',
!stacked && 'flex flex-wrap items-center justify-between gap-x-6 gap-y-3', !stacked && 'flex flex-wrap items-center justify-between gap-x-6 gap-y-3',
className, className,
)} )}
> {...props}
<div className={cn('min-w-0', !stacked && 'flex-[1_1_260px]')}> />
<L htmlFor={htmlFor} className="block leading-tight font-bold">
{label}
</L>
{description && <div className="mt-[3px] text-sm leading-normal text-fg-subtle">{description}</div>}
</div>
{children && <div className={cn(stacked ? 'mt-3.5' : 'max-w-full flex-none')}>{children}</div>}
</div>
); );
} }
export function SettingsRowText({ className, ...props }: ComponentProps<'div'>) {
return (
<div
data-slot="settings-row-text"
className={cn('min-w-0 flex-[1_1_260px] group-data-stacked/row:flex-none', className)}
{...props}
/>
);
}
/** A `<label>`; set `htmlFor` to the control's id. */
export function SettingsRowLabel({ className, ...props }: ComponentProps<typeof Label>) {
return <Label data-slot="settings-row-label" className={cn('block leading-tight font-bold', className)} {...props} />;
}
export function SettingsRowDescription({ className, ...props }: ComponentProps<'div'>) {
return (
<div
data-slot="settings-row-description"
className={cn('mt-[3px] text-sm leading-normal text-fg-subtle', className)}
{...props}
/>
);
}
export function SettingsRowControl({ className, ...props }: ComponentProps<'div'>) {
return (
<div
data-slot="settings-row-control"
className={cn('max-w-full flex-none group-data-stacked/row:mt-3.5', className)}
{...props}
/>
);
}
/* ---------------------------------------------------------------- Pickers */
/** Selectable card; the checked one gets an accent ring. */
const radioCard =
'group flex flex-col rounded-xl border border-line bg-inset text-fg hover:bg-hover data-[state=checked]:shadow-[0_0_0_2px_var(--cl-accent)] data-[state=checked]:focus-visible:shadow-[0_0_0_2px_var(--cl-accent),0_0_0_5px_var(--cl-accent-ring)]';
export type ThemeChoice = 'light' | 'dark' | 'system'; export type ThemeChoice = 'light' | 'dark' | 'system';
/** Radio cards for the theme: `ThemeOption`s. Arrow keys move the choice. */
export function ThemePicker({ className, ...props }: ComponentProps<typeof RadioGroup>) {
return (
<RadioGroup
aria-label="Design"
data-slot="theme-picker"
className={cn('grid-cols-[repeat(auto-fit,minmax(140px,1fr))]', className)}
{...props}
/>
);
}
/** One card: a `ThemePreview` and a `ThemeOptionLabel`. */
export function ThemeOption({ className, ...props }: ComponentProps<typeof RadioGroupItem>) {
return (
<RadioGroupItem
data-slot="theme-option"
className={cn(radioCard, 'gap-2.5 px-2 pt-2 pb-2.5 text-left', className)}
{...props}
/>
);
}
function MiniWindow({ variant, className }: { variant: 'light' | 'dark'; className?: string }) { function MiniWindow({ variant, className }: { variant: 'light' | 'dark'; className?: string }) {
const c = const c =
variant === 'light' variant === 'light'
? { bg: '#F4F4F5', side: '#FFFFFF', card: '#FFFFFF', line: '#DEDEE3', bar: '#E4E4E7' } ? { bg: '#F4F4F5', side: '#FFFFFF', card: '#FFFFFF', line: '#DEDEE3', bar: '#E4E4E7' }
: { bg: '#050505', side: '#0E0E0E', card: '#141414', line: '#2E2E2E', bar: '#262626' }; : { bg: '#050505', side: '#0E0E0E', card: '#141414', line: '#2E2E2E', bar: '#262626' };
return ( return (
<span aria-hidden="true" className={cn('box-border flex h-[74px] w-full gap-1.5 p-2', className)} style={{ background: c.bg }}> <span
aria-hidden="true"
className={cn('box-border flex h-[74px] w-full gap-1.5 p-2', className)}
style={{ background: c.bg }}
>
<span className="w-[26%] rounded-[5px]" style={{ background: c.side }} /> <span className="w-[26%] rounded-[5px]" style={{ background: c.side }} />
<span className="flex flex-auto flex-col gap-[5px]"> <span className="flex flex-auto flex-col gap-[5px]">
<span className="h-[26px] rounded-[5px]" style={{ background: c.card, boxShadow: `inset 0 0 0 1px ${c.line}` }} /> <span
className="h-[26px] rounded-[5px]"
style={{ background: c.card, boxShadow: `inset 0 0 0 1px ${c.line}` }}
/>
<span className="h-2 w-[70%] rounded" style={{ background: c.bar }} /> <span className="h-2 w-[70%] rounded" style={{ background: c.bar }} />
<span className="h-2 w-[45%] rounded" style={{ background: c.bar }} /> <span className="h-2 w-[45%] rounded" style={{ background: c.bar }} />
</span> </span>
@@ -133,119 +225,92 @@ function MiniWindow({ variant, className }: { variant: 'light' | 'dark'; classNa
); );
} }
/** Selectable card; the checked one gets an accent ring. */ /** Miniature app window in the given theme; `system` shows half light, half dark. */
const radioCard = export function ThemePreview({ theme, className }: { theme: ThemeChoice; className?: string }) {
'group flex flex-col rounded-xl border border-line bg-inset text-fg hover:bg-hover data-[state=checked]:shadow-[0_0_0_2px_var(--cl-accent)] data-[state=checked]:focus-visible:shadow-[0_0_0_2px_var(--cl-accent),0_0_0_5px_var(--cl-accent-ring)]'; if (theme !== 'system') return <MiniWindow variant={theme} className={cn('rounded-[9px]', className)} />;
const themeLabels: Record<ThemeChoice, string> = { light: 'Hell', dark: 'Dunkel', system: 'System' };
export interface ThemePickerProps {
value: ThemeChoice;
onChange?: (value: ThemeChoice) => void;
className?: string;
}
/** Radio cards with a miniature preview of each theme. */
export function ThemePicker({ value, onChange, className }: ThemePickerProps) {
return ( return (
<RadioGroup <span className={cn('flex h-[74px] w-full overflow-hidden rounded-[9px]', className)}>
aria-label="Design" <span className="flex flex-1 basis-0 overflow-hidden">
value={value} <MiniWindow variant="light" className="w-[200%] flex-none" />
onValueChange={(v) => onChange?.(v as ThemeChoice)} </span>
className={cn('grid-cols-[repeat(auto-fit,minmax(140px,1fr))]', className)} <span className="flex flex-1 basis-0 justify-end overflow-hidden">
> <MiniWindow variant="dark" className="w-[200%] flex-none" />
{(['light', 'dark', 'system'] as const).map((t) => ( </span>
<RadioGroupItem </span>
key={t}
value={t}
className={cn(radioCard, 'gap-2.5 px-2 pt-2 pb-2.5 text-left')}
>
{t === 'system' ? (
<span className="flex h-[74px] w-full overflow-hidden rounded-[9px]">
<span className="flex flex-1 basis-0 overflow-hidden">
<MiniWindow variant="light" className="w-[200%] flex-none" />
</span>
<span className="flex flex-1 basis-0 justify-end overflow-hidden">
<MiniWindow variant="dark" className="w-[200%] flex-none" />
</span>
</span>
) : (
<MiniWindow variant={t} className="rounded-[9px]" />
)}
<span className="flex items-center justify-between gap-2 px-1 text-sm font-bold">
{themeLabels[t]}
<span className="box-border h-4 w-4 flex-none rounded-full border-[1.5px] border-line-control group-data-[state=checked]:border-accent group-data-[state=checked]:bg-accent group-data-[state=checked]:shadow-[inset_0_0_0_3px_var(--cl-inset)]" />
</span>
</RadioGroupItem>
))}
</RadioGroup>
); );
} }
export interface ColorSchemeOption { /** Name of the option, with a radio dot on the right. */
id: string; export function ThemeOptionLabel({ className, children, ...props }: ComponentProps<'span'>) {
name: string; return (
<span
data-slot="theme-option-label"
className={cn('flex items-center justify-between gap-2 px-1 text-sm font-bold', className)}
{...props}
>
{children}
<span className="box-border h-4 w-4 flex-none rounded-full border-[1.5px] border-line-control group-data-[state=checked]:border-accent group-data-[state=checked]:bg-accent group-data-[state=checked]:shadow-[inset_0_0_0_3px_var(--cl-inset)]" />
</span>
);
}
/** Accent color swatches ("Farbschema"): `ColorSchemeOption`s. */
export function ColorSchemePicker({ className, ...props }: ComponentProps<typeof RadioGroup>) {
return (
<RadioGroup
data-slot="color-scheme-picker"
className={cn('grid-cols-[repeat(auto-fill,minmax(88px,1fr))] gap-2.5', className)}
{...props}
/>
);
}
export interface ColorSchemeOptionProps extends ComponentProps<typeof RadioGroupItem> {
color: string; color: string;
} }
export interface ColorSchemePickerProps { /** Round swatch in the color (checked: with a check mark), then `children` as the name. */
options: readonly ColorSchemeOption[]; export function ColorSchemeOption({ color, className, children, ...props }: ColorSchemeOptionProps) {
value: string;
onChange?: (id: string) => void;
/** id of the element that labels the group. */
labelledBy?: string;
className?: string;
}
/** Accent color swatches ("Farbschema"). */
export function ColorSchemePicker({ options, value, onChange, labelledBy, className }: ColorSchemePickerProps) {
return ( return (
<RadioGroup <RadioGroupItem
aria-labelledby={labelledBy} data-slot="color-scheme-option"
aria-label={labelledBy ? undefined : 'Farbschema'} className={cn(radioCard, 'items-center gap-2 px-1.5 pt-3 pb-2.5 text-xs font-bold', className)}
value={value} {...props}
onValueChange={(v) => onChange?.(v)}
className={cn('grid-cols-[repeat(auto-fill,minmax(88px,1fr))] gap-2.5', className)}
> >
{options.map((o) => ( <span
<RadioGroupItem aria-hidden="true"
key={o.id} className="flex h-8 w-8 items-center justify-center rounded-full text-on-accent"
value={o.id} style={{
className={cn(radioCard, 'items-center gap-2 px-1.5 pt-3 pb-2.5 text-xs font-bold')} background: `linear-gradient(180deg, color-mix(in srgb, ${color} 88%, #fff) 0%, color-mix(in srgb, ${color} 90%, #000) 100%)`,
> boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.28), 0 1px 2px rgba(0,0,0,0.5)',
<span }}
aria-hidden="true" >
className="flex h-8 w-8 items-center justify-center rounded-full text-on-accent" <Check size={16} strokeWidth={3} className="hidden group-data-[state=checked]:block" />
style={{ </span>
background: `linear-gradient(180deg, color-mix(in srgb, ${o.color} 88%, #fff) 0%, color-mix(in srgb, ${o.color} 90%, #000) 100%)`, {children}
boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.28), 0 1px 2px rgba(0,0,0,0.5)', </RadioGroupItem>
}}
>
<Check size={16} strokeWidth={3} className="hidden group-data-[state=checked]:block" />
</span>
{o.name}
</RadioGroupItem>
))}
</RadioGroup>
); );
} }
export interface SaveStatusProps { /* ---------------------------------------------------------------- Status */
export interface SaveStatusProps extends ComponentProps<'span'> {
state: 'idle' | 'saving' | 'saved'; state: 'idle' | 'saving' | 'saved';
className?: string;
} }
/** Autosave indicator: "Wird gespeichert …" then "Gespeichert". */ /** Autosave indicator: "Wird gespeichert …" then "Gespeichert". Renders nothing while idle. */
export function SaveStatus({ state, className }: SaveStatusProps) { export function SaveStatus({ state, className, ...props }: SaveStatusProps) {
if (state === 'idle') return null; if (state === 'idle') return null;
return ( return (
<span <span
role="status" role="status"
data-slot="save-status"
className={cn( className={cn(
'flex items-center gap-1.5 text-xs font-bold', 'flex items-center gap-1.5 text-xs font-bold',
state === 'saving' ? 'text-fg-subtle' : 'text-success-fg', state === 'saving' ? 'text-fg-subtle' : 'text-success-fg',
className, className,
)} )}
{...props}
> >
{state === 'saving' ? <Spinner size={14} /> : <Check size={14} strokeWidth={2.5} aria-hidden="true" />} {state === 'saving' ? <Spinner size={14} /> : <Check size={14} strokeWidth={2.5} aria-hidden="true" />}
{state === 'saving' ? 'Wird gespeichert …' : 'Gespeichert'} {state === 'saving' ? 'Wird gespeichert …' : 'Gespeichert'}
+116 -42
View File
@@ -1,74 +1,148 @@
import type { Meta, StoryObj } from '@storybook/react'; import type { Meta, StoryObj } from '@storybook/react';
import { useState } from 'react'; import { Bell, Calendar, ChevronsUpDown, Kanban, LayoutDashboard, SquareCheck, Users } from 'lucide-react';
import { me, notificationsEarlier, notificationsToday } from '../../stories/fixtures'; import { useState, type ReactNode } from 'react';
import { NotificationPanel } from '../Notifications/Notifications'; import { me } from '../../stories/fixtures';
import { AccountMenuItems, NotificationsDemo } from '../../stories/examples';
import { PersonAvatar } from '../Avatar/Avatar';
import { IndicatorDot } from '../Badge/Badge';
import { Button } from '../Button/Button'; import { Button } from '../Button/Button';
import { Sidebar, UserMenu } from './Sidebar'; import { Menu, MenuContent, MenuTrigger } from '../Menu/Menu';
import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from '../ui/popover';
import {
NavItem,
NavItemLabel,
Sidebar,
SidebarActions,
SidebarButton,
SidebarFooter,
SidebarHeader,
SidebarLogo,
SidebarNav,
SidebarToggle,
SidebarUserButton,
SidebarUserName,
} from './Sidebar';
const meta: Meta<typeof Sidebar> = { const meta: Meta<typeof Sidebar> = {
title: 'Navigation/Sidebar', title: 'Navigation/Sidebar',
component: Sidebar, component: Sidebar,
parameters: { layout: 'fullscreen' }, parameters: { layout: 'fullscreen' },
args: { user: me, unreadCount: 4, activeId: 'dashboard', collapsed: false },
argTypes: {
activeId: { control: 'inline-radio', options: ['dashboard', 'aufgaben', 'kanban', 'kalender', 'gruppen'] },
user: { control: false },
items: { control: false },
},
}; };
export default meta; export default meta;
type Story = StoryObj<typeof Sidebar>; type Story = StoryObj<typeof Sidebar>;
export const Interaktiv: Story = { const icon = { size: 18, strokeWidth: 1.75, 'aria-hidden': true } as const;
render: function Render(args) { const nav: { id: string; label: string; icon: ReactNode }[] = [
const [collapsed, setCollapsed] = useState(args.collapsed); { id: 'dashboard', label: 'Dashboard', icon: <LayoutDashboard {...icon} /> },
const [notif, setNotif] = useState(false); { id: 'tasks', label: 'Aufgaben', icon: <SquareCheck {...icon} /> },
{ id: 'kanban', label: 'Kanban', icon: <Kanban {...icon} /> },
{ id: 'calendar', label: 'Kalender', icon: <Calendar {...icon} /> },
{ id: 'groups', label: 'Gruppen', icon: <Users {...icon} /> },
];
function Navigation({ active = 'dashboard' }: { active?: string }) {
return (
<SidebarNav>
{nav.map((it) => (
<NavItem key={it.id} href="#" active={it.id === active}>
{it.icon}
<NavItemLabel>{it.label}</NavItemLabel>
</NavItem>
))}
</SidebarNav>
);
}
const userButton = (
<SidebarUserButton aria-label={`Konto-Menü, ${me.name}`}>
<PersonAvatar person={me} size={32} aria-hidden="true" />
<SidebarUserName>{me.name}</SidebarUserName>
<ChevronsUpDown size={16} strokeWidth={1.75} aria-hidden="true" />
</SidebarUserButton>
);
/** Bell opens the notification popover right of the sidebar; the user button opens the account menu. */
export const Interactive: Story = {
render: function Render() {
const [notifications, setNotifications] = useState(false);
const [theme, setTheme] = useState<'dark' | 'light'>('dark'); const [theme, setTheme] = useState<'dark' | 'light'>('dark');
return ( return (
<div className="relative flex h-[760px]"> <div className="relative flex h-[760px]">
<Sidebar <Popover open={notifications} onOpenChange={setNotifications}>
{...args} <PopoverAnchor asChild>
collapsed={collapsed} <Sidebar className="max-w-[338px]">
onToggleCollapsed={() => setCollapsed((c) => !c)} <SidebarHeader>
userMenu={{ theme, onToggleTheme: () => setTheme((t) => (t === 'dark' ? 'light' : 'dark')) }} <SidebarLogo />
notificationsOpen={notif} <SidebarActions>
onNotificationsOpenChange={setNotif} <PopoverTrigger asChild>
notifications={ <SidebarButton aria-label="Benachrichtigungen, 4 ungelesen">
<NotificationPanel <Bell {...icon} />
today={notificationsToday} <IndicatorDot />
earlier={notificationsEarlier} </SidebarButton>
onClose={() => setNotif(false)} </PopoverTrigger>
onMarkAllRead={() => undefined} <SidebarToggle />
/> </SidebarActions>
} </SidebarHeader>
className="max-w-[338px]" <Navigation />
/> <SidebarFooter>
<Menu>
<MenuTrigger asChild>{userButton}</MenuTrigger>
<MenuContent aria-label="Konto" size="lg" side="top" align="start">
<AccountMenuItems
user={me}
theme={theme}
onToggleTheme={() => setTheme((t) => (t === 'dark' ? 'light' : 'dark'))}
/>
</MenuContent>
</Menu>
</SidebarFooter>
</Sidebar>
</PopoverAnchor>
{/* Just right of the sidebar, as in the design. */}
<PopoverContent side="right" align="start" sideOffset={12} alignOffset={12} collisionPadding={12}>
<NotificationsDemo onClose={() => setNotifications(false)} />
</PopoverContent>
</Popover>
<div className="flex-[999_1_560px]" /> <div className="flex-[999_1_560px]" />
</div> </div>
); );
}, },
}; };
export const Eingeklappt: Story = { export const Collapsed: Story = {
args: { collapsed: true }, render: () => (
render: (args) => (
<div className="flex h-[640px]"> <div className="flex h-[640px]">
<Sidebar {...args} /> <Sidebar defaultCollapsed>
<SidebarHeader>
<SidebarLogo />
<SidebarActions>
<SidebarButton aria-label="Benachrichtigungen, 4 ungelesen">
<Bell {...icon} />
<IndicatorDot />
</SidebarButton>
<SidebarToggle />
</SidebarActions>
</SidebarHeader>
<Navigation />
<SidebarFooter>{userButton}</SidebarFooter>
</Sidebar>
</div> </div>
), ),
}; };
export const Kontomenue: Story = { export const AccountMenu: Story = {
name: 'Kontomenü',
parameters: { layout: 'padded' }, parameters: { layout: 'padded' },
render: () => ( render: () => (
<div className="flex h-[300px] items-end"> <div className="flex h-[300px] items-end">
<UserMenu <Menu defaultOpen>
user={me} <MenuTrigger asChild>
defaultOpen <Button variant="secondary">Konto</Button>
trigger={<Button variant="secondary">Konto</Button>} </MenuTrigger>
/> <MenuContent aria-label="Konto" size="lg" side="top" align="start">
<AccountMenuItems user={me} theme="dark" />
</MenuContent>
</Menu>
</div> </div>
), ),
}; };
+176 -216
View File
@@ -1,247 +1,207 @@
import { forwardRef, type AnchorHTMLAttributes, type ReactNode } from 'react'; import { createContext, useContext, useState, type ComponentProps } from 'react';
import { import { PanelLeftClose, PanelLeftOpen } from 'lucide-react';
Bell, import { Slot } from 'radix-ui';
Calendar,
ChevronRight,
ChevronsUpDown,
Kanban,
LayoutDashboard,
LogOut,
Moon,
PanelLeftClose,
PanelLeftOpen,
Settings,
SquareCheck,
Sun,
Users,
} from 'lucide-react';
import { cn } from '../../lib/cn'; import { cn } from '../../lib/cn';
import { Avatar, type Person } from '../Avatar/Avatar';
import { Logo } from '../Logo/Logo'; import { Logo } from '../Logo/Logo';
import { Menu, MenuHeader, MenuItem, MenuLink, MenuSeparator, type MenuProps } from '../Menu/Menu';
import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from '../ui/popover';
const icon = { size: 18, strokeWidth: 1.75, 'aria-hidden': true } as const; interface SidebarContextValue {
collapsed: boolean;
export interface NavItemData { setCollapsed: (collapsed: boolean) => void;
id: string;
label: string;
href: string;
icon: ReactNode;
} }
/** The app's main destinations, as in the design. */ const SidebarContext = createContext<SidebarContextValue>({ collapsed: false, setCollapsed: () => {} });
export const defaultNavItems: NavItemData[] = [
{ id: 'dashboard', label: 'Dashboard', href: '#', icon: <LayoutDashboard {...icon} /> },
{ id: 'aufgaben', label: 'Aufgaben', href: '#', icon: <SquareCheck {...icon} /> },
{ id: 'kanban', label: 'Kanban', href: '#', icon: <Kanban {...icon} /> },
{ id: 'kalender', label: 'Kalender', href: '#', icon: <Calendar {...icon} /> },
{ id: 'gruppen', label: 'Gruppen', href: '#', icon: <Users {...icon} /> },
];
export interface NavItemProps extends AnchorHTMLAttributes<HTMLAnchorElement> { /** Collapsed state of the surrounding `Sidebar`. */
icon: ReactNode; export const useSidebar = () => useContext(SidebarContext);
active?: boolean;
/** Hide the label visually (collapsed sidebar). */ export interface SidebarProps extends ComponentProps<'aside'> {
collapsed?: boolean; collapsed?: boolean;
defaultCollapsed?: boolean;
onCollapsedChange?: (collapsed: boolean) => void;
} }
/** Sidebar navigation link. The active item gets an inset frame and accent icon. */ /**
export const NavItem = forwardRef<HTMLAnchorElement, NavItemProps>(function NavItem( * Collapsible app sidebar. Parts read the collapsed state from it.
{ icon, active, collapsed, className, children, ...props }, *
ref, * <Sidebar>
) { * <SidebarHeader><SidebarLogo /><SidebarActions><SidebarButton …/><SidebarToggle /></SidebarActions></SidebarHeader>
* <SidebarNav><NavItem href="…" active><LayoutDashboard /><NavItemLabel>Dashboard</NavItemLabel></NavItem></SidebarNav>
* <SidebarFooter><SidebarUserButton>…</SidebarUserButton></SidebarFooter>
* </Sidebar>
*/
export function Sidebar({
collapsed: collapsedProp,
defaultCollapsed = false,
onCollapsedChange,
className,
...props
}: SidebarProps) {
const [own, setOwn] = useState(defaultCollapsed);
const collapsed = collapsedProp ?? own;
const setCollapsed = (next: boolean) => {
setOwn(next);
onCollapsedChange?.(next);
};
return ( return (
<a <SidebarContext value={{ collapsed, setCollapsed }}>
ref={ref} <aside
aria-current={active ? 'page' : undefined} aria-label="Seitenleiste"
title={collapsed && typeof children === 'string' ? children : undefined} data-slot="sidebar"
data-collapsed={collapsed}
className={cn(
'group/sidebar box-border flex min-w-0 flex-col gap-7 overflow-hidden border-r border-side-line bg-side shadow-side',
'transition-[flex-basis,padding] duration-[180ms] ease-out',
collapsed ? 'flex-[0_0_68px] px-3 py-5' : 'flex-[1_1_248px] px-3.5 py-5',
className,
)}
{...props}
/>
</SidebarContext>
);
}
/** Logo row with the header buttons; stacks vertically when collapsed. */
export function SidebarHeader({ className, ...props }: ComponentProps<'div'>) {
return (
<div
data-slot="sidebar-header"
className={cn( className={cn(
'box-border flex h-[38px] items-center gap-3 rounded-lg', 'flex items-center gap-2.5 pr-1 pl-2 group-data-[collapsed=true]/sidebar:flex-col group-data-[collapsed=true]/sidebar:gap-3.5 group-data-[collapsed=true]/sidebar:px-0',
collapsed ? 'flex-[1_1_100%] justify-center px-0' : 'flex-[1_1_190px] justify-start px-3',
active
? 'bg-side-active font-bold text-fg shadow-nav-active hover:text-fg'
: 'text-fg-muted hover:text-fg',
className, className,
)} )}
{...props} {...props}
> />
<span className={cn('flex', active && 'text-accent-fg')}>{icon}</span>
<span className={collapsed ? 'sr-only' : 'whitespace-nowrap'}>{children}</span>
</a>
); );
});
export interface SidebarProps {
items?: NavItemData[];
activeId?: string;
collapsed?: boolean;
onToggleCollapsed?: () => void;
unreadCount?: number;
/** Popover content opened by the bell, usually a `NotificationPanel`. */
notifications?: ReactNode;
notificationsOpen?: boolean;
onNotificationsOpenChange?: (open: boolean) => void;
user: Person & { email?: string };
/** Account menu opened by the user button. */
userMenu?: Omit<UserMenuProps, 'user' | 'trigger'>;
/** Extra content between navigation and the user button (e.g. actions in Variante D). */
children?: ReactNode;
className?: string;
} }
/** Collapsible app sidebar: logo, notifications bell, navigation and account button. */ /** Wordmark, or the mark when collapsed. */
export function Sidebar({ export function SidebarLogo(props: Omit<ComponentProps<typeof Logo>, 'variant'>) {
items = defaultNavItems, return <Logo variant={useSidebar().collapsed ? 'mark' : 'wordmark'} {...props} />;
activeId = 'dashboard', }
collapsed = false,
onToggleCollapsed, export function SidebarActions({ className, ...props }: ComponentProps<'div'>) {
unreadCount = 0, return (
notifications, <div
notificationsOpen, data-slot="sidebar-actions"
onNotificationsOpenChange,
user,
userMenu,
children,
className,
}: SidebarProps) {
const toggleLabel = collapsed ? 'Seitenleiste ausklappen' : 'Seitenleiste einklappen';
const ghost =
'flex h-8 w-8 flex-none items-center justify-center rounded-lg text-fg-muted hover:bg-hover hover:text-fg focus-visible:shadow-focus focus-visible:outline-none';
const bell = (
<button
type="button"
aria-label={`Benachrichtigungen, ${unreadCount} ungelesen`}
className={cn(ghost, 'relative data-[state=open]:bg-elevated')}
>
<Bell {...icon} />
{unreadCount > 0 && (
<span className="absolute top-[7px] right-2 h-[7px] w-[7px] rounded-full bg-danger shadow-[0_0_0_2px_var(--cl-side)]" />
)}
</button>
);
const userButton = (
<button
type="button"
aria-label={`Konto-Menü, ${user.name}`}
className={cn( className={cn(
'box-border flex w-full items-center gap-2.5 rounded-[10px] p-1.5 text-left text-fg hover:bg-hover data-[state=open]:bg-elevated', 'ml-auto flex items-center gap-0.5 group-data-[collapsed=true]/sidebar:ml-0 group-data-[collapsed=true]/sidebar:flex-col',
collapsed ? 'justify-center' : 'justify-start',
)}
>
<Avatar person={user} size={32} aria-hidden="true" />
{!collapsed && (
<>
<span className="min-w-0 flex-auto truncate font-bold">{user.name}</span>
<ChevronsUpDown size={16} strokeWidth={1.75} aria-hidden="true" className="text-fg-subtle" />
</>
)}
</button>
);
const aside = (
<aside
aria-label="Seitenleiste"
className={cn(
'box-border flex min-w-0 flex-col gap-7 overflow-hidden border-r border-side-line bg-side shadow-side',
'transition-[flex-basis,padding] duration-[180ms] ease-out',
collapsed ? 'flex-[0_0_68px] px-3 py-5' : 'flex-[1_1_248px] px-3.5 py-5',
className, className,
)} )}
{...props}
/>
);
}
/** 32px icon button for the header, e.g. notifications. Holds an `IndicatorDot`. Give it an `aria-label`. */
export function SidebarButton({ className, type = 'button', ...props }: ComponentProps<'button'>) {
return (
<button
type={type}
data-slot="sidebar-button"
className={cn(
'relative flex h-8 w-8 flex-none items-center justify-center rounded-lg text-fg-muted hover:bg-hover hover:text-fg focus-visible:shadow-focus focus-visible:outline-none data-[state=open]:bg-elevated',
'[--indicator-ring:var(--cl-side)] *:data-[slot=indicator-dot]:top-[7px] *:data-[slot=indicator-dot]:right-2',
className,
)}
{...props}
/>
);
}
/** Collapses and expands the sidebar. */
export function SidebarToggle({ onClick, ...props }: ComponentProps<'button'>) {
const { collapsed, setCollapsed } = useSidebar();
const label = collapsed ? 'Seitenleiste ausklappen' : 'Seitenleiste einklappen';
const Icon = collapsed ? PanelLeftOpen : PanelLeftClose;
return (
<SidebarButton
aria-expanded={!collapsed}
aria-label={label}
title={label}
onClick={(e) => {
onClick?.(e);
if (!e.defaultPrevented) setCollapsed(!collapsed);
}}
{...props}
> >
<div className={cn('flex items-center', collapsed ? 'flex-col gap-3.5' : 'gap-2.5 pr-1 pl-2')}> <Icon size={18} strokeWidth={1.75} aria-hidden="true" />
<Logo variant={collapsed ? 'mark' : 'wordmark'} /> </SidebarButton>
<div className={cn('flex items-center gap-0.5', collapsed ? 'flex-col' : 'ml-auto')}>
{notifications ? <PopoverTrigger asChild>{bell}</PopoverTrigger> : bell}
<button type="button" onClick={onToggleCollapsed} aria-expanded={!collapsed} aria-label={toggleLabel} title={toggleLabel} className={ghost}>
{collapsed ? <PanelLeftOpen {...icon} /> : <PanelLeftClose {...icon} />}
</button>
</div>
</div>
<nav aria-label="Hauptnavigation" className="flex flex-wrap gap-0.5">
{items.map((it) => (
<NavItem key={it.id} href={it.href} icon={it.icon} active={it.id === activeId} collapsed={collapsed}>
{it.label}
</NavItem>
))}
</nav>
{children}
<div className="mt-auto border-t border-side-line pt-3">
{userMenu ? <UserMenu user={user} trigger={userButton} {...userMenu} /> : userButton}
</div>
</aside>
); );
if (!notifications) return aside; }
export function SidebarNav({ className, ...props }: ComponentProps<'nav'>) {
return ( return (
<Popover open={notificationsOpen} onOpenChange={onNotificationsOpenChange}> <nav
<PopoverAnchor asChild>{aside}</PopoverAnchor> aria-label="Hauptnavigation"
{/* Sits just right of the sidebar, as in the design. */} data-slot="sidebar-nav"
<PopoverContent side="right" align="start" sideOffset={12} alignOffset={12} collisionPadding={12}> className={cn('flex flex-wrap gap-0.5', className)}
{notifications} {...props}
</PopoverContent> />
</Popover>
); );
} }
export interface UserMenuProps extends Pick<MenuProps, 'open' | 'defaultOpen' | 'onOpenChange' | 'side' | 'align'> { export interface NavItemProps extends ComponentProps<'a'> {
user: Person & { email?: string }; active?: boolean;
/** The element that opens the menu. */ asChild?: boolean;
trigger: ReactNode;
theme?: 'dark' | 'light';
onToggleTheme?: () => void;
settingsHref?: string;
logoutHref?: string;
className?: string;
} }
/** Account menu, opened by the sidebar's user button. */ /** Navigation link: an icon, then a `NavItemLabel`. The active one gets an inset frame and accent icon. */
export function UserMenu({ export function NavItem({ active, asChild, className, ...props }: NavItemProps) {
user, const Comp = asChild ? Slot.Root : 'a';
trigger,
theme = 'dark',
onToggleTheme,
settingsHref = '#',
logoutHref = '#',
className,
side = 'top',
align = 'start',
...menu
}: UserMenuProps) {
return ( return (
<Menu label="Konto" size="lg" trigger={trigger} side={side} align={align} className={className} {...menu}> <Comp
<MenuHeader> aria-current={active ? 'page' : undefined}
<Avatar person={user} size={36} aria-hidden="true" /> data-slot="nav-item"
<div className="min-w-0 flex-auto"> className={cn(
<div className="leading-tight font-bold">{user.name}</div> 'box-border flex h-[38px] flex-[1_1_190px] items-center justify-start gap-3 rounded-lg px-3 text-fg-muted hover:text-fg',
{user.email && <div className="truncate text-xs text-fg-subtle">{user.email}</div>} 'group-data-[collapsed=true]/sidebar:flex-[1_1_100%] group-data-[collapsed=true]/sidebar:justify-center group-data-[collapsed=true]/sidebar:px-0',
</div> 'aria-[current=page]:bg-side-active aria-[current=page]:font-bold aria-[current=page]:text-fg aria-[current=page]:shadow-nav-active aria-[current=page]:[&>svg]:text-accent-fg',
</MenuHeader> className,
<MenuSeparator /> )}
<MenuLink href={settingsHref} icon={<Settings {...icon} />}> {...props}
Einstellungen />
</MenuLink> );
<MenuItem }
// Keep the menu open so the new theme is visible right away.
onSelect={(e) => { /** Label of a `NavItem`; only screen readers get it when the sidebar is collapsed. */
e.preventDefault(); export function NavItemLabel({ className, ...props }: ComponentProps<'span'>) {
onToggleTheme?.(); return (
}} <span
icon={theme === 'dark' ? <Moon {...icon} /> : <Sun {...icon} />} data-slot="nav-item-label"
detail={ className={cn('whitespace-nowrap group-data-[collapsed=true]/sidebar:sr-only', className)}
<> {...props}
{theme === 'dark' ? 'Dunkel' : 'Hell'} />
<ChevronRight size={14} strokeWidth={1.75} aria-hidden="true" /> );
</> }
}
> export function SidebarFooter({ className, ...props }: ComponentProps<'div'>) {
Darstellung return (
</MenuItem> <div data-slot="sidebar-footer" className={cn('mt-auto border-t border-side-line pt-3', className)} {...props} />
<MenuSeparator /> );
<MenuLink href={logoutHref} icon={<LogOut {...icon} />}> }
Abmelden
</MenuLink> /** Account button: avatar, `SidebarUserName`, chevron. Only the avatar shows when collapsed. Give it an `aria-label`. */
</Menu> export function SidebarUserButton({ className, type = 'button', ...props }: ComponentProps<'button'>) {
return (
<button
type={type}
data-slot="sidebar-user-button"
className={cn(
'box-border flex w-full items-center justify-start gap-2.5 rounded-[10px] p-1.5 text-left text-fg hover:bg-hover data-[state=open]:bg-elevated [&>svg]:text-fg-subtle',
'group-data-[collapsed=true]/sidebar:justify-center group-data-[collapsed=true]/sidebar:[&>svg]:hidden',
className,
)}
{...props}
/>
);
}
export function SidebarUserName({ className, ...props }: ComponentProps<'span'>) {
return (
<span
data-slot="sidebar-user-name"
className={cn('min-w-0 flex-auto truncate font-bold group-data-[collapsed=true]/sidebar:hidden', className)}
{...props}
/>
); );
} }
+244 -87
View File
@@ -1,18 +1,45 @@
import type { Meta, StoryObj } from '@storybook/react'; import type { Meta, StoryObj } from '@storybook/react';
import { ChevronRight } from 'lucide-react'; import { ChevronRight } from 'lucide-react';
import { useState } from 'react'; import { useState } from 'react';
import { deadlines, tasks as sample } from '../../stories/fixtures'; import { deadlines, tasks as sample, type TaskData } from '../../stories/fixtures';
import { taskStatusBar, taskStatusLabel, taskStatusOrder, type TaskStatus } from '../../lib/tokens'; import { taskStatusBar, taskStatusLabel, taskStatusOrder, type TaskStatus } from '../../lib/tokens';
import { ButtonLink } from '../Button/Button'; import { PersonAvatar } from '../Avatar/Avatar';
import { Card, CardFooter, CardHeader } from '../Card/Card'; import { CountBadge, StatusBadge, Swatch } from '../Badge/Badge';
import { SegmentedControl } from '../SegmentedControl/SegmentedControl'; import { Button } from '../Button/Button';
import { DeadlineItem, PriorityLabel, TaskSectionHeader, TaskTable, TaskTableHeader, type TaskData } from './Task'; import { Card, CardAction, CardFooter, CardFrame, CardHeader, CardTitle } from '../Card/Card';
import { TaskCheckbox } from '../Checkbox/Checkbox';
import { MetaSeparator } from '../Layout/Layout';
import { SegmentedControl, SegmentedControlCount, SegmentedControlItem } from '../SegmentedControl/SegmentedControl';
import {
DateTile,
DeadlineContent,
DeadlineItem,
DeadlineLink,
DeadlineList,
DeadlineWhen,
PriorityLabel,
TaskAssignee,
TaskCell,
TaskCommentCount,
TaskDue,
TaskMeta,
TaskOpenButton,
TaskRow,
TaskSection,
TaskSectionContent,
TaskSectionDot,
TaskSectionTrigger,
TaskTable,
TaskTableEmpty,
TaskTableHead,
TaskTableHeader,
TaskTitle,
type TaskColumns,
} from './Task';
const meta: Meta<typeof TaskTable> = { const meta: Meta<typeof TaskTable> = {
title: 'Aufgaben/Aufgabenliste', title: 'Tasks/TaskTable',
component: TaskTable, component: TaskTable,
args: { tasks: sample, columns: 'compact' },
argTypes: { columns: { control: 'inline-radio', options: ['compact', 'full'] }, tasks: { control: false } },
}; };
export default meta; export default meta;
@@ -38,15 +65,103 @@ function useTasks() {
return { tasks, loading, toggle }; return { tasks, loading, toggle };
} }
export const Kompakt: Story = { /** One `TaskData` as a row: the composition you'd write in the app. */
render: function Render(args) { function Row({
t,
columns,
loading,
onToggle,
onOpen,
}: {
t: TaskData;
columns: TaskColumns;
loading?: boolean;
onToggle: (id: string) => void;
onOpen?: (id: string) => void;
}) {
const done = t.status === 'done';
const late = t.overdue && !done;
const title = (
<>
<TaskTitle>{t.title}</TaskTitle>
<TaskMeta>
<Swatch color={t.group.color} />
{t.group.name}
{!!t.comments && <TaskCommentCount count={t.comments} />}
</TaskMeta>
</>
);
return (
<TaskRow done={done}>
<TaskCell>
<TaskCheckbox
checked={done}
loading={loading}
size={columns === 'compact' ? 36 : 40}
aria-label={done ? `${t.title} wieder öffnen` : `${t.title} als erledigt markieren`}
onCheckedChange={() => onToggle(t.id)}
/>
</TaskCell>
<TaskCell>
{onOpen ? (
<TaskOpenButton aria-label={`${t.title} öffnen`} onClick={() => onOpen(t.id)}>
{title}
</TaskOpenButton>
) : (
title
)}
</TaskCell>
{columns === 'full' && (
<TaskCell>
{t.assignee && (
<TaskAssignee>
<PersonAvatar person={t.assignee} size={24} aria-hidden="true" />
<span>{t.assignee.name}</span>
</TaskAssignee>
)}
</TaskCell>
)}
<TaskCell>
<PriorityLabel priority={t.priority} />
</TaskCell>
<TaskCell>
<TaskDue overdue={late}>{late ? `${t.due} · überfällig` : t.due}</TaskDue>
</TaskCell>
<TaskCell>
<StatusBadge status={t.status} />
</TaskCell>
</TaskRow>
);
}
function Header({ columns }: { columns: TaskColumns }) {
return (
<TaskTableHeader>
<TaskTableHead />
<TaskTableHead>Aufgabe</TaskTableHead>
{columns === 'full' && <TaskTableHead>Zuständig</TaskTableHead>}
<TaskTableHead>Priorität</TaskTableHead>
<TaskTableHead>Fällig</TaskTableHead>
<TaskTableHead>Status</TaskTableHead>
</TaskTableHeader>
);
}
export const Compact: Story = {
render: function Render() {
const { tasks, loading, toggle } = useTasks(); const { tasks, loading, toggle } = useTasks();
return <TaskTable {...args} tasks={tasks} loadingIds={loading} onToggle={toggle} />; return (
<TaskTable aria-label="Aufgaben">
<Header columns="compact" />
{tasks.map((t) => (
<Row key={t.id} t={t} columns="compact" loading={loading.includes(t.id)} onToggle={toggle} />
))}
</TaskTable>
);
}, },
}; };
export const Dashboardkarte: Story = { export const DashboardCard: Story = {
name: 'Dashboard: Meine Aufgaben',
render: function Render() { render: function Render() {
const { tasks, loading, toggle } = useTasks(); const { tasks, loading, toggle } = useTasks();
const [filter, setFilter] = useState('all'); const [filter, setFilter] = useState('all');
@@ -58,106 +173,148 @@ export const Dashboardkarte: Story = {
done: tasks.filter((t) => t.status === 'done').length, done: tasks.filter((t) => t.status === 'done').length,
}; };
const shown = tasks.filter((t) => const shown = tasks.filter((t) =>
filter === 'all' ? true : filter === 'open' ? t.status !== 'done' : filter === 'late' ? isLate(t) : t.status === 'done', filter === 'all'
? true
: filter === 'open'
? t.status !== 'done'
: filter === 'late'
? isLate(t)
: t.status === 'done',
); );
return ( return (
<Card aria-labelledby="h-tasks"> <CardFrame>
<CardHeader <Card asChild>
titleId="h-tasks" <section aria-labelledby="h-tasks">
title="Meine Aufgaben" <CardHeader>
count={counts.open} <CardTitle id="h-tasks">
actions={ Meine Aufgaben <CountBadge>{counts.open}</CountBadge>
<SegmentedControl </CardTitle>
label="Filter" <CardAction>
value={filter} <SegmentedControl aria-label="Filter" value={filter} onValueChange={setFilter}>
onChange={setFilter} <SegmentedControlItem value="all">
options={[ Alle <SegmentedControlCount>{counts.all}</SegmentedControlCount>
{ value: 'all', label: 'Alle', count: counts.all }, </SegmentedControlItem>
{ value: 'open', label: 'Offen', count: counts.open }, <SegmentedControlItem value="open">
{ value: 'late', label: 'Überfällig', count: counts.late }, Offen <SegmentedControlCount>{counts.open}</SegmentedControlCount>
{ value: 'done', label: 'Erledigt', count: counts.done }, </SegmentedControlItem>
]} <SegmentedControlItem value="late">
/> Überfällig <SegmentedControlCount>{counts.late}</SegmentedControlCount>
} </SegmentedControlItem>
/> <SegmentedControlItem value="done">
<TaskTable tasks={shown} loadingIds={loading} onToggle={toggle} /> Erledigt <SegmentedControlCount>{counts.done}</SegmentedControlCount>
<CardFooter> </SegmentedControlItem>
<ButtonLink href="#" size="sm" className="h-[34px]" iconEnd={<ChevronRight size={14} strokeWidth={1.75} />}> </SegmentedControl>
Alle Aufgaben </CardAction>
</ButtonLink> </CardHeader>
</CardFooter> <TaskTable aria-label="Meine Aufgaben">
</Card> <Header columns="compact" />
{shown.map((t) => (
<Row key={t.id} t={t} columns="compact" loading={loading.includes(t.id)} onToggle={toggle} />
))}
{shown.length === 0 && <TaskTableEmpty>Hier ist gerade nichts.</TaskTableEmpty>}
</TaskTable>
<CardFooter>
<Button asChild size="sm" className="h-[34px]">
<a href="#">
Alle Aufgaben
<ChevronRight size={14} strokeWidth={1.75} />
</a>
</Button>
</CardFooter>
</section>
</Card>
</CardFrame>
); );
}, },
}; };
export const Vollstaendig: Story = { /** The Aufgaben page: rows grouped by status in collapsible sections. */
name: 'Aufgabenseite (gruppiert)', export const TaskPage: Story = {
render: function Render() { render: function Render() {
const { tasks, loading, toggle } = useTasks(); const { tasks, loading, toggle } = useTasks();
const [open, setOpen] = useState<Record<string, boolean>>({ doing: true, review: true, open: true, done: false });
const order: TaskStatus[] = ['doing', 'review', 'open', 'done']; const order: TaskStatus[] = ['doing', 'review', 'open', 'done'];
return ( return (
<Card aria-label="Aufgabenliste" padding="none" innerClassName="overflow-hidden"> <CardFrame>
<TaskTableHeader columns="full" /> <Card padding="none" className="overflow-hidden">
{order.map((s) => { <TaskTable columns="full" aria-label="Aufgabenliste">
const rows = tasks.filter((t) => t.status === s); <Header columns="full" />
return ( {order.map((s) => {
<div key={s}> const rows = tasks.filter((t) => t.status === s);
<TaskSectionHeader return (
title={taskStatusLabel[s]} <TaskSection key={s} defaultOpen={s !== 'done'}>
count={rows.length} <TaskSectionTrigger>
color={taskStatusBar[s]} <TaskSectionDot color={taskStatusBar[s]} />
open={open[s]} {taskStatusLabel[s]}
onToggle={() => setOpen((o) => ({ ...o, [s]: !o[s] }))} <CountBadge>{rows.length}</CountBadge>
/> </TaskSectionTrigger>
{open[s] && ( <TaskSectionContent>
<TaskTable {rows.map((t) => (
tasks={rows} <Row
columns="full" key={t.id}
header={false} t={t}
emptyText={null} columns="full"
loadingIds={loading} loading={loading.includes(t.id)}
onToggle={toggle} onToggle={toggle}
onOpen={() => undefined} onOpen={() => undefined}
/> />
)} ))}
</div> </TaskSectionContent>
); </TaskSection>
})} );
</Card> })}
</TaskTable>
</Card>
</CardFrame>
); );
}, },
}; };
export const Prioritaet: Story = { export const Priority: Story = {
name: 'Priorität',
render: () => ( render: () => (
<div className="flex gap-6"> <div className="flex gap-6">
<PriorityLabel priority="Hoch" /> <PriorityLabel priority="high" />
<PriorityLabel priority="Mittel" /> <PriorityLabel priority="medium" />
<PriorityLabel priority="Niedrig" /> <PriorityLabel priority="low" />
</div> </div>
), ),
}; };
export const Deadlines: Story = { export const Deadlines: Story = {
render: () => ( render: () => (
<div className="max-w-[460px]"> <CardFrame className="max-w-[460px]">
<Card aria-labelledby="h-deadlines" innerClassName="gap-2"> <Card asChild className="gap-2">
<CardHeader titleId="h-deadlines" title="Anstehende Deadlines" count={deadlines.length} /> <section aria-labelledby="h-deadlines">
<ul className="m-0 flex flex-col p-0"> <CardHeader>
{deadlines.map((d, i) => ( <CardTitle id="h-deadlines">
<DeadlineItem key={d.title} {...d} last={i === deadlines.length - 1} /> Anstehende Deadlines <CountBadge>{deadlines.length}</CountBadge>
))} </CardTitle>
</ul> </CardHeader>
<DeadlineList>
{deadlines.map((d) => (
<DeadlineItem key={d.title}>
<DeadlineLink href="#">
<DateTile weekday={d.weekday} day={d.day} />
<DeadlineContent>
<TaskTitle>{d.title}</TaskTitle>
<TaskMeta>
<Swatch color={d.group.color} />
{d.group.name}
<MetaSeparator />
<DeadlineWhen soon={d.soon}>{d.when}</DeadlineWhen>
</TaskMeta>
</DeadlineContent>
<ChevronRight size={16} strokeWidth={1.75} aria-hidden="true" />
</DeadlineLink>
</DeadlineItem>
))}
</DeadlineList>
</section>
</Card> </Card>
</div> </CardFrame>
), ),
}; };
export const StatusReihenfolge: Story = { export const StatusColors: Story = {
name: 'Statusfarben',
render: () => ( render: () => (
<div className="flex gap-4"> <div className="flex gap-4">
{taskStatusOrder.map((s) => ( {taskStatusOrder.map((s) => (
+289 -227
View File
@@ -1,39 +1,35 @@
import type { ReactNode } from 'react'; import { createContext, useContext, type ComponentProps } from 'react';
import { ChevronRight, Flag, MessageSquare } from 'lucide-react'; import { ChevronRight, Flag, MessageSquare } from 'lucide-react';
import { Slot } from 'radix-ui';
import { cn } from '../../lib/cn'; import { cn } from '../../lib/cn';
import type { Priority, TaskStatus } from '../../lib/tokens'; import { priorityLabel, type Priority } from '../../lib/tokens';
import { Avatar, type Person } from '../Avatar/Avatar'; import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '../ui/collapsible';
import { StatusBadge, Swatch } from '../Badge/Badge';
import { TaskCheckbox } from '../Checkbox/Checkbox';
const prioColor: Record<Priority, string> = { const prioColor: Record<Priority, string> = {
Hoch: 'text-danger-fg', high: 'text-danger-fg',
Mittel: 'text-warning-fg', medium: 'text-warning-fg',
Niedrig: 'text-fg-dim', low: 'text-fg-dim',
}; };
/** Flag icon plus "Hoch" / "Mittel" / "Niedrig". */ export interface PriorityLabelProps extends ComponentProps<'span'> {
export function PriorityLabel({ priority, className }: { priority: Priority; className?: string }) { priority: Priority;
}
/** Flag icon plus the label ("Hoch" / "Mittel" / "Niedrig"); `children` override it. */
export function PriorityLabel({ priority, className, children, ...props }: PriorityLabelProps) {
return ( return (
<span className={cn('flex items-center gap-1.5 text-sm text-fg-muted', className)}> <span
data-slot="priority-label"
className={cn('flex items-center gap-1.5 text-sm text-fg-muted', className)}
{...props}
>
<Flag size={14} strokeWidth={1.75} aria-hidden="true" className={cn('fill-current', prioColor[priority])} /> <Flag size={14} strokeWidth={1.75} aria-hidden="true" className={cn('fill-current', prioColor[priority])} />
{priority} {children ?? priorityLabel[priority]}
</span> </span>
); );
} }
export interface TaskData { /* ---------------------------------------------------------------- Table */
id: string;
title: string;
group: { name: string; color: string };
priority: Priority;
/** Display date, e.g. "Mi, 4. Nov". */
due: string;
status: TaskStatus;
overdue?: boolean;
assignee?: Person;
comments?: number;
}
export type TaskColumns = 'compact' | 'full'; export type TaskColumns = 'compact' | 'full';
@@ -42,251 +38,317 @@ const grid: Record<TaskColumns, string> = {
full: 'grid-cols-[40px_minmax(0,1fr)_180px_96px_130px_104px]', full: 'grid-cols-[40px_minmax(0,1fr)_180px_96px_130px_104px]',
}; };
export interface TaskRowProps { const TaskTableContext = createContext<TaskColumns>('compact');
task: TaskData;
/** `compact` (dashboard) or `full` with assignee (Aufgaben page). */ export interface TaskTableProps extends ComponentProps<'div'> {
/**
* `compact` (dashboard): checkbox, task, priority, due, status.
* `full` (Aufgaben page): checkbox, task, assignee, priority, due, status.
*/
columns?: TaskColumns; columns?: TaskColumns;
onToggle?: (id: string) => void;
onOpen?: (id: string) => void;
loading?: boolean;
/** Hide the bottom rule (last row). */
last?: boolean;
/** Highlight, e.g. the row whose details are open. */
selected?: boolean;
} }
export function TaskRow({ task: t, columns = 'compact', onToggle, onOpen, loading, last, selected }: TaskRowProps) { /**
const done = t.status === 'done'; * Task table; scrolls horizontally on narrow screens.
const late = t.overdue && !done; *
const title = ( * <TaskTable aria-label="Aufgaben">
<> * <TaskTableHeader><TaskTableHead />…<TaskTableHead>Status</TaskTableHead></TaskTableHeader>
<span * <TaskRow done={…}>
className={cn( * <TaskCell><TaskCheckbox …/></TaskCell>
'block truncate leading-tight font-bold', * <TaskCell><TaskTitle>…</TaskTitle><TaskMeta>…</TaskMeta></TaskCell>
done ? 'text-fg-subtle line-through' : 'text-fg', * …
)} * </TaskRow>
> * </TaskTable>
{t.title} */
</span> export function TaskTable({ columns = 'compact', className, children, ...props }: TaskTableProps) {
<span className="mt-[3px] flex items-center gap-[7px] text-xs text-fg-muted">
<Swatch color={t.group.color} />
{t.group.name}
{!!t.comments && (
<span className="ml-1.5 flex items-center gap-1 text-fg-subtle">
<MessageSquare size={12} strokeWidth={1.75} aria-hidden="true" />
{t.comments}
</span>
)}
</span>
</>
);
return ( return (
<div <TaskTableContext value={columns}>
role="row" <div data-slot="task-table" className={cn('overflow-x-auto', className)}>
className={cn( <div
'grid items-center gap-3', role="table"
grid[columns], data-columns={columns}
columns === 'compact' ? 'py-[9px]' : 'py-1.5 pr-[18px] pl-2.5', className={columns === 'compact' ? 'min-w-[600px]' : 'min-w-[760px]'}
columns === 'compact' ? !last && 'border-b border-line-row' : 'border-t border-line-row', {...props}
selected && 'bg-hover-row', >
)} {children}
> </div>
<span role="cell"> </div>
<TaskCheckbox </TaskTableContext>
checked={done}
loading={loading}
taskTitle={t.title}
size={columns === 'compact' ? 36 : 40}
onToggle={() => onToggle?.(t.id)}
/>
</span>
<span role="cell" className="min-w-0">
{onOpen ? (
<button
type="button"
onClick={() => onOpen(t.id)}
aria-label={`${t.title} öffnen`}
className="block w-full min-w-0 py-1.5 text-left"
>
{title}
</button>
) : (
title
)}
</span>
{columns === 'full' && (
<span role="cell" className="flex min-w-0 items-center gap-2 text-sm text-fg-muted">
{t.assignee && (
<>
<Avatar person={t.assignee} size={24} aria-hidden="true" />
<span className="truncate">{t.assignee.name}</span>
</>
)}
</span>
)}
<span role="cell">
<PriorityLabel priority={t.priority} />
</span>
<span
role="cell"
className={cn(
'text-sm tabular-nums',
late ? 'font-bold text-danger-fg' : done ? 'text-fg-subtle' : 'text-fg-muted',
)}
>
{late ? `${t.due} · überfällig` : t.due}
</span>
<span role="cell">
<StatusBadge status={t.status} />
</span>
</div>
); );
} }
/** Column labels for a task table. */ export function TaskTableHeader({ className, ...props }: ComponentProps<'div'>) {
export function TaskTableHeader({ columns = 'compact' }: { columns?: TaskColumns }) { const columns = useContext(TaskTableContext);
const headers =
columns === 'compact'
? ['Aufgabe', 'Priorität', 'Fällig', 'Status']
: ['Aufgabe', 'Zuständig', 'Priorität', 'Fällig', 'Status'];
return ( return (
<div <div
role="row" role="row"
data-slot="task-table-header"
className={cn( className={cn(
'grid items-center gap-3 text-xs text-fg-subtle', 'grid items-center gap-3 text-xs text-fg-subtle',
grid[columns], grid[columns],
columns === 'compact' ? 'border-b border-line-divider pb-2.5' : 'pt-3 pr-[18px] pb-2.5 pl-2.5', columns === 'compact' ? 'border-b border-line-divider pb-2.5' : 'pt-3 pr-[18px] pb-2.5 pl-2.5',
className,
)} )}
> {...props}
<span role="columnheader" /> />
{headers.map((h) => (
<span key={h} role="columnheader">
{h}
</span>
))}
</div>
); );
} }
export interface TaskTableProps { /** Column label. The checkbox column gets an empty one. */
tasks: TaskData[]; export function TaskTableHead(props: ComponentProps<'span'>) {
columns?: TaskColumns; return <span role="columnheader" data-slot="task-table-head" {...props} />;
/** Render the column labels. Turn off for the sections of a grouped list. */
header?: boolean;
onToggle?: (id: string) => void;
onOpen?: (id: string) => void;
loadingIds?: string[];
emptyText?: ReactNode;
className?: string;
} }
/** Header row plus task rows; scrolls horizontally on narrow screens. */ export function TaskTableEmpty({ className, ...props }: ComponentProps<'div'>) {
export function TaskTable({
tasks,
columns = 'compact',
header = true,
onToggle,
onOpen,
loadingIds = [],
emptyText = 'Hier ist gerade nichts.',
className,
}: TaskTableProps) {
return ( return (
<div className={cn('overflow-x-auto', className)}> <div data-slot="task-table-empty" className={cn('px-4 py-9 text-center text-fg-muted', className)} {...props} />
<div role="table" aria-label="Aufgaben" className={columns === 'compact' ? 'min-w-[600px]' : 'min-w-[760px]'}>
{header && <TaskTableHeader columns={columns} />}
{tasks.length === 0 && emptyText && <div className="px-4 py-9 text-center text-fg-muted">{emptyText}</div>}
{tasks.map((t, i) => (
<TaskRow
key={t.id}
task={t}
columns={columns}
onToggle={onToggle}
onOpen={onOpen}
loading={loadingIds.includes(t.id)}
last={i === tasks.length - 1}
/>
))}
</div>
</div>
); );
} }
export interface TaskSectionHeaderProps { export interface TaskRowProps extends ComponentProps<'div'> {
title: string; /** Strikes the title through and mutes the due date. */
count: number; done?: boolean;
/** Status dot color. */ /** Highlight, e.g. the row whose details are open. */
color: string; selected?: boolean;
open: boolean;
onToggle?: () => void;
} }
/** Collapsible group header in the full task list ("In Arbeit 3"). */ export function TaskRow({ done, selected, className, ...props }: TaskRowProps) {
export function TaskSectionHeader({ title, count, color, open, onToggle }: TaskSectionHeaderProps) { const columns = useContext(TaskTableContext);
return (
<div
role="row"
data-slot="task-row"
data-done={done || undefined}
className={cn(
'group/task grid items-center gap-3',
grid[columns],
columns === 'compact'
? 'border-b border-line-row py-[9px] last:border-b-0'
: 'border-t border-line-row py-1.5 pr-[18px] pl-2.5',
selected && 'bg-hover-row',
className,
)}
{...props}
/>
);
}
export function TaskCell({ className, ...props }: ComponentProps<'span'>) {
return <span role="cell" data-slot="task-cell" className={cn('min-w-0', className)} {...props} />;
}
/** Makes title and meta one button that opens the task. Give it an `aria-label`. */
export function TaskOpenButton({ className, type = 'button', ...props }: ComponentProps<'button'>) {
return ( return (
<button <button
type="button" type={type}
onClick={onToggle} data-slot="task-open-button"
aria-expanded={open} className={cn('block w-full min-w-0 py-1.5 text-left', className)}
className="flex w-full items-center gap-2 border-0 border-t border-line-subtle bg-section px-[18px] py-2.5 text-left text-sm font-bold text-fg" {...props}
> />
<ChevronRight
size={14}
strokeWidth={1.75}
aria-hidden="true"
className={cn('text-fg-subtle transition-transform duration-150', open && 'rotate-90')}
/>
<span className="h-2 w-2 rounded-full" style={{ background: color }} />
{title}
<span className="inline-flex h-5 items-center rounded-full bg-chip px-[7px] text-xs font-normal text-fg-3">
{count}
</span>
</button>
); );
} }
export interface DeadlineItemProps { export function TaskTitle({ className, ...props }: ComponentProps<'span'>) {
return (
<span
data-slot="task-title"
className={cn(
'block truncate leading-tight font-bold text-fg group-data-done/task:text-fg-subtle group-data-done/task:line-through',
className,
)}
{...props}
/>
);
}
/** Line under the title: group swatch and name, comments, relative date. */
export function TaskMeta({ className, ...props }: ComponentProps<'span'>) {
return (
<span
data-slot="task-meta"
className={cn('mt-[3px] flex items-center gap-[7px] text-xs text-fg-muted', className)}
{...props}
/>
);
}
export interface TaskCommentCountProps extends ComponentProps<'span'> {
count: number;
}
export function TaskCommentCount({ count, className, ...props }: TaskCommentCountProps) {
return (
<span
data-slot="task-comment-count"
className={cn('ml-1.5 flex items-center gap-1 text-fg-subtle', className)}
{...props}
>
<MessageSquare size={12} strokeWidth={1.75} aria-hidden="true" />
{count}
<span className="sr-only"> Kommentare</span>
</span>
);
}
/** Avatar and name of the assignee. */
export function TaskAssignee({ className, ...props }: ComponentProps<'span'>) {
return (
<span
data-slot="task-assignee"
className={cn('flex min-w-0 items-center gap-2 text-sm text-fg-muted [&>span:last-child]:truncate', className)}
{...props}
/>
);
}
export interface TaskDueProps extends ComponentProps<'span'> {
overdue?: boolean;
}
/** Due date; red and bold when overdue, muted when the row is done. */
export function TaskDue({ overdue, className, ...props }: TaskDueProps) {
return (
<span
data-slot="task-due"
data-overdue={overdue || undefined}
className={cn(
'text-sm text-fg-muted tabular-nums data-overdue:font-bold data-overdue:text-danger-fg',
'group-data-done/task:font-normal group-data-done/task:text-fg-subtle',
className,
)}
{...props}
/>
);
}
/* ---------------------------------------------------------------- Sections */
/** Collapsible group of rows inside a `TaskTable` (e.g. per status). Use `open` / `onOpenChange` or `defaultOpen`. */
export function TaskSection(props: ComponentProps<typeof Collapsible>) {
return <Collapsible role="rowgroup" data-slot="task-section" {...props} />;
}
/** Section header row: `TaskSectionDot`, title, `CountBadge`. */
export function TaskSectionTrigger({ className, children, ...props }: ComponentProps<typeof CollapsibleTrigger>) {
return (
<div role="row">
<span role="rowheader">
<CollapsibleTrigger
data-slot="task-section-trigger"
className={cn(
'group/trigger flex w-full items-center gap-2 border-0 border-t border-line-subtle bg-section px-[18px] py-2.5 text-left text-sm font-bold text-fg',
className,
)}
{...props}
>
<ChevronRight
size={14}
strokeWidth={1.75}
aria-hidden="true"
className="text-fg-subtle transition-transform duration-150 group-data-[state=open]/trigger:rotate-90"
/>
{children}
</CollapsibleTrigger>
</span>
</div>
);
}
export interface TaskSectionDotProps extends ComponentProps<'span'> {
color: string;
}
export function TaskSectionDot({ color, className, style, ...props }: TaskSectionDotProps) {
return (
<span
aria-hidden="true"
data-slot="task-section-dot"
className={cn('h-2 w-2 rounded-full', className)}
style={{ background: color, ...style }}
{...props}
/>
);
}
export const TaskSectionContent = CollapsibleContent;
/* ---------------------------------------------------------------- Deadlines */
/**
* Upcoming deadlines on the dashboard.
*
* <DeadlineList>
* <DeadlineItem>
* <DeadlineLink href="…">
* <DateTile weekday="MO" day={2} />
* <DeadlineContent><TaskTitle>…</TaskTitle><TaskMeta>…<DeadlineWhen soon>morgen</DeadlineWhen></TaskMeta></DeadlineContent>
* <ChevronRight />
* </DeadlineLink>
* </DeadlineItem>
* </DeadlineList>
*/
export function DeadlineList({ className, ...props }: ComponentProps<'ul'>) {
return <ul data-slot="deadline-list" className={cn('m-0 flex flex-col p-0', className)} {...props} />;
}
export function DeadlineItem({ className, ...props }: ComponentProps<'li'>) {
return (
<li
data-slot="deadline-item"
className={cn('list-none border-line-subtle not-last:border-b', className)}
{...props}
/>
);
}
export interface DeadlineLinkProps extends ComponentProps<'a'> {
asChild?: boolean;
}
export function DeadlineLink({ asChild, className, ...props }: DeadlineLinkProps) {
const Comp = asChild ? Slot.Root : 'a';
return (
<Comp
data-slot="deadline-link"
className={cn(
'-mx-2 flex items-center gap-3.5 rounded-lg px-2 py-3 text-fg hover:bg-hover-row hover:text-fg [&>svg]:flex-none [&>svg]:text-fg-faint',
className,
)}
{...props}
/>
);
}
export function DeadlineContent({ className, ...props }: ComponentProps<'div'>) {
return <div data-slot="deadline-content" className={cn('min-w-0 flex-auto', className)} {...props} />;
}
export interface DeadlineWhenProps extends ComponentProps<'span'> {
/** Highlights it in amber. */
soon?: boolean;
}
/** Relative time, e.g. "morgen", "in 3 Tagen". */
export function DeadlineWhen({ soon, className, ...props }: DeadlineWhenProps) {
return <span data-slot="deadline-when" className={cn(soon && 'font-bold text-warning-fg', className)} {...props} />;
}
export interface DateTileProps extends ComponentProps<'div'> {
/** Weekday short, e.g. "MO". */ /** Weekday short, e.g. "MO". */
weekday: string; weekday: string;
day: string | number; day: string | number;
title: string;
group: { name: string; color: string };
/** Relative time, e.g. "morgen", "in 3 Tagen". */
when: string;
/** Highlights `when` in amber. */
soon?: boolean;
href?: string;
last?: boolean;
} }
/** Deadline row with a date tile, used on the dashboard. */ export function DateTile({ weekday, day, className, ...props }: DateTileProps) {
export function DeadlineItem({ weekday, day, title, group, when, soon, href = '#', last }: DeadlineItemProps) {
return (
<li className={cn('list-none', !last && 'border-b border-line-subtle')}>
<a href={href} className="-mx-2 flex items-center gap-3.5 rounded-lg px-2 py-3 text-fg hover:bg-hover-row hover:text-fg">
<DateTile weekday={weekday} day={day} />
<div className="min-w-0 flex-auto">
<div className="truncate leading-tight font-bold">{title}</div>
<div className="mt-[3px] flex items-center gap-[7px] text-xs text-fg-muted">
<Swatch color={group.color} />
{group.name}
<span className="text-fg-dim">·</span>
<span className={soon ? 'font-bold text-warning-fg' : undefined}>{when}</span>
</div>
</div>
<ChevronRight size={16} strokeWidth={1.75} aria-hidden="true" className="text-fg-faint" />
</a>
</li>
);
}
export function DateTile({ weekday, day, className }: { weekday: string; day: string | number; className?: string }) {
return ( return (
<div <div
data-slot="date-tile"
className={cn( className={cn(
'box-border flex h-12 w-11 flex-none flex-col items-center justify-center rounded-[10px] border border-line-divider bg-raised', 'box-border flex h-12 w-11 flex-none flex-col items-center justify-center rounded-[10px] border border-line-divider bg-raised',
className, className,
)} )}
{...props}
> >
<div className="text-[10px] leading-tight font-bold tracking-[0.04em] text-fg-subtle">{weekday}</div> <div className="text-[10px] leading-tight font-bold tracking-[0.04em] text-fg-subtle">{weekday}</div>
<div className="text-[18px] leading-[1.1] font-bold tabular-nums">{day}</div> <div className="text-[18px] leading-[1.1] font-bold tabular-nums">{day}</div>
@@ -3,11 +3,12 @@ import { Plus } from 'lucide-react';
import { colorSchemes } from '../../lib/tokens'; import { colorSchemes } from '../../lib/tokens';
import { StatusBadge } from '../Badge/Badge'; import { StatusBadge } from '../Badge/Badge';
import { Button } from '../Button/Button'; import { Button } from '../Button/Button';
import { Card, CardHeader } from '../Card/Card'; import { Card, CardAction, CardFrame, CardHeader, CardTitle } from '../Card/Card';
import { CountBadge } from '../Badge/Badge';
import { ThemeProvider } from './ThemeProvider'; import { ThemeProvider } from './ThemeProvider';
const meta: Meta<typeof ThemeProvider> = { const meta: Meta<typeof ThemeProvider> = {
title: 'Grundlagen/ThemeProvider', title: 'Foundations/ThemeProvider',
component: ThemeProvider, component: ThemeProvider,
args: { theme: 'light', accent: colorSchemes[0].color, tint: 'off' }, args: { theme: 'light', accent: colorSchemes[0].color, tint: 'off' },
argTypes: { argTypes: {
@@ -22,24 +23,34 @@ type Story = StoryObj<typeof ThemeProvider>;
function Sample() { function Sample() {
return ( return (
<Card> <CardFrame>
<CardHeader title="Meine Aufgaben" count={6} actions={<StatusBadge status="doing" />} /> <Card>
<p className="m-0 text-fg-muted"> <CardHeader>
Neutraltöne, Akzent und Status kommen aus dem nächstgelegenen <code>ThemeProvider</code>.{' '} <CardTitle>
<a href="#">Ein Link</a> Meine Aufgaben <CountBadge>6</CountBadge>
</p> </CardTitle>
<div className="flex gap-2"> <CardAction>
<Button variant="primary" icon={<Plus size={16} strokeWidth={2.25} />}> <StatusBadge status="doing" />
Neue Aufgabe </CardAction>
</Button> </CardHeader>
<Button>Abbrechen</Button> <p className="m-0 text-fg-muted">
</div> Neutraltöne, Akzent und Status kommen aus dem nächstgelegenen <code>ThemeProvider</code>.{' '}
</Card> <a href="#">Ein Link</a>
</p>
<div className="flex gap-2">
<Button variant="primary">
<Plus size={16} strokeWidth={2.25} />
Neue Aufgabe
</Button>
<Button>Abbrechen</Button>
</div>
</Card>
</CardFrame>
); );
} }
/** A nested scope overrides the toolbar theme for its subtree. */ /** A nested scope overrides the toolbar theme for its subtree. */
export const Verschachtelt: Story = { export const Nested: Story = {
render: (args) => ( render: (args) => (
<div className="grid grid-cols-[repeat(auto-fit,minmax(320px,1fr))] gap-6"> <div className="grid grid-cols-[repeat(auto-fit,minmax(320px,1fr))] gap-6">
<Sample /> <Sample />
+14 -7
View File
@@ -1,11 +1,11 @@
import { forwardRef, useCallback, useState, type CSSProperties, type HTMLAttributes } from 'react'; import { useCallback, useState, type ComponentProps, type CSSProperties } from 'react';
import { cn } from '../../lib/cn'; import { cn } from '../../lib/cn';
import { PortalContainerContext } from '../../lib/portal'; import { PortalContainerContext } from '../../lib/portal';
export type Theme = 'dark' | 'light'; export type Theme = 'dark' | 'light';
export type Tint = 'off' | 'subtle' | 'strong'; export type Tint = 'off' | 'subtle' | 'strong';
export interface ThemeProviderProps extends HTMLAttributes<HTMLDivElement> { export interface ThemeProviderProps extends ComponentProps<'div'> {
/** Color theme. */ /** Color theme. */
theme?: Theme; theme?: Theme;
/** Accent color for buttons, links and highlights. */ /** Accent color for buttons, links and highlights. */
@@ -19,11 +19,18 @@ export interface ThemeProviderProps extends HTMLAttributes<HTMLDivElement> {
* scopes can be nested (e.g. a light preview inside a dark page). Dialogs, menus * scopes can be nested (e.g. a light preview inside a dark page). Dialogs, menus
* and popovers opened inside portal into this element, so they share its theme. * and popovers opened inside portal into this element, so they share its theme.
*/ */
export const ThemeProvider = forwardRef<HTMLDivElement, ThemeProviderProps>(function ThemeProvider( export function ThemeProvider({
{ theme = 'dark', accent = '#6A5FCB', tint = 'off', className, style, children, ...props }, theme = 'dark',
accent = '#6A5FCB',
tint = 'off',
className,
style,
children,
ref, ref,
) { ...props
}: ThemeProviderProps) {
const [el, setEl] = useState<HTMLDivElement | null>(null); const [el, setEl] = useState<HTMLDivElement | null>(null);
// Stable callback: a new one each render would detach/reattach and set state in a loop.
const setRefs = useCallback( const setRefs = useCallback(
(node: HTMLDivElement | null) => { (node: HTMLDivElement | null) => {
setEl(node); setEl(node);
@@ -41,7 +48,7 @@ export const ThemeProvider = forwardRef<HTMLDivElement, ThemeProviderProps>(func
style={{ '--cl-acc': accent, ...style } as CSSProperties} style={{ '--cl-acc': accent, ...style } as CSSProperties}
{...props} {...props}
> >
<PortalContainerContext.Provider value={el}>{children}</PortalContainerContext.Provider> <PortalContainerContext value={el}>{children}</PortalContainerContext>
</div> </div>
); );
}); }
+38 -11
View File
@@ -1,30 +1,57 @@
import type { Meta, StoryObj } from '@storybook/react'; import type { Meta, StoryObj } from '@storybook/react';
import { fn } from '@storybook/test'; import { fn } from '@storybook/test';
import { CheckCircle2 } from 'lucide-react';
import { Button } from '../Button/Button'; import { Button } from '../Button/Button';
import { Toast, Toaster, toast } from './Toast'; import { Toast, ToastAction, ToastClose, Toaster, toast } from './Toast';
const meta: Meta<typeof Toast> = { const meta: Meta<typeof Toast> = {
title: 'Overlays/Toast', title: 'Overlays/Toast',
component: Toast, component: Toast,
args: { message: 'Aufgabe gelöscht', onUndo: fn(), onClose: fn() },
}; };
export default meta; export default meta;
type Story = StoryObj<typeof Toast>; type Story = StoryObj<typeof Toast>;
export const MitRueckgaengig: Story = { name: 'Mit Rückgängig' }; export const WithUndo: Story = {
render: () => (
export const Einfach: Story = { <Toast role="status">
args: { message: 'Aufgabe erstellt', onUndo: undefined }, <CheckCircle2 size={16} strokeWidth={2.5} aria-hidden="true" />
Aufgabe gelöscht
<ToastAction onClick={fn()}>Rückgängig</ToastAction>
<ToastClose onClick={fn()} />
</Toast>
),
}; };
export const Ausloesen: Story = { export const Simple: Story = {
name: 'Auslösen mit toast()', render: () => (
render: (args) => ( <Toast role="status">
<div className="h-[200px]"> <CheckCircle2 size={16} strokeWidth={2.5} aria-hidden="true" />
<Button variant="danger-outline" onClick={() => toast('Aufgabe gelöscht', { onUndo: args.onUndo })}> Aufgabe erstellt
<ToastClose onClick={fn()} />
</Toast>
),
};
/** `toast()` shows the standard composition; pass a render function for your own. */
export const Imperative: Story = {
render: () => (
<div className="flex h-[200px] items-start gap-3">
<Button variant="danger-outline" onClick={() => toast('Aufgabe gelöscht', { onUndo: fn() })}>
Aufgabe löschen Aufgabe löschen
</Button> </Button>
<Button
onClick={() =>
toast((dismiss) => (
<Toast role="status">
<CheckCircle2 size={16} strokeWidth={2.5} aria-hidden="true" />3 Aufgaben verschoben
<ToastAction onClick={dismiss}>Anzeigen</ToastAction>
</Toast>
))
}
>
Eigener Toast
</Button>
<Toaster /> <Toaster />
</div> </div>
), ),
+72 -54
View File
@@ -1,50 +1,52 @@
import type { ComponentProps, ReactNode } from 'react'; import type { ComponentProps, ReactElement, ReactNode } from 'react';
import { CheckCircle2, X } from 'lucide-react'; import { CheckCircle2, X } from 'lucide-react';
import { toast as sonner } from 'sonner'; import { toast as sonner } from 'sonner';
import { cn } from '../../lib/cn'; import { cn } from '../../lib/cn';
import { Toaster as UiToaster } from '../ui/sonner'; import { Toaster as UiToaster } from '../ui/sonner';
export interface ToastProps { /** Confirmation snackbar. An icon as first child is colored as success. */
message: ReactNode; export function Toast({ className, ...props }: ComponentProps<'div'>) {
/** Shows a "Rückgängig" action. */
onUndo?: () => void;
undoLabel?: string;
onClose?: () => void;
className?: string;
}
/** Confirmation snackbar, e.g. "Aufgabe gelöscht · Rückgängig". Usually shown with `toast()`. */
export function Toast({ message, onUndo, undoLabel = 'Rückgängig', onClose, className }: ToastProps) {
return ( return (
<div <div
role="status" data-slot="toast"
className={cn( className={cn(
'inline-flex items-center gap-2.5 rounded-xl border border-line-strong bg-elevated py-2.5 pr-2.5 pl-3.5 text-base font-bold text-fg shadow-toast', 'inline-flex items-center gap-2.5 rounded-xl border border-line-strong bg-elevated py-2.5 pr-2.5 pl-3.5 text-base font-bold text-fg shadow-toast [&>svg]:flex-none [&>svg]:text-success-fg',
className, className,
)} )}
{...props}
/>
);
}
/** Text action in a toast, e.g. "Rückgängig". */
export function ToastAction({ className, type = 'button', ...props }: ComponentProps<'button'>) {
return (
<button
type={type}
data-slot="toast-action"
className={cn(
'h-7 rounded-[7px] px-2.5 text-sm font-bold text-accent-fg hover:bg-hover hover:text-accent-fg-hover',
className,
)}
{...props}
/>
);
}
export function ToastClose({ className, children, ...props }: ComponentProps<'button'>) {
return (
<button
type="button"
aria-label="Hinweis schließen"
data-slot="toast-close"
className={cn(
'flex h-7 w-7 items-center justify-center rounded-[7px] text-fg-subtle hover:bg-hover hover:text-fg',
className,
)}
{...props}
> >
<CheckCircle2 size={16} strokeWidth={2.5} aria-hidden="true" className="flex-none text-success-fg" /> {children ?? <X size={14} strokeWidth={1.75} />}
{message} </button>
{onUndo && (
<button
type="button"
onClick={onUndo}
className="h-7 rounded-[7px] px-2.5 text-sm font-bold text-accent-fg hover:bg-hover hover:text-accent-fg-hover"
>
{undoLabel}
</button>
)}
{onClose && (
<button
type="button"
onClick={onClose}
aria-label="Hinweis schließen"
className="flex h-7 w-7 items-center justify-center rounded-[7px] text-fg-subtle hover:bg-hover hover:text-fg"
>
<X size={14} strokeWidth={1.75} />
</button>
)}
</div>
); );
} }
@@ -53,29 +55,45 @@ export function Toaster(props: ComponentProps<typeof UiToaster>) {
return <UiToaster position="bottom-center" offset={24} {...props} />; return <UiToaster position="bottom-center" offset={24} {...props} />;
} }
export interface ShowToastOptions extends Pick<ToastProps, 'onUndo' | 'undoLabel'> { export interface ShowToastOptions {
/** Adds a "Rückgängig" action that runs this and hides the toast. */
onUndo?: () => void;
undoLabel?: string;
/** ms until it hides; default 4000. */ /** ms until it hides; default 4000. */
duration?: number; duration?: number;
} }
/** Shows a `Toast` in the `Toaster`. Returns its id, for `dismissToast`. */ /**
export function toast(message: ReactNode, { onUndo, undoLabel, duration }: ShowToastOptions = {}) { * Shows a toast in the `Toaster` and returns its id. Pass a message for the standard
* confirmation, or a render function for your own `<Toast>` composition.
*/
export function toast(
content: ReactNode | ((dismiss: () => void) => ReactElement),
{ onUndo, undoLabel = 'Rückgängig', duration }: ShowToastOptions = {},
) {
return sonner.custom( return sonner.custom(
(id) => ( (id) => {
<Toast const dismiss = () => sonner.dismiss(id);
message={message} if (typeof content === 'function') return content(dismiss);
undoLabel={undoLabel} return (
onUndo={ <Toast role="status">
onUndo && <CheckCircle2 size={16} strokeWidth={2.5} aria-hidden="true" />
(() => { {content}
onUndo(); {onUndo && (
sonner.dismiss(id); <ToastAction
}) onClick={() => {
} onUndo();
onClose={() => sonner.dismiss(id)} dismiss();
/> }}
), >
// Center the snackbar in Sonner's fixed-width slot. {undoLabel}
</ToastAction>
)}
<ToastClose onClick={dismiss} />
</Toast>
);
},
// Center the toast in Sonner's fixed-width slot.
{ duration, className: 'flex w-full justify-center' }, { duration, className: 'flex w-full justify-center' },
); );
} }
+22 -6
View File
@@ -30,8 +30,8 @@ function AlertDialogContent({ className, ...props }: React.ComponentProps<typeof
<AlertDialogPrimitive.Content <AlertDialogPrimitive.Content
data-slot="alert-dialog-content" data-slot="alert-dialog-content"
className={cn( className={cn(
"fixed top-[20vh] left-1/2 z-[61] box-border max-w-[calc(100vw-32px)] -translate-x-1/2 rounded-2xl border border-line-strong bg-raised text-fg shadow-[0_24px_64px_-12px_var(--cl-sh-85)] outline-none data-[state=open]:animate-panel-in", "fixed top-[20vh] left-1/2 z-[61] box-border w-[420px] max-w-[calc(100vw-32px)] -translate-x-1/2 rounded-2xl border border-line-strong bg-raised text-fg shadow-[0_24px_64px_-12px_var(--cl-sh-85)] outline-none data-[state=open]:animate-panel-in",
className className,
)} )}
{...props} {...props}
/> />
@@ -43,6 +43,12 @@ function AlertDialogHeader({ className, ...props }: React.ComponentProps<"div">)
return <div data-slot="alert-dialog-header" className={cn("px-[22px] pt-5 pb-4", className)} {...props} /> return <div data-slot="alert-dialog-header" className={cn("px-[22px] pt-5 pb-4", className)} {...props} />
} }
function AlertDialogBody({ className, ...props }: React.ComponentProps<"div">) {
return (
<div data-slot="alert-dialog-body" className={cn("flex flex-col gap-4 px-[22px] pb-5", className)} {...props} />
)
}
function AlertDialogFooter({ className, ...props }: React.ComponentProps<"div">) { function AlertDialogFooter({ className, ...props }: React.ComponentProps<"div">) {
return ( return (
<div <div
@@ -55,11 +61,18 @@ function AlertDialogFooter({ className, ...props }: React.ComponentProps<"div">)
function AlertDialogTitle({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Title>) { function AlertDialogTitle({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
return ( return (
<AlertDialogPrimitive.Title data-slot="alert-dialog-title" className={cn("m-0 text-lg font-bold", className)} {...props} /> <AlertDialogPrimitive.Title
data-slot="alert-dialog-title"
className={cn("m-0 text-lg font-bold", className)}
{...props}
/>
) )
} }
function AlertDialogDescription({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Description>) { function AlertDialogDescription({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
return ( return (
<AlertDialogPrimitive.Description <AlertDialogPrimitive.Description
data-slot="alert-dialog-description" data-slot="alert-dialog-description"
@@ -73,7 +86,8 @@ function AlertDialogAction({
variant = "danger", variant = "danger",
size, size,
...props ...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Action> & Pick<React.ComponentProps<typeof Button>, "variant" | "size">) { }: React.ComponentProps<typeof AlertDialogPrimitive.Action> &
Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
return ( return (
<Button variant={variant} size={size} asChild> <Button variant={variant} size={size} asChild>
<AlertDialogPrimitive.Action data-slot="alert-dialog-action" {...props} /> <AlertDialogPrimitive.Action data-slot="alert-dialog-action" {...props} />
@@ -85,7 +99,8 @@ function AlertDialogCancel({
variant = "secondary", variant = "secondary",
size, size,
...props ...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel> & Pick<React.ComponentProps<typeof Button>, "variant" | "size">) { }: React.ComponentProps<typeof AlertDialogPrimitive.Cancel> &
Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
return ( return (
<Button variant={variant} size={size} asChild> <Button variant={variant} size={size} asChild>
<AlertDialogPrimitive.Cancel data-slot="alert-dialog-cancel" {...props} /> <AlertDialogPrimitive.Cancel data-slot="alert-dialog-cancel" {...props} />
@@ -97,6 +112,7 @@ export {
AlertDialog, AlertDialog,
AlertDialogAction, AlertDialogAction,
AlertDialogCancel, AlertDialogCancel,
AlertDialogBody,
AlertDialogContent, AlertDialogContent,
AlertDialogDescription, AlertDialogDescription,
AlertDialogFooter, AlertDialogFooter,
+4 -1
View File
@@ -22,7 +22,10 @@ function AvatarFallback({ className, ...props }: React.ComponentProps<typeof Ava
return ( return (
<AvatarPrimitive.Fallback <AvatarPrimitive.Fallback
data-slot="avatar-fallback" data-slot="avatar-fallback"
className={cn("flex size-full items-center justify-center rounded-full bg-chip font-black text-on-color", className)} className={cn(
"flex size-full items-center justify-center rounded-full bg-chip font-black text-on-color",
className,
)}
{...props} {...props}
/> />
) )
+3 -1
View File
@@ -27,7 +27,9 @@ function Badge({
...props ...props
}: React.ComponentProps<"span"> & VariantProps<typeof badgeVariants> & { asChild?: boolean }) { }: React.ComponentProps<"span"> & VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot.Root : "span" const Comp = asChild ? Slot.Root : "span"
return <Comp data-slot="badge" data-variant={variant} className={cn(badgeVariants({ variant }), className)} {...props} /> return (
<Comp data-slot="badge" data-variant={variant} className={cn(badgeVariants({ variant }), className)} {...props} />
)
} }
export { Badge, badgeVariants } export { Badge, badgeVariants }
+4 -8
View File
@@ -33,22 +33,18 @@ const buttonVariants = cva(
variant: "secondary", variant: "secondary",
size: "md", size: "md",
}, },
} },
) )
type ButtonProps = React.ComponentPropsWithoutRef<"button"> & type ButtonProps = React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & { VariantProps<typeof buttonVariants> & {
asChild?: boolean asChild?: boolean
} }
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(function Button( function Button({ className, variant, size, iconOnly, fullWidth, asChild = false, ...props }: ButtonProps) {
{ className, variant, size, iconOnly, fullWidth, asChild = false, ...props },
ref
) {
const Comp = asChild ? Slot.Root : "button" const Comp = asChild ? Slot.Root : "button"
return ( return (
<Comp <Comp
ref={ref}
data-slot="button" data-slot="button"
data-variant={variant} data-variant={variant}
data-size={size} data-size={size}
@@ -56,6 +52,6 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(function Button(
{...props} {...props}
/> />
) )
}) }
export { Button, buttonVariants, type ButtonProps } export { Button, buttonVariants, type ButtonProps }
+28 -10
View File
@@ -2,17 +2,22 @@ import * as React from "react"
import { cn } from "@/lib/cn" import { cn } from "@/lib/cn"
import { Slot } from "radix-ui" import { Slot } from "radix-ui"
/** The raised inner surface of a Collabry card. */ /** The raised inner surface of a Collabry card. Use `asChild` for `section`, `article` or `form`. */
function Card({ className, ...props }: React.ComponentProps<"div">) { function Card({ className, asChild, ...props }: React.ComponentProps<"div"> & { asChild?: boolean }) {
const Comp = asChild ? Slot.Root : "div"
return ( return (
<div <Comp
data-slot="card" data-slot="card"
className={cn("box-border flex min-w-0 flex-auto flex-col rounded-[13px] border border-line bg-surface text-fg", className)} className={cn(
"box-border flex min-w-0 flex-auto flex-col rounded-[13px] border border-line bg-surface text-fg",
className,
)}
{...props} {...props}
/> />
) )
} }
/** `CardTitle` (or a `CardHeading` with title and description), then `CardAction` on the right. Wraps when narrow. */
function CardHeader({ className, ...props }: React.ComponentProps<"div">) { function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return ( return (
<div <div
@@ -23,22 +28,35 @@ function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
) )
} }
/** Pass `asChild` to render a heading element. */ /** Card heading (`h2`; use `asChild` for another level). Put a `CountBadge` inside for a count. */
function CardTitle({ className, asChild = false, ...props }: React.ComponentProps<"div"> & { asChild?: boolean }) { function CardTitle({ className, asChild, ...props }: React.ComponentProps<"h2"> & { asChild?: boolean }) {
const Comp = asChild ? Slot.Root : "div" const Comp = asChild ? Slot.Root : "h2"
return <Comp data-slot="card-title" className={cn("m-0 text-md font-bold", className)} {...props} /> return (
<Comp
data-slot="card-title"
className={cn("m-0 flex items-center gap-2 text-md font-bold", className)}
{...props}
/>
)
} }
/** Groups `CardTitle` and `CardDescription` on the left of a `CardHeader`. */
function CardHeading({ className, ...props }: React.ComponentProps<"div">) {
return <div data-slot="card-heading" className={cn("min-w-0", className)} {...props} />
}
/** Secondary line under the title. */
function CardDescription({ className, ...props }: React.ComponentProps<"div">) { function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return <div data-slot="card-description" className={cn("text-sm text-fg-subtle", className)} {...props} /> return <div data-slot="card-description" className={cn("mt-1 text-sm text-fg-subtle", className)} {...props} />
} }
function CardAction({ className, ...props }: React.ComponentProps<"div">) { function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return <div data-slot="card-action" className={cn("flex items-center gap-3", className)} {...props} /> return <div data-slot="card-action" className={cn("flex items-center gap-3", className)} {...props} />
} }
/** Footer row that pins its content to the bottom of a card. */
function CardFooter({ className, ...props }: React.ComponentProps<"div">) { function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return <div data-slot="card-footer" className={cn("mt-auto flex pt-1", className)} {...props} /> return <div data-slot="card-footer" className={cn("mt-auto flex pt-1", className)} {...props} />
} }
export { Card, CardHeader, CardFooter, CardTitle, CardAction, CardDescription } export { Card, CardHeader, CardHeading, CardFooter, CardTitle, CardAction, CardDescription }
+3 -7
View File
@@ -3,17 +3,13 @@ import { cn } from "@/lib/cn"
import { CheckIcon } from "lucide-react" import { CheckIcon } from "lucide-react"
import { Checkbox as CheckboxPrimitive } from "radix-ui" import { Checkbox as CheckboxPrimitive } from "radix-ui"
const Checkbox = React.forwardRef< function Checkbox({ className, ...props }: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
HTMLButtonElement,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(function Checkbox({ className, ...props }, ref) {
return ( return (
<CheckboxPrimitive.Root <CheckboxPrimitive.Root
ref={ref}
data-slot="checkbox" data-slot="checkbox"
className={cn( className={cn(
"peer box-border flex size-4 shrink-0 items-center justify-center rounded-[4px] border border-line-control bg-raised text-on-accent shadow-bevel outline-none transition-colors focus-visible:shadow-focus disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:border-accent data-[state=checked]:bg-accent", "peer box-border flex size-4 shrink-0 items-center justify-center rounded-[4px] border border-line-control bg-raised text-on-accent shadow-bevel outline-none transition-colors focus-visible:shadow-focus disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:border-accent data-[state=checked]:bg-accent",
className className,
)} )}
{...props} {...props}
> >
@@ -22,6 +18,6 @@ const Checkbox = React.forwardRef<
</CheckboxPrimitive.Indicator> </CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root> </CheckboxPrimitive.Root>
) )
}) }
export { Checkbox } export { Checkbox }
+17
View File
@@ -0,0 +1,17 @@
import * as React from "react"
import { Collapsible as CollapsiblePrimitive } from "radix-ui"
function Collapsible({ ...props }: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />
}
function CollapsibleTrigger({ ...props }: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
return <CollapsiblePrimitive.CollapsibleTrigger data-slot="collapsible-trigger" {...props} />
}
function CollapsibleContent({ ...props }: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
return <CollapsiblePrimitive.CollapsibleContent data-slot="collapsible-content" {...props} />
}
export { Collapsible, CollapsibleTrigger, CollapsibleContent }
+39 -18
View File
@@ -15,29 +15,41 @@ function Command({ className, ...props }: React.ComponentProps<typeof CommandPri
) )
} }
function CommandDialog({ /** `Command` inside a `DialogContent`; put it in a `Dialog` next to a `DialogTrigger`. Props go to `Command`. */
function CommandDialogContent({
title = "Suche", title = "Suche",
description = "Suche nach Aufgaben, Gruppen, Seiten und Aktionen.", description = "Suche nach Aufgaben, Gruppen, Seiten und Aktionen.",
children, children,
className, className,
commandProps,
...props ...props
}: React.ComponentProps<typeof Dialog> & { }: Omit<React.ComponentProps<typeof CommandPrimitive>, "title"> & {
title?: string title?: string
description?: string description?: string
className?: string
commandProps?: React.ComponentProps<typeof CommandPrimitive>
}) { }) {
return ( return (
<Dialog {...props}> <DialogContent
<DialogContent showCloseButton={false}
showCloseButton={false} className={cn("top-[12vh] flex w-[640px] flex-col overflow-hidden", className)}
className={cn("top-[12vh] flex w-[640px] flex-col overflow-hidden", className)} >
> <DialogTitle className="sr-only">{title}</DialogTitle>
<DialogTitle className="sr-only">{title}</DialogTitle> <DialogDescription className="sr-only">{description}</DialogDescription>
<DialogDescription className="sr-only">{description}</DialogDescription> <Command {...props}>{children}</Command>
<Command {...commandProps}>{children}</Command> </DialogContent>
</DialogContent> )
}
/** Shorthand for `Dialog` + `CommandDialogContent` (shadcn's API). */
function CommandDialog({
open,
defaultOpen,
onOpenChange,
modal,
...props
}: React.ComponentProps<typeof CommandDialogContent> &
Pick<React.ComponentProps<typeof Dialog>, "open" | "defaultOpen" | "onOpenChange" | "modal">) {
return (
<Dialog open={open} defaultOpen={defaultOpen} onOpenChange={onOpenChange} modal={modal}>
<CommandDialogContent {...props} />
</Dialog> </Dialog>
) )
} }
@@ -54,7 +66,7 @@ function CommandInput({ className, children, ...props }: React.ComponentProps<ty
data-slot="command-input" data-slot="command-input"
className={cn( className={cn(
"h-full min-w-0 flex-auto border-0 bg-transparent text-[16px] text-fg outline-none placeholder:text-fg-subtle", "h-full min-w-0 flex-auto border-0 bg-transparent text-[16px] text-fg outline-none placeholder:text-fg-subtle",
className className,
)} )}
{...props} {...props}
/> />
@@ -89,7 +101,7 @@ function CommandGroup({ className, ...props }: React.ComponentProps<typeof Comma
data-slot="command-group" data-slot="command-group"
className={cn( className={cn(
"[&_[cmdk-group-heading]]:px-2.5 [&_[cmdk-group-heading]]:pt-2.5 [&_[cmdk-group-heading]]:pb-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-bold [&_[cmdk-group-heading]]:text-fg-subtle", "[&_[cmdk-group-heading]]:px-2.5 [&_[cmdk-group-heading]]:pt-2.5 [&_[cmdk-group-heading]]:pb-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-bold [&_[cmdk-group-heading]]:text-fg-subtle",
className className,
)} )}
{...props} {...props}
/> />
@@ -102,11 +114,20 @@ function CommandItem({ className, ...props }: React.ComponentProps<typeof Comman
data-slot="command-item" data-slot="command-item"
className={cn( className={cn(
"group/item box-border flex min-h-11 w-full cursor-pointer items-center gap-3 rounded-[10px] px-2.5 py-1.5 text-base outline-none select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-option-active", "group/item box-border flex min-h-11 w-full cursor-pointer items-center gap-3 rounded-[10px] px-2.5 py-1.5 text-base outline-none select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-option-active",
className className,
)} )}
{...props} {...props}
/> />
) )
} }
export { Command, CommandDialog, CommandInput, CommandList, CommandEmpty, CommandGroup, CommandItem } export {
Command,
CommandDialog,
CommandDialogContent,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandItem,
}
+36 -5
View File
@@ -33,6 +33,14 @@ function DialogOverlay({ className, ...props }: React.ComponentProps<typeof Dial
) )
} }
/** Focus the first form field on open (instead of the close button), unless the handler prevented it. */
function focusFirstField(e: Event) {
const field = (e.currentTarget as HTMLElement).querySelector<HTMLElement>("[autofocus], input, textarea, select")
if (!field) return
e.preventDefault()
field.focus({ preventScroll: true })
}
/** Close button in the design's ghost style. */ /** Close button in the design's ghost style. */
const closeButtonClass = cn(buttonVariants({ variant: "ghost", size: "sm", iconOnly: true }), "text-fg-subtle") const closeButtonClass = cn(buttonVariants({ variant: "ghost", size: "sm", iconOnly: true }), "text-fg-subtle")
@@ -40,6 +48,7 @@ function DialogContent({
className, className,
children, children,
showCloseButton = true, showCloseButton = true,
onOpenAutoFocus,
...props ...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & { }: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean showCloseButton?: boolean
@@ -50,14 +59,22 @@ function DialogContent({
<DialogPrimitive.Content <DialogPrimitive.Content
data-slot="dialog-content" data-slot="dialog-content"
className={cn( className={cn(
"fixed top-[10vh] left-1/2 z-[61] box-border max-w-[calc(100vw-32px)] -translate-x-1/2 rounded-2xl border border-line-strong bg-raised text-fg shadow-dialog outline-none data-[state=open]:animate-panel-in", "fixed top-[10vh] left-1/2 z-[61] box-border w-[560px] max-w-[calc(100vw-32px)] -translate-x-1/2 rounded-2xl border border-line-strong bg-raised text-fg shadow-dialog outline-none data-[state=open]:animate-panel-in",
className className,
)} )}
onOpenAutoFocus={(e) => {
onOpenAutoFocus?.(e)
if (!e.defaultPrevented) focusFirstField(e)
}}
{...props} {...props}
> >
{children} {children}
{showCloseButton && ( {showCloseButton && (
<DialogPrimitive.Close data-slot="dialog-close" aria-label="Schließen" className={cn(closeButtonClass, "absolute top-5 right-4")}> <DialogPrimitive.Close
data-slot="dialog-close"
aria-label="Schließen"
className={cn(closeButtonClass, "absolute top-5 right-4")}
>
<XIcon size={16} strokeWidth={1.75} /> <XIcon size={16} strokeWidth={1.75} />
</DialogPrimitive.Close> </DialogPrimitive.Close>
)} )}
@@ -67,7 +84,17 @@ function DialogContent({
} }
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) { function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return <div data-slot="dialog-header" className={cn("flex flex-col gap-1", className)} {...props} /> return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-1 pt-5 pr-[60px] pb-1 pl-[22px]", className)}
{...props}
/>
)
}
function DialogBody({ className, ...props }: React.ComponentProps<"div">) {
return <div data-slot="dialog-body" className={cn("flex flex-col gap-4 px-[22px] pt-4 pb-5", className)} {...props} />
} }
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) { function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
@@ -81,7 +108,9 @@ function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
} }
function DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) { function DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {
return <DialogPrimitive.Title data-slot="dialog-title" className={cn("m-0 text-lg font-bold", className)} {...props} /> return (
<DialogPrimitive.Title data-slot="dialog-title" className={cn("m-0 text-lg font-bold", className)} {...props} />
)
} }
function DialogDescription({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Description>) { function DialogDescription({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Description>) {
@@ -101,9 +130,11 @@ export {
DialogDescription, DialogDescription,
DialogFooter, DialogFooter,
DialogHeader, DialogHeader,
DialogBody,
DialogOverlay, DialogOverlay,
DialogPortal, DialogPortal,
DialogTitle, DialogTitle,
DialogTrigger, DialogTrigger,
closeButtonClass, closeButtonClass,
focusFirstField,
} }
+24 -5
View File
@@ -14,16 +14,23 @@ function DropdownMenuTrigger(props: React.ComponentProps<typeof DropdownMenuPrim
function DropdownMenuContent({ function DropdownMenuContent({
className, className,
sideOffset = 6, sideOffset = 6,
align = "end",
size = "md",
...props ...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) { }: React.ComponentProps<typeof DropdownMenuPrimitive.Content> & {
/** `lg` for the account menu (40px items), `md` for card menus (38px). */
size?: "md" | "lg"
}) {
return ( return (
<DropdownMenuPrimitive.Portal container={usePortalContainer()}> <DropdownMenuPrimitive.Portal container={usePortalContainer()}>
<DropdownMenuPrimitive.Content <DropdownMenuPrimitive.Content
data-slot="dropdown-menu-content" data-slot="dropdown-menu-content"
data-size={size}
sideOffset={sideOffset} sideOffset={sideOffset}
align={align}
className={cn( className={cn(
"z-50 box-border flex max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) flex-col overflow-y-auto rounded-xl border border-line-strong bg-raised p-1.5 text-fg shadow-dropdown outline-none data-[state=open]:animate-panel-in", "group/menu z-50 box-border flex w-[220px] data-[size=lg]:w-72 data-[size=lg]:rounded-[14px] data-[size=lg]:shadow-menu max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) flex-col overflow-y-auto rounded-xl border border-line-strong bg-raised p-1.5 text-fg shadow-dropdown outline-none data-[state=open]:animate-panel-in",
className className,
)} )}
{...props} {...props}
/> />
@@ -47,8 +54,8 @@ function DropdownMenuItem({
data-slot="dropdown-menu-item" data-slot="dropdown-menu-item"
data-variant={variant} data-variant={variant}
className={cn( className={cn(
"relative flex h-[38px] w-full cursor-pointer items-center gap-2.5 rounded-lg px-2.5 text-left text-base text-fg-2 outline-none select-none focus:bg-hover-menu focus:text-fg-strong data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[variant=destructive]:text-danger-fg data-[variant=destructive]:focus:text-danger-fg [&_svg]:pointer-events-none [&_svg]:shrink-0", "relative flex h-[38px] w-full cursor-pointer items-center gap-2.5 rounded-lg px-2.5 text-left text-base text-fg-2 outline-none select-none focus:bg-hover-menu focus:text-fg-strong data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[variant=destructive]:text-danger-fg data-[variant=destructive]:focus:text-danger-fg group-data-[size=lg]/menu:h-10 group-data-[size=lg]/menu:gap-3 group-data-[size=lg]/menu:rounded-[9px] [&_svg]:pointer-events-none [&_svg]:shrink-0 [&>svg]:text-fg-muted data-[variant=destructive]:[&>svg]:text-danger-fg",
className className,
)} )}
{...props} {...props}
/> />
@@ -65,6 +72,17 @@ function DropdownMenuLabel({ className, ...props }: React.ComponentProps<typeof
) )
} }
/** Right-aligned detail in an item, e.g. the current theme "Dunkel ›". */
function DropdownMenuDetail({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
data-slot="dropdown-menu-detail"
className={cn("ml-auto flex items-center gap-1 text-sm text-fg-subtle", className)}
{...props}
/>
)
}
function DropdownMenuSeparator({ className, ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) { function DropdownMenuSeparator({ className, ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
return ( return (
<DropdownMenuPrimitive.Separator <DropdownMenuPrimitive.Separator
@@ -83,4 +101,5 @@ export {
DropdownMenuLabel, DropdownMenuLabel,
DropdownMenuItem, DropdownMenuItem,
DropdownMenuSeparator, DropdownMenuSeparator,
DropdownMenuDetail,
} }
+3 -6
View File
@@ -5,11 +5,8 @@ import { cn } from "@/lib/cn"
const fieldClass = const fieldClass =
"box-border w-full min-w-0 rounded-[10px] border border-line bg-inset text-base text-fg font-[inherit] transition-[border-color,box-shadow] duration-100 outline-none placeholder:text-fg-subtle focus:border-accent-focus focus:shadow-focus disabled:opacity-50 aria-invalid:border-danger-fg" "box-border w-full min-w-0 rounded-[10px] border border-line bg-inset text-base text-fg font-[inherit] transition-[border-color,box-shadow] duration-100 outline-none placeholder:text-fg-subtle focus:border-accent-focus focus:shadow-focus disabled:opacity-50 aria-invalid:border-danger-fg"
const Input = React.forwardRef<HTMLInputElement, React.ComponentPropsWithoutRef<"input">>(function Input( function Input({ className, type, ...props }: React.ComponentProps<"input">) {
{ className, type, ...props }, return <input type={type} data-slot="input" className={cn(fieldClass, "h-[38px] px-3", className)} {...props} />
ref }
) {
return <input ref={ref} type={type} data-slot="input" className={cn(fieldClass, "h-[38px] px-3", className)} {...props} />
})
export { Input, fieldClass } export { Input, fieldClass }
+1 -1
View File
@@ -7,7 +7,7 @@ function Kbd({ className, ...props }: React.ComponentProps<"kbd">) {
data-slot="kbd" data-slot="kbd"
className={cn( className={cn(
"box-border inline-flex h-[22px] min-w-[22px] items-center justify-center rounded-[5px] border border-line-heavy bg-elevated px-[5px] font-sans text-xs text-fg-muted select-none", "box-border inline-flex h-[22px] min-w-[22px] items-center justify-center rounded-[5px] border border-line-heavy bg-elevated px-[5px] font-sans text-xs text-fg-muted select-none",
className className,
)} )}
{...props} {...props}
/> />
+3 -7
View File
@@ -5,20 +5,16 @@ import { fieldClass } from "@/components/ui/input"
const heights = { md: "h-[38px]", lg: "h-[42px]", settings: "h-10" } const heights = { md: "h-[38px]", lg: "h-[42px]", settings: "h-10" }
type NativeSelectProps = Omit<React.ComponentPropsWithoutRef<"select">, "size"> & { type NativeSelectProps = Omit<React.ComponentProps<"select">, "size"> & {
/** 38px (filters, dialogs), 42px (auth forms) or 40px (settings rows). */ /** 38px (filters, dialogs), 42px (auth forms) or 40px (settings rows). */
size?: keyof typeof heights size?: keyof typeof heights
} }
/** Native select with the design's chevron. `className` sizes the wrapper. */ /** Native select with the design's chevron. `className` sizes the wrapper. */
const NativeSelect = React.forwardRef<HTMLSelectElement, NativeSelectProps>(function NativeSelect( function NativeSelect({ className, size = "md", ...props }: NativeSelectProps) {
{ className, size = "md", ...props },
ref
) {
return ( return (
<span data-slot="native-select-wrapper" className={cn("relative flex", className)}> <span data-slot="native-select-wrapper" className={cn("relative flex", className)}>
<select <select
ref={ref}
data-slot="native-select" data-slot="native-select"
data-size={size} data-size={size}
className={cn(fieldClass, heights[size], "cursor-pointer appearance-none pr-8 pl-3")} className={cn(fieldClass, heights[size], "cursor-pointer appearance-none pr-8 pl-3")}
@@ -33,7 +29,7 @@ const NativeSelect = React.forwardRef<HTMLSelectElement, NativeSelectProps>(func
/> />
</span> </span>
) )
}) }
function NativeSelectOption(props: React.ComponentProps<"option">) { function NativeSelectOption(props: React.ComponentProps<"option">) {
return <option data-slot="native-select-option" {...props} /> return <option data-slot="native-select-option" {...props} />
+1 -1
View File
@@ -26,7 +26,7 @@ function PopoverContent({
sideOffset={sideOffset} sideOffset={sideOffset}
className={cn( className={cn(
"z-50 origin-(--radix-popover-content-transform-origin) text-fg outline-none data-[state=open]:animate-panel-in", "z-50 origin-(--radix-popover-content-transform-origin) text-fg outline-none data-[state=open]:animate-panel-in",
className className,
)} )}
{...props} {...props}
/> />
+4 -1
View File
@@ -11,7 +11,10 @@ function RadioGroupItem({ className, ...props }: React.ComponentProps<typeof Rad
return ( return (
<RadioGroupPrimitive.Item <RadioGroupPrimitive.Item
data-slot="radio-group-item" data-slot="radio-group-item"
className={cn("outline-none focus-visible:shadow-focus disabled:cursor-not-allowed disabled:opacity-50", className)} className={cn(
"outline-none focus-visible:shadow-focus disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
{...props} {...props}
/> />
) )
+42 -7
View File
@@ -4,7 +4,7 @@ import { usePortalContainer } from "@/lib/portal"
import { XIcon } from "lucide-react" import { XIcon } from "lucide-react"
import { Dialog as SheetPrimitive } from "radix-ui" import { Dialog as SheetPrimitive } from "radix-ui"
import { closeButtonClass } from "@/components/ui/dialog" import { closeButtonClass, focusFirstField } from "@/components/ui/dialog"
function Sheet(props: React.ComponentProps<typeof SheetPrimitive.Root>) { function Sheet(props: React.ComponentProps<typeof SheetPrimitive.Root>) {
return <SheetPrimitive.Root data-slot="sheet" {...props} /> return <SheetPrimitive.Root data-slot="sheet" {...props} />
@@ -33,6 +33,7 @@ function SheetContent({
className, className,
children, children,
showCloseButton = true, showCloseButton = true,
onOpenAutoFocus,
...props ...props
}: React.ComponentProps<typeof SheetPrimitive.Content> & { }: React.ComponentProps<typeof SheetPrimitive.Content> & {
showCloseButton?: boolean showCloseButton?: boolean
@@ -43,14 +44,18 @@ function SheetContent({
<SheetPrimitive.Content <SheetPrimitive.Content
data-slot="sheet-content" data-slot="sheet-content"
className={cn( className={cn(
"fixed top-2 right-2 bottom-2 z-50 box-border flex max-w-[calc(100vw-16px)] flex-col overflow-hidden rounded-2xl border border-line-strong bg-raised text-fg shadow-popover outline-none data-[state=open]:animate-drawer-in", "fixed top-2 right-2 bottom-2 z-50 box-border flex w-[460px] max-w-[calc(100vw-16px)] flex-col overflow-hidden rounded-2xl border border-line-strong bg-raised text-fg shadow-popover outline-none data-[state=open]:animate-drawer-in",
className className,
)} )}
onOpenAutoFocus={(e) => {
onOpenAutoFocus?.(e)
if (!e.defaultPrevented) focusFirstField(e)
}}
{...props} {...props}
> >
{children} {children}
{showCloseButton && ( {showCloseButton && (
<SheetPrimitive.Close aria-label="Schließen" className={cn(closeButtonClass, "absolute top-3 right-3")}> <SheetPrimitive.Close aria-label="Schließen" className={cn(closeButtonClass, "absolute top-3.5 right-3")}>
<XIcon size={16} strokeWidth={1.75} /> <XIcon size={16} strokeWidth={1.75} />
</SheetPrimitive.Close> </SheetPrimitive.Close>
)} )}
@@ -63,7 +68,22 @@ function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
return ( return (
<div <div
data-slot="sheet-header" data-slot="sheet-header"
className={cn("flex items-center gap-2.5 border-b border-line-divider py-3.5 pr-3 pl-5", className)} className={cn("flex items-center gap-2.5 border-b border-line-divider py-3.5 pr-[46px] pl-5", className)}
{...props}
/>
)
}
/** Extra header buttons, placed before the close button. */
function SheetActions({ className, ...props }: React.ComponentProps<"div">) {
return <div data-slot="sheet-actions" className={cn("ml-auto flex gap-0.5", className)} {...props} />
}
function SheetBody({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sheet-body"
className={cn("flex flex-auto flex-col gap-[18px] overflow-y-auto px-5 pt-[18px] pb-6", className)}
{...props} {...props}
/> />
) )
@@ -85,8 +105,23 @@ function SheetTitle({ className, ...props }: React.ComponentProps<typeof SheetPr
function SheetDescription({ className, ...props }: React.ComponentProps<typeof SheetPrimitive.Description>) { function SheetDescription({ className, ...props }: React.ComponentProps<typeof SheetPrimitive.Description>) {
return ( return (
<SheetPrimitive.Description data-slot="sheet-description" className={cn("text-sm text-fg-subtle", className)} {...props} /> <SheetPrimitive.Description
data-slot="sheet-description"
className={cn("text-sm text-fg-subtle", className)}
{...props}
/>
) )
} }
export { Sheet, SheetTrigger, SheetClose, SheetContent, SheetHeader, SheetFooter, SheetTitle, SheetDescription } export {
Sheet,
SheetTrigger,
SheetClose,
SheetContent,
SheetHeader,
SheetActions,
SheetBody,
SheetFooter,
SheetTitle,
SheetDescription,
}
+2 -6
View File
@@ -2,18 +2,14 @@ import * as React from "react"
import { cn } from "@/lib/cn" import { cn } from "@/lib/cn"
import { fieldClass } from "@/components/ui/input" import { fieldClass } from "@/components/ui/input"
const Textarea = React.forwardRef<HTMLTextAreaElement, React.ComponentPropsWithoutRef<"textarea">>(function Textarea( function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
{ className, ...props },
ref
) {
return ( return (
<textarea <textarea
ref={ref}
data-slot="textarea" data-slot="textarea"
className={cn(fieldClass, "resize-y px-3 py-2.5 leading-normal", className)} className={cn(fieldClass, "resize-y px-3 py-2.5 leading-normal", className)}
{...props} {...props}
/> />
) )
}) }
export { Textarea } export { Textarea }
+3 -8
View File
@@ -12,8 +12,7 @@ const toggleVariants = cva(
segment: segment:
"box-border gap-1.5 rounded-[7px] border border-transparent bg-transparent text-sm font-bold text-fg-muted transition-colors duration-100 hover:text-fg disabled:opacity-50 data-[state=on]:border-line-heavy data-[state=on]:bg-seg-active data-[state=on]:text-fg data-[state=on]:shadow-seg", "box-border gap-1.5 rounded-[7px] border border-transparent bg-transparent text-sm font-bold text-fg-muted transition-colors duration-100 hover:text-fg disabled:opacity-50 data-[state=on]:border-line-heavy data-[state=on]:bg-seg-active data-[state=on]:text-fg data-[state=on]:shadow-seg",
/** Rounded filter pill. */ /** Rounded filter pill. */
chip: chip: "h-8 gap-2 rounded-full border border-line-divider bg-transparent px-3 text-sm font-bold text-fg-subtle hover:text-fg disabled:opacity-50 data-[state=on]:border-line-heavy data-[state=on]:bg-elevated data-[state=on]:text-fg",
"h-8 gap-2 rounded-full border border-line-divider bg-transparent px-3 text-sm font-bold text-fg-subtle hover:text-fg disabled:opacity-50 data-[state=on]:border-line-heavy data-[state=on]:bg-elevated data-[state=on]:text-fg",
/** No look of its own; style the children. */ /** No look of its own; style the children. */
bare: "", bare: "",
}, },
@@ -25,7 +24,7 @@ const toggleVariants = cva(
defaultVariants: { defaultVariants: {
variant: "segment", variant: "segment",
}, },
} },
) )
function Toggle({ function Toggle({
@@ -35,11 +34,7 @@ function Toggle({
...props ...props
}: React.ComponentProps<typeof TogglePrimitive.Root> & VariantProps<typeof toggleVariants>) { }: React.ComponentProps<typeof TogglePrimitive.Root> & VariantProps<typeof toggleVariants>) {
return ( return (
<TogglePrimitive.Root <TogglePrimitive.Root data-slot="toggle" className={cn(toggleVariants({ variant, size }), className)} {...props} />
data-slot="toggle"
className={cn(toggleVariants({ variant, size }), className)}
{...props}
/>
) )
} }
+1
View File
@@ -28,3 +28,4 @@ export * from './components/Settings/Settings';
export * from './components/Auth/Auth'; export * from './components/Auth/Auth';
export * from './components/Comment/Comment'; export * from './components/Comment/Comment';
export * from './components/Layout/Layout'; export * from './components/Layout/Layout';
export { Popover, PopoverTrigger, PopoverAnchor, PopoverContent, PopoverClose } from './components/ui/popover';
+14 -1
View File
@@ -7,7 +7,20 @@ const twMerge = extendTailwindMerge({
extend: { extend: {
theme: { theme: {
text: ['2xs', 'md', 'display', 'hero'], text: ['2xs', 'md', 'display', 'hero'],
shadow: ['popover', 'menu', 'dropdown', 'dialog', 'toast', 'seg', 'bevel', 'nav-active', 'focus', 'side', 'primary', 'primary-flat'], shadow: [
'popover',
'menu',
'dropdown',
'dialog',
'toast',
'seg',
'bevel',
'nav-active',
'focus',
'side',
'primary',
'primary-flat',
],
}, },
}, },
}); });
+13 -7
View File
@@ -1,12 +1,12 @@
/** Accent color schemes offered in "Einstellungen – Allgemein". */ /** Accent color schemes offered in "Einstellungen – Allgemein". */
export const colorSchemes = [ export const colorSchemes = [
{ id: 'violett', name: 'Violett', color: '#6A5FCB' }, { id: 'violet', name: 'Violett', color: '#6A5FCB' },
{ id: 'blau', name: 'Blau', color: '#3B6FD6' }, { id: 'blue', name: 'Blau', color: '#3B6FD6' },
{ id: 'petrol', name: 'Petrol', color: '#0C7C7C' }, { id: 'teal', name: 'Petrol', color: '#0C7C7C' },
{ id: 'gruen', name: 'Grün', color: '#2A7D4A' }, { id: 'green', name: 'Grün', color: '#2A7D4A' },
{ id: 'bernstein', name: 'Bernstein', color: '#B4570A' }, { id: 'amber', name: 'Bernstein', color: '#B4570A' },
{ id: 'rose', name: 'Rosé', color: '#C23B6E' }, { id: 'rose', name: 'Rosé', color: '#C23B6E' },
{ id: 'graphit', name: 'Graphit', color: '#5E6270' }, { id: 'graphite', name: 'Graphit', color: '#5E6270' },
] as const; ] as const;
export type ColorSchemeId = (typeof colorSchemes)[number]['id']; export type ColorSchemeId = (typeof colorSchemes)[number]['id'];
@@ -38,4 +38,10 @@ export const taskStatusBar: Record<TaskStatus, string> = {
open: 'var(--cl-open-bar)', open: 'var(--cl-open-bar)',
}; };
export type Priority = 'Hoch' | 'Mittel' | 'Niedrig'; export type Priority = 'high' | 'medium' | 'low';
export const priorityLabel: Record<Priority, string> = {
high: 'Hoch',
medium: 'Mittel',
low: 'Niedrig',
};
+30 -8
View File
@@ -2,7 +2,7 @@ import type { Meta, StoryObj } from '@storybook/react';
import { colorSchemes, swatches } from '../lib/tokens'; import { colorSchemes, swatches } from '../lib/tokens';
const meta: Meta = { const meta: Meta = {
title: 'Grundlagen/Tokens', title: 'Foundations/Tokens',
parameters: { controls: { disable: true } }, parameters: { controls: { disable: true } },
}; };
export default meta; export default meta;
@@ -11,19 +11,41 @@ type Story = StoryObj;
const groups: { title: string; tokens: string[] }[] = [ const groups: { title: string; tokens: string[] }[] = [
{ {
title: 'Flächen', title: 'Surfaces',
tokens: ['app', 'frame', 'surface', 'inset', 'raised', 'elevated', 'chip', 'track', 'soft', 'section', 'side', 'side-active'], tokens: [
'app',
'frame',
'surface',
'inset',
'raised',
'elevated',
'chip',
'track',
'soft',
'section',
'side',
'side-active',
],
}, },
{ {
title: 'Linien', title: 'Lines',
tokens: ['line-frame', 'line', 'line-strong', 'line-heavy', 'line-divider', 'line-subtle', 'line-row', 'line-control'], tokens: [
'line-frame',
'line',
'line-strong',
'line-heavy',
'line-divider',
'line-subtle',
'line-row',
'line-control',
],
}, },
{ {
title: 'Text', title: 'Text',
tokens: ['fg', 'fg-strong', 'fg-2', 'fg-3', 'fg-4', 'fg-muted', 'fg-subtle', 'fg-faint', 'fg-dim'], tokens: ['fg', 'fg-strong', 'fg-2', 'fg-3', 'fg-4', 'fg-muted', 'fg-subtle', 'fg-faint', 'fg-dim'],
}, },
{ {
title: 'Akzent & Status', title: 'Accent & status',
tokens: [ tokens: [
'accent', 'accent',
'accent-fg', 'accent-fg',
@@ -57,7 +79,7 @@ function Swatch({ token }: { token: string }) {
); );
} }
export const Farben: Story = { export const Colors: Story = {
render: () => ( render: () => (
<div className="flex flex-col gap-8"> <div className="flex flex-col gap-8">
{groups.map((g) => ( {groups.map((g) => (
@@ -112,7 +134,7 @@ const type: { cls: string; label: string; sample: string }[] = [
{ cls: 'text-2xs font-bold text-fg-subtle', label: '2xs · 11 / 700', sample: 'Mit ⌘ + Enter senden' }, { cls: 'text-2xs font-bold text-fg-subtle', label: '2xs · 11 / 700', sample: 'Mit ⌘ + Enter senden' },
]; ];
export const Typografie: Story = { export const Typography: Story = {
render: () => ( render: () => (
<div className="flex flex-col gap-5"> <div className="flex flex-col gap-5">
{type.map((t) => ( {type.map((t) => (
+5 -2
View File
@@ -1,6 +1,6 @@
import { Meta } from '@storybook/blocks'; import { Meta } from '@storybook/blocks';
<Meta title="Einführung" /> <Meta title="Introduction" />
# Collabry Components # Collabry Components
@@ -47,5 +47,8 @@ The components are built on [shadcn/ui](https://ui.shadcn.com) primitives in `sr
(Radix UI, cmdk, Sonner), restyled to the Collabry tokens. Dialogs, menus and popovers portal into the (Radix UI, cmdk, Sonner), restyled to the Collabry tokens. Dialogs, menus and popovers portal into the
nearest `ThemeProvider`, so they keep its theme. nearest `ThemeProvider`, so they keep its theme.
Like shadcn/ui, everything is composed from small parts (`CardHeader`, `CardTitle`, `NavItem`, …) rather
than configured through props. Each story shows a composition; copy it as a starting point.
The design's signature panel is a **double frame**: a 5px dark rim (`bg-frame`) around a raised The design's signature panel is a **double frame**: a 5px dark rim (`bg-frame`) around a raised
surface (`bg-surface`). `Card` and `SettingsSection` implement it. surface (`bg-surface`): `<CardFrame><Card>…</Card></CardFrame>`. `GroupCard`, `SettingsSection` and `InviteBanner` include it.
+296
View File
@@ -0,0 +1,296 @@
/* Compositions used by more than one story: how the parts fit together for real screens. */
import { AlertCircle, CheckCircle2, ChevronRight, Clock, LogOut, Moon, Settings, Sun, X } from 'lucide-react';
import { useState, type ComponentProps } from 'react';
import { PersonAvatar } from '../components/Avatar/Avatar';
import { CountBadge, Swatch } from '../components/Badge/Badge';
import { Button, type ButtonState } from '../components/Button/Button';
import {
Empty,
EmptyDescription,
EmptyMedia,
EmptyTitle,
MetaSeparator,
SectionLabel,
} from '../components/Layout/Layout';
import { MenuItem, MenuItemDetail, MenuLabel, MenuSeparator } from '../components/Menu/Menu';
import {
NotificationActions,
NotificationContent,
NotificationIcon,
NotificationItem,
NotificationLink,
NotificationList,
NotificationMeta,
NotificationPanel,
NotificationPanelActions,
NotificationPanelBar,
NotificationPanelBody,
NotificationPanelFooter,
NotificationPanelHeader,
NotificationPanelLink,
NotificationPanelTitle,
NotificationQuote,
NotificationResult,
NotificationText,
NotificationUnreadDot,
} from '../components/Notifications/Notifications';
import {
SegmentedControl,
SegmentedControlCount,
SegmentedControlItem,
} from '../components/SegmentedControl/SegmentedControl';
import type { Person } from '../components/Avatar/Avatar';
import { notificationsEarlier, notificationsToday, type NotificationData } from './fixtures';
/* ---------------------------------------------------------------- Notifications */
export interface NotificationEntryProps {
n: NotificationData;
onOpen?: (id: string) => void;
onAccept?: (id: string) => void;
onDecline?: (id: string) => void;
acceptState?: ButtonState;
}
/** One `NotificationData` as `NotificationItem` parts. */
export function NotificationEntry({ n, onOpen, onAccept, onDecline, acceptState }: NotificationEntryProps) {
return (
<NotificationItem unread={n.unread}>
<NotificationLink
href="#"
onClick={(e) => {
e.preventDefault();
onOpen?.(n.id);
}}
>
{n.kind === 'person' && n.person ? (
<PersonAvatar person={n.person} size={36} aria-hidden="true" />
) : (
<NotificationIcon tone={n.kind === 'deadline' ? 'warning' : 'danger'}>
{n.kind === 'deadline' ? (
<Clock size={18} strokeWidth={1.75} />
) : (
<AlertCircle size={18} strokeWidth={1.75} />
)}
</NotificationIcon>
)}
<NotificationContent>
<NotificationText>
<strong>{n.actor}</strong>
{n.verb && ` ${n.verb}`} {n.object && <strong>{n.object}</strong>}
{n.tail}
</NotificationText>
{n.quote && <NotificationQuote>{n.quote}</NotificationQuote>}
<NotificationMeta>
{n.group && (
<>
<Swatch color={n.group.color} />
<span>{n.group.name}</span>
<MetaSeparator />
</>
)}
<span>{n.time}</span>
</NotificationMeta>
</NotificationContent>
<NotificationUnreadDot />
</NotificationLink>
{n.invite && !n.inviteResult && (
<NotificationActions>
<Button
variant="primary"
size="sm"
className="h-[34px] px-3.5 shadow-primary-flat"
state={acceptState}
onClick={() => onAccept?.(n.id)}
>
Beitreten
</Button>
<Button variant="secondary" size="sm" className="h-[34px] px-3.5" onClick={() => onDecline?.(n.id)}>
Ablehnen
</Button>
</NotificationActions>
)}
{n.inviteResult && (
<NotificationResult tone={n.inviteResult === 'joined' ? 'success' : 'muted'}>
{n.inviteResult === 'joined' ? '✓ Du bist der Gruppe beigetreten' : 'Einladung abgelehnt'}
</NotificationResult>
)}
</NotificationItem>
);
}
export interface NotificationsDemoProps extends ComponentProps<typeof NotificationPanel> {
initialToday?: NotificationData[];
initialEarlier?: NotificationData[];
onClose?: () => void;
}
/** The full popover: tabs, sections, mark-all-read, invites, empty state. */
export function NotificationsDemo({
initialToday = notificationsToday,
initialEarlier = notificationsEarlier,
onClose,
...props
}: NotificationsDemoProps) {
const [today, setToday] = useState(initialToday);
const [earlier, setEarlier] = useState(initialEarlier);
const [tab, setTab] = useState('all');
const [markAll, setMarkAll] = useState<ButtonState>('idle');
const [accept, setAccept] = useState<ButtonState>('idle');
const update = (fn: (n: NotificationData) => NotificationData) => {
setToday((l) => l.map(fn));
setEarlier((l) => l.map(fn));
};
const read = (id?: string) => update((n) => (!id || n.id === id ? { ...n, unread: false } : n));
const all = [...today, ...earlier];
const unread = all.filter((n) => n.unread).length;
const shown = (list: NotificationData[]) => (tab === 'unread' ? list.filter((n) => n.unread) : list);
const entry = (n: NotificationData) => (
<NotificationEntry
key={n.id}
n={n}
onOpen={read}
acceptState={accept}
onAccept={(id) => {
setAccept('loading');
setTimeout(() => {
update((x) => (x.id === id ? { ...x, unread: false, inviteResult: 'joined' } : x));
setAccept('idle');
}, 900);
}}
onDecline={(id) => update((x) => (x.id === id ? { ...x, unread: false, inviteResult: 'declined' } : x))}
/>
);
return (
<NotificationPanel {...props}>
<NotificationPanelHeader>
<NotificationPanelBar>
<NotificationPanelTitle>Benachrichtigungen</NotificationPanelTitle>
{unread > 0 && <CountBadge tone="accent">{unread}</CountBadge>}
<NotificationPanelActions>
{unread > 0 && (
<Button
variant="ghost"
size="sm"
className="px-2.5"
state={markAll}
onClick={() => {
setMarkAll('loading');
setTimeout(() => {
read();
setMarkAll('idle');
}, 900);
}}
>
Alle gelesen
</Button>
)}
{onClose && (
<Button
variant="ghost"
size="sm"
iconOnly
aria-label="Schließen"
onClick={onClose}
className="text-fg-subtle"
>
<X size={16} strokeWidth={1.75} />
</Button>
)}
</NotificationPanelActions>
</NotificationPanelBar>
<SegmentedControl aria-label="Filter" value={tab} onValueChange={setTab} className="mr-1.5 *:flex-1 *:basis-0">
<SegmentedControlItem value="all">
Alle <SegmentedControlCount>{all.length}</SegmentedControlCount>
</SegmentedControlItem>
<SegmentedControlItem value="unread">
Ungelesen <SegmentedControlCount>{unread}</SegmentedControlCount>
</SegmentedControlItem>
</SegmentedControl>
</NotificationPanelHeader>
<NotificationPanelBody>
{shown(today).length > 0 && (
<>
<SectionLabel>Heute</SectionLabel>
<NotificationList>{shown(today).map(entry)}</NotificationList>
</>
)}
{shown(earlier).length > 0 && (
<>
<SectionLabel>Früher</SectionLabel>
<NotificationList>{shown(earlier).map(entry)}</NotificationList>
</>
)}
{shown(today).length + shown(earlier).length === 0 && (
<Empty>
<EmptyMedia className="text-success-fg">
<CheckCircle2 size={28} strokeWidth={1.75} />
</EmptyMedia>
<EmptyTitle>Alles gelesen</EmptyTitle>
<EmptyDescription>Neue Benachrichtigungen erscheinen hier.</EmptyDescription>
</Empty>
)}
</NotificationPanelBody>
<NotificationPanelFooter>
<NotificationPanelLink href="#">Benachrichtigungs-Einstellungen</NotificationPanelLink>
</NotificationPanelFooter>
</NotificationPanel>
);
}
/* ---------------------------------------------------------------- Account menu */
const mi = { size: 18, strokeWidth: 1.75 } as const;
/** Items of the account menu; put them in a `<MenuContent size="lg">`. */
export function AccountMenuItems({
user,
theme,
onToggleTheme,
}: {
user: Person & { email: string };
theme: 'dark' | 'light';
onToggleTheme?: () => void;
}) {
return (
<>
<MenuLabel>
<PersonAvatar person={user} size={36} aria-hidden="true" />
<div className="min-w-0 flex-auto">
<div className="leading-tight font-bold">{user.name}</div>
<div className="truncate text-xs text-fg-subtle">{user.email}</div>
</div>
</MenuLabel>
<MenuSeparator />
<MenuItem asChild>
<a href="#">
<Settings {...mi} />
Einstellungen
</a>
</MenuItem>
<MenuItem
onSelect={(e) => {
// Keep the menu open so the new theme is visible right away.
e.preventDefault();
onToggleTheme?.();
}}
>
{theme === 'dark' ? <Moon {...mi} /> : <Sun {...mi} />}
Darstellung
<MenuItemDetail>
{theme === 'dark' ? 'Dunkel' : 'Hell'}
<ChevronRight size={14} strokeWidth={1.75} />
</MenuItemDetail>
</MenuItem>
<MenuSeparator />
<MenuItem asChild>
<a href="#">
<LogOut {...mi} />
Abmelden
</a>
</MenuItem>
</>
);
}
+200 -19
View File
@@ -1,11 +1,54 @@
/* Sample data taken from the Collabry design, shared by the stories. */ /* Sample data taken from the Collabry design, shared by the stories. */
import { useState, type ReactNode } from 'react'; import { useState, type ReactNode } from 'react';
import type { Person } from '../components/Avatar/Avatar'; import type { Person } from '../components/Avatar/Avatar';
import type { GroupData } from '../components/Group/Group';
import type { NotificationData } from '../components/Notifications/Notifications';
import type { TaskData } from '../components/Task/Task';
import { PortalContainerContext } from '../lib/portal'; import { PortalContainerContext } from '../lib/portal';
import { swatches } from '../lib/tokens'; import { swatches, type Priority, type TaskStatus } from '../lib/tokens';
/* Sample data shapes. The components take parts, not these objects; stories map data to parts. */
export interface GroupRef {
name: string;
color: string;
}
export interface TaskData {
id: string;
title: string;
group: GroupRef;
priority: Priority;
/** Display date, e.g. "Mi, 4. Nov". */
due: string;
status: TaskStatus;
overdue?: boolean;
assignee?: Person;
comments?: number;
}
export interface GroupData extends GroupRef {
id: string;
members: Person[];
done: number;
total: number;
description?: string;
role?: 'admin' | 'member';
next?: string;
}
export interface NotificationData {
id: string;
kind: 'person' | 'deadline' | 'overdue';
person?: Person;
actor: string;
verb?: string;
object?: string;
tail?: string;
quote?: string;
group?: GroupRef;
time: string;
unread?: boolean;
invite?: boolean;
inviteResult?: 'joined' | 'declined';
}
export const people = { export const people = {
NH: { name: 'Niklas Haiden', initials: 'NH', color: swatches.violet }, NH: { name: 'Niklas Haiden', initials: 'NH', color: swatches.violet },
@@ -61,18 +104,85 @@ export const groups: GroupData[] = [
]; ];
export const tasks: TaskData[] = [ export const tasks: TaskData[] = [
{ id: 't1', title: 'Gruppen-Einladung per Link', group: groupRefs.swe, priority: 'Hoch', due: 'Fr, 30. Okt', overdue: true, status: 'doing', assignee: people.NH, comments: 3 }, {
{ id: 't2', title: 'Login & Registrierung umsetzen', group: groupRefs.swe, priority: 'Hoch', due: 'Mi, 4. Nov', status: 'doing', assignee: people.NH, comments: 1 }, id: 't1',
{ id: 't3', title: 'ER-Diagramm finalisieren', group: groupRefs.db, priority: 'Mittel', due: 'Mo, 2. Nov', status: 'open', assignee: people.PM }, title: 'Gruppen-Einladung per Link',
{ id: 't4', title: 'Dashboard-UI entwerfen', group: groupRefs.swe, priority: 'Mittel', due: 'Do, 5. Nov', status: 'review', assignee: people.KB, comments: 2 }, group: groupRefs.swe,
{ id: 't5', title: 'Git-Branching-Regeln dokumentieren', group: groupRefs.swe, priority: 'Niedrig', due: 'Mo, 9. Nov', status: 'open', assignee: people.LK }, priority: 'high',
{ id: 't6', title: 'Umfrage-Ergebnisse auswerten', group: groupRefs.mk, priority: 'Mittel', due: 'Mi, 11. Nov', status: 'open', assignee: people.KB }, due: 'Fr, 30. Okt',
{ id: 't7', title: 'Review Iteration 1 schreiben', group: groupRefs.swe, priority: 'Mittel', due: 'Sa, 31. Okt', status: 'done', assignee: people.LB }, overdue: true,
status: 'doing',
assignee: people.NH,
comments: 3,
},
{
id: 't2',
title: 'Login & Registrierung umsetzen',
group: groupRefs.swe,
priority: 'high',
due: 'Mi, 4. Nov',
status: 'doing',
assignee: people.NH,
comments: 1,
},
{
id: 't3',
title: 'ER-Diagramm finalisieren',
group: groupRefs.db,
priority: 'medium',
due: 'Mo, 2. Nov',
status: 'open',
assignee: people.PM,
},
{
id: 't4',
title: 'Dashboard-UI entwerfen',
group: groupRefs.swe,
priority: 'medium',
due: 'Do, 5. Nov',
status: 'review',
assignee: people.KB,
comments: 2,
},
{
id: 't5',
title: 'Git-Branching-Regeln dokumentieren',
group: groupRefs.swe,
priority: 'low',
due: 'Mo, 9. Nov',
status: 'open',
assignee: people.LK,
},
{
id: 't6',
title: 'Umfrage-Ergebnisse auswerten',
group: groupRefs.mk,
priority: 'medium',
due: 'Mi, 11. Nov',
status: 'open',
assignee: people.KB,
},
{
id: 't7',
title: 'Review Iteration 1 schreiben',
group: groupRefs.swe,
priority: 'medium',
due: 'Sa, 31. Okt',
status: 'done',
assignee: people.LB,
},
]; ];
export const deadlines = [ export const deadlines = [
{ weekday: 'MO', day: 2, title: 'ER-Diagramm finalisieren', group: groupRefs.db, when: 'morgen', soon: true }, { weekday: 'MO', day: 2, title: 'ER-Diagramm finalisieren', group: groupRefs.db, when: 'morgen', soon: true },
{ weekday: 'MI', day: 4, title: 'Login & Registrierung umsetzen', group: groupRefs.swe, when: 'in 3 Tagen', soon: true }, {
weekday: 'MI',
day: 4,
title: 'Login & Registrierung umsetzen',
group: groupRefs.swe,
when: 'in 3 Tagen',
soon: true,
},
{ weekday: 'DO', day: 5, title: 'Präsentation Marktanalyse', group: groupRefs.mk, when: 'in 4 Tagen' }, { weekday: 'DO', day: 5, title: 'Präsentation Marktanalyse', group: groupRefs.mk, when: 'in 4 Tagen' },
{ weekday: 'FR', day: 6, title: 'Kanban-Board: API-Endpunkte', group: groupRefs.swe, when: 'in 5 Tagen' }, { weekday: 'FR', day: 6, title: 'Kanban-Board: API-Endpunkte', group: groupRefs.swe, when: 'in 5 Tagen' },
{ weekday: 'MO', day: 9, title: 'Git-Branching-Regeln dokumentieren', group: groupRefs.swe, when: 'in 8 Tagen' }, { weekday: 'MO', day: 9, title: 'Git-Branching-Regeln dokumentieren', group: groupRefs.swe, when: 'in 8 Tagen' },
@@ -80,16 +190,87 @@ export const deadlines = [
]; ];
export const notificationsToday: NotificationData[] = [ export const notificationsToday: NotificationData[] = [
{ id: 'n1', kind: 'person', person: people.LB, actor: 'Lena Berger', verb: 'hat dir', object: '„Login & Registrierung umsetzen“', tail: ' zugewiesen.', group: groupRefs.swe, time: 'vor 12 Min.', unread: true }, {
{ id: 'n2', kind: 'person', person: people.PM, actor: 'Philip Mai', verb: 'hat', object: '„ER-Diagramm finalisieren“', tail: ' kommentiert:', quote: 'Kannst du die n:m-Beziehung zwischen Gruppe und Mitglied noch auflösen?', group: groupRefs.db, time: 'vor 1 Std.', unread: true }, id: 'n1',
{ id: 'n3', kind: 'person', person: people.KB, actor: 'Kevin Baumgartner', verb: 'hat dich in die Gruppe', object: '„Statistik Projekt“', tail: ' eingeladen.', time: 'Einladung · vor 2 Std.', unread: true, invite: true }, kind: 'person',
{ id: 'n4', kind: 'deadline', actor: 'Deadline morgen:', object: '„ER-Diagramm finalisieren“', tail: ' ist am Mo, 2. Nov fällig.', group: groupRefs.db, time: 'vor 3 Std.', unread: true }, person: people.LB,
actor: 'Lena Berger',
verb: 'hat dir',
object: '„Login & Registrierung umsetzen“',
tail: ' zugewiesen.',
group: groupRefs.swe,
time: 'vor 12 Min.',
unread: true,
},
{
id: 'n2',
kind: 'person',
person: people.PM,
actor: 'Philip Mai',
verb: 'hat',
object: '„ER-Diagramm finalisieren“',
tail: ' kommentiert:',
quote: 'Kannst du die n:m-Beziehung zwischen Gruppe und Mitglied noch auflösen?',
group: groupRefs.db,
time: 'vor 1 Std.',
unread: true,
},
{
id: 'n3',
kind: 'person',
person: people.KB,
actor: 'Kevin Baumgartner',
verb: 'hat dich in die Gruppe',
object: '„Statistik Projekt“',
tail: ' eingeladen.',
time: 'Einladung · vor 2 Std.',
unread: true,
invite: true,
},
{
id: 'n4',
kind: 'deadline',
actor: 'Deadline morgen:',
object: '„ER-Diagramm finalisieren“',
tail: ' ist am Mo, 2. Nov fällig.',
group: groupRefs.db,
time: 'vor 3 Std.',
unread: true,
},
]; ];
export const notificationsEarlier: NotificationData[] = [ export const notificationsEarlier: NotificationData[] = [
{ id: 'n5', kind: 'person', person: people.KB, actor: 'Kevin Baumgartner', verb: 'hat', object: '„Dashboard-UI entwerfen“', tail: ' auf Review gesetzt.', group: groupRefs.swe, time: 'Gestern, 18:40' }, {
{ id: 'n6', kind: 'overdue', actor: 'Überfällig:', object: '„Gruppen-Einladung per Link“', tail: ' war am Fr, 30. Okt fällig.', group: groupRefs.swe, time: 'Sa, 31. Okt' }, id: 'n5',
{ id: 'n7', kind: 'person', person: people.LK, actor: 'Lukas Kammerhofer', verb: 'ist der Gruppe', object: '„Marketing Seminar“', tail: ' beigetreten.', group: groupRefs.mk, time: 'Fr, 30. Okt' }, kind: 'person',
person: people.KB,
actor: 'Kevin Baumgartner',
verb: 'hat',
object: '„Dashboard-UI entwerfen“',
tail: ' auf Review gesetzt.',
group: groupRefs.swe,
time: 'Gestern, 18:40',
},
{
id: 'n6',
kind: 'overdue',
actor: 'Überfällig:',
object: '„Gruppen-Einladung per Link“',
tail: ' war am Fr, 30. Okt fällig.',
group: groupRefs.swe,
time: 'Sa, 31. Okt',
},
{
id: 'n7',
kind: 'person',
person: people.LK,
actor: 'Lukas Kammerhofer',
verb: 'ist der Gruppe',
object: '„Marketing Seminar“',
tail: ' beigetreten.',
group: groupRefs.mk,
time: 'Fr, 30. Okt',
},
]; ];
/** /**