1 Commits
Author SHA1 Message Date
Maurus Decimus 9c6577cc98 v2.0.1 2026-10-27 08:02:54 +01:00
128 changed files with 1812 additions and 3289 deletions

No files matched your search

-48
View File
@@ -2,54 +2,6 @@
All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/).
## [2.0.6] - 2026-11-13
### Fixed
- OIDC sign-in keeps a query already present in the provider's `authorization_endpoint` (for example Casdoor's `?organization=`) and appends its own parameters with `&`.
- Clicking or hovering a list row in Safari now targets that row instead of the last row of the table.
## [2.0.5] - 2026-11-05
### Added
- Passkey registration under Account > Credentials.
### Changed
### Fixed
- Dates and numbers are formatted with the account locale, or the browser's preferred language when the account uses the default, instead of always en-US.
- The last setup screen no longer tells users to sign in with credentials that were never created when an external directory is used.
## [2.0.4] - 2026-11-02
### Added
- New WebUI design with more pizzazz:
- Cleaner generated forms: two-column fields that stack on mobile, simpler nested objects, collapsible list items, segmented variant pickers, a section index on wide screens and a floating save bar.
- Dashboards support a layout with stat, chart, headline and ranking tiles, plus column and row spans, tones and delta polarity, all defined in the schema.
- Custom OAuth scopes can be requested through the `oauth-scopes` meta tag; they are added to the scopes required by the server.
### Changed
### Fixed
## [2.0.3] - 2026-10-29
### Added
### Changed
- Logging out no longer revokes the OAuth tokens.
### Fixed
- OAuth sign-in sends the RFC 8707 `resource` parameter in the authorization request, the code exchange and token refreshes, so external identity providers that require an audience or scopes issue tokens the server accepts.
## [2.0.2] - 2026-10-28
### Added
### Changed
- Object pickers in forms are now scoped to the tenant of the record being edited: for objects that belong to a tenant (`memberTenantId`), only options from the same tenant are offered.
### Fixed
## [2.0.1] - 2026-10-27
### Added
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 577 KiB

After

Width:  |  Height:  |  Size: 446 KiB

-1
View File
@@ -5,7 +5,6 @@
<meta charset="UTF-8" />
<base href="/" />
<meta name="oauth-client-id" content="" />
<meta name="oauth-scopes" content="" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Portal</title>
+264 -33
View File
@@ -1,17 +1,14 @@
{
"name": "stalwart-webui",
"version": "2.0.4",
"version": "2.0.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "stalwart-webui",
"version": "2.0.4",
"version": "2.0.1",
"dependencies": {
"@daypicker/react": "^10.0.2",
"@fontsource-variable/inter": "^5.3.0",
"@fontsource-variable/jetbrains-mono": "^5.3.0",
"@fontsource-variable/plus-jakarta-sans": "^5.3.0",
"@noble/hashes": "^2.4.0",
"@radix-ui/react-alert-dialog": "^1.2.1",
"@radix-ui/react-checkbox": "^1.4.1",
@@ -67,7 +64,8 @@
"tw-animate-css": "^1.4.0",
"typescript": "~6.0.3",
"typescript-eslint": "^8.71.2",
"vite": "^8.3.4"
"vite": "^8.3.4",
"vitest": "5.0.3"
}
},
"node_modules/@babel/code-frame": {
@@ -587,33 +585,6 @@
"integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==",
"license": "MIT"
},
"node_modules/@fontsource-variable/inter": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/inter/-/inter-5.3.0.tgz",
"integrity": "sha512-OupL48va4JNofb97w6NYeF9S7W/kHNKM0Er8Dem5nqi4jeOLrVJDoE8tZEpnMJmtkvNbB1EIPPwHcdkF6b1oUA==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/jetbrains-mono": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/jetbrains-mono/-/jetbrains-mono-5.3.0.tgz",
"integrity": "sha512-F32xpS2NsGYoQi2ADSkKTgpJj7ozajsGgDJ8woTnqjmIB+dxDIqImjl4pXZVEExu8UFZ2ndhmX18EBS/hdz3Lw==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/plus-jakarta-sans": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/plus-jakarta-sans/-/plus-jakarta-sans-5.3.0.tgz",
"integrity": "sha512-/l/4r0yyWK9JzAlmA0LiYgGgmJe/Gswt4jTJEzr5QhJfwMbvJZDmYWyW0M4X7yCK69BajMVlV/Lx8g7WDc1+sw==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@humanfs/core": {
"version": "0.19.2",
"resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz",
@@ -2738,6 +2709,17 @@
"@babel/types": "^7.28.2"
}
},
"node_modules/@types/chai": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
"integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/deep-eql": "*",
"assertion-error": "^2.0.1"
}
},
"node_modules/@types/d3-array": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz",
@@ -2810,6 +2792,13 @@
"@types/ms": "*"
}
},
"node_modules/@types/deep-eql": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
"integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/esrecurse": {
"version": "4.3.1",
"resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz",
@@ -3191,6 +3180,54 @@
}
}
},
"node_modules/@vitest/mocker": {
"version": "5.0.3",
"resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.0.3.tgz",
"integrity": "sha512-T8sWAIbkSyAjkwTcaEc3Iu0o9A27X1/kdXrizhZkGuSKScRQtRzclfAMpOTcGdXCsqxeWlpGy3XjqaW8CpLORg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/trace-mapping": "0.3.31",
"@vitest/spy": "5.0.3",
"estree-walker": "^3.0.3",
"magic-string": "^1.2.3"
},
"funding": {
"url": "https://opencollective.com/vitest"
},
"peerDependencies": {
"msw": "^2.4.9",
"vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
},
"peerDependenciesMeta": {
"msw": {
"optional": true
},
"vite": {
"optional": true
}
}
},
"node_modules/@vitest/mocker/node_modules/magic-string": {
"version": "1.4.5",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz",
"integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.6.0"
}
},
"node_modules/@vitest/spy": {
"version": "5.0.3",
"resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.0.3.tgz",
"integrity": "sha512-XhFysQTB8AZ+P4gMi+Lpo99vg2AZi0qKpaB9yXQl37+CaMEAPO3iH/wGVnSyL5MPERiLezpqTVtrR6UZH5GCXg==",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/acorn": {
"version": "8.17.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.17.0.tgz",
@@ -3267,6 +3304,16 @@
"node": ">=10"
}
},
"node_modules/assertion-error": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
"integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
}
},
"node_modules/babel-plugin-react-compiler": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/babel-plugin-react-compiler/-/babel-plugin-react-compiler-1.0.0.tgz",
@@ -3411,6 +3458,16 @@
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/chai": {
"version": "6.3.0",
"resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz",
"integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=18"
}
},
"node_modules/character-entities": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz",
@@ -3835,6 +3892,13 @@
"node": ">=10.13.0"
}
},
"node_modules/es-module-lexer": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz",
"integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==",
"dev": true,
"license": "MIT"
},
"node_modules/es-toolkit": {
"version": "1.45.1",
"resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.45.1.tgz",
@@ -4069,6 +4133,16 @@
"url": "https://opencollective.com/unified"
}
},
"node_modules/estree-walker": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
"integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/estree": "^1.0.0"
}
},
"node_modules/esutils": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz",
@@ -4085,6 +4159,16 @@
"integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==",
"license": "MIT"
},
"node_modules/expect-type": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
"integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==",
"dev": true,
"license": "Apache-2.0",
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/extend": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",
@@ -5594,6 +5678,20 @@
"node": ">=18"
}
},
"node_modules/obug": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/obug/-/obug-2.2.1.tgz",
"integrity": "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==",
"dev": true,
"funding": [
"https://github.com/sponsors/sxzz",
"https://opencollective.com/debug"
],
"license": "MIT",
"engines": {
"node": ">=12.20.0"
}
},
"node_modules/optionator": {
"version": "0.9.4",
"resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",
@@ -6378,6 +6476,13 @@
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/std-env": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz",
"integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==",
"dev": true,
"license": "MIT"
},
"node_modules/string-width": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
@@ -6486,6 +6591,26 @@
"integrity": "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==",
"license": "MIT"
},
"node_modules/tinybench": {
"version": "6.2.2",
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.2.tgz",
"integrity": "sha512-nIZ2N2dFpjBsg2hgitKu7mA+FvsIJuGJOwysRngmVRRmWgR/UyPjwJj8c/fT/dhm8EkHnF5EOogRf+0Z2qrimA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/tinyexec": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz",
"integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=18"
}
},
"node_modules/tinyglobby": {
"version": "0.2.17",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
@@ -7190,6 +7315,99 @@
"url": "https://opencollective.com/parcel"
}
},
"node_modules/vitest": {
"version": "5.0.3",
"resolved": "https://registry.npmjs.org/vitest/-/vitest-5.0.3.tgz",
"integrity": "sha512-xMw97S3rjdtj5dkVat7jCsqWBpvchs3RlpQctUqwJD0KkERk40vz2fJ77lDwW/Vzh/pk18eItYAzkodhSes3jQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/chai": "^5.2.2",
"@vitest/mocker": "5.0.3",
"chai": "^6.2.2",
"es-module-lexer": "^2.3.2",
"expect-type": "^1.4.0",
"magic-string": "^1.2.3",
"obug": "^2.1.4",
"picomatch": "^4.0.7",
"std-env": "^4.2.0",
"tinybench": "^6.1.4",
"tinyexec": "^1.3.0",
"tinyglobby": "^0.2.17",
"why-is-node-running": "3.2.1"
},
"bin": {
"vitest": "vitest.mjs"
},
"engines": {
"node": "^22.12.0 || ^24.0.0 || >=26.0.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
},
"peerDependencies": {
"@edge-runtime/vm": "*",
"@opentelemetry/api": "^1.9.0",
"@types/node": "^22.0.0 || >=24.0.0",
"@vitest/browser-playwright": "5.0.3",
"@vitest/browser-preview": "5.0.3",
"@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0",
"@vitest/coverage-istanbul": "5.0.3",
"@vitest/coverage-v8": "5.0.3",
"@vitest/ui": "5.0.3",
"happy-dom": "*",
"jsdom": "*",
"vite": "^6.4.0 || ^7.0.0 || ^8.0.0"
},
"peerDependenciesMeta": {
"@edge-runtime/vm": {
"optional": true
},
"@opentelemetry/api": {
"optional": true
},
"@types/node": {
"optional": true
},
"@vitest/browser-playwright": {
"optional": true
},
"@vitest/browser-preview": {
"optional": true
},
"@vitest/browser-webdriverio": {
"optional": true
},
"@vitest/coverage-istanbul": {
"optional": true
},
"@vitest/coverage-v8": {
"optional": true
},
"@vitest/ui": {
"optional": true
},
"happy-dom": {
"optional": true
},
"jsdom": {
"optional": true
},
"vite": {
"optional": false
}
}
},
"node_modules/vitest/node_modules/magic-string": {
"version": "1.4.5",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz",
"integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.6.0"
}
},
"node_modules/which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
@@ -7212,6 +7430,19 @@
"integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==",
"license": "ISC"
},
"node_modules/why-is-node-running": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz",
"integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==",
"dev": true,
"license": "MIT",
"bin": {
"why-is-node-running": "cli.js"
},
"engines": {
"node": ">=20.11"
}
},
"node_modules/word-wrap": {
"version": "1.2.5",
"resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz",
+5 -6
View File
@@ -1,7 +1,7 @@
{
"name": "stalwart-webui",
"private": true,
"version": "2.0.6",
"version": "2.0.1",
"stalwart": {
"minServerVersion": "1.0.0"
},
@@ -12,15 +12,13 @@
"build": "tsc -b && vite build",
"typecheck": "tsc -p tsconfig.app.json --noEmit",
"lint": "eslint .",
"test": "vitest run",
"preview": "vite preview",
"format": "prettier --write src/",
"format:check": "prettier --check src/"
},
"dependencies": {
"@daypicker/react": "^10.0.2",
"@fontsource-variable/inter": "^5.3.0",
"@fontsource-variable/jetbrains-mono": "^5.3.0",
"@fontsource-variable/plus-jakarta-sans": "^5.3.0",
"@noble/hashes": "^2.4.0",
"@radix-ui/react-alert-dialog": "^1.2.1",
"@radix-ui/react-checkbox": "^1.4.1",
@@ -76,6 +74,7 @@
"tw-animate-css": "^1.4.0",
"typescript": "~6.0.3",
"typescript-eslint": "^8.71.2",
"vite": "^8.3.4"
"vite": "^8.3.4",
"vitest": "5.0.3"
}
}
}
+36 -42
View File
@@ -7,18 +7,18 @@
import type { ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { Check } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Card, CardContent } from '@/components/ui/card';
import { CopyButton } from '@/components/common/CopyButton';
import { DefaultLogo } from '@/components/common/Logo';
import type { Fields } from '@/types/schema';
export function WizardShell({ children }: { children: ReactNode }) {
return (
<div className="flex min-h-screen flex-col bg-background">
<header className="sticky top-0 z-20 flex h-16 items-center bg-background/80 px-6 backdrop-blur-md">
<div className="flex min-h-screen flex-col bg-content-background">
<header className="flex items-center px-6 py-4 border-b bg-background">
<DefaultLogo />
</header>
<main className="flex-1 overflow-auto px-4 pb-10 pt-4 sm:px-6">
<main className="flex-1 overflow-auto p-6">
<div className="mx-auto max-w-3xl">{children}</div>
</main>
</div>
@@ -29,16 +29,15 @@ export function ProgressIndicator({ total, current }: { total: number; current:
const { t } = useTranslation();
return (
<div
className="flex items-center gap-1.5"
className="flex items-center gap-2"
aria-label={t('bootstrap.stepOf', 'Step {{current}} of {{total}}', { current: current + 1, total })}
>
{Array.from({ length: total }, (_, i) => (
<div
key={i}
className={cn(
'h-1.5 rounded-full transition-all duration-300 ease-bento',
i === current ? 'w-8 bg-primary' : i < current ? 'w-4 bg-primary/45' : 'w-4 bg-muted-strong',
)}
className={`h-2 w-2 rounded-full transition-colors ${
i < current ? 'bg-primary' : i === current ? 'bg-primary' : 'bg-muted-foreground/20'
}`}
/>
))}
</div>
@@ -63,14 +62,14 @@ export function SuccessScreen({
const hasCredentials = entries.length > 0;
return (
<div className="space-y-3.5">
<div className="flex flex-col items-start gap-4 px-1 pb-2 pt-3">
<span className="grid size-11 place-items-center rounded-[13px] bg-success-soft text-success">
<Check className="h-5 w-5" aria-hidden="true" />
</span>
<div className="space-y-6">
<div className="flex flex-col items-start gap-3">
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary/10">
<Check className="h-5 w-5 text-primary" />
</div>
<div>
<h1 className="page-title">{t('bootstrap.complete', 'Setup complete')}</h1>
<p className="mt-1.5 text-sm text-muted-foreground">
<h2 className="text-2xl font-semibold tracking-tight">{t('bootstrap.complete', 'Setup complete')}</h2>
<p className="text-sm text-muted-foreground mt-1">
{hasCredentials
? t(
'bootstrap.credentialsCreated',
@@ -82,37 +81,32 @@ export function SuccessScreen({
</div>
{hasCredentials && (
<section className="tile divide-y divide-border px-5 sm:px-6">
{entries.map(([key, value]) => {
const field = fields.properties[key];
const label = labelsByName.get(key) ?? field?.description?.split('\n')[0] ?? key;
return (
<div key={key} className="space-y-2 py-4">
<div className="text-[13.5px] font-semibold">{label}</div>
<div className="flex items-center gap-2">
<code className="flex-1 select-all break-all rounded-xl bg-muted px-3 py-2.5 font-mono text-sm">
{value}
</code>
<CopyButton value={value} label={label} />
<Card>
<CardContent className="pt-6 space-y-4">
{entries.map(([key, value]) => {
const field = fields.properties[key];
const label = labelsByName.get(key) ?? field?.description?.split('\n')[0] ?? key;
return (
<div key={key} className="space-y-1.5">
<div className="text-sm font-medium">{label}</div>
<div className="flex gap-2">
<code className="flex-1 rounded bg-muted p-2 text-sm break-all select-all">{value}</code>
<CopyButton value={value} label={label} />
</div>
</div>
</div>
);
})}
</section>
);
})}
</CardContent>
</Card>
)}
<div className="rounded-xl bg-info-soft p-4 text-info">
<div className="rounded-md border border-primary/20 bg-primary/5 p-4">
<p className="text-sm">
<span className="font-medium">{t('bootstrap.nextStepLabel', 'Next step:')}</span>{' '}
{hasCredentials
? t(
'bootstrap.nextStepBody',
'restart Stalwart for the new configuration to take effect. Once restarted, sign in with the credentials above to continue administering your server.',
)
: t(
'bootstrap.nextStepBodyNoCredentials',
'restart Stalwart for the new configuration to take effect. No administrator account was created because accounts come from the external directory. Once restarted, sign in with the recovery administrator set in STALWART_RECOVERY_ADMIN and assign an administrator role to a directory account.',
)}
{t(
'bootstrap.nextStepBody',
'restart Stalwart for the new configuration to take effect. Once restarted, sign in with the credentials above to continue administering your server.',
)}
</p>
</div>
</div>
+45 -40
View File
@@ -8,7 +8,7 @@ import { useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { ArrowLeft, ArrowRight, Loader2, Rocket } from 'lucide-react';
import { useSchemaStore } from '@/stores/schemaStore';
@@ -208,8 +208,8 @@ export function BootstrapWizard() {
if (!schema || !resolved) {
return (
<WizardShell>
<div className="flex items-center justify-center p-12 text-muted-foreground" role="status">
<Loader2 className="mr-2 h-6 w-6 animate-spin text-brand-text" aria-hidden="true" />
<div className="flex items-center justify-center p-12 text-muted-foreground">
<Loader2 className="h-6 w-6 animate-spin mr-2" />
{t('form.loadingSchema', 'Loading schema...')}
</div>
</WizardShell>
@@ -219,8 +219,8 @@ export function BootstrapWizard() {
if (loading) {
return (
<WizardShell>
<div className="flex items-center justify-center p-12 text-muted-foreground" role="status">
<Loader2 className="mr-2 h-6 w-6 animate-spin text-brand-text" aria-hidden="true" />
<div className="flex items-center justify-center p-12 text-muted-foreground">
<Loader2 className="h-6 w-6 animate-spin mr-2" />
{t('bootstrap.loadingSetup', 'Loading setup...')}
</div>
</WizardShell>
@@ -230,7 +230,7 @@ export function BootstrapWizard() {
if (loadError) {
return (
<WizardShell>
<div className="mt-3 space-y-4 rounded-xl bg-destructive-soft p-4">
<div className="space-y-4 rounded-md border border-destructive/20 bg-destructive/10 p-4">
<p className="text-sm text-destructive" role="alert">
{loadError}
</p>
@@ -262,7 +262,7 @@ export function BootstrapWizard() {
if (sections.length === 0) {
return (
<WizardShell>
<div className="mt-3 rounded-xl bg-destructive-soft p-4 text-sm text-destructive">
<div className="rounded-md border border-destructive/20 bg-destructive/10 p-4 text-sm text-destructive">
{t('bootstrap.emptyForm', 'Setup form is empty. The server did not return any bootstrap fields.')}
</div>
</WizardShell>
@@ -273,47 +273,52 @@ export function BootstrapWizard() {
return (
<WizardShell>
<div className="space-y-3.5">
<div className="flex flex-wrap items-end justify-between gap-4 px-1 pb-2 pt-3">
<div>
<h1 className="page-title">{t('bootstrap.welcome', 'Welcome to Stalwart')}</h1>
<p className="mt-1.5 text-sm text-muted-foreground">
{t('bootstrap.welcomeSubtitle', "Let's get your server set up.")}
</p>
</div>
<ProgressIndicator total={sections.length} current={currentPage} />
<div className="space-y-6">
<div>
<h2 className="text-2xl font-semibold tracking-tight">{t('bootstrap.welcome', 'Welcome to Stalwart')}</h2>
<p className="text-sm text-muted-foreground mt-1">
{t('bootstrap.welcomeSubtitle', "Let's get your server set up.")}
</p>
</div>
<ProgressIndicator total={sections.length} current={currentPage} />
{generalError && (
<div className="rounded-xl bg-destructive-soft p-4" role="alert">
<p className="whitespace-pre-line text-sm text-destructive">{generalError}</p>
<div className="rounded-md bg-destructive/10 border border-destructive/20 p-4">
<p className="text-sm text-destructive whitespace-pre-line">{generalError}</p>
</div>
)}
<section className="tile @container px-5 pb-1.5 sm:px-6">
{current.title && <h2 className="section-title pb-1 pt-5">{current.title}</h2>}
<fieldset disabled={saving} className={cn('min-w-0 divide-y divide-border', !current.title && 'pt-1')}>
<FormProvider schema={schema} mode="create" hideEnterprise>
{current.fields.map(({ formField, field }) => (
<FieldRow
key={formField.name}
field={field}
formField={formField}
value={formData[formField.name]}
onChange={(v) => handleFieldChange(formField.name, v)}
error={fieldErrors[formField.name]}
/>
))}
</FormProvider>
</fieldset>
</section>
<Card>
{current.title && (
<CardHeader>
<CardTitle className="text-base">{current.title}</CardTitle>
</CardHeader>
)}
<CardContent className={current.title ? '' : 'pt-6'}>
<fieldset disabled={saving} className="min-w-0 space-y-6">
<FormProvider schema={schema} mode="create" hideEnterprise>
{current.fields.map(({ formField, field }) => (
<FieldRow
key={formField.name}
field={field}
formField={formField}
value={formData[formField.name]}
onChange={(v) => handleFieldChange(formField.name, v)}
error={fieldErrors[formField.name]}
/>
))}
</FormProvider>
</fieldset>
</CardContent>
</Card>
<div className="flex items-center justify-between gap-3 pt-2">
<div className="flex items-center justify-between pt-2">
<Button type="button" variant="outline" onClick={handleBack} disabled={!canGoBack || saving}>
<ArrowLeft aria-hidden="true" />
<ArrowLeft className="h-4 w-4 mr-2" />
{t('common.back', 'Back')}
</Button>
<div className="text-xs font-medium text-dim">
<div className="text-xs text-muted-foreground">
{t('bootstrap.stepOf', 'Step {{current}} of {{total}}', {
current: currentPage + 1,
total: sections.length,
@@ -321,13 +326,13 @@ export function BootstrapWizard() {
</div>
{isLastPage ? (
<Button type="button" onClick={handleSubmit} disabled={saving}>
{saving ? <Loader2 className="animate-spin" aria-hidden="true" /> : <Rocket aria-hidden="true" />}
{saving ? <Loader2 className="h-4 w-4 mr-2 animate-spin" /> : <Rocket className="h-4 w-4 mr-2" />}
{t('bootstrap.finishSetup', 'Finish setup')}
</Button>
) : (
<Button type="button" onClick={handleNext} disabled={saving}>
{t('common.next', 'Next')}
<ArrowRight aria-hidden="true" />
<ArrowRight className="h-4 w-4 ml-2" />
</Button>
)}
</div>
+5 -7
View File
@@ -50,7 +50,7 @@ export function CommandPalette({ open, onOpenChange }: CommandPaletteProps) {
<Command
shouldFilter={false}
loop
className="[&_[cmdk-group-heading]]:px-2.5 [&_[cmdk-group-heading]]:pt-2.5 [&_[cmdk-group-heading]]:text-[11px] [&_[cmdk-group-heading]]:font-semibold [&_[cmdk-group-heading]]:uppercase [&_[cmdk-group-heading]]:tracking-wider [&_[cmdk-group-heading]]:text-dim [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-14 [&_[cmdk-item]]:gap-3 [&_[cmdk-item]]:rounded-xl [&_[cmdk-item]]:px-2.5 [&_[cmdk-item]]:py-2 [&_[cmdk-item][data-selected=true]]:bg-muted [&_[cmdk-item]_svg]:h-4 [&_[cmdk-item]_svg]:w-4 [&_[cmdk-list]]:max-h-[min(60vh,420px)] [&_[cmdk-list]]:pb-2"
className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5"
>
<CommandInput
placeholder={t('globalSearch.placeholder', 'Search pages, fields, settings...')}
@@ -59,7 +59,7 @@ export function CommandPalette({ open, onOpenChange }: CommandPaletteProps) {
trailing={
<kbd
aria-hidden="true"
className="pointer-events-none ml-2 inline-flex h-5 shrink-0 select-none items-center rounded-md bg-muted px-1.5 font-mono text-[10px] font-medium text-dim"
className="pointer-events-none ml-2 inline-flex h-5 shrink-0 select-none items-center rounded-md border bg-muted px-1.5 font-mono text-[10px] font-medium text-muted-foreground"
>
ESC
</kbd>
@@ -79,14 +79,12 @@ export function CommandPalette({ open, onOpenChange }: CommandPaletteProps) {
return (
<CommandItem key={itemValue} value={itemValue} onSelect={() => selectEntry(entry)}>
<span className="grid size-8 shrink-0 place-items-center rounded-[10px] bg-highlight text-highlight-foreground">
<ActionIcon aria-hidden="true" className="h-4 w-4" />
</span>
<ActionIcon aria-hidden="true" className="mr-2 h-4 w-4 shrink-0 text-muted-foreground" />
<div className="flex flex-1 flex-col overflow-hidden">
<span className="truncate font-medium">{friendlyName(entry.text)}</span>
<span className="truncate text-xs text-dim">{entry.breadcrumb}</span>
<span className="truncate text-xs text-muted-foreground">{entry.breadcrumb}</span>
</div>
<span className="ml-auto shrink-0 pl-2 text-xs font-medium text-dim">{actionLabel}</span>
<span className="ml-auto shrink-0 pl-2 text-xs text-muted-foreground">{actionLabel}</span>
</CommandItem>
);
})}
+1 -8
View File
@@ -5,7 +5,6 @@
*/
import { useTranslation } from 'react-i18next';
import { Sparkles } from 'lucide-react';
import {
Dialog,
@@ -29,12 +28,6 @@ export function EnterpriseUpsell({ open, onClose }: EnterpriseUpsellProps) {
<Dialog open={open} onOpenChange={(isOpen) => !isOpen && onClose()}>
<DialogContent className="gap-6">
<DialogHeader className="space-y-4">
<span
className="grid size-11 place-items-center rounded-[13px] bg-highlight text-highlight-foreground max-sm:mx-auto"
aria-hidden="true"
>
<Sparkles className="h-5 w-5" />
</span>
<DialogTitle>{t('enterprise.trialTitle')}</DialogTitle>
<DialogDescription>{t('enterprise.trialDescription')}</DialogDescription>
</DialogHeader>
@@ -43,7 +36,7 @@ export function EnterpriseUpsell({ open, onClose }: EnterpriseUpsellProps) {
href="https://stalw.art/compare#why-isnt-feature-x-open-source"
target="_blank"
rel="noopener noreferrer"
className="text-center text-xs font-medium text-muted-foreground underline-offset-4 hover:text-brand-text hover:underline sm:mr-auto sm:text-left"
className="text-center text-xs text-muted-foreground underline-offset-4 hover:underline sm:mr-auto sm:text-left"
>
{t('enterprise.whyNotFree')}
</a>
@@ -1,29 +0,0 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import type { ReactNode } from 'react';
export function FloatingActionBar({ label, children }: { label?: string; children: ReactNode }) {
return (
<div className="pointer-events-none sticky bottom-4 z-20 flex justify-center pt-2">
<div
role={label ? 'group' : undefined}
aria-label={label}
className="pointer-events-auto flex max-w-full items-center gap-1.5 rounded-full bg-ink p-1.5 text-ink-foreground shadow-ink"
>
{children}
</div>
</div>
);
}
export function FloatingActionDivider() {
return <span className="mx-0.5 h-5 w-px bg-ink-foreground/15" aria-hidden="true" />;
}
export function FloatingActionDot() {
return <span className="h-2 w-2 shrink-0 rounded-full bg-ink-accent" aria-hidden="true" />;
}
+1 -1
View File
@@ -31,7 +31,7 @@ export function HelpTooltip({ content, label, side = 'top', icon: Icon = HelpCir
type="button"
aria-label={ariaLabel}
className={cn(
'inline-flex shrink-0 cursor-help items-center rounded-full text-dim transition-colors hover:text-brand-text focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
'inline-flex shrink-0 cursor-help items-center rounded-sm text-muted-foreground/60 hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring',
className,
)}
onClick={(e) => e.preventDefault()}
+3 -8
View File
@@ -11,14 +11,9 @@ import { cn } from '@/lib/utils';
export function LoadingFallback({ fullScreen = false }: { fullScreen?: boolean }) {
const { t } = useTranslation();
return (
<div
className={cn(
'flex flex-col items-center justify-center gap-3',
fullScreen ? 'min-h-screen bg-background' : 'p-8',
)}
>
<Loader2 className="h-7 w-7 animate-spin text-brand-text" aria-hidden="true" />
<p className="text-sm text-muted-foreground">{t('common.loading')}</p>
<div className={cn('flex flex-col items-center justify-center gap-3', fullScreen ? 'min-h-screen' : 'p-8')}>
<Loader2 className="h-8 w-8 animate-spin text-primary" />
<p className="text-muted-foreground">{t('common.loading')}</p>
</div>
);
}
+1 -1
View File
@@ -19,7 +19,7 @@ export function Markdown({ source, className }: MarkdownProps) {
return (
<div
className={cn(
'[&_a]:font-medium [&_a]:underline [&_a]:underline-offset-2 [&_code]:rounded [&_code]:bg-current/10 [&_code]:px-1 [&_code]:py-px [&_code]:font-mono [&_code]:text-[0.92em] [&_ol]:list-decimal [&_ol]:pl-4 [&_p+p]:mt-1 [&_ul]:list-disc [&_ul]:pl-4',
'[&_a]:underline [&_code]:font-mono [&_ol]:list-decimal [&_ol]:pl-4 [&_p+p]:mt-1 [&_ul]:list-disc [&_ul]:pl-4',
className,
)}
>
+8 -8
View File
@@ -8,7 +8,7 @@ import { useTranslation } from 'react-i18next';
import { Loader2, X } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { ObjectFieldFrame, ObjectSearchPopover } from '@/components/common/ObjectSearchPopover';
import { ObjectSearchPopover } from '@/components/common/ObjectSearchPopover';
import { useNoPermissionMessage } from '@/lib/objectOptions';
import { useObjectOptions, useDisplayName } from '@/data/objectOptions';
import type { Schema } from '@/types/schema';
@@ -36,11 +36,11 @@ export function ObjectPicker({ schema, objectName, label, value, onChange, onCle
const noPermissionMessage = useNoPermissionMessage(schema, objectName);
return (
<ObjectFieldFrame disabled={!!noPermissionMessage}>
<div className="flex items-center gap-2 flex-wrap">
{value && (
<Badge variant="secondary" className="h-7 max-w-xs gap-1 pl-3 pr-1 text-[13px] font-medium">
<Badge variant="secondary" className="gap-1 pr-1.5 text-sm max-w-xs">
{labelLoading ? (
<Loader2 className="h-3 w-3 animate-spin" aria-hidden="true" />
<Loader2 className="h-3 w-3 animate-spin" />
) : (
<span className="truncate" title={display ?? value}>
{display ?? value}
@@ -50,17 +50,17 @@ export function ObjectPicker({ schema, objectName, label, value, onChange, onCle
<button
type="button"
onClick={onClear}
className="grid size-5 shrink-0 place-items-center rounded-full bg-card text-muted-foreground transition-colors hover:bg-highlight hover:text-highlight-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
className="ml-1 rounded-full hover:bg-muted-foreground/20 p-0.5"
aria-label={t('field.clearValue', 'Clear {{name}}', { name: label })}
>
<X className="h-3 w-3" aria-hidden="true" />
<X className="h-3 w-3" />
</button>
)}
</Badge>
)}
{!value && placeholder && <span className="text-sm text-muted-foreground">{placeholder}</span>}
<ObjectSearchPopover
label={t('field.chooseValue', 'Choose {{name}}', { name: label })}
placeholder={value ? '' : (placeholder ?? t('field.selectEllipsis', 'Select...'))}
options={list.options}
loading={list.loading}
error={list.error}
@@ -68,6 +68,6 @@ export function ObjectPicker({ schema, objectName, label, value, onChange, onCle
onSelect={onChange}
disabledMessage={noPermissionMessage}
/>
</ObjectFieldFrame>
</div>
);
}
+9 -47
View File
@@ -6,14 +6,12 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import type { ReactNode } from 'react';
import { ChevronsUpDown, Loader2, Search } from 'lucide-react';
import { Loader2, Search } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from '@/components/ui/command';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { errorMessage } from '@/lib/jmapErrors';
import { cn } from '@/lib/utils';
import type { ObjectOption } from '@/data/objectOptions';
import type { ControlProps } from '@/components/forms/widgets/types';
@@ -27,26 +25,8 @@ export interface ObjectSearchPopoverProps {
disabled?: boolean;
label: string;
control?: ControlProps;
placeholder?: string;
}
export function ObjectFieldFrame({ disabled, children }: { disabled?: boolean; children: ReactNode }) {
return (
<div
data-slot="object-field"
className={cn(
'field-surface flex min-h-9 w-full flex-wrap items-center gap-1.5 rounded-lg p-1',
disabled && 'opacity-60',
)}
>
{children}
</div>
);
}
const INLINE_TRIGGER =
'h-7 min-w-[6rem] flex-1 justify-between gap-2 rounded-md px-2 text-sm font-normal text-dim shadow-none hover:bg-transparent hover:text-foreground focus-visible:ring-0 focus-visible:ring-offset-0';
export function ObjectSearchPopover({
options,
loading,
@@ -57,7 +37,6 @@ export function ObjectSearchPopover({
disabled,
label,
control,
placeholder,
}: ObjectSearchPopoverProps) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
@@ -71,11 +50,8 @@ export function ObjectSearchPopover({
{...control}
type="button"
variant="ghost"
size={placeholder === undefined ? 'icon' : 'sm'}
className={cn(
'cursor-not-allowed',
placeholder === undefined ? 'h-8 w-8 bg-muted opacity-60' : INLINE_TRIGGER,
)}
size="icon"
className="h-7 w-7 cursor-not-allowed opacity-60"
aria-label={label}
aria-disabled="true"
onClick={(e) => {
@@ -84,7 +60,7 @@ export function ObjectSearchPopover({
setTooltipOpen(true);
}}
>
<TriggerContent placeholder={placeholder} />
<Search className="h-4 w-4" aria-hidden="true" />
</Button>
</TooltipTrigger>
<TooltipContent>{disabledMessage}</TooltipContent>
@@ -105,19 +81,15 @@ export function ObjectSearchPopover({
{...control}
type="button"
variant="ghost"
size={placeholder === undefined ? 'icon' : 'sm'}
className={
placeholder === undefined
? 'h-8 w-8 bg-muted hover:bg-highlight hover:text-highlight-foreground'
: INLINE_TRIGGER
}
size="icon"
className="h-7 w-7"
aria-label={label}
disabled={disabled}
>
<TriggerContent placeholder={placeholder} />
<Search className="h-4 w-4" aria-hidden="true" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-72 overflow-hidden p-0" align="start">
<PopoverContent className="w-72 p-0" align="start">
<Command>
<CommandInput placeholder={t('common.searchPlaceholder', 'Search...')} />
<CommandList>
@@ -128,7 +100,7 @@ export function ObjectSearchPopover({
</div>
)}
{!loading && error && (
<div className="m-2 space-y-2 rounded-xl bg-destructive-soft px-3 py-4 text-center text-sm" role="alert">
<div className="space-y-2 px-3 py-4 text-center text-sm" role="alert">
<p className="text-destructive">
{errorMessage(error, t('field.optionsLoadFailed', 'Failed to load options.'))}
</p>
@@ -161,13 +133,3 @@ export function ObjectSearchPopover({
</Popover>
);
}
function TriggerContent({ placeholder }: { placeholder?: string }) {
if (placeholder === undefined) return <Search className="h-4 w-4" aria-hidden="true" />;
return (
<>
<span className="truncate">{placeholder}</span>
<ChevronsUpDown className="h-4 w-4 shrink-0 opacity-60" aria-hidden="true" />
</>
);
}
-2
View File
@@ -42,7 +42,6 @@ import {
ListTodoIcon,
ListTreeIcon,
LockIcon,
LockKeyholeIcon,
MailIcon,
MailMinusIcon,
MailXIcon,
@@ -113,7 +112,6 @@ export const ICONS: Readonly<Record<string, LucideIcon>> = {
'list-todo': ListTodoIcon,
'list-tree': ListTreeIcon,
lock: LockIcon,
'lock-keyhole': LockKeyholeIcon,
mail: MailIcon,
'mail-minus': MailMinusIcon,
'mail-x': MailXIcon,
+15 -13
View File
@@ -10,7 +10,7 @@ import { useBufferedValue } from '@/hooks/useBufferedValue';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import { Separator } from '@/components/ui/separator';
import { X, Plus } from 'lucide-react';
@@ -98,12 +98,12 @@ export function ExpressionEditor({ value, onChange, readOnly = false, label, con
};
return (
<div className="space-y-2.5 rounded-xl bg-muted p-3">
<div className="rounded-lg border bg-card p-4 space-y-3">
{matchEntries.map(([key, entry], index) => (
<div key={key}>
<div className="space-y-2 rounded-lg bg-card p-3">
<div className="rounded-md border bg-muted/30 p-3 space-y-2">
<div className="flex items-center gap-2">
<span className="w-12 shrink-0 text-[11px] font-semibold uppercase tracking-wider text-dim">
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground w-12 shrink-0">
{t('expression.if', 'IF')}
</span>
<BufferedExprInput
@@ -117,18 +117,18 @@ export function ExpressionEditor({ value, onChange, readOnly = false, label, con
{!readOnly && (
<Button
type="button"
variant="ghost-danger"
size="icon-sm"
className="shrink-0"
variant="ghost"
size="icon"
className="h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive"
onClick={() => handleRemove(key)}
aria-label={t('expression.removeCondition', 'Remove condition {{n}}', { n: index + 1 })}
>
<X aria-hidden="true" />
<X className="h-4 w-4" />
</Button>
)}
</div>
<div className="flex items-center gap-2">
<span className="w-12 shrink-0 text-[11px] font-semibold uppercase tracking-wider text-dim">
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground w-12 shrink-0">
{t('expression.then', 'THEN')}
</span>
<BufferedExprInput
@@ -142,6 +142,7 @@ export function ExpressionEditor({ value, onChange, readOnly = false, label, con
{!readOnly && <div className="w-8 shrink-0" />}
</div>
</div>
{index < matchEntries.length - 1 && <Separator className="my-3" />}
</div>
))}
@@ -152,17 +153,18 @@ export function ExpressionEditor({ value, onChange, readOnly = false, label, con
variant="ghost"
size="sm"
onClick={handleAdd}
className="h-7 gap-1 px-3 text-xs hover:bg-card"
className="h-7 gap-1 px-2 text-xs text-muted-foreground hover:text-foreground"
>
<Plus className="!size-3.5" aria-hidden="true" />
<Plus className="h-3 w-3" />
{t('expression.addCondition', 'Add condition')}
</Button>
</div>
)}
<div className={cn('flex items-center gap-2', matchEntries.length > 0 && 'border-t border-border pt-2.5')}>
{matchEntries.length > 0 && <Separator />}
<div className="flex items-center gap-2">
{matchEntries.length > 0 && (
<span className="w-12 shrink-0 text-[11px] font-semibold uppercase tracking-wider text-dim">
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground w-12 shrink-0">
{t('expression.else', 'ELSE')}
</span>
)}
+4 -6
View File
@@ -48,18 +48,16 @@ export function CreatedValuesDialog({ values, labels, onContinue }: CreatedValue
)}
</DialogDescription>
</DialogHeader>
<div className="space-y-1 divide-y divide-border rounded-xl bg-muted px-4 py-1">
<div className="space-y-3 py-2">
{values &&
Object.entries(values).map(([key, value]) => {
const text = displayValue(value);
const label = labels.get(key) ?? key;
return (
<div key={key} className="flex flex-col gap-1.5 py-3">
<span className="text-[13px] font-semibold text-muted-foreground">{label}</span>
<div key={key} className="flex flex-col gap-1">
<span className="text-sm font-medium">{label}</span>
<div className="flex items-start gap-2">
<code className="flex-1 select-all break-all rounded-lg bg-card px-3 py-2 font-mono text-sm">
{text}
</code>
<code className="flex-1 rounded bg-muted p-2 text-sm break-all select-all">{text}</code>
<CopyButton value={text} label={label} />
</div>
</div>
+58 -165
View File
@@ -4,26 +4,20 @@
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import { useEffect, useId, useState, useSyncExternalStore } from 'react';
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { ArrowLeft, Check, Loader2, RefreshCw, Trash2 } from 'lucide-react';
import { ArrowLeft, Loader2, RefreshCw, Save, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { ConfirmDialog } from '@/components/common/ConfirmDialog';
import { FloatingActionBar, FloatingActionDivider, FloatingActionDot } from '@/components/common/FloatingActionBar';
import { useCanAccess } from '@/hooks/usePermissions';
import { coerceLabel } from '@/lib/objectOptions';
import { TENANT_PROPERTY } from '@/lib/schemaResolver';
import { CreatedValuesDialog } from '@/components/forms/CreatedValuesDialog';
import { FormProvider } from '@/components/forms/FormProvider';
import { FormSections } from '@/components/forms/FormSections';
import { UnsavedChangesDialog } from '@/components/forms/UnsavedChangesDialog';
import { formFieldLabels } from '@/components/forms/formLogic';
import { useDynamicForm, type DynamicFormModel } from '@/components/forms/useDynamicForm';
import type { RenderableSection } from '@/components/forms/formLogic';
import { cn } from '@/lib/utils';
const SECTION_INDEX_MIN = 3;
interface DynamicFormProps {
viewName: string;
@@ -49,80 +43,6 @@ function useFormTitle(model: DynamicFormModel): string {
: t('form.editTitle', 'Edit {{name}}', { name });
}
const WIDE_QUERY = '(min-width: 80rem)';
function subscribeWide(onChange: () => void): () => void {
const query = window.matchMedia(WIDE_QUERY);
query.addEventListener('change', onChange);
return () => query.removeEventListener('change', onChange);
}
function isWide(): boolean {
return window.matchMedia(WIDE_QUERY).matches;
}
function useActiveSection(ids: readonly string[]): string | undefined {
const [active, setActive] = useState<string | undefined>(ids[0]);
const key = ids.join('|');
useEffect(() => {
if (!key) return;
const list = key.split('|');
const visible = new Set<string>();
const observer = new IntersectionObserver(
(entries) => {
for (const entry of entries) {
if (entry.isIntersecting) visible.add(entry.target.id);
else visible.delete(entry.target.id);
}
const first = list.find((id) => visible.has(id));
if (first) setActive(first);
},
{ rootMargin: '-80px 0px -55% 0px' },
);
for (const id of list) {
const el = document.getElementById(id);
if (el) observer.observe(el);
}
return () => observer.disconnect();
}, [key]);
return active;
}
function SectionIndex({ sections, sectionId }: { sections: RenderableSection[]; sectionId: (key: string) => string }) {
const { t } = useTranslation();
const titled = sections.filter((s) => s.title);
const active = useActiveSection(titled.map((s) => sectionId(s.key)));
return (
<nav
aria-label={t('form.sectionIndex', 'Form sections')}
className="sticky top-20 flex max-h-[calc(100vh-6rem)] flex-col gap-0.5 overflow-y-auto pt-1"
>
{titled.map((section) => {
const id = sectionId(section.key);
return (
<button
key={section.key}
type="button"
aria-current={active === id ? 'location' : undefined}
onClick={() => {
const section = document.getElementById(id);
section?.scrollIntoView({ behavior: 'smooth', block: 'start' });
section?.focus({ preventScroll: true });
}}
className={cn(
'rounded-[10px] px-3 py-1.5 text-left text-[13px] font-medium text-muted-foreground transition-colors hover:bg-card hover:text-foreground',
active === id &&
'bg-highlight font-semibold text-highlight-foreground hover:bg-highlight hover:text-highlight-foreground',
)}
>
{section.title}
</button>
);
})}
</nav>
);
}
function Loading({ label }: { label: string }) {
return (
<div className="flex items-center justify-center p-12 text-muted-foreground" role="status">
@@ -141,8 +61,6 @@ export function DynamicForm({ viewName, objectId }: DynamicFormProps) {
const { schema, resolved, mode, isSingleton, state, isDirty, saving, loading, loadError } = model;
const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
const title = useFormTitle(model);
const sectionPrefix = useId();
const wide = useSyncExternalStore(subscribeWide, isWide, () => false);
if (!schema || !resolved) return <Loading label={t('form.loadingSchema', 'Loading schema...')} />;
if (loading) return <Loading label={t('form.loadingData', 'Loading data...')} />;
@@ -153,19 +71,18 @@ export function DynamicForm({ viewName, objectId }: DynamicFormProps) {
const subtitle = (model.parentForm ?? model.variantForm)?.subtitle;
const errorText = state.generalError ?? loadError;
const header = (
<div className="flex items-start gap-3.5 px-1 pb-1 pt-3">
<div className="flex items-center gap-4">
<Button
type="button"
variant="outline"
size="icon-lg"
className="shrink-0"
variant="ghost"
size="icon"
onClick={() => navigate(-1)}
aria-label={t('common.back', 'Back')}
>
<ArrowLeft className="h-5 w-5" aria-hidden="true" />
</Button>
<div className="min-w-0 flex-1 pt-1">
<h1 className="page-title break-words">{title}</h1>
<div className="flex-1">
<h1 className="text-2xl font-semibold tracking-tight">{title}</h1>
{subtitle && <p className="mt-1 text-sm text-muted-foreground">{subtitle}</p>}
</div>
</div>
@@ -173,9 +90,9 @@ export function DynamicForm({ viewName, objectId }: DynamicFormProps) {
if (model.loadFailed) {
return (
<div className="mx-auto max-w-5xl space-y-5">
<div className="mx-auto max-w-4xl space-y-6">
{header}
<div className="rounded-xl bg-destructive-soft p-4" role="alert">
<div className="rounded-md border border-destructive/20 bg-destructive/10 p-4" role="alert">
<p className="whitespace-pre-line text-sm text-destructive">{loadError}</p>
</div>
<Button type="button" variant="outline" onClick={model.retryLoad}>
@@ -191,91 +108,67 @@ export function DynamicForm({ viewName, objectId }: DynamicFormProps) {
t('form.item', 'item')
).toLowerCase();
const sch = resolved.resolvedSchema;
const tenantValue = state.data[TENANT_PROPERTY];
const sectionId = (key: string) => `${sectionPrefix}-section-${key.replace(/[^A-Za-z0-9_-]/g, '_')}`;
const showIndex = model.sections.filter((s) => s.title).length >= SECTION_INDEX_MIN;
return (
<div className={cn('mx-auto space-y-5', showIndex ? 'max-w-6xl' : 'max-w-5xl')}>
<div className="mx-auto max-w-4xl space-y-6">
{header}
{errorText && (
<div className="rounded-xl bg-destructive-soft p-4" role="alert">
<div className="rounded-md border border-destructive/20 bg-destructive/10 p-4" role="alert">
<p className="whitespace-pre-line text-sm text-destructive">{errorText}</p>
</div>
)}
<div className={cn(showIndex && 'xl:grid xl:grid-cols-[11rem_minmax(0,1fr)] xl:items-start xl:gap-6')}>
{showIndex && wide && <SectionIndex sections={model.sections} sectionId={sectionId} />}
<div className="space-y-3.5">
<FormProvider
schema={schema}
mode={mode}
readOnly={readOnly}
recordLabel={model.recordLabel}
baseline={state.original}
tenantId={typeof tenantValue === 'string' ? tenantValue : null}
>
<FormSections
sections={model.sections}
sectionId={sectionId}
data={state.data}
errors={state.fieldErrors}
readOnly={readOnly}
onFieldChange={model.setField}
variant={
sch.type === 'multiple'
? { variants: sch.variants, value: state.variant, onChange: model.setVariant }
: undefined
}
/>
</FormProvider>
<FormProvider
schema={schema}
mode={mode}
readOnly={readOnly}
recordLabel={model.recordLabel}
baseline={state.original}
>
<FormSections
sections={model.sections}
data={state.data}
errors={state.fieldErrors}
readOnly={readOnly}
onFieldChange={model.setField}
variant={
sch.type === 'multiple'
? { variants: sch.variants, value: state.variant, onChange: model.setVariant }
: undefined
}
/>
</FormProvider>
<div className="flex items-center justify-between pb-8 pt-2">
<div>
{canDelete && (
<Button type="button" variant="destructive" disabled={saving} onClick={() => setDeleteConfirmOpen(true)}>
<Trash2 className="mr-2 h-4 w-4" aria-hidden="true" />
{t('common.delete', 'Delete')}
</Button>
)}
</div>
<div className="flex items-center gap-3">
{isDirty && (
<span className="text-xs text-muted-foreground">{t('form.unsavedChangesLabel', 'Unsaved changes')}</span>
)}
<Button type="button" variant="outline" onClick={() => navigate(-1)} disabled={saving}>
{t('common.cancel', 'Cancel')}
</Button>
{!readOnly && (
<Button type="button" onClick={() => void model.save()} disabled={saving || (!isCreate && !isDirty)}>
{saving ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden="true" />
) : (
<Save className="mr-2 h-4 w-4" aria-hidden="true" />
)}
{isCreate ? t('common.create', 'Create') : t('common.save', 'Save')}
</Button>
)}
</div>
</div>
<FloatingActionBar label={t('form.actions', 'Form actions')}>
{canDelete && (
<>
<Button
type="button"
variant="ink-danger"
size="sm"
disabled={saving}
onClick={() => setDeleteConfirmOpen(true)}
>
<Trash2 className="h-4 w-4" aria-hidden="true" />
<span className="max-sm:sr-only">{t('common.delete', 'Delete')}</span>
</Button>
<FloatingActionDivider />
</>
)}
{isDirty && (
<span className="flex items-center gap-2 px-2 text-[13px] text-ink-muted max-sm:hidden">
<FloatingActionDot />
{t('form.unsavedChangesLabel', 'Unsaved changes')}
</span>
)}
<Button type="button" variant="ink" size="sm" onClick={() => navigate(-1)} disabled={saving}>
{t('common.cancel', 'Cancel')}
</Button>
{!readOnly && (
<Button
type="button"
size="sm"
className="shadow-none"
onClick={() => void model.save()}
disabled={saving || (!isCreate && !isDirty)}
>
{saving ? (
<Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />
) : (
<Check className="h-4 w-4" aria-hidden="true" />
)}
{isCreate ? t('common.create', 'Create') : t('common.save', 'Save')}
</Button>
)}
</FloatingActionBar>
<UnsavedChangesDialog blocker={model.guard.blocker} />
<ConfirmDialog
+22 -39
View File
@@ -44,16 +44,16 @@ interface FieldLabelProps {
export function FieldLabel({ id, htmlFor, label, marker, locked }: FieldLabelProps) {
const { t } = useTranslation();
return (
<div className="flex items-center gap-1.5">
<Label id={id} htmlFor={htmlFor} className="text-[13.5px] font-semibold leading-snug">
<div className="flex items-center gap-2">
<Label id={id} htmlFor={htmlFor} className="text-sm font-medium">
{label}
{marker === 'required' && (
<span className="ml-1 text-brand-text" aria-hidden="true">
<span className="ml-0.5 text-destructive" aria-hidden="true">
*
</span>
)}
{marker === 'optional' && (
<span className="ml-1.5 text-xs font-normal text-dim">{t('field.optional', '(optional)')}</span>
<span className="ml-1.5 text-xs font-normal text-muted-foreground">{t('field.optional', '(optional)')}</span>
)}
</Label>
{locked && (
@@ -70,7 +70,7 @@ export function FieldLabel({ id, htmlFor, label, marker, locked }: FieldLabelPro
export function FieldError({ id, error }: { id: string; error?: string }) {
if (!error) return null;
return (
<p id={id} className="text-xs font-medium text-destructive">
<p id={id} className="text-xs text-destructive">
{error}
</p>
);
@@ -132,49 +132,32 @@ export function FieldRow({ field, formField, value, onChange, error, readOnly: f
if (traits.labelMode === 'none') {
return (
<div data-slot="field-row" className="space-y-1.5 py-4">
<div className="space-y-1.5">
{body}
<FieldError id={ids.errorId} error={error} />
</div>
);
}
const layout = asValue && traits.layout === 'inline' ? 'side' : traits.layout;
return (
<div
data-slot="field-row"
className={cn(
'py-4',
layout === 'side' ? 'field-grid' : 'grid gap-x-8 gap-y-2',
layout === 'inline' && 'grid-cols-[minmax(0,1fr)_auto]',
)}
>
<div className={cn('min-w-0 space-y-1', layout === 'side' && '@xl:pt-2')}>
<FieldLabel
id={ids.labelId}
htmlFor={traits.labelMode === 'control' && !asValue ? ids.inputId : undefined}
label={formField.label}
marker={marker}
locked={locked}
/>
{field.description && (
<div id={ids.descriptionId}>
<Markdown source={field.description} className="text-[12.5px] leading-relaxed text-muted-foreground" />
</div>
)}
</div>
<div className={cn('min-w-0 space-y-1.5', layout === 'inline' && 'pt-0.5', asValue && '@xl:pt-2')}>
<div className={cn(locked && 'opacity-60')}>{body}</div>
{ft.type === 'string' && ft.format === 'sieve' && (
<SievepadButton scriptName={ctx.recordLabel} source={typeof value === 'string' ? value : ''} />
)}
{layout !== 'inline' && <FieldError id={ids.errorId} error={error} />}
</div>
{layout === 'inline' && error && (
<div className="col-span-full">
<FieldError id={ids.errorId} error={error} />
<div className="space-y-1.5">
<FieldLabel
id={ids.labelId}
htmlFor={traits.labelMode === 'control' && !asValue ? ids.inputId : undefined}
label={formField.label}
marker={marker}
locked={locked}
/>
{field.description && (
<div id={ids.descriptionId}>
<Markdown source={field.description} className="text-xs text-muted-foreground" />
</div>
)}
<div className={cn(locked && 'opacity-60')}>{body}</div>
{ft.type === 'string' && ft.format === 'sieve' && (
<SievepadButton scriptName={ctx.recordLabel} source={typeof value === 'string' ? value : ''} />
)}
<FieldError id={ids.errorId} error={error} />
</div>
);
}
-3
View File
@@ -23,7 +23,6 @@ interface FormProviderProps {
hideEnterprise?: boolean;
recordLabel?: string;
baseline?: unknown;
tenantId?: string | null;
children: ReactNode;
}
@@ -34,7 +33,6 @@ export function FormProvider({
hideEnterprise = false,
recordLabel = '',
baseline = null,
tenantId = null,
children,
}: FormProviderProps) {
const isCommunity = useIsCommunity();
@@ -48,7 +46,6 @@ export function FormProvider({
idPrefix,
recordLabel,
baseline,
tenantId,
};
const scope: FieldScope = { path: [], readOnly };
return (
+14 -21
View File
@@ -5,10 +5,10 @@
*/
import type { ReactNode } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { FieldRow } from '@/components/forms/FieldRow';
import { VariantSelect } from '@/components/forms/VariantSelect';
import type { EmbeddedVariant } from '@/lib/embeddedSchema';
import { cn } from '@/lib/utils';
import type { FieldErrors, FieldValues, RenderableSection } from '@/components/forms/formLogic';
interface VariantControl {
@@ -19,7 +19,6 @@ interface VariantControl {
interface FormSectionsProps {
sections: RenderableSection[];
sectionId?: (key: string) => string;
data: FieldValues;
errors: FieldErrors;
readOnly: boolean;
@@ -27,19 +26,11 @@ interface FormSectionsProps {
variant?: VariantControl;
}
export function FormSections({
sections,
sectionId,
data,
errors,
readOnly,
onFieldChange,
variant,
}: FormSectionsProps) {
export function FormSections({ sections, data, errors, readOnly, onFieldChange, variant }: FormSectionsProps) {
return (
<>
{sections.map((section) => (
<FormSectionCard key={section.key} id={sectionId?.(section.key)} title={section.title}>
<FormSectionCard key={section.key} title={section.title}>
{section.fields.map(({ formField, field }) => {
if (!field) {
if (!variant) return null;
@@ -71,15 +62,17 @@ export function FormSections({
);
}
export function FormSectionCard({ id, title, children }: { id?: string; title?: string; children: ReactNode }) {
export function FormSectionCard({ title, children }: { title?: string; children: ReactNode }) {
return (
<section
id={id}
tabIndex={id ? -1 : undefined}
className="tile @container scroll-mt-20 px-5 pb-1.5 outline-none sm:px-6"
>
{title && <h2 className="section-title pb-1 pt-5">{title}</h2>}
<div className={cn('divide-y divide-border', !title && 'pt-1')}>{children}</div>
</section>
<Card>
{title && (
<CardHeader>
<CardTitle className="text-base">{title}</CardTitle>
</CardHeader>
)}
<CardContent className={title ? '' : 'pt-6'}>
<div className="space-y-6">{children}</div>
</CardContent>
</Card>
);
}
+3 -3
View File
@@ -48,8 +48,8 @@ export function SievepadButton({ scriptName, source }: SievepadButtonProps) {
return (
<>
<div className="flex justify-end">
<Button type="button" variant="secondary" size="sm" onClick={handleClick} disabled={!source.trim()}>
<Bug aria-hidden="true" />
<Button type="button" variant="outline" size="sm" onClick={handleClick} disabled={!source.trim()}>
<Bug className="h-4 w-4" />
{t('sievepad.debug', 'Debug')}
</Button>
</div>
@@ -64,7 +64,7 @@ export function SievepadButton({ scriptName, source }: SievepadButtonProps) {
confirmLabel={t('common.continue')}
onConfirm={handleContinue}
>
<div className="flex items-center gap-2.5 rounded-xl bg-muted px-3.5 py-3">
<div className="flex items-center gap-2">
<Checkbox
id="sievepad-dont-show-again"
checked={dontShowAgain}
+17 -132
View File
@@ -4,17 +4,12 @@
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import type { KeyboardEvent } from 'react';
import { useTranslation } from 'react-i18next';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { FieldLabel } from '@/components/forms/FieldRow';
import { fieldIds, useFieldScope, useFormContext, useInPanel } from '@/components/forms/formContext';
import { fieldIds, useFieldScope, useFormContext } from '@/components/forms/formContext';
import { VARIANT_FIELD } from '@/components/forms/formLogic';
import type { EmbeddedVariant } from '@/lib/embeddedSchema';
import { cn } from '@/lib/utils';
const SEGMENTED_MAX_VARIANTS = 4;
const SEGMENTED_MAX_LABEL_CHARS = 44;
interface VariantSelectProps {
label?: string;
@@ -26,102 +21,6 @@ interface VariantSelectProps {
readOnly: boolean;
}
function isSegmented(variants: readonly EmbeddedVariant[]): boolean {
return (
variants.length > 1 &&
variants.length <= SEGMENTED_MAX_VARIANTS &&
variants.reduce((sum, v) => sum + v.label.length, 0) <= SEGMENTED_MAX_LABEL_CHARS
);
}
interface VariantControlProps {
id: string;
labelledBy?: string;
ariaLabel?: string;
variants: readonly EmbeddedVariant[];
value: string;
onChange: (variant: string) => void;
readOnly: boolean;
}
const ROVING_KEYS: Record<string, number> = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 };
function moveRadioFocus(e: KeyboardEvent<HTMLDivElement>) {
const step = Object.hasOwn(ROVING_KEYS, e.key) ? ROVING_KEYS[e.key] : 0;
if (!step && e.key !== 'Home' && e.key !== 'End') return;
const radios = Array.from(e.currentTarget.querySelectorAll<HTMLButtonElement>('[role="radio"]'));
if (radios.length === 0) return;
e.preventDefault();
const current = radios.indexOf(document.activeElement as HTMLButtonElement);
const next =
e.key === 'Home'
? 0
: e.key === 'End'
? radios.length - 1
: (Math.max(current, 0) + step + radios.length) % radios.length;
radios[next].focus();
}
function SegmentedVariants({ id, labelledBy, ariaLabel, variants, value, onChange, readOnly }: VariantControlProps) {
const inPanel = useInPanel();
const hasChecked = variants.some((v) => v.name === value);
return (
<div
role="radiogroup"
id={id}
aria-labelledby={labelledBy}
aria-label={ariaLabel}
aria-disabled={readOnly || undefined}
onKeyDown={moveRadioFocus}
className={cn(
'inline-flex max-w-full flex-wrap gap-0.5 rounded-full p-1',
inPanel ? 'bg-muted-strong' : 'bg-muted',
)}
>
{variants.map((v, i) => {
const checked = v.name === value;
return (
<button
key={v.name}
type="button"
role="radio"
aria-checked={checked}
tabIndex={checked || (!hasChecked && i === 0) ? 0 : -1}
disabled={readOnly}
onClick={() => {
if (!checked) onChange(v.name);
}}
className={cn(
'inline-flex h-7 items-center rounded-full px-3 text-[13px] font-semibold text-muted-foreground outline-none transition-[color,background-color,box-shadow] duration-200 focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-60',
checked ? 'bg-card text-foreground shadow-tile' : 'hover:text-foreground',
)}
>
{v.label}
</button>
);
})}
</div>
);
}
function DropdownVariants({ id, labelledBy, ariaLabel, variants, value, onChange, readOnly }: VariantControlProps) {
const { t } = useTranslation();
return (
<Select value={value} onValueChange={onChange} disabled={readOnly}>
<SelectTrigger id={id} className="w-full" aria-labelledby={labelledBy} aria-label={ariaLabel}>
<SelectValue placeholder={t('form.selectType', 'Select type...')} />
</SelectTrigger>
<SelectContent>
{variants.map((v) => (
<SelectItem key={v.name} value={v.name}>
{v.label}
</SelectItem>
))}
</SelectContent>
</Select>
);
}
export function VariantSelect({
label,
labelledBy,
@@ -136,43 +35,29 @@ export function VariantSelect({
const scope = useFieldScope();
const ids = fieldIds(ctx.idPrefix, [...scope.path, VARIANT_FIELD]);
const external = !!labelledBy || !!ariaLabel;
const segmented = isSegmented(variants);
const Control = segmented ? SegmentedVariants : DropdownVariants;
const controlProps = {
id: ids.inputId,
variants,
value,
onChange,
readOnly,
};
if (external) {
return (
<div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2">
<span className="text-xs font-semibold uppercase tracking-wider text-dim" aria-hidden="true">
{t('field.type', 'Type')}
</span>
<div className={cn('min-w-0', !segmented && 'w-full max-w-sm')}>
<Control {...controlProps} labelledBy={labelledBy} ariaLabel={ariaLabel} />
</div>
</div>
);
}
return (
<div data-slot="field-row" className="field-grid py-4">
<div className="@xl:pt-2">
<div className="space-y-1.5">
{!external && (
<FieldLabel
id={ids.labelId}
htmlFor={segmented ? undefined : ids.inputId}
htmlFor={ids.inputId}
label={label || t('field.type', 'Type')}
marker={null}
locked={false}
/>
</div>
<div className="min-w-0">
<Control {...controlProps} labelledBy={segmented ? ids.labelId : undefined} />
</div>
)}
<Select value={value} onValueChange={onChange} disabled={readOnly}>
<SelectTrigger id={ids.inputId} className="w-full" aria-labelledby={labelledBy} aria-label={ariaLabel}>
<SelectValue placeholder={t('form.selectType', 'Select type...')} />
</SelectTrigger>
<SelectContent>
{variants.map((v) => (
<SelectItem key={v.name} value={v.name}>
{v.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
);
}
-7
View File
@@ -18,7 +18,6 @@ export interface FormContextValue {
idPrefix: string;
recordLabel: string;
baseline: unknown;
tenantId: string | null;
}
export interface FieldScope {
@@ -30,8 +29,6 @@ export const FormContext = createContext<FormContextValue | null>(null);
export const FieldScopeContext = createContext<FieldScope>({ path: [], readOnly: false });
export const PanelContext = createContext(false);
export function useFormContext(): FormContextValue {
const ctx = useContext(FormContext);
if (!ctx) throw new Error('Form widgets must be rendered inside a FormProvider');
@@ -42,10 +39,6 @@ export function useFieldScope(): FieldScope {
return useContext(FieldScopeContext);
}
export function useInPanel(): boolean {
return useContext(PanelContext);
}
export function isEnterpriseLockedIn(ctx: FormContextValue, enterprise: boolean | undefined): boolean {
return !!enterprise && ctx.isCommunity;
}
+1 -3
View File
@@ -9,7 +9,6 @@ import { deepMerge, resolveForm, resolveObject, type ResolvedView } from '@/lib/
import { SECRET_MASK } from '@/lib/jmapUtils';
import { embeddedEntries, isRecord, resolveEmbedded } from '@/lib/embeddedSchema';
import { isMissingValue, isRequiredField, isUnchangedSecret } from '@/lib/fieldRules';
import { widgetTraits } from '@/components/forms/widgets/registry';
import type { BlobUpload } from '@/services/jmap/client';
import type { JmapSetError, ValidationError } from '@/types/jmap';
import type { Field, FieldType, Fields, Form, FormField, Schema } from '@/types/schema';
@@ -298,8 +297,7 @@ export interface RenderableSection {
}
export function buildSections(form: Form | null, fields: Fields | null, mode: FormMode): RenderableSection[] {
const visible = (field: Field) =>
mode === 'create' ? field.update !== 'serverSet' : !widgetTraits(field.type).createOnly;
const visible = (field: Field) => !(mode === 'create' && field.update === 'serverSet');
if (!form) {
if (!fields) return [];
const all = Object.entries(fields.properties)
+5 -12
View File
@@ -11,14 +11,11 @@ import { Button } from '@/components/ui/button';
import { useBlobText } from '@/data/objects';
import { errorMessage } from '@/lib/jmapErrors';
import { BufferedTextarea } from '@/components/forms/widgets/BufferedInputs';
import { SievepadButton } from '@/components/forms/SievepadButton';
import { useFormContext } from '@/components/forms/formContext';
import type { WidgetProps } from '@/components/forms/widgets/types';
import type { FieldTypeBlobId } from '@/types/schema';
export function BlobWidget({ type, value, onChange, readOnly, control }: WidgetProps<FieldTypeBlobId>) {
export function BlobWidget({ value, onChange, readOnly, control }: WidgetProps<FieldTypeBlobId>) {
const { t } = useTranslation();
const { recordLabel } = useFormContext();
const [edited, setEdited] = useState<string | null>(null);
if (edited !== null && value !== edited) {
setEdited(null);
@@ -30,7 +27,7 @@ export function BlobWidget({ type, value, onChange, readOnly, control }: WidgetP
if (blobId && blob.isPending) {
return (
<div className="flex items-center gap-2 py-2 text-sm text-muted-foreground" role="status">
<Loader2 className="h-4 w-4 animate-spin text-brand-text" aria-hidden="true" />
<Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />
{t('field.loadingContent', 'Loading content...')}
</div>
);
@@ -38,7 +35,7 @@ export function BlobWidget({ type, value, onChange, readOnly, control }: WidgetP
if (blobId && (blob.isError || blob.data === null)) {
return (
<div className="flex items-center justify-between gap-3 rounded-xl bg-destructive-soft py-2.5 pl-4 pr-2.5">
<div className="flex items-center justify-between gap-2 rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2">
<p className="text-sm text-destructive" role="alert">
{blob.isError
? errorMessage(blob.error, t('field.blobLoadFailed', 'Failed to load content.'))
@@ -48,7 +45,6 @@ export function BlobWidget({ type, value, onChange, readOnly, control }: WidgetP
type="button"
variant="outline"
size="sm"
className="shrink-0"
onClick={() => void blob.refetch()}
disabled={blob.isFetching}
>
@@ -58,13 +54,11 @@ export function BlobWidget({ type, value, onChange, readOnly, control }: WidgetP
);
}
const text = edited ?? blob.data ?? '';
return (
<div className="space-y-1">
<BufferedTextarea
{...control}
value={text}
value={edited ?? blob.data ?? ''}
onCommit={(text) => {
setEdited(text);
onChange(text);
@@ -74,11 +68,10 @@ export function BlobWidget({ type, value, onChange, readOnly, control }: WidgetP
className="font-mono text-xs"
/>
{isOwnEdit && (
<p className="text-xs font-medium text-warning">
<p className="text-xs text-muted-foreground">
{t('field.contentModified', 'Content modified (will be saved as a new blob)')}
</p>
)}
{type.format === 'sieve' && <SievepadButton scriptName={recordLabel} source={text} />}
</div>
);
}
@@ -40,7 +40,6 @@ export function BufferedInput({ value, onCommit, onBlur, onKeyDown, ...rest }: B
}
interface BufferedTextareaProps extends Omit<TextareaHTMLAttributes<HTMLTextAreaElement>, 'onChange' | 'value'> {
variant?: 'field' | 'bare';
value: string;
onCommit: (v: string) => void;
}
@@ -20,7 +20,7 @@ const Calendar = lazy(() => import('@/components/ui/calendar').then((m) => ({ de
function CalendarFallback() {
return (
<div className="flex h-72 w-64 items-center justify-center" role="status">
<Loader2 className="h-5 w-5 animate-spin text-brand-text" aria-hidden="true" />
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" aria-hidden="true" />
</div>
);
}
@@ -50,15 +50,15 @@ export function DateTimeWidget({ type, value, onChange, readOnly, control }: Wid
<Button
{...control}
type="button"
variant="field"
variant="outline"
disabled={readOnly}
className={cn('flex-1 justify-start px-3 text-left', !selected && 'text-dim')}
className={cn('flex-1 justify-start text-left font-normal', !selected && 'text-muted-foreground')}
>
<CalendarIcon className="text-dim" aria-hidden="true" />
<CalendarIcon className="mr-2 h-4 w-4" aria-hidden="true" />
{selected ? formatDateTime(selected) : t('field.pickDate', 'Pick a date')}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto overflow-hidden p-0" align="start">
<PopoverContent className="w-auto p-0" align="start">
<Suspense fallback={<CalendarFallback />}>
<Calendar
mode="single"
@@ -70,7 +70,7 @@ export function DateTimeWidget({ type, value, onChange, readOnly, control }: Wid
}}
/>
</Suspense>
<div className="border-t border-border bg-muted/60 p-3">
<div className="border-t p-3">
<Input
type="time"
value={localTime}
@@ -92,7 +92,7 @@ export function DateTimeWidget({ type, value, onChange, readOnly, control }: Wid
onClick={() => onChange(null)}
aria-label={t('common.clear', 'Clear')}
>
<X aria-hidden="true" />
<X className="h-4 w-4" />
</Button>
)}
</div>
@@ -8,11 +8,10 @@ import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { FieldRow } from '@/components/forms/FieldRow';
import { VariantSelect } from '@/components/forms/VariantSelect';
import { PanelContext, useFormContext, useInPanel } from '@/components/forms/formContext';
import { useFormContext } from '@/components/forms/formContext';
import { buildEmbeddedDefaults } from '@/lib/schemaResolver';
import { embeddedEntries, isRecord, resolveEmbedded, switchVariantValues } from '@/lib/embeddedSchema';
import type { ControlProps, WidgetProps } from '@/components/forms/widgets/types';
import { cn } from '@/lib/utils';
import type { FieldTypeObject } from '@/types/schema';
interface EmbeddedObjectEditorProps {
@@ -21,20 +20,11 @@ interface EmbeddedObjectEditorProps {
value: unknown;
onChange: (value: unknown) => void;
readOnly: boolean;
bare?: boolean;
}
export function EmbeddedObjectEditor({
objectName,
control,
value,
onChange,
readOnly,
bare = false,
}: EmbeddedObjectEditorProps) {
function EmbeddedObjectEditor({ objectName, control, value, onChange, readOnly }: EmbeddedObjectEditorProps) {
const { t } = useTranslation();
const { schema, mode, baseline } = useFormContext();
const inPanel = useInPanel();
const [initial, setInitial] = useState({ baseline, value });
if (initial.baseline !== baseline) setInitial({ baseline, value });
const resolved = resolveEmbedded(schema, objectName, value);
@@ -56,46 +46,28 @@ export function EmbeddedObjectEditor({
};
const entries = embeddedEntries(resolved).filter(({ field }) => field.update !== 'serverSet');
if (!resolved.variants && entries.length === 0) return null;
const frame = bare ? 'bare' : inPanel ? 'rule' : 'panel';
return (
<PanelContext value={true}>
<div
data-slot="embedded-object"
className={cn(
'@container',
frame === 'panel' && 'rounded-xl bg-muted px-4',
frame === 'rule' && 'border-l-2 border-input pl-4',
)}
>
{resolved.variants && (
<div className={cn(frame === 'panel' ? 'py-3' : 'py-2', entries.length > 0 && 'border-b border-border')}>
<VariantSelect
labelledBy={control?.['aria-labelledby']}
ariaLabel={control?.['aria-label']}
variants={resolved.variants}
value={resolved.variant?.name ?? ''}
onChange={changeVariant}
readOnly={readOnly}
/>
</div>
)}
{entries.length > 0 && (
<div className={cn('divide-y divide-border', frame === 'rule' && '[&>[data-slot=field-row]]:py-3')}>
{entries.map(({ formField, field }) => (
<FieldRow
key={formField.name}
field={field}
formField={formField}
value={obj[formField.name]}
onChange={(v) => onChange({ ...obj, [formField.name]: v })}
/>
))}
</div>
)}
</div>
</PanelContext>
<div className="space-y-4 rounded-md border p-4">
{resolved.variants && (
<VariantSelect
labelledBy={control?.['aria-labelledby']}
ariaLabel={control?.['aria-label']}
variants={resolved.variants}
value={resolved.variant?.name ?? ''}
onChange={changeVariant}
readOnly={readOnly}
/>
)}
{entries.map(({ formField, field }) => (
<FieldRow
key={formField.name}
field={field}
formField={formField}
value={obj[formField.name]}
onChange={(v) => onChange({ ...obj, [formField.name]: v })}
/>
))}
</div>
);
}
+8 -13
View File
@@ -98,7 +98,7 @@ export function EnumMultiSelect({ enumName, items, onChange, readOnly, minItems,
const checkboxItem = (v: EnumVariant, idPrefix: string) => {
const id = `${idPrefix}-${v.name.replace(/[^A-Za-z0-9_-]/g, '_')}`;
return (
<div key={v.name} className="flex items-center gap-2.5 rounded-lg px-2 py-1.5 transition-colors hover:bg-muted">
<div key={v.name} className="flex items-center gap-2 py-0.5">
<Checkbox
id={id}
checked={items.includes(v.name)}
@@ -116,11 +116,7 @@ export function EnumMultiSelect({ enumName, items, onChange, readOnly, minItems,
if (variants.length <= SEARCHABLE_THRESHOLD) {
return (
<div
className={
variants.length > GRID_THRESHOLD ? '-mx-2 grid gap-x-2 gap-y-0.5 sm:grid-cols-2' : '-mx-2 space-y-0.5'
}
>
<div className={variants.length > GRID_THRESHOLD ? 'grid grid-cols-2 gap-2' : 'space-y-2'}>
{variants.map((v) => checkboxItem(v, baseId))}
</div>
);
@@ -154,23 +150,22 @@ export function EnumMultiSelect({ enumName, items, onChange, readOnly, minItems,
)}
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button {...control} type="button" variant="secondary" size="sm" disabled={readOnly}>
<Search aria-hidden="true" />
<Button {...control} type="button" variant="outline" size="sm" className="gap-1" disabled={readOnly}>
<Search className="h-4 w-4" aria-hidden="true" />
{t('field.selectOptions', 'Select options...')}
</Button>
</PopoverTrigger>
<PopoverContent className="w-72 overflow-hidden p-0" align="start">
<div className="p-2 pb-1">
<PopoverContent className="w-72 p-0" align="start">
<div className="border-b p-2">
<Input
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder={t('common.searchPlaceholder', 'Search...')}
aria-label={t('common.search', 'Search')}
variant="pill"
className="h-8 px-3.5"
className="h-8"
/>
</div>
<div className="max-h-60 space-y-0.5 overflow-y-auto p-1.5">
<div className="max-h-60 space-y-1 overflow-y-auto p-2">
{filtered.length === 0 && (
<p className="py-2 text-center text-sm text-muted-foreground">{t('field.noMatches', 'No matches')}</p>
)}
@@ -40,12 +40,6 @@ const OtpAuthField = lazy(() =>
import('@/components/forms/widgets/OtpAuthField').then((m) => ({ default: m.OtpAuthField })),
);
const PasskeyRegistrationField = lazy(() =>
import('@/components/forms/widgets/PasskeyRegistrationField').then((m) => ({
default: m.PasskeyRegistrationField,
})),
);
function narrow<T extends FieldType>(props: WidgetProps): WidgetProps<T> {
return props as WidgetProps<T>;
}
@@ -88,12 +82,6 @@ export function FieldControl(props: WidgetProps) {
<OtpAuthField {...narrow<FieldTypeObject>(props)} />
</Suspense>
);
case 'object:x:PasskeyRegistration':
return (
<Suspense fallback={null}>
<PasskeyRegistrationField {...narrow<FieldTypeObject>(props)} />
</Suspense>
);
case 'objectList':
return <ObjectListWidget {...narrow<FieldTypeObjectList>(props)} />;
case 'set':
+69 -129
View File
@@ -4,24 +4,22 @@
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import { useId, useState, type KeyboardEvent } from 'react';
import { useState, type KeyboardEvent } from 'react';
import { useTranslation } from 'react-i18next';
import { ChevronRight, Loader2, Plus, Trash2 } from 'lucide-react';
import { ChevronRight, Loader2, Plus, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { ObjectSearchPopover } from '@/components/common/ObjectSearchPopover';
import { FieldScopeProvider } from '@/components/forms/FormProvider';
import { PanelContext, useFormContext, useInPanel } from '@/components/forms/formContext';
import { useFormContext } from '@/components/forms/formContext';
import { FieldControl } from '@/components/forms/widgets/FieldControl';
import { EmbeddedObjectEditor } from '@/components/forms/widgets/EmbeddedObjectWidget';
import { formatPlaceholder } from '@/components/forms/widgets/placeholders';
import { widgetKey } from '@/components/forms/widgets/registry';
import { useNoPermissionMessage } from '@/lib/objectOptions';
import { useDisplayName, useObjectOptions } from '@/data/objectOptions';
import { buildNewObjectValue, getEnum, getEnumVariant } from '@/lib/schemaResolver';
import { isRecord } from '@/lib/embeddedSchema';
import { cn } from '@/lib/utils';
import type { WidgetProps } from '@/components/forms/widgets/types';
import type { Field, FieldType, FieldTypeMap, MapValueType, ScalarType } from '@/types/schema';
@@ -39,8 +37,6 @@ function defaultMapValue(valueClass: MapValueType, newObject: (objectName: strin
export function MapWidget({ type, formField, value, onChange, readOnly }: WidgetProps<FieldTypeMap>) {
const { t } = useTranslation();
const { schema } = useFormContext();
const inPanel = useInPanel();
const baseId = useId();
const map = isRecord(value) ? value : {};
const entries = Object.entries(map);
const [newKey, setNewKey] = useState('');
@@ -82,133 +78,77 @@ export function MapWidget({ type, formField, value, onChange, readOnly }: Widget
}
};
const objectValues = valueField.type.type === 'object' && widgetKey(valueField.type) !== 'object:x:Rate';
const valueLabel = formField.valueLabel ?? '';
const removeButton = (key: string) =>
!readOnly && (
<Button
type="button"
variant="ghost-danger"
size="icon-sm"
className="shrink-0"
onClick={() => removeEntry(key)}
disabled={!canRemove}
aria-label={t('field.removeEntry', 'Remove entry {{name}}', { name: key })}
>
<Trash2 className="h-4 w-4" aria-hidden="true" />
</Button>
);
const valueControl = (key: string, val: unknown) => (
<FieldScopeProvider name={key} readOnly={readOnly}>
{valueField.type.type === 'object' && widgetKey(valueField.type) === 'object' ? (
<EmbeddedObjectEditor
bare
objectName={valueField.type.objectName}
control={{ 'aria-label': valueLabel || key }}
value={val}
onChange={(v) => onChange({ ...map, [key]: v })}
readOnly={readOnly}
/>
) : (
<FieldControl
type={valueField.type}
field={valueField}
formField={{ name: key, label: valueLabel }}
value={val}
onChange={(v) => onChange({ ...map, [key]: v })}
readOnly={readOnly}
control={{ 'aria-label': valueLabel || key }}
/>
)}
</FieldScopeProvider>
);
return (
<PanelContext value={true}>
<div
data-slot="map-widget"
className={cn('space-y-0.5 rounded-xl p-1.5', inPanel ? 'bg-card shadow-tile' : 'bg-muted')}
>
{!objectValues && entries.length > 0 && (formField.keyLabel || formField.valueLabel) && (
<div
aria-hidden="true"
className="grid grid-cols-[minmax(0,1fr)_minmax(0,1.2fr)_2rem] gap-3 px-3 pb-0.5 pt-1.5 text-[11px] font-semibold uppercase tracking-wider text-dim"
>
<span>{formField.keyLabel}</span>
<span>{formField.valueLabel}</span>
</div>
)}
{entries.map(([key, val]) =>
objectValues ? (
<div key={key} className={cn('rounded-lg', expanded.has(key) && (inPanel ? 'bg-muted' : 'bg-card'))}>
<div className="flex items-center gap-1 pr-1">
<div className="space-y-3">
{entries.map(([key, val]) => (
<Collapsible key={key} open={expanded.has(key)} onOpenChange={(open) => setOpen(key, open)}>
<div className="rounded-md border">
<div className="flex items-center">
<CollapsibleTrigger asChild>
<button
type="button"
onClick={() => setOpen(key, !expanded.has(key))}
aria-expanded={expanded.has(key)}
aria-controls={`${baseId}-${key}`}
className="flex min-w-0 flex-1 items-center gap-2.5 rounded-lg px-2.5 py-2 text-left text-[13.5px] font-semibold outline-none focus-visible:ring-2 focus-visible:ring-ring"
className="flex flex-1 items-center gap-2 rounded-t-md p-3 text-sm font-medium transition-colors hover:bg-accent/50 [&[data-state=open]>svg]:rotate-90"
>
<ChevronRight
className={cn(
'h-4 w-4 shrink-0 text-dim transition-transform duration-200',
expanded.has(key) && 'rotate-90',
)}
aria-hidden="true"
/>
<span className="truncate">
<MapKeyLabel keyClass={type.keyClass} keyValue={key} />
</span>
<ChevronRight className="h-4 w-4 shrink-0 transition-transform duration-200" aria-hidden="true" />
<MapKeyLabel keyClass={type.keyClass} keyValue={key} />
</button>
{removeButton(key)}
</div>
{expanded.has(key) && (
<div id={`${baseId}-${key}`} className="border-t border-border px-4">
{valueControl(key, val)}
</div>
</CollapsibleTrigger>
{!readOnly && (
<Button
type="button"
variant="ghost"
size="icon"
className="mr-2 h-7 w-7 shrink-0"
onClick={() => removeEntry(key)}
disabled={!canRemove}
aria-label={t('field.removeEntry', 'Remove entry {{name}}', { name: key })}
>
<X className="h-4 w-4" aria-hidden="true" />
</Button>
)}
</div>
) : (
<div
key={key}
className="grid grid-cols-[minmax(0,1fr)_minmax(0,1.2fr)_2rem] items-center gap-3 rounded-lg py-1 pl-3 transition-colors hover:bg-muted-strong/60"
>
<span className="truncate text-sm font-medium">
<MapKeyLabel keyClass={type.keyClass} keyValue={key} />
</span>
<div className="min-w-0">{valueControl(key, val)}</div>
{removeButton(key)}
</div>
),
)}
{!readOnly && canAdd && (
<div className="flex items-center gap-2 p-1">
<MapKeyInput
keyClass={type.keyClass}
label={formField.keyLabel ?? t('field.newKey', 'New key')}
value={newKey}
onChange={setNewKey}
onKeyDown={handleKeyDown}
existingKeys={map}
/>
<Button
type="button"
variant="outline"
size="sm"
onClick={addEntry}
disabled={!trimmedKey || Object.hasOwn(map, trimmedKey)}
className="shrink-0"
>
<Plus className="h-4 w-4" aria-hidden="true" />
{t('field.add', 'Add')}
</Button>
<CollapsibleContent>
<div className="px-4 pb-4 pt-1">
<FieldScopeProvider name={key} readOnly={readOnly}>
<FieldControl
type={valueField.type}
field={valueField}
formField={{ name: key, label: formField.valueLabel ?? '' }}
value={val}
onChange={(v) => onChange({ ...map, [key]: v })}
readOnly={readOnly}
control={{ 'aria-label': formField.valueLabel ?? key }}
/>
</FieldScopeProvider>
</div>
</CollapsibleContent>
</div>
)}
{readOnly && entries.length === 0 && (
<p className="px-2.5 py-2 text-sm text-muted-foreground">{t('field.none', 'None')}</p>
)}
</div>
</PanelContext>
</Collapsible>
))}
{!readOnly && canAdd && (
<div className="flex items-center gap-2">
<MapKeyInput
keyClass={type.keyClass}
label={formField.keyLabel ?? t('field.newKey', 'New key')}
value={newKey}
onChange={setNewKey}
onKeyDown={handleKeyDown}
existingKeys={map}
/>
<Button
type="button"
variant="outline"
size="sm"
onClick={addEntry}
disabled={!trimmedKey || Object.hasOwn(map, trimmedKey)}
className="shrink-0 gap-1"
>
<Plus className="h-4 w-4" aria-hidden="true" />
{t('field.add', 'Add')}
</Button>
</div>
)}
</div>
);
}
@@ -295,8 +235,8 @@ function MapKeyObjectIdInput({
onChange: (v: string) => void;
existingKeys: Record<string, unknown>;
}) {
const { schema, tenantId } = useFormContext();
const list = useObjectOptions(objectName, schema, tenantId);
const { schema } = useFormContext();
const list = useObjectOptions(objectName, schema);
const noPermissionMessage = useNoPermissionMessage(schema, objectName);
return (
<div className="flex flex-1 items-center gap-2">
@@ -143,7 +143,7 @@ function UnitNumberWidget({
onClick={() => onChange(null)}
aria-label={t('common.clear', 'Clear')}
>
<X aria-hidden="true" />
<X className="h-4 w-4" />
</Button>
)}
</div>
@@ -6,7 +6,7 @@
import { useTranslation } from 'react-i18next';
import { Loader2 } from 'lucide-react';
import { ObjectFieldFrame, ObjectSearchPopover } from '@/components/common/ObjectSearchPopover';
import { ObjectSearchPopover } from '@/components/common/ObjectSearchPopover';
import { useNoPermissionMessage } from '@/lib/objectOptions';
import { useObjectOptions, useDisplayName, type ObjectOption } from '@/data/objectOptions';
import { useFormContext } from '@/components/forms/formContext';
@@ -47,43 +47,35 @@ export function ObjectIdWidget({
control,
}: WidgetProps<FieldTypeObjectId>) {
const { t } = useTranslation();
const { schema, tenantId } = useFormContext();
const { schema } = useFormContext();
const id = typeof value === 'string' ? value : '';
const list = useObjectOptions(type.objectName, schema, tenantId);
const list = useObjectOptions(type.objectName, schema);
const noPermissionMessage = useNoPermissionMessage(schema, type.objectName);
const pill = id ? (
<ObjectIdPill
objectName={type.objectName}
id={id}
options={list.options}
onRemove={!readOnly && type.nullable ? () => onChange(null) : undefined}
/>
) : null;
if (readOnly) {
return (
<div className="flex flex-wrap items-center gap-2">
{pill ?? <span className="text-sm text-dim">{t('field.none', 'None')}</span>}
</div>
);
}
return (
<ObjectFieldFrame disabled={!!noPermissionMessage}>
{pill}
<ObjectSearchPopover
control={control}
label={t('field.chooseValue', 'Choose {{name}}', { name: formField.label })}
placeholder={id ? '' : t('field.selectEllipsis', 'Select...')}
options={list.options}
loading={list.loading}
error={list.error}
ensureLoaded={list.ensureLoaded}
onSelect={(next) => onChange(next)}
disabledMessage={noPermissionMessage}
/>
</ObjectFieldFrame>
<div className="flex flex-wrap items-center gap-2">
{id && (
<ObjectIdPill
objectName={type.objectName}
id={id}
options={list.options}
onRemove={!readOnly && type.nullable ? () => onChange(null) : undefined}
/>
)}
{!id && readOnly && <span className="text-sm text-muted-foreground">{t('field.none', 'None')}</span>}
{!readOnly && (
<ObjectSearchPopover
control={control}
label={t('field.chooseValue', 'Choose {{name}}', { name: formField.label })}
options={list.options}
loading={list.loading}
error={list.error}
ensureLoaded={list.ensureLoaded}
onSelect={(next) => onChange(next)}
disabledMessage={noPermissionMessage}
/>
)}
</div>
);
}
@@ -107,46 +99,39 @@ export function ObjectIdMultiSelect({
control,
}: ObjectIdMultiSelectProps) {
const { t } = useTranslation();
const { schema, tenantId } = useFormContext();
const list = useObjectOptions(objectName, schema, tenantId);
const { schema } = useFormContext();
const list = useObjectOptions(objectName, schema);
const noPermissionMessage = useNoPermissionMessage(schema, objectName);
const available = list.options.filter((o) => !items.includes(o.id));
const atMinimum = minItems != null && items.length <= minItems;
const pills = items.map((id) => (
<ObjectIdPill
key={id}
objectName={objectName}
id={id}
options={list.options}
removeDisabled={atMinimum}
onRemove={readOnly ? undefined : () => onChange(items.filter((i) => i !== id))}
/>
));
if (readOnly) {
return (
<div className="flex flex-wrap items-center gap-2">
{pills}
{items.length === 0 && <span className="text-sm text-dim">{t('field.none', 'None')}</span>}
</div>
);
}
return (
<ObjectFieldFrame disabled={!!noPermissionMessage}>
{pills}
<ObjectSearchPopover
control={control}
label={t('field.addValue', 'Add {{name}}', { name: label })}
placeholder={items.length === 0 ? t('field.selectEllipsis', 'Select...') : ''}
options={available}
loading={list.loading}
error={list.error}
ensureLoaded={list.ensureLoaded}
onSelect={(id) => onChange([...items, id])}
disabledMessage={noPermissionMessage}
/>
</ObjectFieldFrame>
<div className="flex flex-wrap items-center gap-2">
{items.map((id) => (
<ObjectIdPill
key={id}
objectName={objectName}
id={id}
options={list.options}
removeDisabled={atMinimum}
onRemove={readOnly ? undefined : () => onChange(items.filter((i) => i !== id))}
/>
))}
{!readOnly && (
<ObjectSearchPopover
control={control}
label={t('field.addValue', 'Add {{name}}', { name: label })}
options={available}
loading={list.loading}
error={list.error}
ensureLoaded={list.ensureLoaded}
onSelect={(id) => onChange([...items, id])}
disabledMessage={noPermissionMessage}
/>
)}
{items.length === 0 && readOnly && (
<span className="text-sm text-muted-foreground">{t('field.none', 'None')}</span>
)}
</div>
);
}
@@ -4,19 +4,14 @@
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import { useId, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { ChevronRight, Plus, Trash2 } from 'lucide-react';
import { Plus, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { FieldScopeProvider } from '@/components/forms/FormProvider';
import { PanelContext, useFormContext, useInPanel } from '@/components/forms/formContext';
import { useFormContext } from '@/components/forms/formContext';
import { FieldControl } from '@/components/forms/widgets/FieldControl';
import { EmbeddedObjectEditor } from '@/components/forms/widgets/EmbeddedObjectWidget';
import { widgetKey } from '@/components/forms/widgets/registry';
import { FieldValue } from '@/components/values/FieldValue';
import { buildNewObjectValue } from '@/lib/schemaResolver';
import { embeddedSummary, isRecord } from '@/lib/embeddedSchema';
import { cn } from '@/lib/utils';
import { isRecord } from '@/lib/embeddedSchema';
import type { WidgetProps } from '@/components/forms/widgets/types';
import type { Field, FieldTypeObject, FieldTypeObjectList } from '@/types/schema';
@@ -27,28 +22,16 @@ export function ObjectListWidget({
value,
onChange,
readOnly,
control,
}: WidgetProps<FieldTypeObjectList>) {
const { t } = useTranslation();
const { schema } = useFormContext();
const inPanel = useInPanel();
const baseId = useId();
const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(() => new Set());
const itemType: FieldTypeObject = { type: 'object', objectName: type.objectName };
const itemField: Field = { description: '', type: itemType, update: field.update, enterprise: field.enterprise };
const embedded = widgetKey(itemType) === 'object';
const items = isRecord(value) ? value : {};
const entries = Object.entries(items).sort(([a], [b]) => Number(a) - Number(b));
const canRemove = type.minItems == null || entries.length > type.minItems;
const canAdd = type.maxItems == null || entries.length < type.maxItems;
const toggle = (key: string) =>
setCollapsed((prev) => {
const next = new Set(prev);
if (!next.delete(key)) next.add(key);
return next;
});
const addItem = () => {
const next = entries.length > 0 ? Math.max(...entries.map(([k]) => Number(k) || 0)) + 1 : 0;
onChange({ ...items, [String(next)]: buildNewObjectValue(schema, type.objectName) });
@@ -58,99 +41,45 @@ export function ObjectListWidget({
const copy = { ...items };
delete copy[key];
onChange(copy);
if (collapsed.has(key)) toggle(key);
};
return (
<div className="space-y-2">
<div className="space-y-3">
{entries.map(([key, item], position) => {
const itemLabel = t('field.itemN', '{{label}} {{n}}', { label: formField.label, n: position + 1 });
const summary = embeddedSummary(schema, type.objectName, item);
const open = !!control['aria-invalid'] || !collapsed.has(key);
const bodyId = `${baseId}-${key}`;
return (
<div
key={key}
data-slot="object-list-item"
className={cn('overflow-hidden rounded-xl', inPanel ? 'bg-card shadow-tile' : 'bg-muted')}
>
<div className="flex items-center gap-1 py-1.5 pl-1.5 pr-1.5">
<button
type="button"
onClick={() => toggle(key)}
aria-expanded={open}
aria-controls={bodyId}
className="flex min-w-0 flex-1 items-center gap-2.5 rounded-lg px-1.5 py-1 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<ChevronRight
className={cn('h-4 w-4 shrink-0 text-dim transition-transform duration-200', open && 'rotate-90')}
aria-hidden="true"
/>
<span className="flex min-w-0 flex-col">
<span className="truncate text-[13.5px] font-semibold">{summary.variantLabel ?? itemLabel}</span>
{summary.summary && (
<span className="truncate text-[12.5px] text-muted-foreground">
{summary.summary.type ? (
<FieldValue
schema={schema}
type={summary.summary.type}
value={summary.summary.value}
variant="compact"
/>
) : (
String(summary.summary.value)
)}
</span>
)}
</span>
</button>
{!readOnly && (
<div key={key} className="space-y-3 rounded-md border p-4">
{!readOnly && (
<div className="flex justify-end">
<Button
type="button"
variant="ghost-danger"
size="icon-sm"
className="shrink-0"
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={() => removeItem(key)}
disabled={!canRemove}
aria-label={t('field.removeItemN', 'Remove item {{n}}', { n: position + 1 })}
>
<Trash2 className="h-4 w-4" aria-hidden="true" />
<X className="h-4 w-4" aria-hidden="true" />
</Button>
)}
</div>
<div id={bodyId} hidden={!open} className="border-t border-border px-4">
<PanelContext value={true}>
<FieldScopeProvider name={key} readOnly={readOnly}>
{embedded ? (
<EmbeddedObjectEditor
bare
objectName={type.objectName}
control={{ 'aria-label': itemLabel }}
value={item}
onChange={(v) => onChange({ ...items, [key]: v })}
readOnly={readOnly}
/>
) : (
<div className="py-3">
<FieldControl
type={itemType}
field={itemField}
formField={{ name: key, label: itemLabel }}
value={item}
onChange={(v) => onChange({ ...items, [key]: v })}
readOnly={readOnly}
control={{ 'aria-label': itemLabel }}
/>
</div>
)}
</FieldScopeProvider>
</PanelContext>
</div>
</div>
)}
<FieldScopeProvider name={key} readOnly={readOnly}>
<FieldControl
type={itemType}
field={itemField}
formField={{ name: key, label: itemLabel }}
value={item}
onChange={(v) => onChange({ ...items, [key]: v })}
readOnly={readOnly}
control={{ 'aria-label': itemLabel }}
/>
</FieldScopeProvider>
</div>
);
})}
{!readOnly && canAdd && (
<Button type="button" variant="secondary" size="sm" onClick={addItem}>
<Button type="button" variant="outline" size="sm" onClick={addItem} className="gap-1">
<Plus className="h-4 w-4" aria-hidden="true" />
{t('field.addItem', 'Add item')}
</Button>
+11 -15
View File
@@ -133,7 +133,7 @@ export function OtpAuthField({ value, onChange, readOnly }: WidgetProps<FieldTyp
if (!isConfigured && setupUrl) {
return (
<div className="space-y-4 rounded-xl bg-muted p-4">
<div className="rounded-md border bg-muted/30 p-4 space-y-4">
<div className="space-y-2">
<p className="text-sm font-medium">{t('otp.scanPrompt', 'Scan with your authenticator app')}</p>
<p className="text-xs text-muted-foreground">
@@ -150,11 +150,11 @@ export function OtpAuthField({ value, onChange, readOnly }: WidgetProps<FieldTyp
alt={t('otp.qrCodeAlt', 'TOTP QR code')}
width={220}
height={220}
className="rounded-xl bg-white p-2 shadow-tile"
className="rounded-md border bg-white p-2"
/>
) : (
<div className="flex h-[220px] w-[220px] items-center justify-center text-muted-foreground">
<Loader2 className="h-6 w-6 animate-spin text-brand-text" aria-hidden="true" />
<Loader2 className="h-6 w-6 animate-spin" />
</div>
)}
</div>
@@ -168,9 +168,7 @@ export function OtpAuthField({ value, onChange, readOnly }: WidgetProps<FieldTyp
)}
</p>
<div className="flex gap-2">
<code className="flex-1 select-all break-all rounded-lg bg-card px-3 py-2 font-mono text-sm">
{setupSecret}
</code>
<code className="flex-1 rounded bg-muted p-2 text-sm font-mono break-all select-all">{setupSecret}</code>
{setupTotp && <CopyButton value={setupTotp.secret.base32} label={t('otp.secret', 'secret')} />}
</div>
</div>
@@ -199,11 +197,11 @@ export function OtpAuthField({ value, onChange, readOnly }: WidgetProps<FieldTyp
)}
</div>
<div className="flex items-center justify-end gap-2">
<Button type="button" variant="ghost" size="sm" onClick={cancelSetup}>
<Button type="button" variant="outline" size="sm" onClick={cancelSetup}>
{t('common.cancel', 'Cancel')}
</Button>
<Button type="button" size="sm" onClick={confirmSetup}>
<ShieldCheck aria-hidden="true" />
<ShieldCheck className="mr-2 h-4 w-4" />
{t('common.confirm', 'Confirm')}
</Button>
</div>
@@ -217,8 +215,8 @@ export function OtpAuthField({ value, onChange, readOnly }: WidgetProps<FieldTyp
<span className="text-sm text-muted-foreground">
{t('otp.statusDisabled', 'Two-factor authentication is not enabled.')}
</span>
<Button type="button" variant="secondary" size="sm" onClick={startSetup}>
<ShieldCheck aria-hidden="true" />
<Button type="button" variant="outline" size="sm" onClick={startSetup}>
<ShieldCheck className="mr-2 h-4 w-4" />
{t('otp.setUp', 'Set up TOTP')}
</Button>
</div>
@@ -226,11 +224,9 @@ export function OtpAuthField({ value, onChange, readOnly }: WidgetProps<FieldTyp
}
return (
<div className="space-y-3 rounded-xl bg-muted p-4">
<div className="rounded-md border bg-muted/30 p-4 space-y-3">
<div className="flex items-center gap-2">
<span className="grid size-7 place-items-center rounded-[9px] bg-success-soft text-success">
<ShieldCheck className="h-4 w-4" aria-hidden="true" />
</span>
<ShieldCheck className="h-4 w-4 text-green-600" />
<span className="text-sm font-medium">{t('otp.statusEnabled', 'Two-factor authentication is enabled.')}</span>
</div>
<p className="text-xs text-muted-foreground">
@@ -257,7 +253,7 @@ export function OtpAuthField({ value, onChange, readOnly }: WidgetProps<FieldTyp
</div>
<div className="flex items-center justify-end">
<Button type="button" variant="destructive" size="sm" onClick={handleDisable} disabled={!otpCodeValue.trim()}>
<ShieldOff aria-hidden="true" />
<ShieldOff className="mr-2 h-4 w-4" />
{t('otp.disable', 'Disable')}
</Button>
</div>
@@ -1,251 +0,0 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import { useEffect, useId, useState, type KeyboardEvent } from 'react';
import { useTranslation } from 'react-i18next';
import { FingerprintPattern, Loader2, ShieldCheck } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useFormContext } from '@/components/forms/formContext';
import { getAccountId, jmapCall, jmapGetOne } from '@/services/jmap/client';
import { JmapMethodError } from '@/services/errors';
import type { WidgetProps } from '@/components/forms/widgets/types';
import type { FieldTypeObject } from '@/types/schema';
interface PasskeyRegistrationValue {
clientDataJson?: string;
attestationObject?: string;
}
interface CredentialDescriptorJson {
type: 'public-key';
id: string;
}
interface CreationOptionsJson {
rp: { id: string; name: string };
user: { id: string; name: string; displayName: string };
challenge: string;
pubKeyCredParams: { type: 'public-key'; alg: number }[];
timeout: number;
excludeCredentials: CredentialDescriptorJson[];
authenticatorSelection: AuthenticatorSelectionCriteria;
attestation: AttestationConveyancePreference;
}
interface RegistrationOptionsResponse {
accountId: string;
publicKey: CreationOptionsJson;
}
type PublicKeyCredentialStatic = {
parseCreationOptionsFromJSON?: (options: CreationOptionsJson) => PublicKeyCredentialCreationOptions;
};
function toBase64Url(buffer: ArrayBuffer): string {
const bytes = new Uint8Array(buffer);
let binary = '';
for (const byte of bytes) binary += String.fromCharCode(byte);
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
function fromBase64Url(value: string): Uint8Array<ArrayBuffer> {
let base64 = value.replace(/-/g, '+').replace(/_/g, '/');
while (base64.length % 4) base64 += '=';
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
return bytes;
}
function parseCreationOptions(options: CreationOptionsJson): PublicKeyCredentialCreationOptions {
const parse = (window.PublicKeyCredential as unknown as PublicKeyCredentialStatic).parseCreationOptionsFromJSON;
if (typeof parse === 'function') return parse(options);
return {
rp: options.rp,
user: { ...options.user, id: fromBase64Url(options.user.id) },
challenge: fromBase64Url(options.challenge),
pubKeyCredParams: options.pubKeyCredParams,
timeout: options.timeout,
excludeCredentials: options.excludeCredentials.map((credential) => ({
type: credential.type,
id: fromBase64Url(credential.id),
})),
authenticatorSelection: options.authenticatorSelection,
attestation: options.attestation,
};
}
function isPasskeySupported(): boolean {
return typeof window !== 'undefined' && !!window.PublicKeyCredential && !!navigator.credentials?.create;
}
function isRegistered(value: unknown): boolean {
const registration = value as PasskeyRegistrationValue | null | undefined;
return !!registration?.clientDataJson && !!registration.attestationObject;
}
export function PasskeyRegistrationField({ value, onChange, readOnly }: WidgetProps<FieldTypeObject>) {
const { t } = useTranslation();
const { mode } = useFormContext();
const secretId = useId();
const otpId = useId();
const [currentSecret, setCurrentSecret] = useState('');
const [otpCode, setOtpCode] = useState('');
const [otpRequired, setOtpRequired] = useState(false);
const [waiting, setWaiting] = useState(false);
const [error, setError] = useState<string | null>(null);
const isActive = mode === 'create' && !readOnly;
useEffect(() => {
if (!isActive) return;
const controller = new AbortController();
jmapGetOne('x:AccountPassword', 'singleton', undefined, { signal: controller.signal })
.then((password) => {
const otpAuth = password?.otpAuth as { otpUrl?: string | null } | undefined;
setOtpRequired(!!otpAuth?.otpUrl);
})
.catch(() => {
if (!controller.signal.aborted) setOtpRequired(true);
});
return () => controller.abort();
}, [isActive]);
if (!isActive) return null;
if (!isPasskeySupported()) {
return (
<p className="text-sm text-muted-foreground">
{t('passkey.unsupported', 'This browser does not support passkeys.')}
</p>
);
}
if (isRegistered(value)) {
return (
<div className="flex items-center gap-2 rounded-xl bg-muted p-4 text-sm">
<ShieldCheck className="h-4 w-4 shrink-0" aria-hidden="true" />
<span className="flex-1">{t('passkey.ready', 'Passkey created. Save to add it to your account.')}</span>
<Button type="button" variant="ghost" size="sm" onClick={() => onChange(null)}>
{t('passkey.createAgain', 'Create again')}
</Button>
</div>
);
}
const createPasskey = async () => {
setError(null);
if (!currentSecret) {
setError(t('passkey.secretRequired', 'Enter your current password to create a passkey.'));
return;
}
const code = otpCode.trim();
if (otpRequired && !code) {
setError(t('passkey.otpRequired', 'Enter your current authenticator code to create a passkey.'));
return;
}
setWaiting(true);
try {
const options = await jmapCall<RegistrationOptionsResponse>('x:Passkey/registrationOptions', {
accountId: getAccountId('x:Passkey'),
currentSecret,
...(code ? { otpCode: code } : {}),
});
const credential = await navigator.credentials.create({ publicKey: parseCreationOptions(options.publicKey) });
if (!(credential instanceof PublicKeyCredential)) throw new Error('No passkey was returned');
const response = credential.response as AuthenticatorAttestationResponse;
setCurrentSecret('');
setOtpCode('');
onChange({
clientDataJson: toBase64Url(response.clientDataJSON),
attestationObject: toBase64Url(response.attestationObject),
});
} catch (err) {
if (err instanceof DOMException && (err.name === 'NotAllowedError' || err.name === 'AbortError')) return;
if (err instanceof DOMException && err.name === 'InvalidStateError') {
setError(t('passkey.alreadyRegistered', 'This device already holds a passkey for your account.'));
} else if (err instanceof JmapMethodError && err.description) {
setError(err.description);
} else {
console.error('Passkey registration failed', err);
setError(t('passkey.createFailed', 'The passkey could not be created. Please try again.'));
}
} finally {
setWaiting(false);
}
};
const submitOnEnter = (e: KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') {
e.preventDefault();
if (!waiting) void createPasskey();
}
};
return (
<div className="space-y-4 rounded-xl bg-muted p-4">
<p className="text-xs text-muted-foreground">
{t(
'passkey.createPrompt',
'Confirm your password, then follow the prompt from your browser to create a passkey on this device or a security key.',
)}
</p>
<div className="space-y-1.5">
<Label htmlFor={secretId} className="text-sm font-medium">
{t('passkey.currentSecretLabel', 'Current password')}
</Label>
<Input
id={secretId}
type="password"
autoComplete="current-password"
value={currentSecret}
onChange={(e) => setCurrentSecret(e.target.value)}
onKeyDown={submitOnEnter}
disabled={waiting}
className="max-w-sm"
/>
</div>
{otpRequired && (
<div className="space-y-1.5">
<Label htmlFor={otpId} className="text-sm font-medium">
{t('otp.currentCodeLabel', 'Current code')}
</Label>
<Input
id={otpId}
type="text"
inputMode="numeric"
autoComplete="one-time-code"
placeholder="123456"
value={otpCode}
onChange={(e) => setOtpCode(e.target.value.replace(/\s+/g, ''))}
onKeyDown={submitOnEnter}
disabled={waiting}
maxLength={10}
className="font-mono tracking-widest text-center max-w-[12rem]"
/>
</div>
)}
{error && (
<p className="text-sm text-destructive" role="alert">
{error}
</p>
)}
<div className="flex items-center justify-end">
<Button type="button" size="sm" onClick={() => void createPasskey()} disabled={waiting}>
{waiting ? (
<Loader2 className="animate-spin" aria-hidden="true" />
) : (
<FingerprintPattern aria-hidden="true" />
)}
{waiting ? t('passkey.waiting', 'Waiting for your passkey') : t('passkey.create', 'Create passkey')}
</Button>
</div>
</div>
);
}
+5 -5
View File
@@ -48,7 +48,7 @@ export function RateWidget({ type, value, onChange, readOnly, control }: WidgetP
};
if (readOnly) {
if (isNull) return <span className="text-sm italic text-dim">{t('field.notSet', 'Not set')}</span>;
if (isNull) return <span className="text-sm italic text-muted-foreground">{t('field.notSet', 'Not set')}</span>;
return (
<span className="text-sm">
{t('rate.summary', '{{amount}} per {{period}}', {
@@ -62,15 +62,15 @@ export function RateWidget({ type, value, onChange, readOnly, control }: WidgetP
if (isNull) {
return (
<div className="flex items-center gap-2">
<span className="text-sm italic text-dim">{t('field.notSet', 'Not set')}</span>
<span className="text-sm italic text-muted-foreground">{t('field.notSet', 'Not set')}</span>
<Button
{...control}
type="button"
variant="secondary"
variant="outline"
size="sm"
onClick={() => onChange({ count: 1, period: 1000 })}
>
<Plus aria-hidden="true" />
<Plus className="mr-1 h-4 w-4" aria-hidden="true" />
{t('field.enable', 'Enable')}
</Button>
</div>
@@ -128,7 +128,7 @@ export function RateWidget({ type, value, onChange, readOnly, control }: WidgetP
onClick={() => onChange(null)}
aria-label={t('common.clear', 'Clear')}
>
<X aria-hidden="true" />
<X className="h-4 w-4" />
</Button>
)}
</div>
@@ -8,7 +8,6 @@ import type { ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { X } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { cn } from '@/lib/utils';
interface RemovablePillProps {
label: string;
@@ -20,10 +19,7 @@ interface RemovablePillProps {
export function RemovablePill({ label, onRemove, removeDisabled, children }: RemovablePillProps) {
const { t } = useTranslation();
return (
<Badge
variant="secondary"
className={cn('h-7 max-w-full gap-1 text-[13px] font-medium', onRemove ? 'pl-3 pr-1' : 'px-3')}
>
<Badge variant="secondary" className="gap-1 pr-1 text-sm">
{children ?? label}
{onRemove && (
<button
@@ -31,7 +27,7 @@ export function RemovablePill({ label, onRemove, removeDisabled, children }: Rem
onClick={onRemove}
disabled={removeDisabled}
aria-label={t('field.removeItem', 'Remove {{name}}', { name: label })}
className="grid size-5 shrink-0 place-items-center rounded-full bg-card text-muted-foreground transition-colors hover:bg-highlight hover:text-highlight-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
className="ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20 disabled:cursor-not-allowed disabled:opacity-50"
>
<X className="h-3 w-3" aria-hidden="true" />
</button>
+3 -4
View File
@@ -128,14 +128,13 @@ function TagInput({ label, items, onChange, readOnly, minItems, maxItems, placeh
/>
<Button
type="button"
variant="secondary"
size="icon"
className="shrink-0"
variant="outline"
size="sm"
onClick={addTag}
disabled={!inputValue.trim() || full}
aria-label={t('field.addValue', 'Add {{name}}', { name: label })}
>
<Plus aria-hidden="true" />
<Plus className="h-4 w-4" aria-hidden="true" />
</Button>
</div>
)}
@@ -58,16 +58,15 @@ export function MultilineWidget(props: WidgetProps<FieldTypeString>) {
if (type.format === 'html') {
return (
<div className="field-surface overflow-hidden rounded-xl">
<div className="flex items-center gap-2 bg-muted px-3.5 py-1.5 text-[11px] font-semibold uppercase tracking-wider text-dim">
<div className="rounded-md border bg-muted/30">
<div className="flex items-center gap-2 border-b px-3 py-1.5 text-xs text-muted-foreground">
<span className="font-mono">HTML</span>
</div>
<BufferedTextarea
{...common}
rows={10}
spellCheck={false}
variant="bare"
className="resize-y font-mono text-xs"
className="resize-y rounded-none rounded-b-md border-0 bg-transparent font-mono text-xs focus-visible:ring-0"
/>
</div>
);
@@ -91,7 +90,7 @@ export function ColorWidget(props: WidgetProps<FieldTypeString>) {
onChange={(e) => commit(e.target.value)}
disabled={readOnly}
aria-label={t('field.colorPicker', 'Color picker')}
className="h-9 w-14 cursor-pointer field-surface rounded-full p-1 [&::-moz-color-swatch]:rounded-full [&::-moz-color-swatch]:border-0 [&::-webkit-color-swatch]:rounded-full [&::-webkit-color-swatch]:border-0 [&::-webkit-color-swatch-wrapper]:p-0"
className="h-9 w-14 cursor-pointer rounded-md border border-input bg-transparent p-1"
/>
<BufferedInput
{...control}
@@ -139,14 +138,14 @@ export function SecretWidget(props: WidgetProps<FieldTypeString>) {
<Button
type="button"
variant="ghost"
size="icon-sm"
className="shrink-0"
size="icon"
className="h-8 w-8 shrink-0"
onClick={() => setVisible((p) => !p)}
aria-label={visible ? t('field.hideValue', 'Hide value') : t('field.showValue', 'Show value')}
aria-pressed={visible}
tabIndex={-1}
>
{visible ? <EyeOff aria-hidden="true" /> : <Eye aria-hidden="true" />}
{visible ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</Button>
);
@@ -10,7 +10,7 @@ import type { WidgetProps } from '@/components/forms/widgets/types';
export function UnsupportedWidget({ type }: WidgetProps) {
const { t } = useTranslation();
return (
<p className="rounded-xl bg-muted px-4 py-3 text-sm text-muted-foreground">
<p className="text-sm text-muted-foreground">
{t('field.unsupportedType', 'Unsupported field type: {{type}}', { type: (type as { type?: string }).type ?? '' })}
</p>
);
+21 -29
View File
@@ -8,13 +8,9 @@ import type { FieldType } from '@/types/schema';
export type LabelMode = 'control' | 'group' | 'none';
type RowLayout = 'side' | 'block' | 'inline';
export interface WidgetTraits {
labelMode: LabelMode;
readOnlyAsValue: boolean;
layout: RowLayout;
createOnly?: true;
}
export type WidgetKey =
@@ -34,7 +30,6 @@ export type WidgetKey =
| 'object:x:Expression'
| 'object:x:Rate'
| 'object:x:OtpAuth'
| 'object:x:PasskeyRegistration'
| 'objectList'
| 'set'
| 'set:enum'
@@ -67,8 +62,6 @@ export function widgetKey(type: FieldType): WidgetKey {
return 'object:x:Rate';
case 'x:OtpAuth':
return 'object:x:OtpAuth';
case 'x:PasskeyRegistration':
return 'object:x:PasskeyRegistration';
default:
return 'object';
}
@@ -88,28 +81,27 @@ export function widgetKey(type: FieldType): WidgetKey {
}
const TRAITS: Record<WidgetKey, WidgetTraits> = {
string: { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
'string:secret': { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
'string:multiline': { labelMode: 'control', readOnlyAsValue: true, layout: 'block' },
'string:color': { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
number: { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
'number:size': { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
'number:duration': { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
utcDateTime: { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
boolean: { labelMode: 'control', readOnlyAsValue: true, layout: 'inline' },
enum: { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
blobId: { labelMode: 'control', readOnlyAsValue: false, layout: 'block' },
objectId: { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
object: { labelMode: 'group', readOnlyAsValue: false, layout: 'block' },
'object:x:Expression': { labelMode: 'group', readOnlyAsValue: false, layout: 'block' },
'object:x:Rate': { labelMode: 'control', readOnlyAsValue: false, layout: 'side' },
'object:x:OtpAuth': { labelMode: 'none', readOnlyAsValue: false, layout: 'block' },
'object:x:PasskeyRegistration': { labelMode: 'none', readOnlyAsValue: false, layout: 'block', createOnly: true },
objectList: { labelMode: 'group', readOnlyAsValue: false, layout: 'block' },
set: { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
'set:enum': { labelMode: 'group', readOnlyAsValue: true, layout: 'side' },
map: { labelMode: 'group', readOnlyAsValue: false, layout: 'block' },
unsupported: { labelMode: 'none', readOnlyAsValue: false, layout: 'block' },
string: { labelMode: 'control', readOnlyAsValue: true },
'string:secret': { labelMode: 'control', readOnlyAsValue: true },
'string:multiline': { labelMode: 'control', readOnlyAsValue: true },
'string:color': { labelMode: 'control', readOnlyAsValue: true },
number: { labelMode: 'control', readOnlyAsValue: true },
'number:size': { labelMode: 'control', readOnlyAsValue: true },
'number:duration': { labelMode: 'control', readOnlyAsValue: true },
utcDateTime: { labelMode: 'control', readOnlyAsValue: true },
boolean: { labelMode: 'control', readOnlyAsValue: true },
enum: { labelMode: 'control', readOnlyAsValue: true },
blobId: { labelMode: 'control', readOnlyAsValue: false },
objectId: { labelMode: 'control', readOnlyAsValue: true },
object: { labelMode: 'group', readOnlyAsValue: false },
'object:x:Expression': { labelMode: 'group', readOnlyAsValue: false },
'object:x:Rate': { labelMode: 'control', readOnlyAsValue: false },
'object:x:OtpAuth': { labelMode: 'none', readOnlyAsValue: false },
objectList: { labelMode: 'group', readOnlyAsValue: false },
set: { labelMode: 'control', readOnlyAsValue: true },
'set:enum': { labelMode: 'group', readOnlyAsValue: true },
map: { labelMode: 'group', readOnlyAsValue: false },
unsupported: { labelMode: 'none', readOnlyAsValue: false },
};
export function widgetTraits(type: FieldType): WidgetTraits {
+5 -7
View File
@@ -5,7 +5,6 @@
*/
import { Component, type ErrorInfo, type ReactNode } from 'react';
import { TriangleAlert } from 'lucide-react';
import { Button } from '@/components/ui/button';
import i18n from '@/i18n';
@@ -51,12 +50,11 @@ export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundarySt
}
return (
<div role="alert" className="mx-auto mt-6 flex max-w-lg flex-col items-center gap-4 tile p-8 text-center">
<span className="grid size-11 place-items-center rounded-[13px] bg-destructive-soft text-destructive">
<TriangleAlert className="h-5 w-5" aria-hidden="true" />
</span>
<div className="section-title text-lg">{i18n.t('errorBoundary.title', 'Something went wrong')}</div>
<p className="max-w-md text-sm text-muted-foreground">
<div role="alert" className="flex flex-col items-center justify-center gap-4 p-8">
<div className="text-destructive text-lg font-semibold">
{i18n.t('errorBoundary.title', 'Something went wrong')}
</div>
<p className="text-muted-foreground text-sm max-w-md text-center">
{this.state.error?.message ?? i18n.t('errors.unexpectedError', 'An unexpected error occurred.')}
</p>
<Button variant="outline" onClick={this.handleReset}>
+2 -2
View File
@@ -108,7 +108,7 @@ function renderView(
}
// SPDX-SnippetEnd
return (
<div className="mt-3 rounded-2xl bg-muted p-10 text-center text-muted-foreground">
<div className="rounded-lg border border-dashed p-12 text-center text-muted-foreground">
{t('errors.unknownComponent', 'Unknown component: {{name}}', { name: componentName })}
</div>
);
@@ -121,7 +121,7 @@ function renderView(
const resolved = resolveObject(schema, viewName);
if (!resolved) {
return (
<div role="alert" className="mt-3 rounded-xl bg-destructive-soft p-4 text-center text-sm text-destructive">
<div role="alert" className="flex items-center justify-center p-8 text-destructive">
{t('errors.unknownView', 'Unknown view: {{name}}', { name: viewName })}
</div>
);
+44 -39
View File
@@ -4,34 +4,33 @@
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import { useEffect, useId, useRef, useState } from 'react';
import { useEffect, useId, useRef, useState, type CSSProperties } from 'react';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { ChevronRight, Lock } from 'lucide-react';
import { ChevronDown, Lock } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Button, buttonVariants } from '@/components/ui/button';
import { DynamicIcon } from '@/components/common/DynamicIcon';
import { EnterpriseUpsell } from '@/components/common/EnterpriseUpsell';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { useUIStore } from '@/stores/uiStore';
import type { Layout } from '@/types/schema';
import { activeViewName, layoutNavNodes, navNodeKey, someLink, viewPath, type NavNode } from './navTree';
import { layoutNavNodes, navNodeKey, pathMatchesView, someLink, viewPath, type NavNode } from './navTree';
import { SIDEBAR_ID, SidebarNavContext, useSidebarNav } from './sidebarContext';
import { useLayoutNavigation } from './useLayoutNavigation';
const itemClass =
'flex w-full items-center gap-2.5 rounded-[10px] px-2.5 text-left font-medium text-muted-foreground outline-none transition-colors duration-200 hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring';
function itemSize(depth: number) {
return depth > 0 ? 'h-8 text-[13px]' : 'h-9 text-sm';
function indent(depth: number): CSSProperties | undefined {
return depth > 0 ? { paddingInlineStart: `${(depth + 1) * 12 + 8}px` } : undefined;
}
const itemClass = 'w-full justify-start gap-2 font-normal';
function NavLink({ node, depth }: { node: Extract<NavNode, { kind: 'link' }>; depth: number }) {
const { t } = useTranslation();
const nav = useSidebarNav();
const ref = useRef<HTMLAnchorElement>(null);
const isActive = node.viewName === nav.activeViewName;
const isActive = pathMatchesView(nav.pathname, nav.sectionName, node.viewName);
useEffect(() => {
if (isActive) ref.current?.scrollIntoView?.({ block: 'nearest' });
@@ -46,11 +45,17 @@ function NavLink({ node, depth }: { node: Extract<NavNode, { kind: 'link' }>; de
<span className="truncate">{label}</span>
</>
);
const className = cn(itemClass, itemSize(depth));
const className = cn(buttonVariants({ variant: 'ghost' }), itemClass, depth > 0 && 'text-sm');
if (nav.isLocked(node.viewName)) {
return (
<button type="button" className={className} onClick={nav.openUpsell} aria-describedby={nav.lockedHintId}>
<button
type="button"
className={className}
style={indent(depth)}
onClick={nav.openUpsell}
aria-describedby={nav.lockedHintId}
>
{content}
<Lock aria-hidden="true" className="ml-auto h-3 w-3 text-muted-foreground" />
</button>
@@ -62,11 +67,8 @@ function NavLink({ node, depth }: { node: Extract<NavNode, { kind: 'link' }>; de
ref={ref}
to={viewPath(nav.sectionName, node.viewName)}
aria-current={isActive ? 'page' : undefined}
className={cn(
className,
isActive &&
'bg-highlight font-semibold text-highlight-foreground hover:bg-highlight hover:text-highlight-foreground',
)}
className={cn(className, isActive && 'bg-accent text-accent-foreground')}
style={indent(depth)}
>
{content}
</Link>
@@ -75,7 +77,9 @@ function NavLink({ node, depth }: { node: Extract<NavNode, { kind: 'link' }>; de
function NavContainer({ node, depth }: { node: Extract<NavNode, { kind: 'container' }>; depth: number }) {
const nav = useSidebarNav();
const containsActive = someLink(node.children, (viewName) => viewName === nav.activeViewName);
const containsActive = someLink(node.children, (viewName) =>
pathMatchesView(nav.pathname, nav.sectionName, viewName),
);
const [open, setOpen] = useState(containsActive);
const [prevContainsActive, setPrevContainsActive] = useState(containsActive);
if (containsActive !== prevContainsActive) {
@@ -88,19 +92,25 @@ function NavContainer({ node, depth }: { node: Extract<NavNode, { kind: 'contain
return (
<Collapsible open={open} onOpenChange={setOpen}>
<CollapsibleTrigger asChild>
<button type="button" className={cn(itemClass, itemSize(depth))}>
<Button variant="ghost" className={cn(itemClass, depth > 0 && 'text-sm')} style={indent(depth)}>
{depth > 0 && (
<ChevronDown
aria-hidden="true"
className="h-3 w-3 shrink-0 transition-transform duration-200 [[data-state=closed]>&]:rotate-[-90deg]"
/>
)}
{node.icon && <DynamicIcon name={node.icon} className="h-4 w-4 shrink-0" />}
<span className="truncate">{node.name}</span>
<ChevronRight
aria-hidden="true"
className="ml-auto h-3.5 w-3.5 shrink-0 opacity-60 transition-transform duration-200 [[data-state=open]>&]:rotate-90"
/>
</button>
{depth === 0 && (
<ChevronDown
aria-hidden="true"
className="ml-auto h-3 w-3 shrink-0 transition-transform duration-200 [[data-state=closed]>&]:rotate-[-90deg]"
/>
)}
</Button>
</CollapsibleTrigger>
<CollapsibleContent>
<div className="my-0.5 ml-[18px] flex flex-col gap-0.5 border-l border-input pl-2">
<NavNodes nodes={node.children} depth={depth + 1} />
</div>
<NavNodes nodes={node.children} depth={depth + 1} />
</CollapsibleContent>
</Collapsible>
);
@@ -126,7 +136,7 @@ function SectionSwitcher({ layouts, activeSection }: { layouts: Layout[]; active
<div
role="group"
aria-label={t('sections', 'Sections')}
className="m-2.5 mt-0 flex items-center gap-0.5 rounded-full bg-muted p-1"
className="flex items-center justify-around border-t bg-background px-2 py-2"
>
{layouts.map((target) => {
const isActive = target.name === activeSection;
@@ -144,10 +154,7 @@ function SectionSwitcher({ layouts, activeSection }: { layouts: Layout[]; active
const path = landingPath(target);
if (path) navigate(path);
}}
className={cn(
'h-8 flex-1 rounded-full',
isActive && 'bg-card text-foreground shadow-tile hover:bg-card hover:text-foreground',
)}
className={cn('h-9 w-9', isActive && 'bg-accent text-accent-foreground')}
>
<DynamicIcon name={target.icon} className="h-4 w-4" />
</Button>
@@ -178,11 +185,9 @@ export function Sidebar() {
const layout = layouts.find((l) => l.name === activeSection);
if (!layout) return null;
const nodes = layoutNavNodes(layout);
const nav = {
sectionName: layout.name,
pathname,
activeViewName: activeViewName(nodes, pathname, layout.name),
isVisible,
isLocked,
openUpsell: () => setUpsellOpen(true),
@@ -193,21 +198,21 @@ export function Sidebar() {
<>
<div
aria-hidden="true"
className="fixed inset-0 top-16 z-20 bg-overlay md:hidden"
className="fixed inset-0 top-14 z-20 bg-black/40 md:hidden"
onClick={() => setSidebarOpen(false)}
/>
<aside
id={SIDEBAR_ID}
aria-label={t('sidebar.label', 'Sidebar')}
className="fixed bottom-3 left-3 top-16 z-30 flex w-60 flex-col tile overflow-hidden"
className="fixed bottom-0 left-0 top-14 z-30 flex w-64 flex-col border-r bg-background"
>
<span id={lockedHintId} className="sr-only">
{t('enterprise.featureHint', 'Enterprise feature')}
</span>
<div className="flex-1 overflow-y-auto py-2.5 [scrollbar-width:thin]">
<nav aria-label={layout.name} className="flex flex-col gap-0.5 px-2.5">
<div className="flex-1 overflow-y-auto py-2 [scrollbar-width:thin]">
<nav aria-label={layout.name} className="flex flex-col gap-0.5 px-2">
<SidebarNavContext value={nav}>
<NavNodes nodes={nodes} depth={0} />
<NavNodes nodes={layoutNavNodes(layout)} depth={0} />
</SidebarNavContext>
</nav>
</div>
+9 -8
View File
@@ -26,7 +26,7 @@ import { EnterpriseUpsell } from '@/components/common/EnterpriseUpsell';
import { DynamicIcon } from '@/components/common/DynamicIcon';
import { useUIStore } from '@/stores/uiStore';
import { useAuthStore } from '@/stores/authStore';
import { buildEndSessionUrl, getPostLogoutRedirectUri } from '@/services/auth/oauth';
import { buildEndSessionUrl, getPostLogoutRedirectUri, revokeSessionTokens } from '@/services/auth/oauth';
import { useEffect, useState } from 'react';
import { useIsCommunity } from '@/hooks/usePermissions';
import { SIDEBAR_ID } from './sidebarContext';
@@ -63,7 +63,7 @@ export function TopBar() {
}, []);
return (
<header className="sticky top-0 z-40 flex h-16 items-center gap-4 bg-background/80 px-4 backdrop-blur-xl backdrop-saturate-150 sm:px-5">
<header className="sticky top-0 z-40 flex h-14 items-center gap-4 border-b bg-background px-4">
<Button
variant="ghost"
size="icon"
@@ -78,7 +78,7 @@ export function TopBar() {
<Tooltip>
<TooltipTrigger asChild>
<Link to="/" className="flex shrink-0 items-center md:w-[228px]">
<Link to="/" className="flex shrink-0 items-center">
<Logo />
</Link>
</TooltipTrigger>
@@ -87,24 +87,24 @@ export function TopBar() {
</TooltipContent>
</Tooltip>
<div className="hidden min-w-0 flex-1 items-center md:flex">
<div className="hidden min-w-0 flex-1 items-center justify-center px-4 md:flex">
<button
type="button"
onClick={() => setPaletteOpen(true)}
className="flex h-10 w-full max-w-md items-center gap-2.5 rounded-full bg-card pl-4 pr-2 text-sm text-dim shadow-tile transition-shadow duration-200 hover:shadow-lift"
className="flex h-9 w-full max-w-md items-center gap-2 rounded-md border border-input bg-transparent px-3 text-sm text-muted-foreground shadow-sm transition-colors hover:bg-accent"
>
<Search aria-hidden="true" className="h-4 w-4" />
<span className="flex-1 text-left">{t('globalSearch.placeholder', 'Search pages, fields, settings...')}</span>
<kbd
aria-hidden="true"
className="pointer-events-none flex h-6 select-none items-center rounded-full bg-muted px-2.5 font-mono text-[11px] font-medium text-muted-foreground"
className="pointer-events-none flex h-5 select-none items-center rounded border bg-muted px-1.5 font-mono text-[10px] font-medium"
>
{IS_MAC ? '⌘K' : 'Ctrl K'}
</kbd>
</button>
</div>
<div className="ml-auto flex items-center gap-1.5">
<div className="ml-auto flex items-center gap-2 md:ml-0">
{isCommunity && <EnterpriseUpsell open={upsellOpen} onClose={() => setUpsellOpen(false)} />}
<Button
@@ -129,7 +129,7 @@ export function TopBar() {
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="icon-lg" aria-label={t('userMenu', 'User menu')}>
<Button variant="ghost" size="icon" aria-label={t('userMenu', 'User menu')}>
<User aria-hidden="true" className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
@@ -186,6 +186,7 @@ export function TopBar() {
const endSessionUrl = endSessionEndpoint
? buildEndSessionUrl(endSessionEndpoint, getPostLogoutRedirectUri())
: null;
if (endSessionUrl) revokeSessionTokens();
logout();
if (endSessionUrl) {
window.location.href = endSessionUrl;
-11
View File
@@ -55,14 +55,3 @@ export function pathMatchesView(pathname: string, sectionName: string, viewName:
export function someLink(nodes: NavNode[], predicate: (viewName: string) => boolean): boolean {
return nodes.some((node) => (node.kind === 'link' ? predicate(node.viewName) : someLink(node.children, predicate)));
}
export function activeViewName(nodes: NavNode[], pathname: string, sectionName: string): string | undefined {
let active: string | undefined;
for (const node of nodes) {
let candidate: string | undefined;
if (node.kind === 'container') candidate = activeViewName(node.children, pathname, sectionName);
else if (pathMatchesView(pathname, sectionName, node.viewName)) candidate = node.viewName;
if (candidate !== undefined && (active === undefined || candidate.length > active.length)) active = candidate;
}
return active;
}
-1
View File
@@ -11,7 +11,6 @@ export const SIDEBAR_ID = 'app-sidebar';
export interface SidebarNavContextValue {
sectionName: string;
pathname: string;
activeViewName: string | undefined;
isVisible: (viewName: string) => boolean;
isLocked: (viewName: string) => boolean;
openUpsell: () => void;
+4 -7
View File
@@ -10,9 +10,6 @@ import { ArrowUpDown, ChevronDown, ChevronUp } from 'lucide-react';
import type { Column } from '@/types/schema';
import type { ListSort } from './listUrlState';
export const HEADER_CELL =
'px-3.5 py-2.5 first:pl-5 last:pr-5 text-left text-[11px] font-semibold uppercase tracking-wider text-dim';
interface ColumnHeaderProps {
column: Column;
sortable: boolean;
@@ -23,7 +20,7 @@ interface ColumnHeaderProps {
export function ColumnHeader({ column, sortable, sort, onSort }: ColumnHeaderProps) {
const { t } = useTranslation();
const direction = sort?.field === column.name ? (sort.ascending ? 'ascending' : 'descending') : 'none';
const className = HEADER_CELL;
const className = 'px-3 py-3 text-left font-medium text-muted-foreground';
if (!sortable) {
return (
@@ -46,13 +43,13 @@ export function ColumnHeader({ column, sortable, sort, onSort }: ColumnHeaderPro
type="button"
onClick={() => onSort(column.name)}
title={hint}
className="-mx-1 inline-flex items-center gap-1 rounded-md px-1 uppercase tracking-wider hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
className="-mx-1 inline-flex items-center gap-1 rounded px-1 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
{column.label}
{direction === 'ascending' ? (
<ChevronUp className="h-3.5 w-3.5" aria-hidden />
<ChevronUp className="h-4 w-4" aria-hidden />
) : direction === 'descending' ? (
<ChevronDown className="h-3.5 w-3.5" aria-hidden />
<ChevronDown className="h-4 w-4" aria-hidden />
) : (
<ArrowUpDown className="h-3 w-3" aria-hidden />
)}
+88 -90
View File
@@ -197,107 +197,105 @@ function DynamicListView({ viewName, schema, resolved, list }: DynamicListViewPr
const viewFor = (name: string) => layoutViewFor(schema, viewToSection, name, viewName);
return (
<div className="space-y-3.5">
<div className="flex flex-wrap items-end justify-between gap-4 px-1 pb-1 pt-3">
<div className="min-w-0">
<h1 className="page-title">{list.title}</h1>
<div className="relative space-y-4">
<div className="flex items-start justify-between gap-4">
<div>
<h1 className="text-2xl font-bold tracking-tight">{list.title}</h1>
{list.subtitle && <p className="mt-1 text-sm text-muted-foreground">{list.subtitle}</p>}
</div>
{canCreate && section && (
<Button onClick={() => navigate(`/${section}/${viewName}/new`)}>
<Plus aria-hidden />
{t('list.create', 'Create {{name}}', { name: list.singularName })}
</Button>
)}
<div className="flex items-center gap-2">
{massActions.length > 0 && selectedCount > 0 && (
<MassActionBar
actions={massActions}
count={selectedCount}
disabled={actions.pending}
onSelect={confirmMassAction}
/>
)}
{canCreate && section && (
<Button onClick={() => navigate(`/${section}/${viewName}/new`)}>
<Plus className="mr-2 h-4 w-4" aria-hidden />
{t('list.create', 'Create {{name}}', { name: list.singularName })}
</Button>
)}
</div>
</div>
{visibleFilters.length > 0 && (
<FilterBar
schema={schema}
filters={visibleFilters}
applied={state.filters}
isXPrefixed={objectName.startsWith('x:')}
disabled={listState.isFetching}
onApply={listState.applyFilters}
onReset={listState.resetFilters}
/>
)}
{listState.error && <ListError message={listState.error} onRetry={listState.refetch} />}
{actions.error && <ListError message={actions.error} onDismiss={actions.clearError} />}
<section className="tile relative overflow-hidden">
{visibleFilters.length > 0 && (
<FilterBar
schema={schema}
filters={visibleFilters}
applied={state.filters}
isXPrefixed={objectName.startsWith('x:')}
disabled={listState.isFetching}
onApply={listState.applyFilters}
onReset={listState.resetFilters}
/>
)}
{massActions.length > 0 && selection.pageState === 'all' && (
<SelectionBanner
allMatching={selection.allMatching}
pageCount={selection.selectedIds.length}
total={total}
pluralName={list.pluralName}
onSelectAllMatching={selection.selectAllMatching}
onClear={selection.clear}
/>
)}
<ListTable
caption={list.title}
columns={list.columns}
fields={fields}
items={items}
schema={schema}
objectName={objectName}
sort={state.sort}
sortable={new Set(list.sort ?? [])}
onSort={listState.toggleSort}
selection={massActions.length > 0 ? selection : null}
rowHref={(id) => (section ? `/${section}/${viewName}/${id}` : null)}
rowLabel={(item) => itemLabel(item, labelProperty)}
renderRowActions={
itemActions.length > 0
? (_item, id, label) => (
<RowActions
actions={itemActions}
label={label}
hrefFor={(action) => itemActionHref(action, id, sectionFor, section, viewFor)}
onMutation={(entry) => confirmItemAction(entry, id, label)}
onLocked={() => setUpsellOpen(true)}
disabled={actions.pending}
/>
)
: null
}
loading={listState.isLoading}
busy={busy}
/>
{(items.length > 0 || state.anchors.length > 0) && (
<Pagination
range={listState.range}
total={total}
count={items.length}
pluralName={list.pluralName}
disabled={listState.isFetching}
onPrev={listState.prevPage}
onNext={listState.nextPage}
/>
)}
{busy && items.length > 0 && (
<div className="absolute inset-0 flex items-center justify-center bg-card/50" aria-hidden>
<Loader2 className="h-6 w-6 animate-spin text-brand-text" />
</div>
)}
</section>
{massActions.length > 0 && selectedCount > 0 && (
<MassActionBar
actions={massActions}
count={selectedCount}
disabled={actions.pending}
onSelect={confirmMassAction}
{massActions.length > 0 && selection.pageState === 'all' && (
<SelectionBanner
allMatching={selection.allMatching}
pageCount={selection.selectedIds.length}
total={total}
pluralName={list.pluralName}
onSelectAllMatching={selection.selectAllMatching}
onClear={selection.clear}
/>
)}
<ListTable
caption={list.title}
columns={list.columns}
fields={fields}
items={items}
schema={schema}
objectName={objectName}
sort={state.sort}
sortable={new Set(list.sort ?? [])}
onSort={listState.toggleSort}
selection={massActions.length > 0 ? selection : null}
rowHref={(id) => (section ? `/${section}/${viewName}/${id}` : null)}
rowLabel={(item) => itemLabel(item, labelProperty)}
renderRowActions={
itemActions.length > 0
? (_item, id, label) => (
<RowActions
actions={itemActions}
label={label}
hrefFor={(action) => itemActionHref(action, id, sectionFor, section, viewFor)}
onMutation={(entry) => confirmItemAction(entry, id, label)}
onLocked={() => setUpsellOpen(true)}
disabled={actions.pending}
/>
)
: null
}
loading={listState.isLoading}
busy={busy}
/>
{(items.length > 0 || state.anchors.length > 0) && (
<Pagination
range={listState.range}
total={total}
count={items.length}
pluralName={list.pluralName}
disabled={listState.isFetching}
onPrev={listState.prevPage}
onNext={listState.nextPage}
/>
)}
{busy && items.length > 0 && (
<div className="absolute inset-0 flex items-center justify-center bg-background/50" aria-hidden>
<Loader2 className="h-6 w-6 animate-spin" />
</div>
)}
<ConfirmDialog
open={confirm !== null}
onOpenChange={(open) => {
+12 -38
View File
@@ -9,7 +9,6 @@ import { useTranslation } from 'react-i18next';
import { ChevronDown, ChevronUp, Filter as FilterIcon, RotateCcw, Search } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import type { Filter, Schema } from '@/types/schema';
import { filtersKey } from './listUrlState';
@@ -51,48 +50,23 @@ export function FilterBar({ schema, filters, applied, isXPrefixed, disabled, onA
onReset();
};
const activeCount = filters.filter((f) => Object.hasOwn(applied, f.field) && applied[f.field] !== '').length;
return (
<Collapsible open={open} onOpenChange={setOpen}>
<div className="flex flex-wrap items-center gap-2 p-2.5">
<CollapsibleTrigger asChild>
<button
type="button"
aria-controls={panelId}
className={cn(
'inline-flex h-8 items-center gap-1.5 rounded-full px-3.5 text-[13px] font-medium transition-colors duration-200 ease-bento focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
activeCount > 0 || open
? 'bg-highlight text-highlight-foreground hover:bg-highlight-strong'
: 'bg-muted text-muted-foreground hover:bg-muted-strong hover:text-foreground',
)}
>
<FilterIcon className="h-3.5 w-3.5" aria-hidden />
{t('list.filters', 'Filters')}
{activeCount > 0 && (
<span
className="grid h-[18px] min-w-[18px] place-items-center rounded-full bg-primary px-1 text-[11px] font-semibold text-primary-foreground"
aria-hidden
>
{activeCount}
</span>
)}
{open ? (
<ChevronUp className="h-3.5 w-3.5" aria-hidden />
) : (
<ChevronDown className="h-3.5 w-3.5" aria-hidden />
)}
</button>
</CollapsibleTrigger>
</div>
<CollapsibleTrigger asChild>
<Button variant="ghost" size="sm" className="gap-2" aria-controls={panelId}>
<FilterIcon className="h-4 w-4" aria-hidden />
{t('list.filters', 'Filters')}
{open ? <ChevronUp className="h-4 w-4" aria-hidden /> : <ChevronDown className="h-4 w-4" aria-hidden />}
</Button>
</CollapsibleTrigger>
<CollapsibleContent id={panelId}>
<form
role="search"
aria-label={t('list.filters', 'Filters')}
onSubmit={handleSubmit}
className="mx-2.5 mb-2.5 rounded-xl bg-muted p-4"
className="mt-2 rounded-lg border bg-background shadow-sm"
>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
<div className="grid gap-4 p-5 sm:grid-cols-2 lg:grid-cols-3">
{filters.map((filter) => (
<FilterField
key={filter.field}
@@ -105,13 +79,13 @@ export function FilterBar({ schema, filters, applied, isXPrefixed, disabled, onA
/>
))}
</div>
<div className="mt-4 flex items-center justify-end gap-2">
<div className="flex items-center justify-end gap-2 border-t px-5 py-3">
<Button type="button" variant="ghost" size="sm" onClick={handleReset} disabled={disabled}>
<RotateCcw aria-hidden />
<RotateCcw className="mr-2 h-4 w-4" aria-hidden />
{t('list.resetFilters', 'Reset')}
</Button>
<Button type="submit" size="sm" disabled={disabled}>
<Search aria-hidden />
<Search className="mr-2 h-4 w-4" aria-hidden />
{t('list.searchFilters', 'Search')}
</Button>
</div>
+2 -2
View File
@@ -34,7 +34,7 @@ function opField(filter: Filter): string {
function LabelledField({ id, label, children }: { id: string; label: string; children: ReactNode }) {
return (
<div className="flex flex-col gap-1.5">
<label htmlFor={id} className="text-[12.5px] font-semibold text-muted-foreground">
<label htmlFor={id} className="text-xs font-medium text-muted-foreground">
{label}
</label>
{children}
@@ -46,7 +46,7 @@ function GroupField({ label, children }: { label: string; children: ReactNode })
const labelId = useId();
return (
<div role="group" aria-labelledby={labelId} className="flex flex-col gap-1.5">
<span id={labelId} className="text-[12.5px] font-semibold text-muted-foreground">
<span id={labelId} className="text-xs font-medium text-muted-foreground">
{label}
</span>
{children}
+6 -11
View File
@@ -14,20 +14,20 @@ export function ListSpinner({ className }: { className?: string }) {
const { t } = useTranslation();
return (
<div role="status" className={className ?? 'flex items-center justify-center p-8'}>
<Loader2 className="h-6 w-6 animate-spin text-brand-text" aria-hidden />
<Loader2 className="h-6 w-6 animate-spin" aria-hidden />
<span className="sr-only">{t('common.loading', 'Loading...')}</span>
</div>
);
}
export function ListMessage({ children }: { children: ReactNode }) {
return <div className="rounded-2xl bg-muted p-10 text-center text-muted-foreground">{children}</div>;
return <div className="p-8 text-center text-muted-foreground">{children}</div>;
}
export function ListTableMessage({ colSpan, children }: { colSpan: number; children: ReactNode }) {
return (
<tr>
<td colSpan={colSpan} className="border-t border-border px-3 py-12 text-center text-muted-foreground">
<td colSpan={colSpan} className="px-3 py-12 text-center text-muted-foreground">
{children}
</td>
</tr>
@@ -47,17 +47,12 @@ export function ListError({
return (
<div
role="alert"
className="flex items-start justify-between gap-3 rounded-xl bg-destructive-soft p-4 text-sm text-destructive"
className="flex items-start justify-between gap-3 rounded-md border border-destructive/50 bg-destructive/10 p-3 text-sm text-destructive"
>
<span className="whitespace-pre-line">{message}</span>
<div className="flex shrink-0 items-center gap-1">
{onRetry && (
<Button
variant="ghost"
size="sm"
className="h-7 text-destructive hover:bg-destructive/10 hover:text-destructive"
onClick={onRetry}
>
<Button variant="ghost" size="sm" className="h-7" onClick={onRetry}>
{t('common.retry', 'Retry')}
</Button>
)}
@@ -65,7 +60,7 @@ export function ListError({
<Button
variant="ghost"
size="icon"
className="h-7 w-7 text-destructive hover:bg-destructive/10 hover:text-destructive"
className="h-7 w-7"
onClick={onDismiss}
aria-label={t('common.close', 'Close')}
>
+105 -131
View File
@@ -4,16 +4,15 @@
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import type { MouseEvent, ReactNode } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import type { ReactNode } from 'react';
import { Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Checkbox } from '@/components/ui/checkbox';
import { cn } from '@/lib/utils';
import type { Column, Field, Schema } from '@/types/schema';
import { isEmptyValue } from '@/lib/embeddedSchema';
import { ListCell } from './ListCell';
import { ColumnHeader, HEADER_CELL } from './ColumnHeader';
import { ColumnHeader } from './ColumnHeader';
import { ListSpinner, ListTableMessage } from './ListStates';
import { itemId, type ListItem } from './listQuery';
import type { ListSort } from './listUrlState';
@@ -37,28 +36,8 @@ interface ListTableProps {
busy: boolean;
}
const BODY_CELL = 'px-3.5 py-2.5 first:pl-5 last:pr-5 align-middle';
const ROW_LINK =
'rounded-sm font-semibold text-foreground hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring';
const INTERACTIVE = 'a, button, input, label, select, textarea, [role="checkbox"], [data-row-controls]';
function isRowClick(event: MouseEvent<HTMLTableRowElement>): boolean {
const target = event.target;
return (
event.button === 0 &&
!event.defaultPrevented &&
!event.metaKey &&
!event.ctrlKey &&
!event.shiftKey &&
!event.altKey &&
target instanceof Element &&
event.currentTarget.contains(target) &&
target.closest(INTERACTIVE) === null &&
window.getSelection()?.isCollapsed !== false
);
}
const STRETCHED_LINK =
"font-medium text-foreground hover:underline focus-visible:outline-none after:absolute after:inset-0 after:content-[''] focus-visible:after:ring-2 focus-visible:after:ring-inset focus-visible:after:ring-ring";
export function ListTable({
caption,
@@ -78,7 +57,6 @@ export function ListTable({
busy,
}: ListTableProps) {
const { t } = useTranslation();
const navigate = useNavigate();
const colSpan = columns.length + (selection ? 1 : 0) + (renderRowActions ? 1 : 0);
const rows = items.flatMap((item) => {
const id = itemId(item);
@@ -86,112 +64,108 @@ export function ListTable({
});
return (
<div className="overflow-x-auto">
<table className="w-full text-sm" aria-busy={busy || undefined}>
<caption className="sr-only">{caption}</caption>
<thead>
<tr>
{selection && (
<th scope="col" className="w-10 py-2.5 pl-5 pr-2 text-left align-middle">
<Checkbox
checked={
selection.pageState === 'all' ? true : selection.pageState === 'some' ? 'indeterminate' : false
}
disabled={rows.length === 0}
onCheckedChange={selection.togglePage}
aria-label={t('list.selectAllOnPage', 'Select all on this page')}
/>
</th>
)}
{columns.map((col) => (
<ColumnHeader key={col.name} column={col} sortable={sortable.has(col.name)} sort={sort} onSort={onSort} />
))}
{renderRowActions && (
<th scope="col" className={cn(HEADER_CELL, 'w-12 text-right last:pr-3')}>
<span className="sr-only">{t('list.actions', 'Actions')}</span>
</th>
)}
</tr>
</thead>
<tbody>
{loading && rows.length === 0 ? (
<tr>
<td colSpan={colSpan} className="border-t border-border px-3 py-12">
<ListSpinner className="flex items-center justify-center" />
</td>
</tr>
) : rows.length === 0 ? (
<ListTableMessage colSpan={colSpan}>{t('list.noResults', 'No results found')}</ListTableMessage>
) : (
rows.map(({ item, id }) => {
const label = rowLabel(item);
const href = rowHref(id);
return (
<tr
key={id}
className={cn(
'border-t border-border transition-colors duration-150',
href && 'cursor-pointer',
selection?.isSelected(id) ? 'bg-highlight/70' : 'hover:bg-muted/55',
)}
onClick={
href
? (event) => {
if (isRowClick(event)) void navigate(href);
}
: undefined
}
>
{selection && (
<td data-row-controls className="w-10 py-2.5 pl-5 pr-2 align-middle">
<Checkbox
checked={selection.isSelected(id)}
onCheckedChange={() => selection.toggle(id)}
aria-label={t('list.selectNamed', 'Select {{label}}', { label })}
/>
</td>
)}
{columns.map((col, index) => {
const value = item[col.name];
const content = (
<ListCell
schema={schema}
objectName={objectName}
column={col.name}
field={fields[col.name]}
value={value}
/>
);
if (index === 0) {
return (
<th key={col.name} scope="row" className={cn(BODY_CELL, 'text-left font-normal')}>
{href ? (
<Link to={href} className={ROW_LINK} aria-label={isEmptyValue(value) ? label : undefined}>
{content}
</Link>
) : (
content
)}
</th>
);
<div className="rounded-lg border bg-background shadow-sm">
<div className="overflow-x-auto rounded-[calc(var(--radius-lg)-1px)]">
<table className="w-full text-sm" aria-busy={busy || undefined}>
<caption className="sr-only">{caption}</caption>
<thead>
<tr className="border-b bg-muted">
{selection && (
<th scope="col" className="w-10 px-3 py-3">
<Checkbox
checked={
selection.pageState === 'all' ? true : selection.pageState === 'some' ? 'indeterminate' : false
}
return (
<td key={col.name} className={BODY_CELL}>
{content}
disabled={rows.length === 0}
onCheckedChange={selection.togglePage}
aria-label={t('list.selectAllOnPage', 'Select all on this page')}
/>
</th>
)}
{columns.map((col) => (
<ColumnHeader
key={col.name}
column={col}
sortable={sortable.has(col.name)}
sort={sort}
onSort={onSort}
/>
))}
{renderRowActions && (
<th scope="col" className="w-12 px-3 py-3 text-right font-medium text-muted-foreground">
{t('list.actions', 'Actions')}
</th>
)}
</tr>
</thead>
<tbody>
{loading && rows.length === 0 ? (
<tr>
<td colSpan={colSpan} className="px-3 py-12">
<ListSpinner className="flex items-center justify-center" />
</td>
</tr>
) : rows.length === 0 ? (
<ListTableMessage colSpan={colSpan}>{t('list.noResults', 'No results found')}</ListTableMessage>
) : (
rows.map(({ item, id }) => {
const label = rowLabel(item);
const href = rowHref(id);
return (
<tr key={id} className="relative border-b transition-colors hover:bg-muted/50">
{selection && (
<td className="relative z-10 px-3 py-2">
<Checkbox
checked={selection.isSelected(id)}
onCheckedChange={() => selection.toggle(id)}
aria-label={t('list.selectNamed', 'Select {{label}}', { label })}
/>
</td>
);
})}
{renderRowActions && (
<td data-row-controls className="py-1.5 pl-2 pr-3 text-right align-middle">
{renderRowActions(item, id, label)}
</td>
)}
</tr>
);
})
)}
</tbody>
</table>
)}
{columns.map((col, index) => {
const value = item[col.name];
const content = (
<ListCell
schema={schema}
objectName={objectName}
column={col.name}
field={fields[col.name]}
value={value}
/>
);
if (index === 0) {
return (
<th key={col.name} scope="row" className="px-3 py-2 text-left font-normal">
{href ? (
<Link
to={href}
className={STRETCHED_LINK}
aria-label={isEmptyValue(value) ? label : undefined}
>
{content}
</Link>
) : (
content
)}
</th>
);
}
return (
<td key={col.name} className="px-3 py-2">
{content}
</td>
);
})}
{renderRowActions && (
<td className="relative z-10 px-3 py-2 text-right">{renderRowActions(item, id, label)}</td>
)}
</tr>
);
})
)}
</tbody>
</table>
</div>
</div>
);
}
+25 -40
View File
@@ -5,10 +5,9 @@
*/
import { useTranslation } from 'react-i18next';
import { ChevronUp, X } from 'lucide-react';
import { ChevronDown } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { FloatingActionBar, FloatingActionDivider, FloatingActionDot } from '@/components/common/FloatingActionBar';
import {
DropdownMenu,
DropdownMenuContent,
@@ -25,47 +24,33 @@ interface MassActionBarProps {
count: number;
disabled: boolean;
onSelect: (action: RunnableMassAction) => void;
onClear: () => void;
}
export function MassActionBar({ actions, count, disabled, onSelect, onClear }: MassActionBarProps) {
export function MassActionBar({ actions, count, disabled, onSelect }: MassActionBarProps) {
const { t } = useTranslation();
return (
<FloatingActionBar>
<span className="pl-2">
<FloatingActionDot />
</span>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ink" size="sm" className="text-ink-foreground" disabled={disabled}>
{t('list.massActionCount', 'Actions ({{count}})', { count })}
<ChevronUp aria-hidden />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="center" side="top" sideOffset={10}>
{actions.map(({ key, action }) =>
action.type === 'separator' ? (
<DropdownMenuSeparator key={key} />
) : (
<DropdownMenuItem
key={key}
className={
action.type === 'delete'
? 'text-destructive focus:bg-destructive-soft focus:text-destructive'
: undefined
}
onSelect={() => onSelect(action)}
>
{action.label}
</DropdownMenuItem>
),
)}
</DropdownMenuContent>
</DropdownMenu>
<FloatingActionDivider />
<Button variant="ink" size="icon-sm" onClick={onClear} aria-label={t('list.clearSelection', 'Clear selection')}>
<X aria-hidden />
</Button>
</FloatingActionBar>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm" disabled={disabled}>
{t('list.massActionCount', 'Actions ({{count}})', { count })}
<ChevronDown className="ml-1 h-4 w-4" aria-hidden />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{actions.map(({ key, action }) =>
action.type === 'separator' ? (
<DropdownMenuSeparator key={key} />
) : (
<DropdownMenuItem
key={key}
className={action.type === 'delete' ? 'text-destructive' : undefined}
onSelect={() => onSelect(action)}
>
{action.label}
</DropdownMenuItem>
),
)}
</DropdownMenuContent>
</DropdownMenu>
);
}
+4 -7
View File
@@ -5,7 +5,6 @@
*/
import { useTranslation } from 'react-i18next';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { Button } from '@/components/ui/button';
import type { PageRange } from './listQuery';
@@ -25,7 +24,7 @@ export function Pagination({ range, total, count, pluralName, disabled, onPrev,
return (
<nav
aria-label={t('list.pagination', 'Pagination')}
className="flex flex-wrap items-center justify-between gap-2 border-t border-border py-2.5 pl-5 pr-2.5 text-[13px] text-muted-foreground"
className="flex items-center justify-between text-sm text-muted-foreground"
>
<p aria-live="polite">
{total !== null
@@ -37,14 +36,12 @@ export function Pagination({ range, total, count, pluralName, disabled, onPrev,
})
: t('list.showingItems', 'Showing {{count}} items', { count })}
</p>
<div className="flex items-center gap-1.5">
<Button variant="secondary" size="sm" disabled={!range.hasPrev || disabled} onClick={onPrev}>
<ChevronLeft aria-hidden />
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" disabled={!range.hasPrev || disabled} onClick={onPrev}>
{t('list.previous', 'Previous')}
</Button>
<Button variant="secondary" size="sm" disabled={!range.hasNext || disabled} onClick={onNext}>
<Button variant="outline" size="sm" disabled={!range.hasNext || disabled} onClick={onNext}>
{t('list.next', 'Next')}
<ChevronRight aria-hidden />
</Button>
</div>
</nav>
+4 -7
View File
@@ -37,7 +37,8 @@ export function RowActions({ actions, label, hrefFor, onMutation, onLocked, disa
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="icon-sm"
size="sm"
className="h-8 w-8 p-0"
disabled={disabled}
aria-label={t('list.actionsFor', 'Actions for {{label}}', { label })}
>
@@ -51,11 +52,7 @@ export function RowActions({ actions, label, hrefFor, onMutation, onLocked, disa
return (
<DropdownMenuItem
key={entry.key}
className={
entry.action.type === 'delete'
? 'text-destructive focus:bg-destructive-soft focus:text-destructive'
: undefined
}
className={entry.action.type === 'delete' ? 'text-destructive' : undefined}
onSelect={() => onMutation(entry)}
>
{entry.action.label}
@@ -66,7 +63,7 @@ export function RowActions({ actions, label, hrefFor, onMutation, onLocked, disa
return (
<DropdownMenuItem key={entry.key} onSelect={onLocked}>
{entry.label}
<Lock className="ml-auto h-3 w-3 text-dim" aria-hidden />
<Lock className="ml-auto h-3 w-3 text-muted-foreground" aria-hidden />
<span className="sr-only">
{t('enterprise.featureDisabled', 'This feature requires an Enterprise license.')}
</span>
+3 -10
View File
@@ -24,15 +24,11 @@ export function SelectionBanner({
onClear,
}: SelectionBannerProps) {
const { t } = useTranslation();
const linkClass =
'font-semibold text-brand-text underline-offset-4 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring rounded-sm';
const linkClass = 'text-primary underline hover:text-primary/80';
if (allMatching) {
return (
<div
role="status"
className="border-t border-border first:border-t-0 bg-highlight/70 px-5 py-2.5 text-center text-[13px]"
>
<div role="status" className="rounded-md border border-primary/50 bg-primary/10 px-4 py-2 text-center text-sm">
{t('list.allMatchingSelected', 'All {{total}} {{name}} matching the current filters are selected.', {
total: total ?? 0,
name: pluralName,
@@ -47,10 +43,7 @@ export function SelectionBanner({
if (total === null || total <= pageCount) return null;
return (
<div
role="status"
className="border-t border-border first:border-t-0 bg-muted/60 px-5 py-2.5 text-center text-[13px]"
>
<div role="status" className="rounded-md border bg-muted/50 px-4 py-2 text-center text-sm">
{t('list.allPageSelected', 'All {{count}} items on this page are selected.', { count: pageCount })}{' '}
<button type="button" className={linkClass} onClick={onSelectAllMatching}>
{t('list.selectAllMatchingNamed', 'Select all {{total}} {{name}} matching the current filters', {
+3 -3
View File
@@ -27,7 +27,7 @@ function AlertDialogOverlay({ className, ...props }: React.ComponentProps<typeof
<AlertDialogPrimitive.Overlay
data-slot="alert-dialog-overlay"
className={cn(
'fixed inset-0 z-50 bg-overlay data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
'fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className,
)}
{...props}
@@ -42,7 +42,7 @@ function AlertDialogContent({ className, ...props }: React.ComponentProps<typeof
<AlertDialogPrimitive.Content
data-slot="alert-dialog-content"
className={cn(
'fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 rounded-3xl bg-card p-6 shadow-pop duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
'fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 sm:rounded-lg',
className,
)}
{...props}
@@ -76,7 +76,7 @@ function AlertDialogTitle({ className, ...props }: React.ComponentProps<typeof A
return (
<AlertDialogPrimitive.Title
data-slot="alert-dialog-title"
className={cn('font-display text-lg font-bold tracking-[-0.015em]', className)}
className={cn('text-lg font-semibold', className)}
{...props}
/>
);
+5 -5
View File
@@ -10,14 +10,14 @@ import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils';
const badgeVariants = cva(
'inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
'inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
{
variants: {
variant: {
default: 'border-transparent bg-highlight text-highlight-foreground',
secondary: 'border-transparent bg-secondary text-secondary-foreground',
destructive: 'border-transparent bg-destructive-soft text-destructive',
outline: 'border-input text-foreground',
default: 'border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80',
secondary: 'border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80',
destructive: 'border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80',
outline: 'text-foreground',
},
},
defaultVariants: {
+9 -15
View File
@@ -11,28 +11,22 @@ import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils';
const buttonVariants = cva(
'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-full text-sm font-semibold transition-[color,background-color,box-shadow] duration-200 ease-bento focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0',
'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0',
{
variants: {
variant: {
default: 'bg-primary text-primary-foreground shadow-primary hover:bg-primary-hover',
destructive: 'bg-destructive text-destructive-foreground hover:bg-destructive-hover',
outline: 'bg-card text-foreground shadow-tile hover:shadow-lift',
secondary: 'bg-secondary text-secondary-foreground hover:bg-highlight hover:text-highlight-foreground',
ghost: 'text-muted-foreground hover:bg-accent hover:text-accent-foreground',
link: 'text-brand-text underline-offset-4 hover:underline',
ink: 'text-ink-muted hover:bg-ink-2 hover:text-ink-foreground',
'ink-danger': 'text-ink-danger hover:bg-ink-danger/12',
'ghost-danger': 'text-muted-foreground hover:bg-destructive-soft hover:text-destructive',
field: 'field-surface rounded-lg font-normal text-foreground focus-visible:ring-0 focus-visible:ring-offset-0',
default: 'bg-primary text-primary-foreground shadow hover:bg-primary/90',
destructive: 'bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90',
outline: 'border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground',
secondary: 'bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80',
ghost: 'hover:bg-accent hover:text-accent-foreground',
link: 'text-primary underline-offset-4 hover:underline',
},
size: {
default: 'h-9 px-4 py-2',
sm: 'h-8 px-3.5 text-[13px]',
lg: 'h-11 px-7',
sm: 'h-8 rounded-md px-3 text-xs',
lg: 'h-10 rounded-md px-8',
icon: 'h-9 w-9',
'icon-sm': 'h-8 w-8',
'icon-lg': 'h-10 w-10',
},
},
defaultVariants: {
+4 -1
View File
@@ -62,7 +62,10 @@ function Calendar({
'flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium',
defaultClassNames.dropdowns,
),
dropdown_root: cn('field-surface relative rounded-lg', defaultClassNames.dropdown_root),
dropdown_root: cn(
'relative rounded-md border border-input shadow-xs has-focus:border-ring has-focus:ring-[3px] has-focus:ring-ring/50',
defaultClassNames.dropdown_root,
),
dropdown: cn('absolute inset-0 bg-popover opacity-0', defaultClassNames.dropdown),
caption_label: cn(
'font-medium select-none',
+5 -9
View File
@@ -12,23 +12,19 @@ function Card({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card"
className={cn('rounded-2xl bg-card text-card-foreground shadow-tile', className)}
className={cn('rounded-xl border bg-card text-card-foreground shadow', className)}
{...props}
/>
);
}
function CardHeader({ className, ...props }: React.ComponentProps<'div'>) {
return <div data-slot="card-header" className={cn('flex flex-col space-y-1.5 p-5', className)} {...props} />;
return <div data-slot="card-header" className={cn('flex flex-col space-y-1.5 p-6', className)} {...props} />;
}
function CardTitle({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-title"
className={cn('font-display font-bold leading-tight tracking-[-0.012em]', className)}
{...props}
/>
<div data-slot="card-title" className={cn('font-semibold leading-none tracking-tight', className)} {...props} />
);
}
@@ -37,11 +33,11 @@ function CardDescription({ className, ...props }: React.ComponentProps<'div'>) {
}
function CardContent({ className, ...props }: React.ComponentProps<'div'>) {
return <div data-slot="card-content" className={cn('p-5 pt-0', className)} {...props} />;
return <div data-slot="card-content" className={cn('p-6 pt-0', className)} {...props} />;
}
function CardFooter({ className, ...props }: React.ComponentProps<'div'>) {
return <div data-slot="card-footer" className={cn('flex items-center p-5 pt-0', className)} {...props} />;
return <div data-slot="card-footer" className={cn('flex items-center p-6 pt-0', className)} {...props} />;
}
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent };
+6 -6
View File
@@ -10,11 +10,11 @@ import type { TooltipPayload } from 'recharts/types/state/tooltipSlice';
import { cn } from '@/lib/utils';
export const CHART_COLORS = [
'var(--chart-1)',
'var(--chart-2)',
'var(--chart-3)',
'var(--chart-4)',
'var(--chart-5)',
'hsl(var(--chart-1))',
'hsl(var(--chart-2))',
'hsl(var(--chart-3))',
'hsl(var(--chart-4))',
'hsl(var(--chart-5))',
] as const;
export function getChartColor(index: number): string {
@@ -39,7 +39,7 @@ export function ChartTooltipContent({
if (!active || !payload?.length) return null;
return (
<div className="popover-surface p-2.5">
<div className="rounded-lg border bg-background p-2 shadow-md">
{label && <p className="mb-1 text-xs text-muted-foreground">{label}</p>}
{payload.map((entry, i) => (
<div key={i} className="flex items-center gap-2 text-sm">
+2 -2
View File
@@ -15,13 +15,13 @@ function Checkbox({ className, ...props }: React.ComponentProps<typeof CheckboxP
<CheckboxPrimitive.Root
data-slot="checkbox"
className={cn(
'peer h-[18px] w-[18px] shrink-0 rounded-[6px] border-0 bg-field shadow-[inset_0_0_0_1.5px_var(--input)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background data-[state=checked]:shadow-none data-[state=indeterminate]:bg-primary data-[state=indeterminate]:text-primary-foreground data-[state=indeterminate]:shadow-none disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground',
'peer h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground',
className,
)}
{...props}
>
<CheckboxPrimitive.Indicator className="flex items-center justify-center text-current">
<Check className="h-3 w-3" strokeWidth={3} />
<Check className="h-4 w-4" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
);
+2 -2
View File
@@ -82,11 +82,11 @@ export function Combobox({
{...ariaProps}
ref={triggerRef}
type="button"
variant="field"
variant="outline"
role="combobox"
aria-expanded={open}
disabled={disabled}
className={cn('w-full justify-between px-3', !selected && 'text-dim', className)}
className={cn('w-full justify-between font-normal', !selected && 'text-muted-foreground', className)}
>
<span className="flex items-center gap-2 truncate">
{selected?.marker}
+2 -2
View File
@@ -17,7 +17,7 @@ function Command({ className, ...props }: React.ComponentProps<typeof CommandPri
<CommandPrimitive
data-slot="command"
className={cn(
'flex h-full w-full flex-col overflow-hidden rounded-2xl bg-popover text-popover-foreground',
'flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground',
className,
)}
{...props}
@@ -100,7 +100,7 @@ function CommandItem({ className, ...props }: React.ComponentProps<typeof Comman
<CommandPrimitive.Item
data-slot="command-item"
className={cn(
'relative flex cursor-default select-none items-center rounded-lg px-2.5 py-1.5 text-sm outline-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50',
'relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50',
className,
)}
{...props}
+4 -4
View File
@@ -37,7 +37,7 @@ function DialogOverlay({ className, ...props }: React.ComponentProps<typeof Dial
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
'fixed inset-0 z-50 bg-overlay data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
'fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className,
)}
{...props}
@@ -56,14 +56,14 @@ function DialogContent({
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
'fixed left-[50%] top-[50%] z-50 grid max-h-[calc(100dvh-2rem)] w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 overflow-y-auto rounded-3xl bg-card p-6 shadow-pop duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
'fixed left-[50%] top-[50%] z-50 grid max-h-[calc(100dvh-2rem)] w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 overflow-y-auto border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 sm:rounded-lg',
className,
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-full p-1.5 opacity-70 hover:bg-muted ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
@@ -97,7 +97,7 @@ function DialogTitle({ className, ...props }: React.ComponentProps<typeof Dialog
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn('font-display text-lg font-bold leading-tight tracking-[-0.015em]', className)}
className={cn('text-lg font-semibold leading-none tracking-tight', className)}
{...props}
/>
);
+6 -6
View File
@@ -44,7 +44,7 @@ function DropdownMenuSubTrigger({
<DropdownMenuPrimitive.SubTrigger
data-slot="dropdown-menu-sub-trigger"
className={cn(
'flex cursor-default gap-2 select-none items-center rounded-lg px-2.5 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0',
'flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0',
inset && 'pl-8',
className,
)}
@@ -64,7 +64,7 @@ function DropdownMenuSubContent({
<DropdownMenuPrimitive.SubContent
data-slot="dropdown-menu-sub-content"
className={cn(
'z-50 min-w-[8rem] overflow-hidden popover-surface p-1.5 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
'z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
className,
)}
{...props}
@@ -83,7 +83,7 @@ function DropdownMenuContent({
data-slot="dropdown-menu-content"
sideOffset={sideOffset}
className={cn(
'z-50 min-w-[8rem] overflow-hidden popover-surface p-1.5',
'z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md',
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
className,
)}
@@ -102,7 +102,7 @@ function DropdownMenuItem({
<DropdownMenuPrimitive.Item
data-slot="dropdown-menu-item"
className={cn(
'relative flex cursor-default select-none items-center gap-2 rounded-lg px-2.5 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&>svg]:size-4 [&>svg]:shrink-0',
'relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&>svg]:size-4 [&>svg]:shrink-0',
inset && 'pl-8',
className,
)}
@@ -121,7 +121,7 @@ function DropdownMenuCheckboxItem({
<DropdownMenuPrimitive.CheckboxItem
data-slot="dropdown-menu-checkbox-item"
className={cn(
'relative flex cursor-default select-none items-center rounded-lg py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
'relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className,
)}
checked={checked}
@@ -146,7 +146,7 @@ function DropdownMenuRadioItem({
<DropdownMenuPrimitive.RadioItem
data-slot="dropdown-menu-radio-item"
className={cn(
'relative flex cursor-default select-none items-center rounded-lg py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
'relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className,
)}
{...props}
+2 -10
View File
@@ -8,21 +8,13 @@ import * as React from 'react';
import { cn } from '@/lib/utils';
function Input({
className,
type,
variant = 'field',
...props
}: React.ComponentProps<'input'> & { variant?: 'field' | 'pill' }) {
function Input({ className, type, ...props }: React.ComponentProps<'input'>) {
return (
<input
type={type}
data-slot="input"
className={cn(
'flex h-9 w-full px-3 py-1 text-base file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-dim focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
variant === 'field'
? 'field-surface rounded-lg'
: 'rounded-full border-0 bg-muted focus-visible:ring-2 focus-visible:ring-ring',
'flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
className,
)}
{...props}
+1 -1
View File
@@ -34,7 +34,7 @@ function PopoverContent({
align={align}
sideOffset={sideOffset}
className={cn(
'z-50 w-72 popover-surface p-4 outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
'z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
className,
)}
{...props}
+4 -12
View File
@@ -22,20 +22,12 @@ function SelectValue(props: React.ComponentProps<typeof SelectPrimitive.Value>)
return <SelectPrimitive.Value data-slot="select-value" {...props} />;
}
function SelectTrigger({
className,
children,
variant = 'field',
...props
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & { variant?: 'field' | 'pill' }) {
function SelectTrigger({ className, children, ...props }: React.ComponentProps<typeof SelectPrimitive.Trigger>) {
return (
<SelectPrimitive.Trigger
data-slot="select-trigger"
className={cn(
'flex items-center justify-between whitespace-nowrap placeholder:text-dim focus:outline-none disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1',
variant === 'field'
? 'field-surface h-9 w-full rounded-lg px-3 py-2 text-sm'
: 'h-8 w-auto gap-2 rounded-full bg-card px-3.5 text-[13px] font-semibold shadow-tile transition-shadow duration-200 hover:shadow-lift focus-visible:ring-2 focus-visible:ring-ring data-[state=open]:shadow-lift',
'flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1',
className,
)}
{...props}
@@ -86,7 +78,7 @@ function SelectContent({
<SelectPrimitive.Content
data-slot="select-content"
className={cn(
'relative z-50 max-h-96 min-w-[8rem] overflow-hidden popover-surface data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
'relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
position === 'popper' &&
'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
className,
@@ -125,7 +117,7 @@ function SelectItem({ className, children, ...props }: React.ComponentProps<type
<SelectPrimitive.Item
data-slot="select-item"
className={cn(
'relative flex w-full cursor-default select-none items-center rounded-lg py-1.5 pl-2.5 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
'relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className,
)}
{...props}
+2 -2
View File
@@ -14,12 +14,12 @@ function Switch({ className, ...props }: React.ComponentProps<typeof SwitchPrimi
<SwitchPrimitives.Root
data-slot="switch"
className={cn(
'peer inline-flex h-6 w-10 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-muted-strong',
'peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input',
className,
)}
{...props}
>
<SwitchPrimitives.Thumb className="pointer-events-none block h-5 w-5 rounded-full bg-card shadow-[0_1px_3px_rgb(0_0_0/0.25)] ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=checked]:bg-white data-[state=unchecked]:translate-x-0" />
<SwitchPrimitives.Thumb className="pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0" />
</SwitchPrimitives.Root>
);
}
+2 -2
View File
@@ -18,7 +18,7 @@ function TabsList({ className, ...props }: React.ComponentProps<typeof TabsPrimi
<TabsPrimitive.List
data-slot="tabs-list"
className={cn(
'inline-flex h-10 items-center justify-center gap-0.5 rounded-full bg-muted p-1 text-muted-foreground',
'inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground',
className,
)}
{...props}
@@ -31,7 +31,7 @@ function TabsTrigger({ className, ...props }: React.ComponentProps<typeof TabsPr
<TabsPrimitive.Trigger
data-slot="tabs-trigger"
className={cn(
'inline-flex h-8 items-center justify-center gap-1.5 whitespace-nowrap rounded-full px-3.5 py-1 text-[13px] font-semibold ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 hover:text-foreground data-[state=active]:bg-card data-[state=active]:text-foreground data-[state=active]:shadow-tile',
'inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow',
className,
)}
{...props}
+2 -7
View File
@@ -8,17 +8,12 @@ import * as React from 'react';
import { cn } from '@/lib/utils';
function Textarea({
className,
variant = 'field',
...props
}: React.ComponentProps<'textarea'> & { variant?: 'field' | 'bare' }) {
function Textarea({ className, ...props }: React.ComponentProps<'textarea'>) {
return (
<textarea
data-slot="textarea"
className={cn(
'flex min-h-[60px] w-full px-3 py-2 text-base placeholder:text-dim focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
variant === 'field' ? 'field-surface rounded-lg' : 'border-0 bg-transparent',
'flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
className,
)}
{...props}
+7 -7
View File
@@ -24,15 +24,15 @@ function ToastViewport({ className, ...props }: React.ComponentProps<'ol'>) {
}
const toastVariants = cva(
'group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-2xl p-4 pr-7 shadow-pop ring-1 transition-all data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full',
'group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full',
{
variants: {
variant: {
default: 'bg-popover text-popover-foreground ring-border',
destructive: 'destructive group bg-destructive-soft text-foreground ring-destructive/40',
success: 'bg-success-soft text-foreground ring-success/40',
warning: 'bg-warning-soft text-foreground ring-warning/40',
info: 'bg-info-soft text-foreground ring-info/40',
default: 'border bg-background text-foreground',
destructive: 'destructive group border-destructive bg-destructive text-destructive-foreground',
success: 'border-green-500 bg-background text-foreground',
warning: 'border-yellow-500 bg-background text-foreground',
info: 'border-blue-500 bg-background text-foreground',
},
},
defaultVariants: {
@@ -71,7 +71,7 @@ function ToastClose({ className, ...props }: React.ComponentProps<'button'>) {
data-slot="toast-close"
aria-label="Close"
className={cn(
'absolute right-1.5 top-1.5 rounded-full p-1 text-foreground/60 transition-colors hover:bg-muted hover:text-foreground focus:outline-none focus:ring-1 focus:ring-ring',
'absolute right-1 top-1 rounded-md p-1 text-foreground/60 transition-colors hover:text-foreground focus:outline-none focus:ring-1 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600',
className,
)}
type="button"
+1 -1
View File
@@ -32,7 +32,7 @@ function TooltipContent({
data-slot="tooltip-content"
sideOffset={sideOffset}
className={cn(
'z-50 overflow-hidden rounded-lg bg-ink px-3 py-1.5 text-xs text-ink-foreground shadow-ink animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
'z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
className,
)}
{...props}
+8 -9
View File
@@ -8,7 +8,6 @@ import { Fragment, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { ChevronRight } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { cn } from '@/lib/utils';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { HelpTooltip } from '@/components/common/HelpTooltip';
import { formatDateTime } from '@/lib/format';
@@ -125,11 +124,11 @@ function SetValue({
);
}
return (
<span className="flex flex-wrap gap-1.5">
<span className="flex flex-wrap gap-1">
{items.map((item) => {
const color = itemType.type === 'enum' ? getEnumVariant(schema, itemType.enumName, item)?.color : undefined;
return (
<Badge key={item} variant="secondary" className="h-6 gap-1.5 font-medium">
<Badge key={item} variant="secondary" className="gap-1 text-xs">
{color && (
<span className="inline-block h-2 w-2 shrink-0 rounded-full" style={{ backgroundColor: color }} />
)}
@@ -170,7 +169,7 @@ function MapValue({
);
}
return (
<dl className="@container divide-y divide-border border-l-2 border-input pl-4">
<dl className="space-y-2">
{entries.map(([key, val]) => (
<ValueRow
key={key}
@@ -206,7 +205,7 @@ function ObjectListValue({
return <span>{t('value.itemCount', '{{count}} items', { count: entries.length })}</span>;
}
return (
<div className="space-y-1.5">
<div className="space-y-2">
{entries.map(([key, item]) => (
<ObjectValue key={key} schema={schema} objectName={objectName} value={item} />
))}
@@ -307,7 +306,7 @@ export function ObjectValue({
<CollapsibleTrigger asChild>
<button
type="button"
className="-ml-1 flex items-center gap-1.5 rounded-md px-1 py-0.5 text-sm text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring [&[data-state=open]>svg]:rotate-90"
className="flex items-center gap-1.5 text-sm text-muted-foreground transition-colors hover:text-foreground [&[data-state=open]>svg]:rotate-90"
>
<ChevronRight className="h-3.5 w-3.5 shrink-0 transition-transform duration-200" aria-hidden="true" />
{typeLabel || summary.summary ? (
@@ -318,7 +317,7 @@ export function ObjectValue({
</button>
</CollapsibleTrigger>
<CollapsibleContent>
<dl className="@container mt-1.5 ml-1.5 divide-y divide-border border-l-2 border-input pl-4">
<dl className="mt-2 ml-5 space-y-2 border-l-2 border-muted/40 pl-4">
{entries.map((entry) => (
<ValueRow
key={entry.key}
@@ -362,8 +361,8 @@ export interface ValueRowProps {
export function ValueRow({ schema, label, description, type, value }: ValueRowProps) {
const block = isBlockValue(type, value);
return (
<div data-slot="value-row" className={cn('py-3', block ? 'grid gap-y-1.5' : 'field-grid')}>
<dt className="flex min-w-0 items-center gap-1 text-[13px] font-medium text-muted-foreground">
<div className={block ? 'space-y-1' : 'flex items-baseline gap-2'}>
<dt className="flex min-w-[140px] shrink-0 items-center gap-1 text-sm text-muted-foreground">
{label}
{description && typeof label === 'string' && <HelpTooltip content={description} label={label} />}
</dt>
+9 -16
View File
@@ -19,8 +19,8 @@ export type ValueVariant = 'full' | 'compact';
export function EmptyValue({ variant = 'full' }: { variant?: ValueVariant }) {
const { t } = useTranslation();
if (variant === 'compact') return <span className="text-dim">-</span>;
return <span className="text-sm italic text-dim">{t('field.notSet', 'Not set')}</span>;
if (variant === 'compact') return <span className="text-muted-foreground">-</span>;
return <span className="text-sm italic text-muted-foreground">{t('field.notSet', 'Not set')}</span>;
}
export function StringValue({
@@ -39,10 +39,7 @@ export function StringValue({
if (format === 'color') {
return (
<span className="inline-flex items-center gap-2 text-sm">
<span
className="inline-block h-3.5 w-3.5 shrink-0 rounded-full shadow-[inset_0_0_0_1px_var(--input)]"
style={{ backgroundColor: str }}
/>
<span className="inline-block h-3.5 w-3.5 shrink-0 rounded-sm border" style={{ backgroundColor: str }} />
<span className="font-mono">{str}</span>
</span>
);
@@ -51,8 +48,8 @@ export function StringValue({
return (
<pre
className={cn(
'whitespace-pre-wrap break-words bg-muted font-mono text-xs',
variant === 'compact' ? 'max-w-md rounded-lg px-2 py-1' : 'rounded-xl p-3',
'whitespace-pre-wrap break-words rounded bg-muted/50 font-mono text-xs',
variant === 'compact' ? 'max-w-md px-1.5 py-1' : 'p-2',
format === 'text' && 'font-sans',
)}
>
@@ -75,9 +72,9 @@ export function NumberValue({ value, format }: { value: unknown; format: string
export function BooleanValue({ value }: { value: unknown }) {
const { t } = useTranslation();
return value === true ? (
<Check className="h-4 w-4 text-success" role="img" aria-label={t('common.yes', 'Yes')} />
<Check className="h-4 w-4 text-green-600" role="img" aria-label={t('common.yes', 'Yes')} />
) : (
<X className="h-4 w-4 text-destructive" role="img" aria-label={t('common.no', 'No')} />
<X className="h-4 w-4 text-red-500" role="img" aria-label={t('common.no', 'No')} />
);
}
@@ -86,11 +83,7 @@ export function EnumValue({ schema, enumName, value }: { schema: Schema; enumNam
const variant = getEnumVariant(schema, enumName, name);
if (!variant) return <span className="text-sm">{name}</span>;
return (
<Badge
variant="secondary"
className={cn('h-6', variant.color && 'text-primary-foreground')}
style={variant.color ? { backgroundColor: variant.color } : undefined}
>
<Badge variant="secondary" style={variant.color ? { backgroundColor: variant.color, color: '#fff' } : undefined}>
{variant.label}
</Badge>
);
@@ -111,7 +104,7 @@ export function ObjectIdValue({
const content = loading && !label ? <Loader2 className="h-3 w-3 animate-spin" /> : (label ?? id);
if (variant === 'compact') return <span>{content}</span>;
return (
<Badge variant="secondary" className="h-6 font-medium">
<Badge variant="secondary" className="text-sm">
{content}
</Badge>
);
+28 -18
View File
@@ -5,8 +5,8 @@
*/
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { ValueRow } from '@/components/values/FieldValue';
import { cn } from '@/lib/utils';
import { resolveForm, resolveSchema, resolveVariantForm } from '@/lib/schemaResolver';
import { isEmptyValue, variantLabel } from '@/lib/embeddedSchema';
import type { Field, Fields, Form, FormField, Schema } from '@/types/schema';
@@ -77,24 +77,34 @@ export function DynamicView({ schema, objectName, viewName, data, visibleFields
const typeLabel = variantLabel(schema, objectName, data['@type']);
return (
<div className="space-y-3.5">
{typeLabel && <Badge variant="default">{typeLabel}</Badge>}
<div className="space-y-4">
{typeLabel && (
<Badge variant="secondary" className="text-xs">
{typeLabel}
</Badge>
)}
{sections.map((section) => (
<section key={section.key} className="tile @container px-5 pb-1.5 sm:px-6">
{section.title && <h2 className="section-title pb-1 pt-5">{section.title}</h2>}
<dl className={cn('divide-y divide-border', !section.title && 'pt-1')}>
{section.items.map(({ formField, field }) => (
<ValueRow
key={formField.name}
schema={schema}
label={formField.label}
description={field.description}
type={field.type}
value={data[formField.name]}
/>
))}
</dl>
</section>
<Card key={section.key}>
{section.title && (
<CardHeader className="pb-3">
<CardTitle className="text-base">{section.title}</CardTitle>
</CardHeader>
)}
<CardContent className={section.title ? 'pt-0' : ''}>
<dl className="space-y-2">
{section.items.map(({ formField, field }) => (
<ValueRow
key={formField.name}
schema={schema}
label={formField.label}
description={field.description}
type={field.type}
value={data[formField.name]}
/>
))}
</dl>
</CardContent>
</Card>
))}
</div>
);
+10 -17
View File
@@ -41,21 +41,19 @@ export function DynamicViewPage({ viewName, objectId }: DynamicViewPageProps) {
if (loading) {
return (
<div className="flex items-center justify-center p-12">
<Loader2 className="h-6 w-6 animate-spin text-brand-text" aria-hidden="true" />
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
);
}
if (error || !data || !schema) {
return (
<div className="mx-auto max-w-5xl space-y-5 pt-3">
<div className="space-y-4">
<Button variant="outline" size="sm" onClick={() => navigate(-1)}>
<ArrowLeft aria-hidden="true" />
<ArrowLeft className="mr-2 h-4 w-4" />
{t('common.back', 'Back')}
</Button>
<div className="rounded-xl bg-destructive-soft p-4 text-sm text-destructive" role="alert">
{error ?? t('view.failedToLoad', 'Failed to load')}
</div>
<div className="text-destructive p-4">{error ?? t('view.failedToLoad', 'Failed to load')}</div>
</div>
);
}
@@ -73,18 +71,13 @@ export function DynamicViewPage({ viewName, objectId }: DynamicViewPageProps) {
: singularName.charAt(0).toUpperCase() + singularName.slice(1);
return (
<div className="mx-auto max-w-5xl space-y-5">
<div className="flex items-start gap-3.5 px-1 pb-1 pt-3">
<Button
variant="outline"
size="icon-lg"
className="shrink-0"
onClick={() => navigate(-1)}
aria-label={t('common.back', 'Back')}
>
<ArrowLeft className="h-5 w-5" aria-hidden="true" />
<div className="space-y-6">
<div className="flex items-center gap-3">
<Button variant="outline" size="sm" onClick={() => navigate(-1)}>
<ArrowLeft className="mr-2 h-4 w-4" />
{t('common.back', 'Back')}
</Button>
<h1 className="page-title min-w-0 flex-1 break-words pt-1.5">{title}</h1>
<h1 className="text-xl font-semibold">{title}</h1>
</div>
<DynamicView schema={schema} objectName={resolved.objectName} viewName={viewName} data={data} />
+1 -2
View File
@@ -19,8 +19,7 @@ export const jmapKeys = {
lists: (objectName: string) => ['jmap', objectName, 'list'] as const,
list: (objectName: string, params: ListPageParams) => ['jmap', objectName, 'list', params] as const,
allOptions: (objectName: string) => ['jmap', objectName, 'options'] as const,
options: (objectName: string, viewName: string, tenantId: string | null = null) =>
['jmap', objectName, 'options', viewName, tenantId] as const,
options: (objectName: string, viewName: string) => ['jmap', objectName, 'options', viewName] as const,
displayNames: (objectName: string) => ['jmap', objectName, 'displayName'] as const,
displayName: (objectName: string, displayProperty: string, id: string) =>
['jmap', objectName, 'displayName', displayProperty, id] as const,
+7 -13
View File
@@ -9,7 +9,7 @@ import { queryOptions, useQuery, useQueryClient, type QueryClient } from '@tanst
import { jmapKeys } from '@/data/keys';
import { loadDisplayName } from '@/data/displayNames';
import { coerceLabel } from '@/lib/objectOptions';
import { getDisplayProperty, isTenantScoped, resolveList, resolveObject, TENANT_PROPERTY } from '@/lib/schemaResolver';
import { getDisplayProperty, resolveList, resolveObject } from '@/lib/schemaResolver';
import { jmapQueryAllAndGet } from '@/services/jmap/client';
import type { Schema } from '@/types/schema';
@@ -48,20 +48,14 @@ export function displayNameQuery(schema: Schema, viewOrObjectName: string, id: s
});
}
export function objectOptionsQuery(schema: Schema, viewOrObjectName: string, tenantId: string | null = null) {
export function objectOptionsQuery(schema: Schema, viewOrObjectName: string) {
const objectName = parentObjectName(schema, viewOrObjectName);
const displayProperty = getDisplayProperty(schema, viewOrObjectName);
const scopedTenantId = tenantId !== null && isTenantScoped(schema, viewOrObjectName) ? tenantId : null;
const filtersStatic = resolveList(schema, viewOrObjectName, objectName)?.filtersStatic;
const filter = filtersStatic && Object.keys(filtersStatic).length > 0 ? filtersStatic : undefined;
return queryOptions({
queryKey: jmapKeys.options(objectName, viewOrObjectName, scopedTenantId),
queryKey: jmapKeys.options(objectName, viewOrObjectName),
queryFn: async ({ signal }): Promise<ObjectOption[]> => {
const filtersStatic = resolveList(schema, viewOrObjectName, objectName)?.filtersStatic;
const filter =
scopedTenantId !== null
? { ...filtersStatic, [TENANT_PROPERTY]: scopedTenantId }
: filtersStatic && Object.keys(filtersStatic).length > 0
? filtersStatic
: undefined;
const { list } = await jmapQueryAllAndGet(objectName, { filter }, ['id', displayProperty], { signal });
const options: ObjectOption[] = [];
for (const item of list) {
@@ -75,10 +69,10 @@ export function objectOptionsQuery(schema: Schema, viewOrObjectName: string, ten
const EMPTY_OPTIONS: ObjectOption[] = [];
export function useObjectOptions(viewOrObjectName: string, schema: Schema, tenantId: string | null = null) {
export function useObjectOptions(viewOrObjectName: string, schema: Schema) {
const [requested, setRequested] = useState(false);
const query = useQuery({
...objectOptionsQuery(schema, viewOrObjectName, tenantId),
...objectOptionsQuery(schema, viewOrObjectName),
enabled: requested,
});
const { isError, refetch } = query;
+2 -2
View File
@@ -120,8 +120,8 @@ export function ActionPage({ viewName }: ActionPageProps) {
);
case 'submitting':
return (
<div role="status" className="flex flex-col items-center justify-center gap-3 rounded-2xl bg-muted py-16">
<Loader2 aria-hidden="true" className="size-8 animate-spin text-brand-text" />
<div role="status" className="flex flex-col items-center justify-center gap-3 py-16">
<Loader2 aria-hidden="true" className="h-8 w-8 animate-spin text-muted-foreground" />
<p className="text-muted-foreground">
{t('actions.executing', 'Executing {{label}}...', { label: state.variant.label })}
</p>
+34 -32
View File
@@ -6,10 +6,10 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { ArrowLeft, Zap } from 'lucide-react';
import { Zap } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { FieldRow } from '@/components/forms/FieldRow';
import { FormSectionCard } from '@/components/forms/FormSections';
import { FormProvider } from '@/components/forms/FormProvider';
import { resolveVariantForm } from '@/lib/schemaResolver';
import type { ObjectVariant, Schema } from '@/types/schema';
@@ -55,54 +55,56 @@ export function ActionForm({ schema, variant, initialData, onSubmit, onBack }: A
return (
<form
className="mx-auto max-w-5xl space-y-3.5"
className="space-y-6"
noValidate
onSubmit={(e) => {
e.preventDefault();
handleSubmit();
}}
>
<div className="flex items-start gap-3.5 px-1 pb-1 pt-3">
<Button
type="button"
variant="outline"
size="icon-lg"
className="shrink-0"
onClick={onBack}
aria-label={t('common.back', 'Back')}
>
<ArrowLeft className="h-5 w-5" aria-hidden="true" />
<div className="flex items-center gap-2">
<Button type="button" variant="outline" size="sm" onClick={onBack}>
{t('common.back', 'Back')}
</Button>
<h1 className="page-title min-w-0 flex-1 break-words pt-1">{variant.label}</h1>
<h1 className="text-xl font-semibold">{variant.label}</h1>
</div>
<FormProvider schema={schema} mode="create">
{sections.map((section) => (
<FormSectionCard key={section.fields.map((f) => f.name).join('|')} title={section.title}>
{section.fields.map((ff) => {
const def = fields.properties[ff.name];
if (!def) return null;
return (
<FieldRow
key={ff.name}
formField={ff}
field={def}
value={formData[ff.name]}
onChange={(v) => handleChange(ff.name, v)}
error={errors[ff.name]}
/>
);
})}
</FormSectionCard>
<Card key={section.fields.map((f) => f.name).join('|')}>
{section.title && (
<CardHeader className="pb-3">
<CardTitle className="text-base">{section.title}</CardTitle>
</CardHeader>
)}
<CardContent className={section.title ? 'pt-0' : undefined}>
<div className="space-y-4">
{section.fields.map((ff) => {
const def = fields.properties[ff.name];
if (!def) return null;
return (
<FieldRow
key={ff.name}
formField={ff}
field={def}
value={formData[ff.name]}
onChange={(v) => handleChange(ff.name, v)}
error={errors[ff.name]}
/>
);
})}
</div>
</CardContent>
</Card>
))}
</FormProvider>
<div className="flex justify-end gap-2 pt-1">
<div className="flex justify-end gap-2">
<Button type="button" variant="outline" onClick={onBack}>
{t('common.cancel', 'Cancel')}
</Button>
<Button type="submit">
<Zap aria-hidden="true" />
<Zap aria-hidden="true" className="mr-2 h-4 w-4" />
{t('actions.execute', 'Execute')}
</Button>
</div>
@@ -26,28 +26,23 @@ function ActionGroupSection({
const headingId = useId();
return (
<section aria-labelledby={headingId}>
<h2 id={headingId} className="mb-2 px-1 text-[11px] font-semibold uppercase tracking-wider text-dim">
<h2 id={headingId} className="mb-2 text-sm font-medium text-muted-foreground">
{group.label}
</h2>
<div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
<div className="grid gap-2 sm:grid-cols-2">
{group.actions.map(({ variant, name }) => (
<Button
key={variant.name}
variant="outline"
className="group h-auto justify-between gap-3 whitespace-normal rounded-2xl px-4 py-3 text-left font-medium"
className="h-auto justify-between px-4 py-3"
disabled={disabled}
onClick={() => onPick(variant)}
>
<span className="flex min-w-0 items-center gap-3">
<span className="grid size-8 shrink-0 place-items-center rounded-[10px] bg-highlight text-highlight-foreground">
<Zap aria-hidden="true" />
</span>
<span className="min-w-0">{name}</span>
<span className="flex items-center gap-2">
<Zap aria-hidden="true" className="h-4 w-4 shrink-0 text-muted-foreground" />
<span>{name}</span>
</span>
<ChevronRight
aria-hidden="true"
className="text-dim transition-transform duration-200 group-hover:translate-x-0.5"
/>
<ChevronRight aria-hidden="true" className="h-4 w-4 text-muted-foreground" />
</Button>
))}
</div>
@@ -57,9 +52,9 @@ function ActionGroupSection({
export function ActionPicker({ title, subtitle, groups, disabled, onPick }: ActionPickerProps) {
return (
<div className="space-y-3.5">
<div className="px-1 pb-1 pt-3">
<h1 className="page-title">{title}</h1>
<div className="space-y-6">
<div>
<h1 className="text-xl font-semibold">{title}</h1>
{subtitle && <p className="mt-1 text-sm text-muted-foreground">{subtitle}</p>}
</div>
<div className="space-y-6">
@@ -23,13 +23,11 @@ export function ActionResult({ schema, variant, data, onNewAction }: ActionResul
const hasData = !!variant.schemaName && Object.keys(data).length > 0;
return (
<div className="space-y-3.5">
<div role="status" className="flex items-center gap-3.5 px-1 pb-1 pt-3">
<span className="grid size-10 shrink-0 place-items-center rounded-full bg-success-soft text-success">
<CircleCheck aria-hidden="true" className="size-5" />
</span>
<div className="min-w-0">
<h1 className="page-title break-words">{variant.label}</h1>
<div className="space-y-6 pt-4">
<div role="status" className="flex items-center gap-3">
<CircleCheck aria-hidden="true" className="h-5 w-5 shrink-0 text-emerald-500" />
<div>
<h1 className="font-medium">{variant.label}</h1>
<p className="text-sm text-muted-foreground">
{t('actions.executedSuccess', 'Action executed successfully.')}
</p>
@@ -45,13 +43,15 @@ export function ActionResult({ schema, variant, data, onNewAction }: ActionResul
visibleFields={new Set(Object.keys(data))}
/>
) : (
<div className="rounded-2xl bg-muted p-10 text-center text-sm text-muted-foreground">
{t('actions.noAdditionalData', 'No additional data returned.')}
</div>
<Card>
<CardContent className="p-6 text-sm text-muted-foreground">
{t('actions.noAdditionalData', 'No additional data returned.')}
</CardContent>
</Card>
)}
<Button onClick={onNewAction}>
<Zap aria-hidden="true" />
<Zap aria-hidden="true" className="mr-2 h-4 w-4" />
{t('actions.executeAnother', 'Execute another action')}
</Button>
</div>
@@ -63,14 +63,12 @@ export function ActionError({ error, onBack }: { error: string; onBack: () => vo
return (
<div className="mx-auto max-w-xl space-y-4 pt-8">
<Card>
<CardContent className="space-y-5 p-6">
<div role="alert" className="flex items-start gap-3.5">
<span className="grid size-10 shrink-0 place-items-center rounded-full bg-destructive-soft text-destructive">
<CircleAlert aria-hidden="true" className="size-5" />
</span>
<div className="min-w-0 pt-0.5">
<h1 className="section-title text-lg">{t('actions.failedTitle', 'Action failed')}</h1>
<p className="mt-1 whitespace-pre-line break-words text-sm text-muted-foreground">{error}</p>
<CardContent className="space-y-4 p-6">
<div role="alert" className="flex items-center gap-3">
<CircleAlert aria-hidden="true" className="h-5 w-5 shrink-0 text-destructive" />
<div>
<h1 className="font-medium">{t('actions.failedTitle', 'Action failed')}</h1>
<p className="mt-1 text-sm text-muted-foreground">{error}</p>
</div>
</div>
<Button variant="outline" onClick={onBack}>
@@ -5,39 +5,35 @@
*/
import { useEffect, useRef, useState, type ReactNode } from 'react';
import { cn } from '@/lib/utils';
export function ChartSizedContainer({
fill = false,
height,
children,
}: {
fill?: boolean;
height: number;
children: (width: number, height: number) => ReactNode;
}) {
const ref = useRef<HTMLDivElement>(null);
const [size, setSize] = useState({ width: 0, height: 0 });
const [width, setWidth] = useState(0);
useEffect(() => {
const el = ref.current;
if (!el) return;
const update = (rawWidth: number, rawHeight: number) => {
const width = Math.round(rawWidth);
const height = Math.round(rawHeight);
if (width <= 0 || height <= 0) return;
setSize((prev) => (prev.width === width && prev.height === height ? prev : { width, height }));
};
const ro = new ResizeObserver((entries) => {
for (const entry of entries) update(entry.contentRect.width, entry.contentRect.height);
for (const entry of entries) {
const w = entry.contentRect.width;
if (w > 0) setWidth(w);
}
});
ro.observe(el);
const rect = el.getBoundingClientRect();
update(rect.width, rect.height);
const w = el.getBoundingClientRect().width;
if (w > 0) setWidth(w);
return () => ro.disconnect();
}, []);
return (
<div ref={ref} className={cn('relative', fill ? 'min-h-[280px] flex-1' : 'h-[280px]')}>
{size.width > 0 && <div className="absolute inset-0">{children(size.width, size.height)}</div>}
<div ref={ref} style={{ height }}>
{width > 0 && children(width, height)}
</div>
);
}
@@ -5,29 +5,38 @@
*/
import { useMemo } from 'react';
import { LineChart, Line, AreaChart, Area, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip } from 'recharts';
import {
LineChart,
Line,
AreaChart,
Area,
BarChart,
Bar,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
} from 'recharts';
import { Info } from 'lucide-react';
import { Card } from '@/components/ui/card';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { HelpTooltip } from '@/components/common/HelpTooltip';
import { ChartTooltipContent, getChartColor } from '@/components/ui/chart';
import type { Chart as ChartSchema, Placement } from '../types/schema';
import { getChartColor } from '@/components/ui/chart';
import { ChartTooltipContent } from '@/components/ui/chart';
import type { Chart as ChartSchema } from '../types/schema';
import type { Metric, Period } from '../types/metrics';
import { bucketTimestamps, bucketValues, getBucketCount, formatTimeTick, formatValue } from '../helpers';
import { ChartSizedContainer } from './ChartSizedContainer';
import { toneClasses } from './tone';
import { cn } from '@/lib/utils';
interface DashboardChartProps {
chart: ChartSchema & Placement;
chart: ChartSchema;
historySamples: Metric[];
historyWindow: { from: Date; to: Date };
period: Period;
className?: string;
}
export function DashboardChart({ chart, historySamples, historyWindow, period, className }: DashboardChartProps) {
const toneClass = toneClasses(chart.tone);
export function DashboardChart({ chart, historySamples, historyWindow, period }: DashboardChartProps) {
const { from, to } = historyWindow;
const bucketCount = getBucketCount(period);
const valueFormat = chart.valueFormat ?? 'number';
@@ -73,7 +82,7 @@ export function DashboardChart({ chart, historySamples, historyWindow, period, c
data,
width: chartWidth,
height: chartHeight,
margin: { top: 6, right: 4, left: 0, bottom: 0 },
margin: { top: 5, right: 10, left: 10, bottom: 5 },
};
const seriesElements = chart.series.map((s, i) => {
@@ -88,11 +97,8 @@ export function DashboardChart({ chart, historySamples, historyWindow, period, c
type="monotone"
dataKey={key}
stroke={color}
strokeWidth={2.25}
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
dot={false}
activeDot={{ r: 3.5, strokeWidth: 0 }}
isAnimationActive={false}
connectNulls
/>
@@ -105,9 +111,8 @@ export function DashboardChart({ chart, historySamples, historyWindow, period, c
dataKey={key}
stroke={color}
fill={color}
fillOpacity={chart.stacked ? 0.35 : 0.14}
fillOpacity={0.3}
strokeWidth={2}
activeDot={{ r: 3.5, strokeWidth: 0 }}
stackId={chart.stacked ? '1' : undefined}
isAnimationActive={false}
connectNulls
@@ -119,8 +124,6 @@ export function DashboardChart({ chart, historySamples, historyWindow, period, c
key={key}
dataKey={key}
fill={color}
radius={chart.stacked ? 0 : [4, 4, 0, 0]}
maxBarSize={28}
stackId={chart.stacked ? '1' : undefined}
isAnimationActive={false}
/>
@@ -130,24 +133,23 @@ export function DashboardChart({ chart, historySamples, historyWindow, period, c
const axes = (
<>
<CartesianGrid vertical={false} className="stroke-border" />
<CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
<XAxis
dataKey="timeLabel"
tick={{ fontSize: 10.5, fill: 'var(--dim)' }}
tick={{ fontSize: 11 }}
className="text-muted-foreground"
tickLine={false}
axisLine={false}
tickMargin={8}
minTickGap={16}
/>
<YAxis
tickFormatter={tickFormatter}
tick={{ fontSize: 10.5, fill: 'var(--dim)' }}
tick={{ fontSize: 11 }}
className="text-muted-foreground"
tickLine={false}
axisLine={false}
width={56}
width={60}
/>
<Tooltip
cursor={chart.kind === 'bar' ? { fill: 'var(--muted)', opacity: 0.6 } : { stroke: 'var(--input)' }}
content={({ active, payload, label }) => (
<ChartTooltipContent
active={active}
@@ -157,6 +159,7 @@ export function DashboardChart({ chart, historySamples, historyWindow, period, c
/>
)}
/>
<Legend iconType="circle" iconSize={8} wrapperStyle={{ fontSize: '12px' }} />
</>
);
@@ -186,32 +189,16 @@ export function DashboardChart({ chart, historySamples, historyWindow, period, c
};
return (
<Card
role="figure"
aria-label={chart.title}
className={cn('flex flex-col gap-3 px-5 pb-3.5 pt-[18px]', toneClass.surface, className)}
>
<div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2">
<div className="flex min-w-0 items-center gap-2">
<h2 className="section-title truncate">{chart.title}</h2>
<Card role="figure" aria-label={chart.title}>
<CardHeader className="pb-2">
<div className="flex items-center gap-2">
<CardTitle className="text-base">{chart.title}</CardTitle>
{chart.description && <HelpTooltip content={chart.description} label={chart.title} icon={Info} />}
</div>
{chart.series.length > 0 && (
<ul className={cn('flex flex-wrap gap-x-3.5 gap-y-1 text-[12.5px]', toneClass.muted)}>
{chart.series.map((s, i) => (
<li key={`${s.label}-${i}`} className="inline-flex items-center gap-1.5">
<span
aria-hidden="true"
className="size-2 shrink-0 rounded-full"
style={{ backgroundColor: getChartColor(i) }}
/>
{s.label}
</li>
))}
</ul>
)}
</div>
<ChartSizedContainer fill={chart.rows === 2}>{(width, height) => renderChart(width, height)}</ChartSizedContainer>
</CardHeader>
<CardContent>
<ChartSizedContainer height={288}>{(width, height) => renderChart(width, height)}</ChartSizedContainer>
</CardContent>
</Card>
);
}
@@ -10,57 +10,20 @@ import { useTranslation } from 'react-i18next';
import { AlertCircle } from 'lucide-react';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useSchemaStore } from '@/stores/schemaStore';
import type { Dashboard, DashboardItem } from '../types/schema';
import type { Dashboard } from '../types/schema';
import type { Metric } from '../types/metrics';
import { useDashboardStore } from '../stores/dashboardStore';
import { useLiveMetricsStore } from '../stores/liveMetricsStore';
import { useClusterNodes, useHistoryMetrics } from '../queries';
import { useCanAccess } from '@/hooks/usePermissions';
import { errorMessage } from '@/lib/jmapErrors';
import {
collectHistoryMetricIds,
collectLiveMetricIds,
dashboardItems,
distinctNodeIds,
nodeOptions,
periodWindow,
} from '../helpers';
import { collectHistoryMetricIds, collectLiveMetricIds, distinctNodeIds, nodeOptions, periodWindow } from '../helpers';
import { StatCard } from './StatCard';
import { DashboardChart } from './DashboardChart';
import { PeriodSelector } from './PeriodSelector';
import { NodeSelector } from './NodeSelector';
import { HeadlineTile } from './HeadlineTile';
import { RankingTile } from './RankingTile';
import { cn } from '@/lib/utils';
const EMPTY_METRICS: Metric[] = [];
const EMPTY_ITEMS: DashboardItem[] = [];
const SPAN_CLASSES = [
'col-span-12 md:col-span-6 xl:col-span-1',
'col-span-12 md:col-span-6 xl:col-span-2',
'col-span-12 md:col-span-6 xl:col-span-3',
'col-span-12 md:col-span-6 xl:col-span-4',
'col-span-12 xl:col-span-5',
'col-span-12 xl:col-span-6',
'col-span-12 xl:col-span-7',
'col-span-12 xl:col-span-8',
'col-span-12 xl:col-span-9',
'col-span-12 xl:col-span-10',
'col-span-12 xl:col-span-11',
'col-span-12',
] as const;
const DEFAULT_SPAN: Record<DashboardItem['type'], number> = {
stat: 3,
chart: 6,
headline: 4,
ranking: 4,
};
function placementClass(item: DashboardItem): string {
return cn(SPAN_CLASSES[(item.span ?? DEFAULT_SPAN[item.type]) - 1], item.rows === 2 && 'xl:row-span-2');
}
interface DashboardViewProps {
dashboardId: string;
@@ -89,9 +52,11 @@ export function DashboardView({ dashboardId, section }: DashboardViewProps) {
}
}, [dashboard, dashboards, navigate, section]);
const items = useMemo(() => (dashboard ? dashboardItems(dashboard) : EMPTY_ITEMS), [dashboard]);
const historyIds = useMemo(() => collectHistoryMetricIds(items), [items]);
const liveIds = useMemo(() => collectLiveMetricIds(items), [items]);
const historyIds = useMemo(
() => (dashboard ? collectHistoryMetricIds(dashboard.cards, dashboard.charts) : new Set<string>()),
[dashboard],
);
const liveIds = useMemo(() => (dashboard ? collectLiveMetricIds(dashboard.cards) : new Set<string>()), [dashboard]);
const history = useHistoryMetrics(period, historyIds, nodeId);
const allNodesHistory = useHistoryMetrics(period, historyIds, null, nodeId === null);
@@ -124,7 +89,7 @@ export function DashboardView({ dashboardId, section }: DashboardViewProps) {
if (!dashboard) {
if (dashboards.length === 0) {
return (
<div className="rounded-2xl bg-muted p-10 text-center text-muted-foreground">
<div className="flex items-center justify-center p-8 text-muted-foreground">
{t('dashboard.noDashboards', 'No dashboards configured.')}
</div>
);
@@ -133,8 +98,8 @@ export function DashboardView({ dashboardId, section }: DashboardViewProps) {
}
return (
<div className="space-y-3.5">
<div className="flex flex-wrap items-end justify-between gap-4 px-1 pb-1 pt-3">
<div className="space-y-6">
<div className="flex flex-wrap items-center justify-between gap-4">
{dashboards.length > 1 && (
<Tabs
className="min-w-0 max-w-full"
@@ -150,7 +115,7 @@ export function DashboardView({ dashboardId, section }: DashboardViewProps) {
</TabsList>
</Tabs>
)}
{dashboards.length === 1 && <h1 className="page-title">{dashboard.label}</h1>}
{dashboards.length === 1 && <h1 className="text-xl font-semibold">{dashboard.label}</h1>}
<div className="ml-auto flex flex-wrap items-center gap-2">
{showNodeSelector && <NodeSelector nodes={nodes} value={nodeId} onChange={setNodeId} />}
@@ -161,7 +126,7 @@ export function DashboardView({ dashboardId, section }: DashboardViewProps) {
{history.isError && (
<div
role="alert"
className="flex items-center gap-2 rounded-xl bg-destructive-soft p-4 text-sm text-destructive"
className="flex items-center gap-2 rounded-lg border border-destructive/50 bg-destructive/10 p-3 text-sm text-destructive"
>
<AlertCircle aria-hidden="true" className="h-4 w-4 shrink-0" />
{errorMessage(history.error, t('dashboard.failedFetchMetrics', 'Failed to fetch metrics'))}
@@ -171,46 +136,37 @@ export function DashboardView({ dashboardId, section }: DashboardViewProps) {
{liveStatus === 'error' && liveError && (
<div
role="alert"
className="flex items-center gap-2 rounded-xl bg-destructive-soft p-4 text-sm text-destructive"
className="flex items-center gap-2 rounded-lg border border-destructive/50 bg-destructive/10 p-3 text-sm text-destructive"
>
<AlertCircle aria-hidden="true" className="h-4 w-4 shrink-0" />
{liveError}
</div>
)}
{items.length > 0 && (
<div className="grid grid-flow-row-dense grid-cols-12 gap-3.5 xl:grid-flow-row">
{items.map((item, i) => {
const key = `${item.type}-${item.title}-${i}`;
const className = placementClass(item);
switch (item.type) {
case 'stat':
return (
<StatCard
key={key}
card={item}
className={className}
historySamples={historySamples}
historyWindow={historyWindow}
/>
);
case 'chart':
return (
<DashboardChart
key={key}
chart={item}
className={className}
historySamples={historySamples}
historyWindow={historyWindow}
period={period}
/>
);
case 'headline':
return <HeadlineTile key={key} headline={item} className={className} historySamples={historySamples} />;
case 'ranking':
return <RankingTile key={key} ranking={item} className={className} historySamples={historySamples} />;
}
})}
{dashboard.cards && dashboard.cards.length > 0 && (
<div className="grid gap-4 grid-cols-[repeat(auto-fit,minmax(220px,1fr))]">
{dashboard.cards.map((card, i) => (
<StatCard
key={`${card.title}-${i}`}
card={card}
historySamples={historySamples}
historyWindow={historyWindow}
/>
))}
</div>
)}
{dashboard.charts && dashboard.charts.length > 0 && (
<div className="space-y-4">
{dashboard.charts.map((chart, i) => (
<DashboardChart
key={`${chart.title}-${i}`}
chart={chart}
historySamples={historySamples}
historyWindow={historyWindow}
period={period}
/>
))}
</div>
)}
</div>
@@ -1,46 +0,0 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: LicenseRef-SEL
*/
import { useTranslation } from 'react-i18next';
import { Card } from '@/components/ui/card';
import { formatPercent } from '@/lib/format';
import { cn } from '@/lib/utils';
import type { Headline, Placement } from '../types/schema';
import type { Metric } from '../types/metrics';
import { headlineRatio } from '../helpers';
import { toneClasses } from './tone';
import { TileHeader } from './TileHeader';
interface HeadlineTileProps {
headline: Headline & Placement;
className?: string;
historySamples: Metric[];
}
export function HeadlineTile({ headline, className, historySamples }: HeadlineTileProps) {
const { t } = useTranslation();
const toneClass = toneClasses(headline.tone);
const ratio = headlineRatio(headline, historySamples);
return (
<Card
role="figure"
aria-label={headline.title}
className={cn('flex min-h-[148px] flex-col gap-3 px-5 pb-5 pt-[18px]', toneClass.surface, className)}
>
<TileHeader icon={headline.icon} title={headline.title} badgeClass={toneClass.badge} />
<div
data-slot="headline-value"
className="font-display text-[2.75rem] font-[750] leading-none tracking-[-0.035em] tabular-nums"
>
{ratio === null ? t('dashboard.noData', 'No data') : formatPercent(ratio * 100)}
</div>
{headline.description && (
<p className={cn('text-[13px] leading-relaxed', toneClass.muted)}>{headline.description}</p>
)}
</Card>
);
}
@@ -5,7 +5,6 @@
*/
import { useTranslation } from 'react-i18next';
import { Server } from 'lucide-react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import type { ClusterNodeInfo } from '../types/metrics';
@@ -31,8 +30,7 @@ export function NodeSelector({ nodes, value, onChange }: NodeSelectorProps) {
return (
<Select value={value === null ? ALL_NODES : String(value)} onValueChange={handleChange}>
<SelectTrigger variant="pill" aria-label={t('dashboard.node', 'Node')}>
<Server aria-hidden="true" className="size-3.5 shrink-0 text-muted-foreground" />
<SelectTrigger className="w-44" aria-label={t('dashboard.node', 'Node')}>
<SelectValue />
</SelectTrigger>
<SelectContent>
@@ -6,7 +6,7 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Calendar, CalendarClock, RefreshCw } from 'lucide-react';
import { Calendar, RefreshCw } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover';
@@ -59,8 +59,7 @@ export function PeriodSelector({ onRefresh, loading }: PeriodSelectorProps) {
<Popover open={customOpen} onOpenChange={setCustomOpen}>
<PopoverAnchor>
<Select value={currentValue} onValueChange={handleSelectChange}>
<SelectTrigger variant="pill" aria-label={t('dashboard.period', 'Period')}>
<CalendarClock aria-hidden="true" className="size-3.5 shrink-0 text-muted-foreground" />
<SelectTrigger className="w-44" aria-label={t('dashboard.period', 'Period')}>
<SelectValue />
</SelectTrigger>
<SelectContent>
@@ -81,7 +80,7 @@ export function PeriodSelector({ onRefresh, loading }: PeriodSelectorProps) {
<PopoverContent className="w-72 p-4" align="end">
<div className="space-y-3">
<h4 className="section-title text-sm">{t('dashboard.customRange', 'Custom range')}</h4>
<h4 className="text-sm font-medium">{t('dashboard.customRange', 'Custom range')}</h4>
<div className="space-y-2">
<Label htmlFor="custom-from" className="text-xs">
{t('dashboard.from', 'From')}
@@ -116,10 +115,10 @@ export function PeriodSelector({ onRefresh, loading }: PeriodSelectorProps) {
size="icon"
onClick={onRefresh}
disabled={loading}
className="size-8"
className="h-9 w-9"
aria-label={t('dashboard.refresh', 'Refresh')}
>
<RefreshCw aria-hidden="true" className={cn('size-4', loading && 'animate-spin')} />
<RefreshCw aria-hidden="true" className={cn('h-4 w-4', loading && 'animate-spin')} />
</Button>
</div>
);
@@ -1,62 +0,0 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: LicenseRef-SEL
*/
import { Card } from '@/components/ui/card';
import { getChartColor } from '@/components/ui/chart';
import { cn } from '@/lib/utils';
import type { Ranking, Placement } from '../types/schema';
import type { Metric } from '../types/metrics';
import { formatValue, rankingEntries } from '../helpers';
import { toneClasses } from './tone';
import { TileHeader } from './TileHeader';
interface RankingTileProps {
ranking: Ranking & Placement;
className?: string;
historySamples: Metric[];
}
export function RankingTile({ ranking, className, historySamples }: RankingTileProps) {
const toneClass = toneClasses(ranking.tone);
const entries = rankingEntries(ranking, historySamples);
const max = entries.reduce((m, e) => Math.max(m, e.value), 0);
const format = ranking.valueFormat ?? 'number';
return (
<Card
role="figure"
aria-label={ranking.title}
className={cn('flex flex-col gap-3.5 px-5 pb-5 pt-[18px]', toneClass.surface, className)}
>
<TileHeader
icon={ranking.icon}
title={ranking.title}
description={ranking.description}
badgeClass={toneClass.badge}
/>
<ul className="grid gap-2.5">
{entries.map((entry, i) => (
<li
key={entry.label}
className="grid grid-cols-[minmax(0,7.5rem)_minmax(0,1fr)_minmax(3.5rem,auto)] items-center gap-3 text-[13px]"
>
<span className="truncate">{entry.label}</span>
<span className={cn('h-2 overflow-hidden rounded-full', toneClass.track)} aria-hidden="true">
<span
className="block h-full rounded-full"
style={{
width: max > 0 ? `${(entry.value / max) * 100}%` : '0%',
backgroundColor: getChartColor(i),
}}
/>
</span>
<span className={cn('text-right tabular-nums', toneClass.muted)}>{formatValue(entry.value, format)}</span>
</li>
))}
</ul>
</Card>
);
}
+42 -77
View File
@@ -6,29 +6,20 @@
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { ArrowDownRight, ArrowUpRight, HelpCircle, Info, Minus } from 'lucide-react';
import { HelpCircle, Info } from 'lucide-react';
import { DynamicIcon } from '@/components/common/DynamicIcon';
import { LineChart, Line } from 'recharts';
import { Card } from '@/components/ui/card';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { HelpTooltip } from '@/components/common/HelpTooltip';
import type { Card as CardSchema, Placement } from '../types/schema';
import type { Card as CardSchema } from '../types/schema';
import type { Metric } from '../types/metrics';
import { cardValue, deltaSentiment, formatValue, sparklineData, computeDelta } from '../helpers';
import { cardValue, formatValue, sparklineData, computeDelta } from '../helpers';
import { useLiveMetricsStore } from '../stores/liveMetricsStore';
import { getChartColor } from '@/components/ui/chart';
import { formatPercent } from '@/lib/format';
import { cn } from '@/lib/utils';
import { toneClasses } from './tone';
function DeltaBadge({
pct,
direction,
className,
}: {
pct: number;
direction: 'up' | 'down' | 'neutral';
className: string;
}) {
function DeltaBadge({ pct, direction }: { pct: number; direction: 'up' | 'down' | 'neutral' }) {
const { t } = useTranslation();
const value = formatPercent(Math.abs(pct), Number.isInteger(pct) ? 0 : 1);
const label =
@@ -37,30 +28,23 @@ function DeltaBadge({
: direction === 'down'
? t('dashboard.deltaDown', 'Down {{value}}', { value })
: t('dashboard.deltaNone', 'No change');
const Icon = direction === 'up' ? ArrowUpRight : direction === 'down' ? ArrowDownRight : Minus;
return (
<span
className={cn(
'inline-flex h-[22px] items-center gap-1 rounded-full px-2 text-xs font-semibold tabular-nums',
className,
)}
>
<Badge variant="secondary" className="text-xs font-normal text-muted-foreground">
<span className="sr-only">{label}</span>
<Icon aria-hidden="true" className="size-3" />
{direction !== 'neutral' && <span aria-hidden="true">{value}</span>}
</span>
<span aria-hidden="true">
{direction === 'up' ? `\u2191 ${value}` : direction === 'down' ? `\u2193 ${value}` : '\u2013'}
</span>
</Badge>
);
}
interface StatCardProps {
card: CardSchema & Placement;
className?: string;
card: CardSchema;
historySamples: Metric[];
historyWindow: { from: Date; to: Date };
}
export function StatCard({ card, className, historySamples, historyWindow }: StatCardProps) {
const toneClass = toneClasses(card.tone);
export function StatCard({ card, historySamples, historyWindow }: StatCardProps) {
const liveSnapshot = useLiveMetricsStore((s) => s.snapshot);
const value = useMemo(() => {
@@ -89,55 +73,36 @@ export function StatCard({ card, className, historySamples, historyWindow }: Sta
}, [card, historySamples, from, to]);
return (
<Card
role="group"
aria-label={card.title}
className={cn('flex min-h-[148px] flex-col gap-2.5 px-5 pb-4 pt-[18px]', toneClass.surface, className)}
>
<div className={cn('flex min-w-0 items-center gap-2.5 text-[13px] font-medium', toneClass.muted)}>
<span className={cn('grid size-9 shrink-0 place-items-center rounded-[11px]', toneClass.badge)}>
<DynamicIcon name={card.icon} fallback={HelpCircle} className="size-[17px]" />
</span>
<span className="min-w-0 truncate">{card.title}</span>
{card.description && <HelpTooltip content={card.description} label={card.title} icon={Info} />}
</div>
<div
data-slot="stat-value"
className="font-display text-[1.75rem] font-bold leading-none tracking-[-0.03em] tabular-nums"
>
{formattedValue}
</div>
{(delta || sparkline) && (
<div className="mt-auto flex items-end justify-between gap-3">
{delta && (
<DeltaBadge
pct={delta.pct}
direction={delta.direction}
className={toneClass.sentiment[deltaSentiment(delta.direction, card.polarity)]}
/>
)}
{sparkline && (
<LineChart
className="ml-auto"
width={120}
height={36}
data={sparkline}
margin={{ top: 2, right: 2, bottom: 2, left: 2 }}
>
<Line
type="monotone"
dataKey="v"
stroke={toneClass.accentColor ?? getChartColor(0)}
strokeWidth={2}
dot={false}
isAnimationActive={false}
/>
</LineChart>
)}
<Card role="group" aria-label={card.title}>
<CardContent className="p-4">
<div className="flex items-center gap-2">
<DynamicIcon name={card.icon} fallback={HelpCircle} className="h-4 w-4 text-muted-foreground" />
<span className="text-sm font-medium text-muted-foreground">{card.title}</span>
{card.description && <HelpTooltip content={card.description} label={card.title} icon={Info} />}
</div>
)}
<div data-slot="stat-value" className="mt-2 text-2xl font-bold">
{formattedValue}
</div>
{(delta || sparkline) && (
<div className="mt-1 flex items-center gap-2">
{delta && <DeltaBadge pct={delta.pct} direction={delta.direction} />}
{sparkline && (
<LineChart width={64} height={32} data={sparkline}>
<Line
type="monotone"
dataKey="v"
stroke={getChartColor(0)}
strokeWidth={1.5}
dot={false}
isAnimationActive={false}
/>
</LineChart>
)}
</div>
)}
</CardContent>
</Card>
);
}
@@ -1,34 +0,0 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: LicenseRef-SEL
*/
import { HelpCircle, Info } from 'lucide-react';
import { DynamicIcon } from '@/components/common/DynamicIcon';
import { HelpTooltip } from '@/components/common/HelpTooltip';
import { cn } from '@/lib/utils';
export function TileHeader({
icon,
title,
description,
badgeClass,
}: {
icon?: string;
title: string;
description?: string;
badgeClass: string;
}) {
return (
<div className="flex min-w-0 items-center gap-2.5">
{icon && (
<span className={cn('grid size-9 shrink-0 place-items-center rounded-[11px]', badgeClass)}>
<DynamicIcon name={icon} fallback={HelpCircle} className="size-[17px]" />
</span>
)}
<h2 className="section-title truncate">{title}</h2>
{description && <HelpTooltip content={description} label={title} icon={Info} />}
</div>
);
}
-72
View File
@@ -1,72 +0,0 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: LicenseRef-SEL
*/
import type { Tone } from '../types/schema';
import type { DeltaSentiment } from '../helpers';
interface ToneClasses {
surface: string;
badge: string;
muted: string;
track: string;
accentColor: string | undefined;
sentiment: Record<DeltaSentiment, string>;
}
const TONES: Record<Tone | 'default', ToneClasses> = {
default: {
surface: '',
badge: 'bg-highlight text-highlight-foreground',
muted: 'text-muted-foreground',
track: 'bg-muted',
accentColor: undefined,
sentiment: {
good: 'bg-success-soft text-success',
bad: 'bg-destructive-soft text-destructive',
neutral: 'bg-muted text-muted-foreground',
},
},
flat: {
surface: 'bg-muted shadow-none',
badge: 'bg-card text-highlight-foreground',
muted: 'text-muted-foreground',
track: 'bg-card',
accentColor: undefined,
sentiment: {
good: 'bg-card text-success',
bad: 'bg-card text-destructive',
neutral: 'bg-card text-muted-foreground',
},
},
accent: {
surface: 'bg-highlight shadow-none',
badge: 'bg-card text-highlight-foreground',
muted: 'text-foreground/70',
track: 'bg-card',
accentColor: undefined,
sentiment: {
good: 'bg-card text-success',
bad: 'bg-card text-destructive',
neutral: 'bg-card text-muted-foreground',
},
},
ink: {
surface: 'bg-clay text-clay-foreground shadow-none',
badge: 'bg-card text-highlight-foreground',
muted: 'text-clay-muted',
track: 'bg-card',
accentColor: undefined,
sentiment: {
good: 'bg-card text-success',
bad: 'bg-card text-destructive',
neutral: 'bg-card text-muted-foreground',
},
},
};
export function toneClasses(tone: Tone | undefined): ToneClasses {
return TONES[tone ?? 'default'];
}
+29 -90
View File
@@ -5,17 +5,7 @@
*/
import type { ClusterNodeInfo, Metric, MetricId, Period, PresetKey } from './types/metrics';
import type {
Aggregate,
Card,
Dashboard,
DashboardItem,
Headline,
MetricFormat,
MetricScope,
Polarity,
Ranking,
} from './types/schema';
import type { Aggregate, Card, Chart, MetricFormat, MetricScope } from './types/schema';
import { PRESET_MS, BUCKET_CONFIG, CUSTOM_BUCKET_COUNT, SPARKLINE_BUCKET_COUNT } from './types/metrics';
import { formatCompactNumber, formatDate, formatElapsed, formatPercent, formatSize, formatTime } from '@/lib/format';
@@ -89,27 +79,9 @@ function pushValue(groups: Map<number, number[]>, nodeId: number, value: number)
else groups.set(nodeId, [value]);
}
const samplesByMetric = new WeakMap<Metric[], Map<MetricId, Metric[]>>();
function indexSamples(samples: Metric[]): Map<MetricId, Metric[]> {
let index = samplesByMetric.get(samples);
if (!index) {
index = new Map();
for (const m of samples) {
const list = index.get(m.metric);
if (list) list.push(m);
else index.set(m.metric, [m]);
}
samplesByMetric.set(samples, index);
}
return index;
}
export function selectSamples(target: MetricTarget, samples: Metric[]): Metric[] {
const index = indexSamples(samples);
const unique = new Set(target.metrics);
if (unique.size === 1) return index.get(target.metrics[0]) ?? [];
return [...unique].flatMap((id) => index.get(id) ?? []);
const ids = new Set(target.metrics);
return samples.filter((m) => ids.has(m.metric));
}
export function latestSamples(samples: Metric[]): Metric[] {
@@ -347,66 +319,33 @@ export function formatTimeTick(date: Date, period: Period): string {
return intraday ? formatTime(date) : formatDate(date, TICK_DATE);
}
export function dashboardItems(dashboard: Dashboard): DashboardItem[] {
if (dashboard.items && dashboard.items.length > 0) return dashboard.items;
const charts = dashboard.charts ?? [];
return [
...(dashboard.cards ?? []).map((card): DashboardItem => ({ type: 'stat', ...card })),
...charts.map((chart, i): DashboardItem => ({
type: 'chart',
...chart,
...(charts.length % 2 === 1 && i === charts.length - 1 && { span: 12 }),
})),
];
}
function itemHistoryMetrics(item: DashboardItem): MetricId[] {
switch (item.type) {
case 'stat':
return item.source === 'history' ? item.metrics : [];
case 'chart':
case 'ranking':
return item.series.flatMap((series) => series.metrics);
case 'headline':
return [...item.numerator, ...item.denominator];
export function collectHistoryMetricIds(cards: Card[] | undefined, charts: Chart[] | undefined): Set<MetricId> {
const ids = new Set<MetricId>();
if (cards) {
for (const card of cards) {
if (card.source === 'history') {
for (const id of card.metrics) ids.add(id);
}
}
}
if (charts) {
for (const chart of charts) {
for (const series of chart.series) {
for (const id of series.metrics) ids.add(id);
}
}
}
return ids;
}
export function collectHistoryMetricIds(items: readonly DashboardItem[]): Set<MetricId> {
return new Set(items.flatMap(itemHistoryMetrics));
}
export function collectLiveMetricIds(items: readonly DashboardItem[]): Set<MetricId> {
return new Set(items.flatMap((item) => (item.type === 'stat' && item.source === 'live' ? item.metrics : [])));
}
export function headlineRatio(headline: Headline, samples: Metric[]): number | null {
const reduce = (metrics: MetricId[]) => {
const target = { metrics, aggregate: headline.aggregate, scope: headline.scope };
return reduceSamples(target, selectSamples(target, samples)) ?? 0;
};
const denominator = reduce(headline.denominator);
if (denominator <= 0) return null;
return reduce(headline.numerator) / denominator;
}
interface RankingEntry {
label: string;
value: number;
}
export function rankingEntries(ranking: Ranking, samples: Metric[]): RankingEntry[] {
return ranking.series
.map((series) => ({ label: series.label, value: reduceSamples(series, selectSamples(series, samples)) ?? 0 }))
.sort((a, b) => b.value - a.value);
}
export type DeltaSentiment = 'good' | 'bad' | 'neutral';
export function deltaSentiment(
direction: 'up' | 'down' | 'neutral',
polarity: Polarity = 'higherIsBetter',
): DeltaSentiment {
if (direction === 'neutral' || polarity === 'neutral') return 'neutral';
return (direction === 'up') === (polarity === 'higherIsBetter') ? 'good' : 'bad';
export function collectLiveMetricIds(cards: Card[] | undefined): Set<MetricId> {
const ids = new Set<MetricId>();
if (cards) {
for (const card of cards) {
if (card.source === 'live') {
for (const id of card.metrics) ids.add(id);
}
}
}
return ids;
}
Loaded 100 of 128 files, more files were not shown because too many files have changed in this diff. Show more