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

No files matched your search

-83
View File
@@ -2,89 +2,6 @@
All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/).
## [2.1.1] - 2026-11-23
### Added
- Mail Rules editor: rules that apply only while the vacation response is in effect, stop-only rules, and replies sent to every message.
### Changed
- Mail Rules editor follows the new rule format: conditions that must all match, alternatives of which at least one must match, and exceptions, each explained in plain words.
- Rule page with a summary of what the rule does, a Conditions step and an Actions step. Each action appears at most once, as a card added from grouped buttons.
- Trash and Junk are ordinary move and copy targets, and read, flagged and not spam are shown by name instead of as keywords.
- The rule summary is fully translatable: whole-sentence templates, plural forms and lists joined for the user's locale.
## [2.1.0] - 2026-11-18
### Added
- Mail Rules editor under Account > Filters & Auto-Replies:
- Rules listed as readable sentences, with an enable switch and reordering by drag and drop, keyboard or menu.
- Rule builder with "all / any" conditions, exceptions and actions on compact rows.
- Blocked senders and Safe senders pages under Account > Filters & Auto-Replies.
- Vacation Response page with a date range picker.
- Weekly schedule editor for working hours (Account > Calendars > Settings) and mail rule schedules.
- Searchable time zone picker that shows UTC offsets and offers the browser's time zone.
- Local time and local date fields, with a time input that follows the 12-hour or 24-hour clock of the user's locale.
- Pasting several values at once into list fields, with duplicate and invalid entry reporting.
### Changed
- Map entries use the value format their key declares in the schema, so the maximum disk space quota is entered with the size field (unit selector) and shown with units.
- Account pages follow the account selected in the top bar, including management settings.
- Forms check required fields and minimum item counts inside nested lists before saving.
### Fixed
- Lists below their minimum number of entries are reported on the field before saving.
- On phones, select menus no longer cut off long labels, popovers keep a margin from the screen edge, and object pickers no longer show an empty row.
- Search boxes use a clear button that matches the theme.
- Switching an object to another variant (for example an MTA route from Local to MX) no longer fails with "name: required": unchanged immutable fields are now sent with the new variant.
## [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 -89
View File
@@ -1,20 +1,14 @@
{
"name": "stalwart-webui",
"version": "2.1.1",
"version": "2.0.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "stalwart-webui",
"version": "2.1.1",
"version": "2.0.1",
"dependencies": {
"@daypicker/react": "^10.0.2",
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.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",
@@ -70,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": {
@@ -390,59 +385,6 @@
}
}
},
"node_modules/@dnd-kit/accessibility": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/@dnd-kit/accessibility/-/accessibility-3.1.1.tgz",
"integrity": "sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==",
"license": "MIT",
"dependencies": {
"tslib": "^2.0.0"
},
"peerDependencies": {
"react": ">=16.8.0"
}
},
"node_modules/@dnd-kit/core": {
"version": "6.3.1",
"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz",
"integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==",
"license": "MIT",
"dependencies": {
"@dnd-kit/accessibility": "^3.1.1",
"@dnd-kit/utilities": "^3.2.2",
"tslib": "^2.0.0"
},
"peerDependencies": {
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
}
},
"node_modules/@dnd-kit/sortable": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/@dnd-kit/sortable/-/sortable-10.0.0.tgz",
"integrity": "sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg==",
"license": "MIT",
"dependencies": {
"@dnd-kit/utilities": "^3.2.2",
"tslib": "^2.0.0"
},
"peerDependencies": {
"@dnd-kit/core": "^6.3.0",
"react": ">=16.8.0"
}
},
"node_modules/@dnd-kit/utilities": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/@dnd-kit/utilities/-/utilities-3.2.2.tgz",
"integrity": "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==",
"license": "MIT",
"dependencies": {
"tslib": "^2.0.0"
},
"peerDependencies": {
"react": ">=16.8.0"
}
},
"node_modules/@emnapi/core": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.1.tgz",
@@ -643,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",
@@ -2794,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",
@@ -2866,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",
@@ -3247,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",
@@ -3323,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",
@@ -3467,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",
@@ -3891,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",
@@ -4125,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",
@@ -4141,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",
@@ -5650,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",
@@ -6434,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",
@@ -6542,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",
@@ -7246,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",
@@ -7268,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",
+4 -8
View File
@@ -1,7 +1,7 @@
{
"name": "stalwart-webui",
"private": true,
"version": "2.1.1",
"version": "2.0.1",
"stalwart": {
"minServerVersion": "1.0.0"
},
@@ -12,18 +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",
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.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",
@@ -79,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 -11
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,14 +36,11 @@ export function ObjectPicker({ schema, objectName, label, value, onChange, onCle
const noPermissionMessage = useNoPermissionMessage(schema, objectName);
return (
<ObjectFieldFrame disabled={!!noPermissionMessage} single>
<div className="flex items-center gap-2 flex-wrap">
{value && (
<Badge
variant="secondary"
className="h-7 min-w-0 max-w-full gap-1 sm:max-w-xs 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}
@@ -53,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}
@@ -71,6 +68,6 @@ export function ObjectPicker({ schema, objectName, label, value, onChange, onCle
onSelect={onChange}
disabledMessage={noPermissionMessage}
/>
</ObjectFieldFrame>
</div>
);
}
+9 -60
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,37 +25,6 @@ export interface ObjectSearchPopoverProps {
disabled?: boolean;
label: string;
control?: ControlProps;
placeholder?: string;
}
export function ObjectFieldFrame({
disabled,
single,
children,
}: {
disabled?: boolean;
single?: boolean;
children: ReactNode;
}) {
return (
<div
data-slot="object-field"
className={cn(
'field-surface flex min-h-9 w-full items-center gap-1.5 rounded-lg p-1',
single ? 'flex-nowrap' : 'flex-wrap',
disabled && 'opacity-60',
)}
>
{children}
</div>
);
}
const INLINE_TRIGGER =
'h-7 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';
function inlineTrigger(placeholder: string): string {
return cn(INLINE_TRIGGER, placeholder ? 'min-w-[6rem]' : 'min-w-8 justify-end');
}
export function ObjectSearchPopover({
@@ -70,7 +37,6 @@ export function ObjectSearchPopover({
disabled,
label,
control,
placeholder,
}: ObjectSearchPopoverProps) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
@@ -84,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' : inlineTrigger(placeholder),
)}
size="icon"
className="h-7 w-7 cursor-not-allowed opacity-60"
aria-label={label}
aria-disabled="true"
onClick={(e) => {
@@ -97,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>
@@ -118,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'
: inlineTrigger(placeholder)
}
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>
@@ -141,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>
@@ -174,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" />
</>
);
}
-59
View File
@@ -1,59 +0,0 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import { useRef, type ComponentProps } from 'react';
import { useTranslation } from 'react-i18next';
import { Search, X } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { cn } from '@/lib/utils';
type SearchInputProps = Omit<ComponentProps<typeof Input>, 'type' | 'value' | 'onChange'> & {
value: string;
onValueChange: (value: string) => void;
icon?: boolean;
};
export function SearchInput({ value, onValueChange, icon = false, className, ...props }: SearchInputProps) {
const { t } = useTranslation();
const input = useRef<HTMLInputElement>(null);
const clear = () => {
onValueChange('');
input.current?.focus();
};
return (
<div data-slot="search-input" className="relative w-full">
{icon && (
<Search
className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-dim"
aria-hidden="true"
/>
)}
<Input
{...props}
ref={input}
type="search"
value={value}
onChange={(event) => onValueChange(event.target.value)}
className={cn(
'[&::-webkit-search-cancel-button]:appearance-none',
icon && 'pl-9',
value !== '' && 'pr-9',
className,
)}
/>
{value !== '' && !props.disabled && (
<button
type="button"
onClick={clear}
aria-label={t('common.clearSearch', 'Clear search')}
className="absolute right-1.5 top-1/2 grid size-6 -translate-y-1/2 place-items-center rounded-md text-dim transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<X className="size-3.5" aria-hidden="true" />
</button>
)}
</div>
);
}
-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>
+62 -185
View File
@@ -4,36 +4,24 @@
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import { useEffect, useId, useState, useSyncExternalStore, type ComponentType } 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, type DynamicFormOptions } from '@/components/forms/useDynamicForm';
import type { FieldValues, RenderableSection } from '@/components/forms/formLogic';
import { cn } from '@/lib/utils';
import { useDynamicForm, type DynamicFormModel } from '@/components/forms/useDynamicForm';
const SECTION_INDEX_MIN = 3;
export interface AfterSectionsProps {
data: FieldValues;
readOnly: boolean;
}
interface DynamicFormProps extends DynamicFormOptions {
interface DynamicFormProps {
viewName: string;
objectId: string | null;
afterSections?: ComponentType<AfterSectionsProps>;
}
function capitalize(text: string): string {
@@ -55,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">
@@ -138,25 +52,15 @@ function Loading({ label }: { label: string }) {
);
}
export function DynamicForm({
viewName,
objectId,
accountId,
fieldOverrides,
createValues,
showCreatedValues,
afterSections: AfterSections,
}: DynamicFormProps) {
export function DynamicForm({ viewName, objectId }: DynamicFormProps) {
const { t } = useTranslation();
const navigate = useNavigate();
const canUpdate = useCanAccess(viewName, 'Update');
const canDestroy = useCanAccess(viewName, 'Destroy');
const model = useDynamicForm(viewName, objectId, { accountId, fieldOverrides, createValues, showCreatedValues });
const model = useDynamicForm(viewName, objectId);
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...')} />;
@@ -167,19 +71,18 @@ export function DynamicForm({
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>
@@ -187,9 +90,9 @@ export function DynamicForm({
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}>
@@ -205,93 +108,67 @@ export function DynamicForm({
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}
renderers={fieldOverrides?.render}
variant={
sch.type === 'multiple'
? { variants: sch.variants, value: state.variant, onChange: model.setVariant }
: undefined
}
/>
{AfterSections && <AfterSections data={state.data} readOnly={readOnly} />}
</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
+34 -42
View File
@@ -11,9 +11,10 @@ import { Label } from '@/components/ui/label';
import { Markdown } from '@/components/common/Markdown';
import { HelpTooltip } from '@/components/common/HelpTooltip';
import { FieldValue } from '@/components/values/FieldValue';
import { SievepadButton } from '@/components/forms/SievepadButton';
import { FieldScopeProvider } from '@/components/forms/FormProvider';
import { FieldControl } from '@/components/forms/widgets/FieldControl';
import { resolveWidget } from '@/extensions/widgets';
import { widgetTraits } from '@/components/forms/widgets/registry';
import { fieldIds, isEnterpriseLockedIn, useFieldScope, useFormContext } from '@/components/forms/formContext';
import { requiredMarker } from '@/components/forms/formLogic';
import { resolveObject } from '@/lib/schemaResolver';
@@ -43,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 && (
@@ -69,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>
);
@@ -93,7 +94,7 @@ export function FieldRow({ field, formField, value, onChange, error, readOnly: f
referencesLocked ||
field.update === 'serverSet' ||
(topLevel && ctx.mode === 'edit' && field.update === 'immutable');
const { traits, RowAddon } = resolveWidget(ft);
const traits = widgetTraits(ft);
const asValue = readOnly && traits.readOnlyAsValue;
const marker = requiredMarker(field, readOnly);
const describedBy =
@@ -106,12 +107,19 @@ export function FieldRow({ field, formField, value, onChange, error, readOnly: f
'aria-required': marker === 'required' && ARIA_REQUIRED_TYPES.has(ft.type) ? true : undefined,
};
const widgetProps = { type: ft, field, formField, value, onChange, readOnly, control, error };
let body: ReactNode = asValue ? (
<FieldValue schema={ctx.schema} type={ft} value={value} />
) : (
<FieldScopeProvider name={formField.name} readOnly={readOnly}>
<FieldControl {...widgetProps} />
<FieldControl
type={ft}
field={field}
formField={formField}
value={value}
onChange={onChange}
readOnly={readOnly}
control={control}
/>
</FieldScopeProvider>
);
if (!asValue && traits.labelMode === 'group') {
@@ -124,48 +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}
{RowAddon && <RowAddon {...widgetProps} />}
<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>
{RowAddon && <RowAddon {...widgetProps} />}
{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 -38
View File
@@ -5,12 +5,11 @@
*/
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';
import type { FieldOverrides } from '@/components/forms/useDynamicForm';
interface VariantControl {
variants: readonly EmbeddedVariant[];
@@ -20,29 +19,18 @@ interface VariantControl {
interface FormSectionsProps {
sections: RenderableSection[];
sectionId?: (key: string) => string;
data: FieldValues;
errors: FieldErrors;
readOnly: boolean;
onFieldChange: (name: string, value: unknown) => void;
variant?: VariantControl;
renderers?: FieldOverrides['render'];
}
export function FormSections({
sections,
sectionId,
data,
errors,
readOnly,
onFieldChange,
variant,
renderers,
}: 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;
@@ -57,20 +45,6 @@ export function FormSections({
/>
);
}
const Render = renderers && Object.hasOwn(renderers, formField.name) ? renderers[formField.name] : null;
if (Render) {
return (
<Render
key={formField.name}
field={field}
formField={formField}
data={data}
errors={errors}
readOnly={readOnly}
onFieldChange={onFieldChange}
/>
);
}
return (
<FieldRow
key={formField.name}
@@ -88,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 -10
View File
@@ -14,8 +14,6 @@ import { Label } from '@/components/ui/label';
import { ConfirmDialog } from '@/components/common/ConfirmDialog';
import { toast } from '@/hooks/use-toast';
import { dismissSievepadWarning, isSievepadWarningDismissed, openInSievepad } from '@/lib/sievepad';
import { useFormContext } from '@/components/forms/formContext';
import type { WidgetProps } from '@/components/forms/widgets/types';
interface SievepadButtonProps {
scriptName: string;
@@ -50,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>
@@ -66,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}
@@ -80,8 +78,3 @@ export function SievepadButton({ scriptName, source }: SievepadButtonProps) {
</>
);
}
export function SievepadRowAddon({ value }: WidgetProps) {
const { recordLabel } = useFormContext();
return <SievepadButton scriptName={recordLabel} source={typeof value === 'string' ? value : ''} />;
}
+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>
);
}
-13
View File
@@ -18,7 +18,6 @@ export interface FormContextValue {
idPrefix: string;
recordLabel: string;
baseline: unknown;
tenantId: string | null;
}
export interface FieldScope {
@@ -30,10 +29,6 @@ export const FormContext = createContext<FormContextValue | null>(null);
export const FieldScopeContext = createContext<FieldScope>({ path: [], readOnly: false });
export const PanelContext = createContext(false);
export const EnclosingSchemaContext = createContext<string | null>(null);
export function useFormContext(): FormContextValue {
const ctx = useContext(FormContext);
if (!ctx) throw new Error('Form widgets must be rendered inside a FormProvider');
@@ -44,14 +39,6 @@ export function useFieldScope(): FieldScope {
return useContext(FieldScopeContext);
}
export function useInPanel(): boolean {
return useContext(PanelContext);
}
export function useEnclosingSchema(): string | null {
return useContext(EnclosingSchemaContext);
}
export function isEnterpriseLockedIn(ctx: FormContextValue, enterprise: boolean | undefined): boolean {
return !!enterprise && ctx.isCommunity;
}
+22 -208
View File
@@ -9,22 +9,9 @@ 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 { parseLocalDate, parseLocalTime } from '@/lib/localDateTime';
import { WORKING_HOURS_SLOT, isScheduleInvalid, scheduleRules } from '@/lib/weeklySchedule';
import { widgetTraits } from '@/extensions/widgets';
import type { BlobUpload } from '@/services/jmap/client';
import type { JmapSetError, ValidationError } from '@/types/jmap';
import type {
Field,
FieldType,
Fields,
Form,
FormField,
MapValueType,
ScalarType,
Schema,
StringFormat,
} from '@/types/schema';
import type { Field, FieldType, Fields, Form, FormField, Schema } from '@/types/schema';
import type { FormMode } from '@/components/forms/formContext';
export type FieldValues = Record<string, unknown>;
@@ -80,180 +67,40 @@ export function requiredMarker(field: Field, readOnly: boolean): 'required' | 'o
return isNullable(field.type) ? 'optional' : 'required';
}
function itemCount(value: unknown): number {
return isRecord(value) ? Object.keys(value).length : 0;
}
function isMissingNestedValue(schema: Schema, field: Field, value: unknown): boolean {
if (field.update === 'serverSet') return false;
if (isRequiredField(field) && isMissingValue(value)) return true;
const { type } = field;
switch (type.type) {
case 'object':
return hasMissingNested(schema, type.objectName, value);
case 'objectList':
return (
(type.minItems != null && itemCount(value) < type.minItems) ||
(isRecord(value) && Object.values(value).some((item) => hasMissingNested(schema, type.objectName, item)))
);
case 'set':
return type.minItems != null && itemCount(value) < type.minItems;
default:
return false;
}
}
export function missingNestedFields(schema: Schema, objectName: string, value: unknown): string[] {
if (!isRecord(value)) return [];
const resolved = resolveEmbedded(schema, objectName, value);
if (!resolved) return [];
return embeddedEntries(resolved)
.filter(({ formField, field }) => isMissingNestedValue(schema, field, value[formField.name]))
.map(({ formField }) => formField.name);
}
function hasMissingNested(schema: Schema, objectName: string, value: unknown): boolean {
if (!isRecord(value)) return false;
const resolved = resolveEmbedded(schema, objectName, value);
if (!resolved) return false;
return embeddedEntries(resolved).some(({ formField, field }) =>
isMissingNestedValue(schema, field, value[formField.name]),
);
}
export function mergeFieldErrors(required: FieldErrors, custom: FieldErrors, format: FieldErrors): FieldErrors {
return { ...required, ...custom, ...format };
}
export interface RequiredMessages {
required: string;
minItems: (count: number) => string;
}
function tooFewItems(type: FieldType, value: unknown): number | null {
if (type.type !== 'set' && type.type !== 'objectList') return null;
return type.minItems != null && itemCount(value) < type.minItems ? type.minItems : null;
for (const { formField, field } of embeddedEntries(resolved)) {
if (field.update === 'serverSet') continue;
const nested = value[formField.name];
if (isRequiredField(field) && isMissingValue(nested)) return true;
if (field.type.type === 'object' && hasMissingNested(schema, field.type.objectName, nested)) return true;
}
return false;
}
export function validateRequired(
data: FieldValues,
fields: Fields,
mode: FormMode,
messages: RequiredMessages | string,
message: string,
visible?: ReadonlySet<string>,
schema?: Schema,
): FieldErrors {
const required = typeof messages === 'string' ? messages : messages.required;
const errors: FieldErrors = {};
for (const [name, field] of Object.entries(fields.properties)) {
if (visible && !visible.has(name)) continue;
const value = data[name];
if (isRequiredField(field, mode) && isMissingValue(value)) {
errors[name] = required;
continue;
if (isRequiredField(field, mode) && isMissingValue(data[name])) errors[name] = message;
else if (
schema &&
field.type.type === 'object' &&
field.update !== 'serverSet' &&
!(mode === 'edit' && field.update === 'immutable') &&
hasMissingNested(schema, field.type.objectName, data[name])
) {
errors[name] = message;
}
if (!schema || field.update === 'serverSet' || (mode === 'edit' && field.update === 'immutable')) continue;
const { type } = field;
const minItems = tooFewItems(type, value);
if (minItems !== null) {
errors[name] = typeof messages === 'string' ? messages : messages.minItems(minItems);
} else if ((type.type === 'object' || type.type === 'objectList') && isMissingNestedValue(schema, field, value)) {
errors[name] = required;
}
}
return errors;
}
export type ValidatedFormat = Extract<StringFormat, 'localTime' | 'localDate'> | 'weeklySchedule';
export type FormatMessages = Record<ValidatedFormat, string>;
function invalidString(format: StringFormat, value: unknown): ValidatedFormat | null {
if (typeof value !== 'string' || value === '') return null;
switch (format) {
case 'localTime':
return parseLocalTime(value) === null ? format : null;
case 'localDate':
return parseLocalDate(value) === null ? format : null;
default:
return null;
}
}
function invalidScalar(type: ScalarType | MapValueType, value: unknown): ValidatedFormat | null {
return type.type === 'string' ? invalidString(type.format, value) : null;
}
function invalidNested(schema: Schema, objectName: string, value: unknown): ValidatedFormat | null {
if (!isRecord(value)) return null;
const resolved = resolveEmbedded(schema, objectName, value);
if (!resolved) return null;
for (const { formField, field } of embeddedEntries(resolved)) {
if (field.update === 'serverSet') continue;
const invalid = invalidValue(schema, field.type, value[formField.name], resolved.schemaName);
if (invalid) return invalid;
}
return null;
}
function invalidValue(
schema: Schema,
type: FieldType,
value: unknown,
container: string | null,
): ValidatedFormat | null {
switch (type.type) {
case 'string':
return invalidString(type.format, value);
case 'object':
return invalidNested(schema, type.objectName, value);
case 'objectList':
if (!isRecord(value)) return null;
if (type.objectName === WORKING_HOURS_SLOT && isScheduleInvalid(value, scheduleRules(container), type.minItems)) {
return 'weeklySchedule';
}
for (const item of Object.values(value)) {
const invalid = invalidNested(schema, type.objectName, item);
if (invalid) return invalid;
}
return null;
case 'set':
if (!isRecord(value)) return null;
for (const key of Object.keys(value)) {
const invalid = invalidScalar(type.class, key);
if (invalid) return invalid;
}
return null;
case 'map': {
if (!isRecord(value)) return null;
const { keyClass, valueClass } = type;
for (const [key, item] of Object.entries(value)) {
const invalid =
invalidScalar(keyClass, key) ??
(valueClass.type === 'object'
? invalidNested(schema, valueClass.objectName, item)
: invalidScalar(valueClass, item));
if (invalid) return invalid;
}
return null;
}
default:
return null;
}
}
export function validateFormat(
data: FieldValues,
fields: Fields,
schema: Schema,
messages: FormatMessages,
visible?: ReadonlySet<string>,
): FieldErrors {
const errors: FieldErrors = {};
for (const [name, field] of Object.entries(fields.properties)) {
if (visible && !visible.has(name)) continue;
if (field.update === 'serverSet') continue;
const invalid = invalidValue(schema, field.type, data[name], null);
if (invalid) errors[name] = messages[invalid];
}
return errors;
}
@@ -305,6 +152,7 @@ export function buildUpdatePatch(original: FieldValues, data: FieldValues, field
if (key === 'id') continue;
const field = fields?.properties[key];
if (field?.update === 'serverSet') continue;
if (field?.update === 'immutable' && valuesEqual(original[key], value)) continue;
if (field && isUnchangedSecret(field, value)) continue;
patch[key] = value === undefined ? null : withoutMaskedSecrets(value);
}
@@ -353,11 +201,9 @@ export function mapSetError(
): { general: string; fieldErrors: FieldErrors } {
const fieldErrors: FieldErrors = {};
const extra: string[] = [];
const validated = new Set(error.validationErrors?.map((ve) => ve.property));
for (const prop of error.properties ?? []) {
const top = prop.split('/')[0];
if (top && knownFields.has(top)) fieldErrors[top] = error.description ?? messages.invalidValue;
else if (!validated.has(prop)) extra.push(`${prop}: ${messages.invalidValue}`);
}
for (const ve of error.validationErrors ?? []) {
if (!ve.property) continue;
@@ -381,17 +227,6 @@ export function combineForms(parent: Form | null, variant: Form | null): Form |
};
}
export function validatedFieldNames(
formNames: ReadonlySet<string>,
fields: Fields,
hidden: ReadonlySet<string>,
): ReadonlySet<string> | undefined {
if (hidden.size === 0) return formNames.size > 0 ? formNames : undefined;
const names = new Set(formNames.size > 0 ? formNames : Object.keys(fields.properties));
for (const name of hidden) names.delete(name);
return names;
}
export function formFieldNames(...forms: (Form | null | undefined)[]): Set<string> {
const names = new Set<string>();
for (const form of forms) {
@@ -461,20 +296,12 @@ export interface RenderableSection {
fields: RenderableField[];
}
const NO_HIDDEN_FIELDS: ReadonlySet<string> = new Set();
export function buildSections(
form: Form | null,
fields: Fields | null,
mode: FormMode,
hidden: ReadonlySet<string> = NO_HIDDEN_FIELDS,
): RenderableSection[] {
const visible = (field: Field) =>
mode === 'create' ? field.update !== 'serverSet' : !widgetTraits(field.type).createOnly;
export function buildSections(form: Form | null, fields: Fields | null, mode: FormMode): RenderableSection[] {
const visible = (field: Field) => !(mode === 'create' && field.update === 'serverSet');
if (!form) {
if (!fields) return [];
const all = Object.entries(fields.properties)
.filter(([name, field]) => !hidden.has(name) && visible(field))
.filter(([, field]) => visible(field))
.map(([name, field]) => ({ formField: { name, label: name }, field }));
return all.length > 0 ? [{ key: 'section-0', fields: all }] : [];
}
@@ -486,7 +313,6 @@ export function buildSections(
rendered.push({ formField: ff, field: null });
continue;
}
if (hidden.has(ff.name)) continue;
const field = fields?.properties[ff.name];
if (field && visible(field)) rendered.push({ formField: ff, field });
}
@@ -495,18 +321,6 @@ export function buildSections(
return sections;
}
export function withoutSectionTitles(
sections: RenderableSection[],
fieldNames: readonly string[] | undefined,
): RenderableSection[] {
if (!fieldNames || fieldNames.length === 0) return sections;
return sections.map((section) =>
section.title && section.fields.some(({ formField }) => fieldNames.includes(formField.name))
? { ...section, title: undefined }
: section,
);
}
export function collectFetchProperties(schema: Schema, view: ResolvedView, viewName: string): string[] {
const { object, resolvedSchema } = view;
const names = new Set<string>(['id']);
+25 -91
View File
@@ -4,7 +4,7 @@
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import { useEffect, useReducer, type ComponentType } from 'react';
import { useEffect, useReducer } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useSchemaStore } from '@/stores/schemaStore';
@@ -14,7 +14,6 @@ import { toast } from '@/hooks/use-toast';
import {
buildCreateDefaults,
buildEmbeddedDefaults,
deepMerge,
getDisplayProperty,
resolveForm,
resolveVariantForm,
@@ -38,32 +37,21 @@ import {
formFieldNames,
isOtpAuthValid,
mapSetError,
mergeFieldErrors,
validateFormat,
validateRequired,
validatedFieldNames,
VARIANT_FIELD,
withoutSectionTitles,
type FieldErrors,
type FieldValues,
} from '@/components/forms/formLogic';
import { formReducer, initialFormState, isFormDirty, type FormState } from '@/components/forms/formReducer';
import { useUnsavedChangesGuard } from '@/components/forms/useUnsavedChangesGuard';
import type { FormMode } from '@/components/forms/formContext';
import type { JmapSetError } from '@/types/jmap';
import type { Field, Fields, Form, FormField, Schema } from '@/types/schema';
import type { Fields, Form, Schema } from '@/types/schema';
const CREATE_ID = 'new-0';
const NOISY_CREATED_KEYS = new Set(['id', 'blobId']);
function createDefaults(
schema: Schema,
view: ResolvedView,
variant: string | undefined,
createValues: FieldValues | undefined,
): FieldValues {
const defaults = buildCreateDefaults(schema, view.object, view.resolvedSchema, variant, view.list?.filtersStatic);
const data = createValues ? deepMerge(defaults, createValues) : defaults;
function createDefaults(schema: Schema, view: ResolvedView, variant: string | undefined): FieldValues {
const data = buildCreateDefaults(schema, view.object, view.resolvedSchema, variant, view.list?.filtersStatic);
if (variant) data[VARIANT_FIELD] = variant;
return data;
}
@@ -75,15 +63,10 @@ function initialCreateVariant(view: ResolvedView): string | undefined {
return typeof fromFilter === 'string' ? fromFilter : (resolvedSchema.variants[0]?.name ?? '');
}
function initialState(
schema: Schema | null,
view: ResolvedView | null,
mode: FormMode,
createValues: FieldValues | undefined,
): FormState {
function initialState(schema: Schema | null, view: ResolvedView | null, mode: FormMode): FormState {
if (mode !== 'create' || !schema || !view) return initialFormState();
const variant = initialCreateVariant(view);
return initialFormState(createDefaults(schema, view, variant, createValues), variant ?? '', view);
return initialFormState(createDefaults(schema, view, variant), variant ?? '', view);
}
function loadedVariant(view: ResolvedView, data: FieldValues): string {
@@ -92,34 +75,7 @@ function loadedVariant(view: ResolvedView, data: FieldValues): string {
return typeof type === 'string' ? type : (view.resolvedSchema.variants[0]?.name ?? '');
}
export interface FieldRenderProps {
field: Field;
formField: FormField;
data: FieldValues;
errors: FieldErrors;
readOnly: boolean;
onFieldChange: (name: string, value: unknown) => void;
}
export interface FieldOverrides {
hidden?: readonly string[];
untitled?: readonly string[];
render?: Readonly<Record<string, ComponentType<FieldRenderProps>>>;
validate?: (data: FieldValues) => FieldErrors;
}
export interface DynamicFormOptions {
accountId?: string;
fieldOverrides?: FieldOverrides;
createValues?: FieldValues;
showCreatedValues?: boolean;
}
export function useDynamicForm(
viewName: string,
objectId: string | null,
{ accountId, fieldOverrides, createValues, showCreatedValues = true }: DynamicFormOptions = {},
) {
export function useDynamicForm(viewName: string, objectId: string | null) {
const { t } = useTranslation();
const navigate = useNavigate();
const schema = useSchemaStore((s) => s.schema);
@@ -130,14 +86,14 @@ export function useDynamicForm(
const isSingleton = resolved?.object.objectType.type === 'singleton';
const objectName = resolved?.object.objectName;
const [state, dispatch] = useReducer(formReducer, null, () => initialState(schema, resolved, mode, createValues));
const [state, dispatch] = useReducer(formReducer, null, () => initialState(schema, resolved, mode));
const isDirty = isFormDirty(state);
if (mode === 'create' && schema && resolved && state.source !== resolved) {
const variant = initialCreateVariant(resolved);
dispatch({
type: 'load',
data: createDefaults(schema, resolved, variant, createValues),
data: createDefaults(schema, resolved, variant),
variant: variant ?? '',
source: resolved,
});
@@ -147,7 +103,7 @@ export function useDynamicForm(
objectName,
mode === 'create' ? null : isSingleton ? 'singleton' : objectId,
schema && resolved ? collectFetchProperties(schema, resolved, viewName) : ['id'],
{ staleTime: 0, refetchOnMount: 'always', accountId },
{ staleTime: 0, refetchOnMount: 'always' },
);
if (objectQuery.data && objectQuery.data !== state.source && !isDirty && resolved) {
dispatch({
@@ -184,8 +140,7 @@ export function useDynamicForm(
}
}
const form = sch?.type === 'multiple' ? combineForms(parentForm, variantForm) : variantForm;
const hidden = new Set(fieldOverrides?.hidden);
const sections = withoutSectionTitles(buildSections(form, fields, mode, hidden), fieldOverrides?.untitled);
const sections = buildSections(form, fields, mode);
const loading = mode === 'edit' && objectQuery.fetchStatus !== 'idle' && !objectQuery.isFetchedAfterMount;
const loadError =
@@ -210,9 +165,7 @@ export function useDynamicForm(
};
const applySetError = (error: JmapSetError) => {
const known = new Set(Object.keys(fields?.properties ?? {}));
for (const name of hidden) known.delete(name);
const { general, fieldErrors } = mapSetError(error, known, {
const { general, fieldErrors } = mapSetError(error, new Set(Object.keys(fields?.properties ?? {})), {
general: friendlySetError(error),
invalidValue: t('form.invalidValue', 'Invalid value.'),
validation: validationErrorMessage,
@@ -230,7 +183,7 @@ export function useDynamicForm(
const { variants } = resolved.resolvedSchema;
const defaults =
mode === 'create'
? createDefaults(schema, resolved, next, createValues)
? createDefaults(schema, resolved, next)
: buildEmbeddedDefaults(schema, resolved.object.objectName, {}, next);
const data = switchVariantValues(
variants.find((v) => v.name === state.variant)?.fields,
@@ -245,33 +198,14 @@ export function useDynamicForm(
const save = async () => {
if (!resolved || saving) return;
if (fields) {
const visibleNames = validatedFieldNames(formFieldNames(parentForm, variantForm), fields, hidden);
const errors = mergeFieldErrors(
validateRequired(
state.data,
fields,
mode,
{
required: t('form.required', 'This field is required.'),
minItems: (count) => t('form.minItems', 'Add at least {{count}} entries.', { count }),
},
visibleNames,
schema ?? undefined,
),
fieldOverrides?.validate?.(state.data) ?? {},
schema
? validateFormat(
state.data,
fields,
schema,
{
localTime: t('form.invalidLocalTime', 'Enter a valid time.'),
localDate: t('form.invalidLocalDate', 'Enter a valid date as YYYY-MM-DD.'),
weeklySchedule: t('form.invalidWeeklySchedule', 'Correct the intervals in this schedule.'),
},
visibleNames,
)
: {},
const visible = formFieldNames(parentForm, variantForm);
const errors = validateRequired(
state.data,
fields,
mode,
t('form.required', 'This field is required.'),
visible.size > 0 ? visible : undefined,
schema ?? undefined,
);
if (Object.keys(errors).length > 0) {
dispatch({
@@ -300,14 +234,14 @@ export function useDynamicForm(
}),
fields,
);
const result = await setMutation.mutateAsync({ create: { [CREATE_ID]: payload }, blobs, accountId });
const result = await setMutation.mutateAsync({ create: { [CREATE_ID]: payload }, blobs });
const created = result.created?.[CREATE_ID];
if (created) {
const extras: FieldValues = {};
for (const [key, value] of Object.entries(created)) {
if (!NOISY_CREATED_KEYS.has(key)) extras[key] = value;
}
if (showCreatedValues && Object.keys(extras).length > 0) {
if (Object.keys(extras).length > 0) {
dispatch({ type: 'created', result: { id: String(created.id), values: extras } });
} else {
toast({ title: t('form.createdSuccess', 'Created successfully'), variant: 'success' });
@@ -329,7 +263,7 @@ export function useDynamicForm(
}
const { blobs, payload } = collectBlobUploads(patch, fields, state.original);
const updateId = isSingleton ? 'singleton' : objectId!;
const result = await setMutation.mutateAsync({ update: { [updateId]: payload }, blobs, accountId });
const result = await setMutation.mutateAsync({ update: { [updateId]: payload }, blobs });
if (result.updated && updateId in result.updated) {
toast({ title: t('form.savedSuccess', 'Saved successfully'), variant: 'success' });
dispatch({ type: 'commit' });
@@ -348,7 +282,7 @@ export function useDynamicForm(
if (!resolved || !objectId) return;
dispatch({ type: 'setErrors', generalError: null });
try {
const result = await setMutation.mutateAsync({ destroy: [objectId], accountId });
const result = await setMutation.mutateAsync({ destroy: [objectId] });
if (result.destroyed?.includes(objectId)) {
const label = resolved.list?.singularName ?? resolved.object.objectType.description;
toast({
+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;
}
@@ -15,12 +15,12 @@ import { cn } from '@/lib/utils';
import type { WidgetProps } from '@/components/forms/widgets/types';
import type { FieldTypeUtcDateTime } from '@/types/schema';
export const Calendar = lazy(() => import('@/components/ui/calendar').then((m) => ({ default: m.Calendar })));
const Calendar = lazy(() => import('@/components/ui/calendar').then((m) => ({ default: m.Calendar })));
export function CalendarFallback() {
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 { EnclosingSchemaContext, 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,48 +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')}>
<EnclosingSchemaContext value={resolved.schemaName}>
{entries.map(({ formField, field }) => (
<FieldRow
key={formField.name}
field={field}
formField={formField}
value={obj[formField.name]}
onChange={(v) => onChange({ ...obj, [formField.name]: v })}
/>
))}
</EnclosingSchemaContext>
</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>
)}
+85 -3
View File
@@ -4,10 +4,92 @@
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import { resolveWidget } from '@/extensions/widgets';
import { lazy, Suspense } from 'react';
import { ColorWidget, MultilineWidget, SecretWidget, TextWidget } from '@/components/forms/widgets/StringWidgets';
import { DurationWidget, NumberWidget, SizeWidget } from '@/components/forms/widgets/NumberWidgets';
import { DateTimeWidget } from '@/components/forms/widgets/DateTimeWidget';
import { BooleanWidget } from '@/components/forms/widgets/BooleanWidget';
import { EnumWidget } from '@/components/forms/widgets/EnumWidgets';
import { BlobWidget } from '@/components/forms/widgets/BlobWidget';
import { ObjectIdWidget } from '@/components/forms/widgets/ObjectIdWidgets';
import { SetWidget } from '@/components/forms/widgets/SetWidget';
import { EmbeddedObjectWidget } from '@/components/forms/widgets/EmbeddedObjectWidget';
import { ObjectListWidget } from '@/components/forms/widgets/ObjectListWidget';
import { MapWidget } from '@/components/forms/widgets/MapWidget';
import { RateWidget } from '@/components/forms/widgets/RateWidget';
import { ExpressionWidget } from '@/components/forms/widgets/ExpressionWidget';
import { UnsupportedWidget } from '@/components/forms/widgets/UnsupportedWidget';
import { widgetKey } from '@/components/forms/widgets/registry';
import type { WidgetProps } from '@/components/forms/widgets/types';
import type {
FieldType,
FieldTypeBlobId,
FieldTypeBoolean,
FieldTypeEnum,
FieldTypeMap,
FieldTypeNumber,
FieldTypeObject,
FieldTypeObjectId,
FieldTypeObjectList,
FieldTypeSet,
FieldTypeString,
FieldTypeUtcDateTime,
} from '@/types/schema';
const OtpAuthField = lazy(() =>
import('@/components/forms/widgets/OtpAuthField').then((m) => ({ default: m.OtpAuthField })),
);
function narrow<T extends FieldType>(props: WidgetProps): WidgetProps<T> {
return props as WidgetProps<T>;
}
export function FieldControl(props: WidgetProps) {
const { Edit } = resolveWidget(props.type);
return <Edit {...props} />;
switch (widgetKey(props.type)) {
case 'string':
return <TextWidget {...narrow<FieldTypeString>(props)} />;
case 'string:secret':
return <SecretWidget {...narrow<FieldTypeString>(props)} />;
case 'string:multiline':
return <MultilineWidget {...narrow<FieldTypeString>(props)} />;
case 'string:color':
return <ColorWidget {...narrow<FieldTypeString>(props)} />;
case 'number':
return <NumberWidget {...narrow<FieldTypeNumber>(props)} />;
case 'number:size':
return <SizeWidget {...narrow<FieldTypeNumber>(props)} />;
case 'number:duration':
return <DurationWidget {...narrow<FieldTypeNumber>(props)} />;
case 'utcDateTime':
return <DateTimeWidget {...narrow<FieldTypeUtcDateTime>(props)} />;
case 'boolean':
return <BooleanWidget {...narrow<FieldTypeBoolean>(props)} />;
case 'enum':
return <EnumWidget {...narrow<FieldTypeEnum>(props)} />;
case 'blobId':
return <BlobWidget {...narrow<FieldTypeBlobId>(props)} />;
case 'objectId':
return <ObjectIdWidget {...narrow<FieldTypeObjectId>(props)} />;
case 'object':
return <EmbeddedObjectWidget {...narrow<FieldTypeObject>(props)} />;
case 'object:x:Expression':
return <ExpressionWidget {...narrow<FieldTypeObject>(props)} />;
case 'object:x:Rate':
return <RateWidget {...narrow<FieldTypeObject>(props)} />;
case 'object:x:OtpAuth':
return (
<Suspense fallback={null}>
<OtpAuthField {...narrow<FieldTypeObject>(props)} />
</Suspense>
);
case 'objectList':
return <ObjectListWidget {...narrow<FieldTypeObjectList>(props)} />;
case 'set':
case 'set:enum':
return <SetWidget {...narrow<FieldTypeSet>(props)} />;
case 'map':
return <MapWidget {...narrow<FieldTypeMap>(props)} />;
case 'unsupported':
return <UnsupportedWidget {...props} />;
}
}
@@ -1,35 +0,0 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import { lazy, Suspense } from 'react';
import type { WidgetProps } from '@/components/forms/widgets/types';
import type { FieldTypeObject } from '@/types/schema';
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,
})),
);
export function OtpAuthWidget(props: WidgetProps<FieldTypeObject>) {
return (
<Suspense fallback={null}>
<OtpAuthField {...props} />
</Suspense>
);
}
export function PasskeyRegistrationWidget(props: WidgetProps<FieldTypeObject>) {
return (
<Suspense fallback={null}>
<PasskeyRegistrationField {...props} />
</Suspense>
);
}
@@ -1,96 +0,0 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import { Suspense, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Calendar as CalendarIcon, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { formatLocalDate } from '@/lib/format';
import {
formatLocalDateValue,
localDateFromCalendarDate,
localDateToCalendarDate,
parseLocalDate,
} from '@/lib/localDateTime';
import { cn } from '@/lib/utils';
import { Calendar, CalendarFallback } from '@/components/forms/widgets/DateTimeWidget';
import type { ControlProps } from '@/components/forms/widgets/types';
export interface LocalDateInputProps extends ControlProps {
value: string | null | undefined;
onChange: (value: string | null) => void;
clearable?: boolean;
disabled?: boolean;
placeholder?: string;
className?: string;
}
export function LocalDateInput({
value,
onChange,
clearable = false,
disabled = false,
placeholder,
className,
...control
}: LocalDateInputProps) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const triggerRef = useRef<HTMLButtonElement>(null);
const parsed = parseLocalDate(value);
const selected = parsed ? localDateToCalendarDate(parsed) : undefined;
const hasValue = typeof value === 'string' && value !== '';
return (
<div className={cn('flex items-center gap-2', className)}>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
{...control}
ref={triggerRef}
type="button"
variant="field"
disabled={disabled}
className={cn('flex-1 justify-start px-3 text-left', !hasValue && 'text-dim')}
>
<CalendarIcon className="text-dim" aria-hidden="true" />
{hasValue ? formatLocalDate(value) : (placeholder ?? t('field.pickDate', 'Pick a date'))}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto overflow-hidden p-0" align="start">
<Suspense fallback={<CalendarFallback />}>
<Calendar
mode="single"
selected={selected}
defaultMonth={selected}
autoFocus
onSelect={(day) => {
if (day) onChange(formatLocalDateValue(localDateFromCalendarDate(day)));
setOpen(false);
}}
/>
</Suspense>
</PopoverContent>
</Popover>
{clearable && hasValue && !disabled && (
<Button
type="button"
variant="ghost"
size="icon"
className="h-9 w-9 shrink-0"
onClick={() => {
onChange(null);
triggerRef.current?.focus();
}}
aria-label={t('common.clear', 'Clear')}
>
<X aria-hidden="true" />
</Button>
)}
</div>
);
}
@@ -1,50 +0,0 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import { LocalDateInput } from '@/components/forms/widgets/LocalDateInput';
import { LocalTimeInput } from '@/components/forms/widgets/LocalTimeInput';
import { formatLocalDate, formatLocalTime } from '@/lib/format';
import type { WidgetProps } from '@/components/forms/widgets/types';
import type { ValueProps } from '@/extensions/types';
import type { FieldTypeString } from '@/types/schema';
function stringOrNull(value: unknown): string | null {
return typeof value === 'string' && value !== '' ? value : null;
}
export function LocalTimeWidget({ type, value, onChange, readOnly, control }: WidgetProps<FieldTypeString>) {
return (
<LocalTimeInput
{...control}
value={stringOrNull(value)}
onChange={onChange}
allowEndOfDay
clearable={!!type.nullable}
disabled={readOnly}
/>
);
}
export function LocalDateWidget({ type, formField, value, onChange, readOnly, control }: WidgetProps<FieldTypeString>) {
return (
<LocalDateInput
{...control}
value={stringOrNull(value)}
onChange={onChange}
clearable={!!type.nullable}
disabled={readOnly}
placeholder={formField.placeholder}
/>
);
}
export function LocalTimeValue({ value }: ValueProps) {
return <span className="text-sm tabular-nums">{formatLocalTime(value)}</span>;
}
export function LocalDateValue({ value }: ValueProps) {
return <span className="text-sm">{formatLocalDate(value)}</span>;
}
@@ -1,468 +0,0 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import { Fragment, useId, useRef, useState, type ChangeEvent, type KeyboardEvent, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { Clock, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { formatLocalTime, localeClock, type LocaleClock } from '@/lib/format';
import {
HOURS_PER_HALF_DAY,
MINUTES_PER_DAY,
MINUTES_PER_HOUR,
hour12Of,
hours24From,
localTimeFromMinutes,
meridiemOf,
parseLocalTime,
type Meridiem,
} from '@/lib/localDateTime';
import { useAccountStore } from '@/stores/accountStore';
import { cn } from '@/lib/utils';
import type { ControlProps } from '@/components/forms/widgets/types';
export interface LocalTimeInputProps extends ControlProps {
value: string | null | undefined;
onChange: (value: string | null) => void;
allowEndOfDay?: boolean;
clearable?: boolean;
disabled?: boolean;
pickerStep?: 15 | 30;
className?: string;
}
type Segment = 'hours' | 'minutes' | 'meridiem';
interface PendingDigit {
segment: Segment;
digit: number;
}
type PickerMove = 'left' | 'right' | 'up' | 'down' | 'first' | 'last';
const LAST_MINUTE = MINUTES_PER_HOUR - 1;
const END_OF_DAY_HOUR = MINUTES_PER_DAY / MINUTES_PER_HOUR;
const DIGIT = /^\d$/;
const SEGMENT_CLASS =
'rounded-sm bg-transparent text-center tabular-nums outline-none placeholder:text-dim focus:bg-highlight focus:text-highlight-foreground disabled:cursor-not-allowed';
const PICKER_COLUMNS_24H = 4;
const PICKER_COLUMNS_12H = 3;
const PICKER_KEYS = new Map<string, PickerMove>([
['ArrowLeft', 'left'],
['ArrowRight', 'right'],
['ArrowUp', 'up'],
['ArrowDown', 'down'],
['Home', 'first'],
['End', 'last'],
]);
function twoDigits(value: number | null): string {
return value === null ? '' : String(value).padStart(2, '0');
}
function wrap(value: number, max: number): number {
return ((value % (max + 1)) + max + 1) % (max + 1);
}
function meridiemForKey(key: string, clock: LocaleClock): Meridiem | null {
const typed = key.toLocaleLowerCase();
const am = clock.am.charAt(0).toLocaleLowerCase();
const pm = clock.pm.charAt(0).toLocaleLowerCase();
if (am !== pm) {
if (typed === am) return 'am';
if (typed === pm) return 'pm';
}
return typed === 'a' ? 'am' : typed === 'p' ? 'pm' : null;
}
export function LocalTimeInput({
value,
onChange,
allowEndOfDay = false,
clearable = false,
disabled = false,
pickerStep = 30,
className,
id,
'aria-label': ariaLabel,
'aria-labelledby': ariaLabelledBy,
'aria-describedby': ariaDescribedBy,
'aria-invalid': ariaInvalid,
'aria-required': ariaRequired,
}: LocalTimeInputProps) {
const { t } = useTranslation();
useAccountStore((s) => s.locale);
const [pending, setPending] = useState<PendingDigit | null>(null);
const [pickerOpen, setPickerOpen] = useState(false);
const hoursRef = useRef<HTMLInputElement>(null);
const minutesRef = useRef<HTMLInputElement>(null);
const meridiemRef = useRef<HTMLInputElement>(null);
const pickerRef = useRef<HTMLDivElement>(null);
const segmentLabelId = useId();
const clock = localeClock();
const twelve = clock.hour12;
const total = parseLocalTime(value);
const hours = total === null ? null : Math.floor(total / MINUTES_PER_HOUR);
const minutes = total === null ? null : total % MINUTES_PER_HOUR;
const atEndOfDay = hours === END_OF_DAY_HOUR;
const maxHour = allowEndOfDay || atEndOfDay ? END_OF_DAY_HOUR : END_OF_DAY_HOUR - 1;
const meridiem: Meridiem | null = hours === null ? null : atEndOfDay ? 'am' : meridiemOf(hours);
const hourMin = twelve ? 1 : 0;
const hourMax = twelve ? HOURS_PER_HALF_DAY : maxHour;
const shownHour = hours === null ? null : twelve ? hour12Of(hours) : hours;
const endOfDayText = twelve && atEndOfDay ? t('field.endOfDay', 'End of day') : null;
const order: readonly Segment[] = !twelve
? ['hours', 'minutes']
: clock.meridiemFirst
? ['meridiem', 'hours', 'minutes']
: ['hours', 'minutes', 'meridiem'];
const refFor = (segment: Segment) =>
segment === 'hours' ? hoursRef : segment === 'minutes' ? minutesRef : meridiemRef;
const neighbour = (segment: Segment, delta: number): Segment | undefined => order[order.indexOf(segment) + delta];
const focusAfter = (segment: Segment) => {
const next = neighbour(segment, 1);
if (next) refFor(next).current?.focus();
};
const emit = (h: number, m: number) => onChange(localTimeFromMinutes(h * MINUTES_PER_HOUR + m));
const setHours = (h: number) => emit(h, h === END_OF_DAY_HOUR ? 0 : (minutes ?? 0));
const setShownHour = (h: number) => setHours(twelve ? hours24From(h, meridiem ?? 'am') : h);
const setMinutes = (m: number) => {
if (!atEndOfDay) emit(hours ?? 0, m);
};
const setMeridiem = (next: Meridiem) => {
const hour12 = hours === null || atEndOfDay ? HOURS_PER_HALF_DAY : hour12Of(hours);
emit(hours24From(hour12, next), atEndOfDay ? 0 : (minutes ?? 0));
};
const typeDigit = (segment: Segment, digit: number) => {
const previous = pending?.segment === segment ? pending.digit : null;
if (segment === 'hours') {
const combined = previous === null ? null : previous * 10 + digit;
if (combined !== null && combined >= hourMin && combined <= hourMax) {
setShownHour(combined);
setPending(null);
focusAfter('hours');
} else if (digit * 10 > hourMax) {
setShownHour(digit);
setPending(null);
focusAfter('hours');
} else {
if (digit >= hourMin) setShownHour(digit);
setPending({ segment, digit });
}
return;
}
if (segment !== 'minutes' || atEndOfDay) return;
if (previous !== null) {
setMinutes(previous * 10 + digit);
setPending(null);
focusAfter('minutes');
} else if (digit * 10 > LAST_MINUTE) {
setMinutes(digit);
setPending(null);
focusAfter('minutes');
} else {
setMinutes(digit);
setPending({ segment, digit });
}
};
const step = (segment: Segment, delta: number) => {
setPending(null);
if (segment === 'hours') {
if (twelve && atEndOfDay) {
setHours(delta > 0 ? 0 : END_OF_DAY_HOUR - 1);
} else if (twelve && allowEndOfDay && hours === (delta > 0 ? END_OF_DAY_HOUR - 1 : 0)) {
setHours(END_OF_DAY_HOUR);
} else if (twelve) {
setShownHour(
shownHour === null
? delta > 0
? hourMin
: hourMax
: wrap(shownHour - 1 + delta, HOURS_PER_HALF_DAY - 1) + 1,
);
} else {
setHours(hours === null ? (delta > 0 ? 0 : maxHour) : wrap(hours + delta, maxHour));
}
} else if (segment === 'minutes') {
setMinutes(minutes === null ? (delta > 0 ? 0 : LAST_MINUTE) : wrap(minutes + delta, LAST_MINUTE));
} else {
setMeridiem(meridiem === 'am' ? 'pm' : 'am');
}
};
const clear = () => {
setPending(null);
if (clearable) onChange(null);
};
const onSegmentChange = (segment: Segment) => (e: ChangeEvent<HTMLInputElement>) => {
const inputType = (e.nativeEvent as Partial<InputEvent>).inputType ?? '';
if (inputType.startsWith('delete')) {
clear();
return;
}
const text = e.target.value;
const typed = text.charAt((e.target.selectionStart ?? text.length) - 1);
if (segment === 'meridiem') {
const next = meridiemForKey(typed, clock);
if (next) {
setMeridiem(next);
focusAfter('meridiem');
}
} else if (DIGIT.test(typed)) {
typeDigit(segment, Number(typed));
}
};
const onSegmentKeyDown = (segment: Segment) => (e: KeyboardEvent<HTMLInputElement>) => {
switch (e.key) {
case 'ArrowUp':
step(segment, 1);
break;
case 'ArrowDown':
step(segment, -1);
break;
case 'Home':
case 'End': {
setPending(null);
const first = e.key === 'Home';
if (segment === 'hours') {
if (twelve && allowEndOfDay && !first) setHours(END_OF_DAY_HOUR);
else setShownHour(first ? hourMin : hourMax);
} else if (segment === 'minutes') setMinutes(first ? 0 : LAST_MINUTE);
else setMeridiem(first ? 'am' : 'pm');
break;
}
case 'Backspace':
case 'Delete':
clear();
break;
case ':':
case '.':
if (segment !== 'hours') return;
minutesRef.current?.focus();
break;
case 'ArrowRight':
case 'ArrowLeft': {
const target = neighbour(segment, e.key === 'ArrowRight' ? 1 : -1);
if (!target) return;
refFor(target).current?.focus();
break;
}
default: {
const next = segment === 'meridiem' ? meridiemForKey(e.key, clock) : null;
if (next) {
setMeridiem(next);
focusAfter('meridiem');
} else if (endOfDayText !== null && segment === 'hours' && DIGIT.test(e.key)) {
typeDigit('hours', Number(e.key));
} else {
return;
}
}
}
e.preventDefault();
};
const segmentLabel = (segment: Segment) =>
segment === 'hours'
? t('field.hours', 'Hours')
: segment === 'minutes'
? t('field.minutes', 'Minutes')
: t('field.dayPeriod', 'AM/PM');
const segmentName = (segment: Segment) => {
if (ariaLabelledBy) return { 'aria-labelledby': `${ariaLabelledBy} ${segmentLabelId}-${segment}` };
if (ariaLabel) {
return {
'aria-label': t('field.segmentOf', '{{field}}, {{segment}}', {
field: ariaLabel,
segment: segmentLabel(segment),
}),
};
}
return { 'aria-label': segmentLabel(segment) };
};
const segmentProps = (segment: Segment, current: number | null, min: number, max: number, text: string) => ({
...segmentName(segment),
type: 'text',
inputMode: segment === 'meridiem' ? ('text' as const) : ('numeric' as const),
role: 'spinbutton',
autoComplete: 'off',
disabled,
placeholder: '--',
value: text,
'aria-valuemin': min,
'aria-valuemax': max,
'aria-valuenow': current ?? undefined,
'aria-valuetext': current === null ? t('field.notSet', 'Not set') : text,
'aria-invalid': ariaInvalid,
'aria-required': ariaRequired,
'aria-describedby': ariaDescribedBy,
onChange: onSegmentChange(segment),
onKeyDown: onSegmentKeyDown(segment),
onFocus: (e: { currentTarget: HTMLInputElement }) => e.currentTarget.select(),
onBlur: () => setPending(null),
className: SEGMENT_CLASS,
});
const meridiemText = meridiem === null ? '' : meridiem === 'am' ? clock.am : clock.pm;
const meridiemWidth = `${Math.max(2, clock.am.length, clock.pm.length) + 0.5}ch`;
const segments: Record<Segment, ReactNode> = {
hours: (
<input
key="hours"
{...segmentProps('hours', shownHour, hourMin, hourMax, endOfDayText ?? twoDigits(shownHour))}
ref={hoursRef}
id={id}
readOnly={endOfDayText !== null}
style={{ width: endOfDayText === null ? '2.5ch' : `${endOfDayText.length + 1}ch` }}
/>
),
minutes: endOfDayText === null && (
<Fragment key="minutes">
<span aria-hidden="true" className="px-0.5 text-dim">
:
</span>
<input
{...segmentProps('minutes', minutes, 0, LAST_MINUTE, twoDigits(minutes))}
ref={minutesRef}
readOnly={atEndOfDay}
style={{ width: '2.5ch' }}
/>
</Fragment>
),
meridiem: endOfDayText === null && (
<input
key="meridiem"
{...segmentProps('meridiem', meridiem === null ? null : meridiem === 'am' ? 0 : 1, 0, 1, meridiemText)}
ref={meridiemRef}
className={cn(SEGMENT_CLASS, clock.meridiemFirst ? 'me-1' : 'ms-1')}
style={{ width: meridiemWidth }}
/>
),
};
const options: number[] = [];
for (let m = 0; m < MINUTES_PER_DAY; m += pickerStep) options.push(m);
if (allowEndOfDay) options.push(MINUTES_PER_DAY);
const focusTarget = total !== null && options.includes(total) ? total : options[0];
const columns = twelve ? PICKER_COLUMNS_12H : PICKER_COLUMNS_24H;
const onPickerKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
const move = PICKER_KEYS.get(e.key);
const buttons = pickerRef.current?.querySelectorAll<HTMLButtonElement>('button');
if (move === undefined || !buttons) return;
e.preventDefault();
const current = Array.prototype.indexOf.call(buttons, document.activeElement);
const delta = move === 'left' ? -1 : move === 'right' ? 1 : move === 'up' ? -columns : columns;
const next = move === 'first' ? 0 : move === 'last' ? buttons.length - 1 : current + delta;
buttons[Math.min(buttons.length - 1, Math.max(0, next))]?.focus();
};
const pick = (m: number) => {
setPending(null);
onChange(localTimeFromMinutes(m));
setPickerOpen(false);
};
return (
<div
role={ariaLabelledBy ? undefined : 'group'}
aria-label={ariaLabelledBy ? undefined : ariaLabel}
aria-describedby={ariaLabelledBy ? undefined : ariaDescribedBy}
aria-invalid={ariaInvalid}
data-slot="local-time-input"
className={cn(
'field-surface inline-flex h-9 items-center gap-1 rounded-lg pr-1 pl-3 text-base md:text-sm',
disabled && 'opacity-50',
className,
)}
>
<div dir="ltr" className="flex items-center">
{order.map((segment) => segments[segment])}
</div>
{ariaLabelledBy && (
<span hidden>
{order.map((segment) => (
<span key={segment} id={`${segmentLabelId}-${segment}`}>
{segmentLabel(segment)}
</span>
))}
</span>
)}
{!disabled && (
<div className="ml-auto flex items-center">
{clearable && total !== null && (
<Button
type="button"
variant="ghost"
size="icon-sm"
className="h-7 w-7"
onClick={() => {
clear();
hoursRef.current?.focus();
}}
aria-label={t('common.clear', 'Clear')}
>
<X aria-hidden="true" />
</Button>
)}
<Popover open={pickerOpen} onOpenChange={setPickerOpen}>
<PopoverTrigger asChild>
<Button
type="button"
variant="ghost"
size="icon-sm"
className="h-7 w-7"
aria-label={t('field.chooseTime', 'Choose a time')}
>
<Clock aria-hidden="true" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-64 p-2" align="end">
<div
ref={pickerRef}
className={cn('grid max-h-64 gap-1 overflow-y-auto', twelve ? 'grid-cols-3' : 'grid-cols-4')}
dir="ltr"
onKeyDown={onPickerKeyDown}
>
{options.map((m) => (
<Button
key={m}
type="button"
variant={m === total ? 'secondary' : 'ghost'}
size="sm"
className={cn('px-0 tabular-nums', m === MINUTES_PER_DAY && 'col-span-full')}
tabIndex={m === focusTarget ? 0 : -1}
aria-current={m === total ? 'time' : undefined}
autoFocus={m === focusTarget}
onClick={() => pick(m)}
>
{m === MINUTES_PER_DAY
? twelve
? t('field.endOfDay', 'End of day')
: t('field.endOfDayOption', 'End of day (24:00)')
: twelve
? formatLocalTime(localTimeFromMinutes(m))
: localTimeFromMinutes(m)}
</Button>
))}
</div>
</PopoverContent>
</Popover>
</div>
)}
</div>
);
}
+70 -130
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, widgetTraits } from '@/extensions/widgets';
import { useNoPermissionMessage } from '@/lib/objectOptions';
import { useDisplayName, useObjectOptions } from '@/data/objectOptions';
import { buildNewObjectValue, getEnum, getEnumVariant, mapEntryValueType } from '@/lib/schemaResolver';
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' && widgetTraits(valueField.type).layout === 'block';
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={mapEntryValueType(schema, type.keyClass, type.valueClass, key) as FieldType}
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} single>
{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 '@/extensions/widgets';
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,20 +19,15 @@ interface RemovablePillProps {
export function RemovablePill({ label, onRemove, removeDisabled, children }: RemovablePillProps) {
const { t } = useTranslation();
return (
<Badge
variant="secondary"
className={cn('h-7 min-w-0 max-w-full gap-1 text-[13px] font-medium', onRemove ? 'pl-3 pr-1' : 'px-3')}
>
<span className="truncate" title={label}>
{children ?? label}
</span>
<Badge variant="secondary" className="gap-1 pr-1 text-sm">
{children ?? label}
{onRemove && (
<button
type="button"
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>
+48 -133
View File
@@ -4,7 +4,7 @@
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import { useId, useState, type ClipboardEvent } from 'react';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Plus } from 'lucide-react';
import { Button } from '@/components/ui/button';
@@ -14,9 +14,8 @@ import { ObjectIdMultiSelect } from '@/components/forms/widgets/ObjectIdWidgets'
import { RemovablePill } from '@/components/forms/widgets/RemovablePill';
import { formatPlaceholder } from '@/components/forms/widgets/placeholders';
import { isRecord } from '@/lib/embeddedSchema';
import { addSetEntries, joinEntries, splitEntries, type SetEntriesResult } from '@/lib/setEntries';
import type { ControlProps, WidgetProps } from '@/components/forms/widgets/types';
import type { FieldTypeSet, ScalarTypeString } from '@/types/schema';
import type { FieldTypeSet } from '@/types/schema';
function toSetObject(items: string[]): Record<string, true> {
const obj: Record<string, true> = {};
@@ -33,7 +32,6 @@ export function SetWidget({ type, formField, value, onChange, readOnly, control
case 'string':
return (
<TagInput
type={scalar}
label={formField.label}
items={items}
onChange={commit}
@@ -76,7 +74,6 @@ export function SetWidget({ type, formField, value, onChange, readOnly, control
}
interface TagInputProps {
type: ScalarTypeString;
label: string;
items: string[];
onChange: (items: string[]) => void;
@@ -87,142 +84,60 @@ interface TagInputProps {
control: ControlProps;
}
const REPORT_SAMPLE = 5;
function isNoteworthy(result: SetEntriesResult): boolean {
return result.added.length > 1 || result.duplicates.length + result.invalid.length + result.overLimit.length > 0;
}
function TagInput({ type, label, items, onChange, readOnly, minItems, maxItems, placeholder, control }: TagInputProps) {
function TagInput({ label, items, onChange, readOnly, minItems, maxItems, placeholder, control }: TagInputProps) {
const { t } = useTranslation();
const [inputValue, setInputValue] = useState('');
const [report, setReport] = useState<SetEntriesResult | null>(null);
const statusId = useId();
const full = maxItems != null && items.length >= maxItems;
const addEntries = (entries: string[]) => {
const result = addSetEntries(items, entries, type, maxItems);
if (result.added.length > 0) onChange([...items, ...result.added]);
setReport(isNoteworthy(result) ? result : null);
return result;
const addTag = () => {
const trimmed = inputValue.trim();
if (!trimmed || items.includes(trimmed) || full) return;
onChange([...items, trimmed]);
setInputValue('');
};
const addTyped = () => {
const entries = splitEntries(inputValue, type.format);
if (entries.length === 0) return;
const result = addEntries(entries);
setInputValue(joinEntries(result.invalid, type.format) ?? '');
};
const onPaste = (e: ClipboardEvent<HTMLInputElement>) => {
const entries = splitEntries(e.clipboardData.getData('text'), type.format);
if (entries.length < 2) return;
e.preventDefault();
const { invalid } = addEntries(entries);
const restored = joinEntries(invalid, type.format);
if (invalid.length > 0 && restored !== null)
setInputValue(inputValue.trim() ? `${inputValue.trim()}, ${restored}` : restored);
};
const sample = (values: string[]) =>
values.length > REPORT_SAMPLE
? t('field.entriesSample', '{{list}} and {{count}} more', {
list: values.slice(0, REPORT_SAMPLE).join(', '),
count: values.length - REPORT_SAMPLE,
})
: values.join(', ');
return (
<div>
<div className="space-y-2">
{items.length > 0 && (
<div className="flex flex-wrap gap-1.5">
{items.map((item) => (
<RemovablePill
key={item}
label={item}
onRemove={
readOnly
? undefined
: () => {
onChange(items.filter((i) => i !== item));
setReport(null);
}
}
removeDisabled={minItems != null && items.length <= minItems}
/>
))}
</div>
)}
{!readOnly && (
<div className="flex items-center gap-2">
<Input
{...control}
aria-describedby={
[control['aria-describedby'], report ? statusId : null].filter(Boolean).join(' ') || undefined
}
value={inputValue}
onChange={(e) => {
setInputValue(e.target.value);
setReport(null);
}}
onPaste={onPaste}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
addTyped();
}
}}
disabled={full}
placeholder={placeholder ?? t('field.typeAndPressEnter', 'Type and press Enter...')}
className="flex-1"
<div className="space-y-2">
{items.length > 0 && (
<div className="flex flex-wrap gap-1.5">
{items.map((item) => (
<RemovablePill
key={item}
label={item}
onRemove={readOnly ? undefined : () => onChange(items.filter((i) => i !== item))}
removeDisabled={minItems != null && items.length <= minItems}
/>
<Button
type="button"
variant="secondary"
size="icon"
className="shrink-0"
onClick={addTyped}
disabled={!inputValue.trim() || full}
aria-label={t('field.addValue', 'Add {{name}}', { name: label })}
>
<Plus aria-hidden="true" />
</Button>
</div>
)}
</div>
<div id={statusId} role="status" className="mt-2 space-y-0.5 text-[12.5px] empty:mt-0">
{report && report.added.length > 0 && (
<p className="text-muted-foreground">
{t('field.entriesAdded', 'Added {{count}} values.', { count: report.added.length })}
</p>
)}
{report && report.duplicates.length > 0 && (
<p className="text-muted-foreground">
{t('field.entriesDuplicate', 'Skipped {{count}} duplicates: {{list}}', {
count: report.duplicates.length,
list: sample(report.duplicates),
})}
</p>
)}
{report && report.invalid.length > 0 && (
<p className="text-destructive">
{t('field.entriesInvalid', 'Not added, invalid: {{list}}', {
count: report.invalid.length,
list: sample(report.invalid),
})}
</p>
)}
{report && report.overLimit.length > 0 && (
<p className="text-destructive">
{t('field.entriesOverLimit', 'Not added, the limit is {{max}}: {{list}}', {
count: report.overLimit.length,
max: maxItems,
list: sample(report.overLimit),
})}
</p>
)}
</div>
))}
</div>
)}
{!readOnly && (
<div className="flex items-center gap-2">
<Input
{...control}
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
addTag();
}
}}
disabled={full}
placeholder={placeholder ?? t('field.typeAndPressEnter', 'Type and press Enter...')}
className="flex-1"
/>
<Button
type="button"
variant="outline"
size="sm"
onClick={addTag}
disabled={!inputValue.trim() || full}
aria-label={t('field.addValue', 'Add {{name}}', { name: label })}
>
<Plus className="h-4 w-4" aria-hidden="true" />
</Button>
</div>
)}
</div>
);
}
+10 -26
View File
@@ -58,41 +58,25 @@ 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>
);
}
if (type.format === 'sieve') {
return <BufferedTextarea {...common} rows={16} spellCheck={false} className="font-mono text-xs" />;
}
return <BufferedTextarea {...common} rows={4} />;
}
export function SieveWidget(props: WidgetProps<FieldTypeString>) {
const { type, formField, value, readOnly, control } = props;
return (
<BufferedTextarea
{...control}
value={stringValue(value)}
onCommit={stringCommitter(props)}
disabled={readOnly}
placeholder={formField.placeholder}
minLength={type.minLength}
maxLength={type.maxLength}
rows={16}
spellCheck={false}
className="font-mono text-xs"
/>
);
}
export function ColorWidget(props: WidgetProps<FieldTypeString>) {
const { t } = useTranslation();
const { value, readOnly, control } = props;
@@ -106,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}
@@ -154,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>
);
@@ -1,94 +0,0 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { LocateFixed } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Combobox, type ComboboxOption } from '@/components/ui/combobox';
import { useFormContext } from '@/components/forms/formContext';
import { formatUtcOffset } from '@/lib/format';
import { getEnum } from '@/lib/schemaResolver';
import type { WidgetProps } from '@/components/forms/widgets/types';
import type { EnumVariant, FieldTypeEnum } from '@/types/schema';
function browserTimeZone(): string | null {
try {
return Intl.DateTimeFormat().resolvedOptions().timeZone || null;
} catch {
return null;
}
}
function zoneOffsets(variants: readonly EnumVariant[], at: Date): ReadonlyMap<string, string> {
const offsets = new Map<string, string>();
for (const { name } of variants) {
const offset = formatUtcOffset(name, at);
if (offset) offsets.set(name, offset);
}
return offsets;
}
export function TimeZoneWidget({ type, value, onChange, readOnly, control }: WidgetProps<FieldTypeEnum>) {
const { t } = useTranslation();
const { schema } = useFormContext();
const variants = getEnum(schema, type.enumName);
const [now] = useState(() => new Date());
const [offsets, setOffsets] = useState<ReadonlyMap<string, string> | null>(null);
const current = typeof value === 'string' ? value : '';
const currentOffset = current ? (offsets?.get(current) ?? formatUtcOffset(current, now)) : null;
const local = browserTimeZone();
const localVariant = local ? variants.find((v) => v.name === local) : undefined;
const options: ComboboxOption[] = variants.map((v) => {
const offset = offsets?.get(v.name);
return {
value: v.name,
label: v.label,
description: offset,
keywords: offset ? [v.name, offset] : [v.name],
};
});
return (
<div className="space-y-1.5">
<Combobox
{...control}
options={options}
value={current}
onValueChange={(v) => onChange(v === '' ? null : v)}
onFirstOpen={() => setOffsets(zoneOffsets(variants, now))}
placeholder={t('field.selectEllipsis', 'Select...')}
searchPlaceholder={t('timeZone.search', 'Search by city, region or offset...')}
emptyText={t('field.noMatches', 'No matches')}
nullLabel={t('field.none', 'None')}
nullable={type.nullable}
disabled={readOnly}
/>
{(currentOffset || (localVariant && local !== current && !readOnly)) && (
<div className="flex flex-wrap items-center gap-x-3 gap-y-1">
{currentOffset && (
<span className="text-[12.5px] text-muted-foreground tabular-nums">
{t('timeZone.currentOffset', 'Currently {{offset}}', { offset: currentOffset })}
</span>
)}
{localVariant && local !== current && !readOnly && (
<Button
type="button"
variant="link"
size="sm"
className="h-auto px-0 py-0.5"
onClick={() => onChange(localVariant.name)}
>
<LocateFixed className="h-3.5 w-3.5" aria-hidden="true" />
{t('timeZone.useMine', 'Use my time zone ({{zone}})', { zone: localVariant.label })}
</Button>
)}
</div>
)}
</div>
);
}
@@ -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>
);
@@ -1,291 +0,0 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import { useId } from 'react';
import { useTranslation } from 'react-i18next';
import { Plus, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useEnclosingSchema, useFormContext, useInPanel } from '@/components/forms/formContext';
import { LocalTimeInput } from '@/components/forms/widgets/LocalTimeInput';
import { WeekChart } from '@/components/values/WeeklyScheduleValue';
import { formatSlot, localeWeekdayOrder } from '@/lib/scheduleFormat';
import { formatWeekday } from '@/lib/format';
import { buildNewObjectValue } from '@/lib/schemaResolver';
import { isRecord } from '@/lib/embeddedSchema';
import {
PRESETS,
WORKING_HOURS_SLOT,
daysValue,
isOvernight,
nextSlotKey,
parseSlot,
presetsFor,
scheduleRules,
slotEntries,
slotIssue,
slotsValue,
type PresetName,
type ScheduleRules,
type Slot,
type SlotIssue,
type Weekday,
} from '@/lib/weeklySchedule';
import { cn } from '@/lib/utils';
import type { WidgetProps } from '@/components/forms/widgets/types';
import type { FieldTypeObjectList } from '@/types/schema';
const FIRST_SLOT_DAYS: readonly Weekday[] = PRESETS.workdays[0].days;
export interface WeeklyScheduleEditorProps {
value: unknown;
onChange: (value: Record<string, unknown>) => void;
rules: ScheduleRules;
readOnly?: boolean;
minItems?: number;
maxItems?: number;
}
function useIssueMessage(): (issue: SlotIssue) => string {
const { t } = useTranslation();
return (issue) => {
switch (issue) {
case 'noDays':
return t('schedule.issueNoDays', 'Choose at least one day.');
case 'missingTime':
return t('schedule.issueMissingTime', 'Enter a start and an end time.');
case 'endNotAfterStart':
return t(
'schedule.issueEndNotAfterStart',
'The end must be later than the start. Split hours that cross midnight into two intervals.',
);
case 'startAtEndOfDay':
return t('schedule.issueStartAtEndOfDay', 'The start must be before 24:00.');
case 'sameStartEnd':
return t('schedule.issueSameStartEnd', 'The start and the end cannot be the same time.');
}
};
}
interface DayTogglesProps {
days: readonly Weekday[];
order: readonly Weekday[];
onToggle: (day: Weekday) => void;
disabled: boolean;
label: string;
}
function DayToggles({ days, order, onToggle, disabled, label }: DayTogglesProps) {
const inPanel = useInPanel();
return (
<div
role="group"
aria-label={label}
className={cn('inline-flex shrink-0 gap-0.5 rounded-full p-1', inPanel ? 'bg-muted' : 'bg-card')}
>
{order.map((day) => {
const on = days.includes(day);
const name = formatWeekday(day, 'long');
return (
<button
key={day}
type="button"
aria-pressed={on}
aria-label={name}
title={name}
disabled={disabled}
onClick={() => onToggle(day)}
className={cn(
'inline-flex h-7 w-7 items-center justify-center rounded-full text-[12.5px] font-semibold outline-none transition-[color,background-color] duration-200 focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-60',
on ? 'bg-primary text-primary-foreground' : 'text-muted-foreground hover:text-foreground',
)}
>
<span aria-hidden="true">{formatWeekday(day, 'narrow')}</span>
</button>
);
})}
</div>
);
}
export function WeeklyScheduleEditor({
value,
onChange,
rules,
readOnly = false,
minItems,
maxItems,
}: WeeklyScheduleEditorProps) {
const { t } = useTranslation();
const { schema } = useFormContext();
const inPanel = useInPanel();
const baseId = useId();
const issueMessage = useIssueMessage();
const order = localeWeekdayOrder();
const items = isRecord(value) ? value : {};
const raw = slotEntries(items);
const entries = raw.map(([key, item]): [string, Slot] => [key, parseSlot(item)]);
const canAdd = !readOnly && (maxItems == null || entries.length < maxItems);
const canRemove = !readOnly && (minItems == null || entries.length > minItems);
const summary = entries.map(([, slot]) => formatSlot(t, slot, order, rules));
const slotRecord = (key: string): Record<string, unknown> => {
const item = items[key];
return isRecord(item) ? item : {};
};
const timeValue = (key: string, name: 'start' | 'end'): string | null => {
const time = slotRecord(key)[name];
return typeof time === 'string' ? time : null;
};
const update = (key: string, patch: Record<string, unknown>) =>
onChange({ ...items, [key]: { ...slotRecord(key), ...patch } });
const toggleDay = (key: string, slot: Slot, day: Weekday) => {
const days = slot.days.includes(day) ? slot.days.filter((d) => d !== day) : [...slot.days, day];
update(key, { days: daysValue(days) });
};
const addSlot = () => {
const last = entries.at(-1)?.[1];
const days = last && last.days.length > 0 ? last.days : FIRST_SLOT_DAYS;
onChange({
...items,
[nextSlotKey(raw)]: { ...buildNewObjectValue(schema, WORKING_HOURS_SLOT), days: daysValue(days) },
});
};
const removeSlot = (key: string) => {
const copy = { ...items };
delete copy[key];
onChange(copy);
};
const applyPreset = (preset: PresetName) => onChange(slotsValue(PRESETS[preset]));
return (
<div className="space-y-3" data-slot="weekly-schedule">
{entries.length > 0 ? (
<div className={cn('rounded-xl p-3', inPanel ? 'bg-card shadow-tile' : 'bg-muted')}>
<WeekChart entries={entries} rules={rules} order={order} label={summary.join('; ')} />
</div>
) : (
<div className="space-y-2">
<p className="text-sm text-muted-foreground">{t('schedule.empty', 'No intervals yet.')}</p>
{!readOnly && (
<div className="space-y-1.5">
<p className="text-[13px] text-muted-foreground">{t('schedule.startFrom', 'Start from:')}</p>
<div className="flex flex-wrap gap-2">
{presetsFor(rules).map((preset) => (
<Button key={preset} type="button" variant="outline" size="sm" onClick={() => applyPreset(preset)}>
{preset === 'outsideWorkdays'
? t('schedule.presetOutsideWorkdays', 'Evenings, nights and weekends')
: formatSlot(t, parseSlot(slotsValue(PRESETS[preset])[0]), order, rules)}
</Button>
))}
</div>
</div>
)}
{minItems != null && minItems > 0 && (
<p className="text-xs font-medium text-destructive">
{t('schedule.issueEmpty', 'Add at least one interval.')}
</p>
)}
</div>
)}
{entries.map(([key, slot], position) => {
const issue = slotIssue(slot, rules);
const slotLabel = t('schedule.interval', 'Interval {{n}}', { n: position + 1 });
const issueId = `${baseId}-${key}-issue`;
const describedBy = issue ? issueId : undefined;
return (
<div
key={key}
role="group"
aria-label={slotLabel}
data-slot="schedule-slot"
className={cn('space-y-2 rounded-xl p-3', inPanel ? 'bg-card shadow-tile' : 'bg-muted')}
>
<div className="flex items-start gap-2 sm:items-center">
<div className="flex min-w-0 flex-1 flex-wrap items-center gap-x-4 gap-y-2">
<DayToggles
days={slot.days}
order={order}
onToggle={(day) => toggleDay(key, slot, day)}
disabled={readOnly}
label={t('schedule.days', 'Days')}
/>
<div className="flex flex-wrap items-center gap-2">
<LocalTimeInput
value={timeValue(key, 'start')}
onChange={(start) => update(key, { start })}
disabled={readOnly}
aria-label={t('schedule.start', '{{slot}} start', { slot: slotLabel })}
aria-invalid={issue !== null && issue !== 'noDays' ? true : undefined}
aria-describedby={describedBy}
/>
<span className="flex items-center gap-2">
<span className="text-[13px] text-muted-foreground">{t('schedule.to', 'to')}</span>
<LocalTimeInput
value={timeValue(key, 'end')}
onChange={(end) => update(key, { end })}
allowEndOfDay
disabled={readOnly}
aria-label={t('schedule.end', '{{slot}} end', { slot: slotLabel })}
aria-invalid={issue !== null && issue !== 'noDays' ? true : undefined}
aria-describedby={describedBy}
/>
</span>
{isOvernight(slot, rules) && (
<span className="text-[12.5px] text-muted-foreground">{t('schedule.nextDay', 'next day')}</span>
)}
</div>
</div>
{!readOnly && (
<Button
type="button"
variant="ghost-danger"
size="icon-sm"
className="mt-0.5 shrink-0 sm:mt-0"
onClick={() => removeSlot(key)}
disabled={!canRemove}
aria-label={t('schedule.remove', 'Remove {{slot}}', { slot: slotLabel })}
>
<Trash2 className="h-4 w-4" aria-hidden="true" />
</Button>
)}
</div>
{issue && (
<p id={issueId} className="text-xs font-medium text-destructive">
{issueMessage(issue)}
</p>
)}
</div>
);
})}
{canAdd && (
<Button type="button" variant="secondary" size="sm" onClick={addSlot}>
<Plus className="h-4 w-4" aria-hidden="true" />
{t('schedule.add', 'Add interval')}
</Button>
)}
</div>
);
}
export function WeeklyScheduleWidget({ type, value, onChange, readOnly }: WidgetProps<FieldTypeObjectList>) {
const rules = scheduleRules(useEnclosingSchema());
return (
<WeeklyScheduleEditor
value={value}
onChange={onChange}
rules={rules}
readOnly={readOnly}
minItems={type.minItems}
maxItems={type.maxItems}
/>
);
}
@@ -18,10 +18,6 @@ export function formatPlaceholder(format: StringFormat): string | undefined {
return 'user@example.com';
case 'uri':
return 'https://example.com';
case 'localTime':
return 'HH:MM';
case 'localDate':
return 'YYYY-MM-DD';
default:
return undefined;
}
+109
View File
@@ -0,0 +1,109 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import type { FieldType } from '@/types/schema';
export type LabelMode = 'control' | 'group' | 'none';
export interface WidgetTraits {
labelMode: LabelMode;
readOnlyAsValue: boolean;
}
export type WidgetKey =
| 'string'
| 'string:secret'
| 'string:multiline'
| 'string:color'
| 'number'
| 'number:size'
| 'number:duration'
| 'utcDateTime'
| 'boolean'
| 'enum'
| 'blobId'
| 'objectId'
| 'object'
| 'object:x:Expression'
| 'object:x:Rate'
| 'object:x:OtpAuth'
| 'objectList'
| 'set'
| 'set:enum'
| 'map'
| 'unsupported';
export function widgetKey(type: FieldType): WidgetKey {
switch (type.type) {
case 'string':
switch (type.format) {
case 'secret':
case 'secretText':
return 'string:secret';
case 'text':
case 'html':
case 'sieve':
return 'string:multiline';
case 'color':
return 'string:color';
default:
return 'string';
}
case 'number':
return type.format === 'size' ? 'number:size' : type.format === 'duration' ? 'number:duration' : 'number';
case 'object':
switch (type.objectName) {
case 'x:Expression':
return 'object:x:Expression';
case 'x:Rate':
return 'object:x:Rate';
case 'x:OtpAuth':
return 'object:x:OtpAuth';
default:
return 'object';
}
case 'set':
return type.class.type === 'enum' ? 'set:enum' : 'set';
case 'utcDateTime':
case 'boolean':
case 'enum':
case 'blobId':
case 'objectId':
case 'objectList':
case 'map':
return type.type;
default:
return 'unsupported';
}
}
const TRAITS: Record<WidgetKey, WidgetTraits> = {
string: { labelMode: 'control', readOnlyAsValue: true },
'string:secret': { labelMode: 'control', readOnlyAsValue: true },
'string:multiline': { labelMode: 'control', readOnlyAsValue: true },
'string:color': { labelMode: 'control', readOnlyAsValue: true },
number: { labelMode: 'control', readOnlyAsValue: true },
'number:size': { labelMode: 'control', readOnlyAsValue: true },
'number:duration': { labelMode: 'control', readOnlyAsValue: true },
utcDateTime: { labelMode: 'control', readOnlyAsValue: true },
boolean: { labelMode: 'control', readOnlyAsValue: true },
enum: { labelMode: 'control', readOnlyAsValue: true },
blobId: { labelMode: 'control', readOnlyAsValue: false },
objectId: { labelMode: 'control', readOnlyAsValue: true },
object: { labelMode: 'group', readOnlyAsValue: false },
'object:x:Expression': { labelMode: 'group', readOnlyAsValue: false },
'object:x:Rate': { labelMode: 'control', readOnlyAsValue: false },
'object:x:OtpAuth': { labelMode: 'none', readOnlyAsValue: false },
objectList: { labelMode: 'group', readOnlyAsValue: false },
set: { labelMode: 'control', readOnlyAsValue: true },
'set:enum': { labelMode: 'group', readOnlyAsValue: true },
map: { labelMode: 'group', readOnlyAsValue: false },
unsupported: { labelMode: 'none', readOnlyAsValue: false },
};
export function widgetTraits(type: FieldType): WidgetTraits {
return TRAITS[widgetKey(type)];
}
-1
View File
@@ -23,5 +23,4 @@ export interface WidgetProps<T extends FieldType = FieldType> {
onChange: (value: unknown) => void;
readOnly: boolean;
control: ControlProps;
error?: string;
}
+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}>
+126 -58
View File
@@ -4,17 +4,49 @@
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import { Suspense, type ReactNode } from 'react';
import { lazy, Suspense, type ComponentType, type ReactNode } from 'react';
import { useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import type { TFunction } from 'i18next';
import { useSchemaStore } from '@/stores/schemaStore';
import { usePermissionCheckers } from '@/hooks/usePermissions';
import { pageObjectId, resolvePage, type PageTarget } from '@/extensions/pages';
import { resolveObject } from '@/lib/schemaResolver';
import type { PermissionCheckers } from '@/lib/permissions';
import { ErrorBoundary } from '@/components/layout/ErrorBoundary';
import { DynamicList } from '@/components/lists/DynamicList';
import { DynamicForm } from '@/components/forms/DynamicForm';
import { DynamicViewPage } from '@/components/views/DynamicViewPage';
import { LoadingFallback } from '@/components/common/LoadingFallback';
import type { Schema } from '@/types/schema';
function lazyFeature<M, P>(load: () => Promise<M>, select: (module: M) => ComponentType<P>) {
return lazy(() => load().then((module) => ({ default: select(module) })));
}
const DeliveryTracePage = lazyFeature(
() => import('@/features/troubleshoot/DeliveryTracePage'),
(m) => m.DeliveryTracePage,
);
// SPDX-SnippetBegin
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
// SPDX-License-Identifier: LicenseRef-SEL
const DashboardView = lazyFeature(
() => import('@/features/dashboard/components/DashboardView'),
(m) => m.DashboardView,
);
const LiveTracingPage = lazyFeature(
() => import('@/features/tracing/components/LiveTracingPage'),
(m) => m.LiveTracingPage,
);
const TraceDetailView = lazyFeature(
() => import('@/features/tracing/components/TraceDetailView'),
(m) => m.TraceDetailView,
);
// SPDX-SnippetEnd
const ActionPage = lazyFeature(
() => import('@/features/actions/ActionPage'),
(m) => m.ActionPage,
);
interface MainContentProps {
viewName?: string;
@@ -22,68 +54,104 @@ interface MainContentProps {
section?: string;
}
function genericView(viewName: string, target: PageTarget, key: string): ReactNode {
switch (target.mode) {
case 'list':
return <DynamicList key={key} viewName={viewName} />;
case 'create':
return <DynamicForm key={key} viewName={viewName} objectId={null} />;
case 'singleton':
return <DynamicForm key={key} viewName={viewName} objectId="singleton" />;
case 'edit':
return <DynamicForm key={key} viewName={viewName} objectId={target.id} />;
case 'detail':
return <DynamicViewPage key={key} viewName={viewName} objectId={target.id} />;
}
}
export function MainContent({ viewName, id, section = '' }: MainContentProps) {
export function MainContent({ viewName, id, section }: MainContentProps) {
const schema = useSchemaStore((s) => s.schema);
const permissions = usePermissionCheckers();
const location = useLocation();
const { t } = useTranslation();
const page = resolvePage(schema, viewName, id, permissions);
let content: ReactNode;
switch (page.kind) {
case 'loading':
content = <LoadingFallback />;
break;
case 'unknownComponent':
content = (
<div className="mt-3 rounded-2xl bg-muted p-10 text-center text-muted-foreground">
{t('errors.unknownComponent', 'Unknown component: {{name}}', { name: page.name })}
</div>
);
break;
case 'unknownView':
content = (
<div role="alert" className="mt-3 rounded-xl bg-destructive-soft p-4 text-center text-sm text-destructive">
{t('errors.unknownView', 'Unknown view: {{name}}', { name: viewName })}
</div>
);
break;
case 'route': {
const Page = page.component;
content = <Page viewName={page.viewName} objectId={id ?? null} section={section} />;
break;
}
case 'object': {
const objectId = pageObjectId(page.target);
const key = objectId ? `${page.viewName}/${objectId}` : page.viewName;
const Page = page.component;
content = Page ? (
<Page key={key} viewName={page.viewName} objectId={objectId} section={section} />
) : (
genericView(page.viewName, page.target, key)
);
break;
}
}
return (
<ErrorBoundary resetKey={location.pathname}>
<Suspense fallback={<LoadingFallback />}>{content}</Suspense>
<Suspense fallback={<LoadingFallback />}>{renderView(t, schema, permissions, viewName, id, section)}</Suspense>
</ErrorBoundary>
);
}
function renderView(
t: TFunction,
schema: Schema | null,
permissions: PermissionCheckers,
viewName?: string,
id?: string,
section?: string,
): ReactNode {
if (!viewName) {
return <LoadingFallback />;
}
// SPDX-SnippetBegin
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
// SPDX-License-Identifier: LicenseRef-SEL
if (viewName.startsWith('Dashboard/')) {
const dashboardId = viewName.slice('Dashboard/'.length);
return <DashboardView dashboardId={dashboardId} section={section ?? ''} />;
}
// SPDX-SnippetEnd
if (viewName.startsWith('CustomComponent/')) {
const componentName = viewName.slice('CustomComponent/'.length);
// SPDX-SnippetBegin
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
// SPDX-License-Identifier: LicenseRef-SEL
if (componentName === 'Dashboard') {
const firstId = schema?.dashboards?.[0]?.id ?? 'overview';
return <DashboardView dashboardId={firstId} section={section ?? ''} />;
}
// SPDX-SnippetEnd
if (componentName === 'LiveDelivery') {
return <DeliveryTracePage />;
}
// SPDX-SnippetBegin
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
// SPDX-License-Identifier: LicenseRef-SEL
if (componentName === 'LiveTracing') {
return <LiveTracingPage />;
}
// SPDX-SnippetEnd
return (
<div className="rounded-lg border border-dashed p-12 text-center text-muted-foreground">
{t('errors.unknownComponent', 'Unknown component: {{name}}', { name: componentName })}
</div>
);
}
if (!schema) {
return <LoadingFallback />;
}
const resolved = resolveObject(schema, viewName);
if (!resolved) {
return (
<div role="alert" className="flex items-center justify-center p-8 text-destructive">
{t('errors.unknownView', 'Unknown view: {{name}}', { name: viewName })}
</div>
);
}
if (resolved.objectName === 'x:Action') {
return <ActionPage key={viewName} viewName={viewName} />;
}
if (resolved.objectType.type === 'singleton') {
return <DynamicForm key={`${viewName}/singleton`} viewName={viewName} objectId="singleton" />;
}
if (id === 'new') {
return <DynamicForm key={`${viewName}/new`} viewName={viewName} objectId={null} />;
}
if (id) {
// SPDX-SnippetBegin
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
// SPDX-License-Identifier: LicenseRef-SEL
if (resolved.objectName === 'x:Trace') {
return <TraceDetailView key={`${viewName}/${id}`} viewName={viewName} objectId={id} />;
}
// SPDX-SnippetEnd
if (!permissions.hasObjectPermission(resolved.permissionPrefix, 'Update')) {
return <DynamicViewPage key={`${viewName}/${id}`} viewName={viewName} objectId={id} />;
}
return <DynamicForm key={`${viewName}/${id}`} viewName={viewName} objectId={id} />;
}
return <DynamicList key={viewName} viewName={viewName} />;
}
+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 grid-cols-1 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>
+7 -7
View File
@@ -11,7 +11,6 @@ import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Combobox } from '@/components/ui/combobox';
import { ObjectPicker } from '@/components/common/ObjectPicker';
import { SearchInput } from '@/components/common/SearchInput';
import { getEnum } from '@/lib/schemaResolver';
import type { Filter, FilterDate, FilterEnum, FilterInteger, FilterObjectId, FilterText, Schema } from '@/types/schema';
@@ -34,8 +33,8 @@ function opField(filter: Filter): string {
function LabelledField({ id, label, children }: { id: string; label: string; children: ReactNode }) {
return (
<div className="flex min-w-0 flex-col gap-1.5">
<label htmlFor={id} className="text-[12.5px] font-semibold text-muted-foreground">
<div className="flex flex-col gap-1.5">
<label htmlFor={id} className="text-xs font-medium text-muted-foreground">
{label}
</label>
{children}
@@ -46,8 +45,8 @@ function LabelledField({ id, label, children }: { id: string; label: string; chi
function GroupField({ label, children }: { label: string; children: ReactNode }) {
const labelId = useId();
return (
<div role="group" aria-labelledby={labelId} className="flex min-w-0 flex-col gap-1.5">
<span id={labelId} className="text-[12.5px] font-semibold text-muted-foreground">
<div role="group" aria-labelledby={labelId} className="flex flex-col gap-1.5">
<span id={labelId} className="text-xs font-medium text-muted-foreground">
{label}
</span>
{children}
@@ -60,11 +59,12 @@ function TextFilter({ filter, values, onChange }: FilterFieldProps<FilterText>)
const id = useId();
return (
<LabelledField id={id} label={filter.label}>
<SearchInput
<Input
id={id}
type="search"
placeholder={t('list.filterPlaceholder', 'Search {{label}}...', { label: filter.label.toLowerCase() })}
value={values[filter.field] ?? ''}
onValueChange={(next) => onChange(filter.field, next)}
onChange={(e) => onChange(filter.field, e.target.value)}
/>
</LabelledField>
);
+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 -3
View File
@@ -25,7 +25,6 @@ function PopoverContent({
className,
align = 'center',
sideOffset = 4,
collisionPadding = 8,
...props
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
return (
@@ -34,9 +33,8 @@ function PopoverContent({
data-slot="popover-content"
align={align}
sideOffset={sideOffset}
collisionPadding={collisionPadding}
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}
+6 -14
View File
@@ -22,27 +22,19 @@ 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]:min-w-0 [&>span]:truncate',
variant === 'field'
? 'field-surface h-9 w-full gap-2 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}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDown className="h-4 w-4 shrink-0 opacity-50" />
<ChevronDown className="h-4 w-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
);
@@ -86,9 +78,9 @@ 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' &&
'max-w-[var(--radix-select-content-available-width)] data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
'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,
)}
position={position}
@@ -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}
+10 -14
View File
@@ -8,12 +8,10 @@ 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';
import { resolveWidget } from '@/extensions/widgets';
import { getEnumVariant, mapEntryValueType } from '@/lib/schemaResolver';
import { getEnumVariant } from '@/lib/schemaResolver';
import {
embeddedEntries,
embeddedSummary,
@@ -51,8 +49,6 @@ export function FieldValue({ schema, type, value, variant = 'full', className }:
function renderValue(schema: Schema, type: FieldType, value: unknown, variant: ValueVariant): ReactNode {
if (isEmptyValue(value)) return <EmptyValue variant={variant} />;
const { View } = resolveWidget(type);
if (View) return <View schema={schema} type={type} value={value} variant={variant} />;
switch (type.type) {
case 'string':
return <StringValue value={value} format={type.format} variant={variant} />;
@@ -128,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 }} />
)}
@@ -173,13 +169,13 @@ 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}
schema={schema}
label={<ScalarLabel schema={schema} type={keyClass} value={key} />}
type={mapEntryValueType(schema, keyClass, valueClass, key) as FieldType}
type={valueClass as FieldType}
value={val}
/>
))}
@@ -209,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} />
))}
@@ -310,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 ? (
@@ -321,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}
@@ -365,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>
);
-23
View File
@@ -1,23 +0,0 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import { useState } from 'react';
import { formatUtcOffset } from '@/lib/format';
import { getEnumVariant } from '@/lib/schemaResolver';
import type { ValueProps } from '@/extensions/types';
export function TimeZoneValue({ schema, type, value, variant }: ValueProps) {
const [now] = useState(() => new Date());
const name = String(value);
const label = (type.type === 'enum' ? getEnumVariant(schema, type.enumName, name)?.label : undefined) ?? name;
const offset = variant === 'full' ? formatUtcOffset(name, now) : null;
return (
<span className="text-sm">
{label}
{offset && <span className="ms-1.5 text-muted-foreground tabular-nums">({offset})</span>}
</span>
);
}
@@ -1,105 +0,0 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import { useTranslation } from 'react-i18next';
import { useInPanel } from '@/components/forms/formContext';
import { formatNumber, formatWeekday } from '@/lib/format';
import { MINUTES_PER_DAY, MINUTES_PER_HOUR } from '@/lib/localDateTime';
import { formatSlot, localeWeekdayOrder } from '@/lib/scheduleFormat';
import {
daySegments,
parseSlot,
slotEntries,
weekdayIndex,
type ScheduleRules,
type Slot,
type Weekday,
} from '@/lib/weeklySchedule';
import { cn } from '@/lib/utils';
import type { ValueProps } from '@/extensions/types';
const AXIS_HOURS = [0, 6, 12, 18, 24] as const;
interface WeekChartProps {
entries: readonly [string, Slot][];
rules: ScheduleRules;
order: readonly Weekday[];
label: string;
}
function percent(minutes: number): string {
return `${(minutes / MINUTES_PER_DAY) * 100}%`;
}
export function WeekChart({ entries, rules, order, label }: WeekChartProps) {
const inPanel = useInPanel();
const segments = daySegments(entries, rules);
return (
<div role="img" aria-label={label} data-slot="week-chart" className="space-y-1">
{order.map((day) => (
<div key={day} className="flex items-center gap-2">
<span className="w-10 shrink-0 truncate text-[12px] text-muted-foreground" aria-hidden="true">
{formatWeekday(day, 'short')}
</span>
<div className={cn('relative h-4 flex-1 overflow-hidden rounded-full', inPanel ? 'bg-muted' : 'bg-card')}>
{AXIS_HOURS.slice(1, -1).map((hour) => (
<span
key={hour}
className="absolute inset-y-0 w-px bg-border"
style={{ insetInlineStart: percent(hour * MINUTES_PER_HOUR) }}
/>
))}
{segments[weekdayIndex(day) ?? 0].map((segment) => (
<span
key={`${segment.key}-${segment.start}`}
data-slot="week-chart-bar"
className="absolute inset-y-0 rounded-full bg-primary"
style={{ insetInlineStart: percent(segment.start), width: percent(segment.end - segment.start) }}
/>
))}
</div>
</div>
))}
<div className="flex gap-2" aria-hidden="true">
<span className="w-10 shrink-0" />
<div className="relative h-4 flex-1 text-[11px] text-dim tabular-nums">
{AXIS_HOURS.map((hour) => (
<span
key={hour}
className={cn(
'absolute',
hour === 0 ? 'start-0' : hour === 24 ? 'end-0' : '-translate-x-1/2 rtl:translate-x-1/2',
)}
style={hour === 0 || hour === 24 ? undefined : { insetInlineStart: percent(hour * MINUTES_PER_HOUR) }}
>
{formatNumber(hour)}
</span>
))}
</div>
</div>
</div>
);
}
const DISPLAY_RULES: ScheduleRules = 'overnight';
export function WeeklyScheduleValue({ value, variant }: ValueProps) {
const { t } = useTranslation();
const order = localeWeekdayOrder();
const entries = slotEntries(value).map(([key, item]): [string, Slot] => [key, parseSlot(item)]);
const lines = entries.map(([, slot]) => formatSlot(t, slot, order, DISPLAY_RULES));
if (variant === 'compact') return <span className="text-sm">{lines.join('; ')}</span>;
return (
<div className="space-y-3">
<WeekChart entries={entries} rules={DISPLAY_RULES} order={order} label={lines.join('; ')} />
<ul className="space-y-0.5 text-sm">
{lines.map((line, i) => (
<li key={entries[i][0]}>{line}</li>
))}
</ul>
</div>
);
}
+21 -27
View File
@@ -4,30 +4,19 @@
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import type { ComponentType } from 'react';
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';
export interface ViewRenderProps {
schema: Schema;
field: Field;
formField: FormField;
data: Record<string, unknown>;
}
export type ViewRenderers = Readonly<Record<string, ComponentType<ViewRenderProps>>>;
export interface DynamicViewProps {
schema: Schema;
objectName: string;
viewName: string;
data: Record<string, unknown>;
visibleFields?: Set<string>;
renderers?: ViewRenderers;
}
interface ViewSection {
@@ -81,24 +70,29 @@ function buildViewSections(
return items.length > 0 ? [{ key: 'section-0', items }] : [];
}
export function DynamicView({ schema, objectName, viewName, data, visibleFields, renderers }: DynamicViewProps) {
export function DynamicView({ schema, objectName, viewName, data, visibleFields }: DynamicViewProps) {
const layout = resolveViewLayout(schema, objectName, viewName, data);
if (!layout) return null;
const sections = buildViewSections(layout, 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 }) => {
const Render = renderers && Object.hasOwn(renderers, formField.name) ? renderers[formField.name] : null;
return Render ? (
<Render key={formField.name} schema={schema} field={field} formField={formField} data={data} />
) : (
<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}
@@ -107,10 +101,10 @@ export function DynamicView({ schema, objectName, viewName, data, visibleFields,
type={field.type}
value={data[formField.name]}
/>
);
})}
</dl>
</section>
))}
</dl>
</CardContent>
</Card>
))}
</div>
);
+14 -29
View File
@@ -13,21 +13,19 @@ import { resolveObject, resolveList, getDisplayProperty } from '@/lib/schemaReso
import { coerceLabel } from '@/lib/objectOptions';
import { errorMessage } from '@/lib/jmapErrors';
import { useJmapObject } from '@/data/objects';
import { DynamicView, type ViewRenderers } from './DynamicView';
import { DynamicView } from './DynamicView';
interface DynamicViewPageProps {
viewName: string;
objectId: string;
accountId?: string;
renderers?: ViewRenderers;
}
export function DynamicViewPage({ viewName, objectId, accountId, renderers }: DynamicViewPageProps) {
export function DynamicViewPage({ viewName, objectId }: DynamicViewPageProps) {
const { t } = useTranslation();
const navigate = useNavigate();
const schema = useSchemaStore((s) => s.schema);
const resolvedObject = schema ? resolveObject(schema, viewName) : null;
const query = useJmapObject(resolvedObject?.objectName, objectId, undefined, { accountId });
const query = useJmapObject(resolvedObject?.objectName, objectId);
const data = query.data ?? null;
const loading = query.isPending && query.fetchStatus !== 'idle';
const error = !schema
@@ -43,21 +41,19 @@ export function DynamicViewPage({ viewName, objectId, accountId, renderers }: Dy
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>
);
}
@@ -75,27 +71,16 @@ export function DynamicViewPage({ viewName, objectId, accountId, renderers }: Dy
: 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}
renderers={renderers}
/>
<DynamicView schema={schema} objectName={resolved.objectName} viewName={viewName} data={data} />
</div>
);
}
+3 -4
View File
@@ -14,13 +14,12 @@ export const jmapKeys = {
all: ['jmap'] as const,
type: (objectName: string) => ['jmap', objectName] as const,
objects: (objectName: string) => ['jmap', objectName, 'object'] as const,
object: (objectName: string, id: string, properties?: readonly string[], accountId?: string) =>
['jmap', objectName, 'object', id, properties ? [...properties].sort() : null, accountId ?? null] as const,
object: (objectName: string, id: string, properties?: readonly string[]) =>
['jmap', objectName, 'object', id, properties ? [...properties].sort() : null] as const,
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 -18
View File
@@ -21,21 +21,11 @@ import type { JmapSetResponse } from '@/types/jmap';
export interface SetVariables extends JmapSetOptions {
blobs?: Record<string, BlobUpload>;
accountId?: string;
}
export type BulkTarget = { ids: string[] } | { query: JmapQueryOptions };
export type BulkVariables = (
| (BulkTarget & ({ action: 'destroy' } | { action: 'update'; patch: JmapObject }))
| { action: 'updateEach'; patches: Record<string, JmapObject> }
) & { accountId?: string };
async function bulkIds(objectName: string, vars: BulkVariables, signal?: AbortSignal): Promise<string[]> {
if (vars.action === 'updateEach') return Object.keys(vars.patches);
if ('ids' in vars) return vars.ids;
return jmapQueryAll(objectName, vars.query, { accountId: vars.accountId, signal });
}
export type BulkVariables = BulkTarget & ({ action: 'destroy' } | { action: 'update'; patch: JmapObject });
function isListOf(key: QueryKey, objectName: string): boolean {
return key[1] === objectName && key[2] === 'list';
@@ -55,9 +45,9 @@ export async function invalidateObjectType(client: QueryClient, objectName: stri
export function useJmapSet(objectName: string | null | undefined) {
const client = useQueryClient();
return useMutation<JmapSetResponse, Error, SetVariables>({
mutationFn: ({ blobs, accountId, ...set }) => {
mutationFn: ({ blobs, ...set }) => {
if (!objectName) throw new Error('No object type to update');
return jmapSet(objectName, set, { blobs, accountId });
return jmapSet(objectName, set, { blobs });
},
onSettled: () => {
if (objectName) return invalidateObjectType(client, objectName);
@@ -66,8 +56,7 @@ export function useJmapSet(objectName: string | null | undefined) {
}
export async function runBulkSet(objectName: string, vars: BulkVariables, signal?: AbortSignal): Promise<SetOutcome> {
const ids = await bulkIds(objectName, vars, signal);
const { accountId } = vars;
const ids = 'ids' in vars ? vars.ids : await jmapQueryAll(objectName, vars.query, { signal });
const batchSize = Math.max(1, useAuthStore.getState().maxObjectsInSet);
const outcome: SetOutcome = { succeeded: [], failed: {} };
for (let offset = 0; offset < ids.length; offset += batchSize) {
@@ -76,11 +65,11 @@ export async function runBulkSet(objectName: string, vars: BulkVariables, signal
let partial: SetOutcome;
try {
if (vars.action === 'destroy') {
partial = destroyedOutcome(await jmapSet(objectName, { destroy: batch }, { accountId, signal }));
partial = destroyedOutcome(await jmapSet(objectName, { destroy: batch }, { signal }));
} else {
const update: Record<string, JmapObject> = {};
for (const id of batch) update[id] = vars.action === 'updateEach' ? vars.patches[id] : vars.patch;
partial = updatedOutcome(await jmapSet(objectName, { update }, { accountId, signal }));
for (const id of batch) update[id] = vars.patch;
partial = updatedOutcome(await jmapSet(objectName, { update }, { signal }));
}
} catch (err) {
const aborted = isAbortError(err);
+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;
+4 -5
View File
@@ -17,15 +17,14 @@ export interface ListPage {
interface QueryTuning {
enabled?: boolean;
accountId?: string;
staleTime?: number;
refetchOnMount?: boolean | 'always';
}
export function jmapObjectQuery(objectName: string, id: string, properties?: string[], accountId?: string) {
export function jmapObjectQuery(objectName: string, id: string, properties?: string[]) {
return queryOptions({
queryKey: jmapKeys.object(objectName, id, properties, accountId),
queryFn: ({ signal }) => jmapGetOne(objectName, id, properties, { signal, accountId }),
queryKey: jmapKeys.object(objectName, id, properties),
queryFn: ({ signal }) => jmapGetOne(objectName, id, properties, { signal }),
staleTime: 0,
});
}
@@ -37,7 +36,7 @@ export function useJmapObject(
tuning: QueryTuning = {},
) {
return useQuery({
...jmapObjectQuery(objectName ?? '', id ?? '', properties, tuning.accountId),
...jmapObjectQuery(objectName ?? '', id ?? '', properties),
enabled: !!objectName && !!id && (tuning.enabled ?? true),
staleTime: tuning.staleTime ?? 0,
refetchOnMount: tuning.refetchOnMount ?? true,
+3 -9
View File
@@ -5,7 +5,6 @@
*/
import { QueryClient, type QueryKey } from '@tanstack/react-query';
import { resolveAccountId, type AccountSelection } from '@/services/jmap/client';
import { isRetryableError } from '@/services/errors';
import { useAuthStore } from '@/stores/authStore';
import { jmapKeys } from '@/data/keys';
@@ -17,10 +16,8 @@ export function shouldRetry(failureCount: number, error: unknown): boolean {
return failureCount < MAX_QUERY_RETRIES && isRetryableError(error);
}
function accountChanged(key: QueryKey, prev: AccountSelection, next: AccountSelection): boolean {
const objectType = key[1];
if (typeof objectType !== 'string') return true;
return resolveAccountId(objectType, prev) !== resolveAccountId(objectType, next);
function isManagementKey(key: QueryKey): boolean {
return typeof key[1] === 'string' && key[1].startsWith('x:');
}
export function createQueryClient(): QueryClient {
@@ -48,10 +45,7 @@ export function bindQueryClientToAuth(client: QueryClient): () => void {
return;
}
if (prev.activeAccountId !== null && state.activeAccountId !== prev.activeAccountId) {
void client.resetQueries({
queryKey: jmapKeys.all,
predicate: (query) => accountChanged(query.queryKey, prev, state),
});
void client.resetQueries({ queryKey: jmapKeys.all, predicate: (query) => !isManagementKey(query.queryKey) });
}
});
}
Loaded 100 of 181 files, more files were not shown because too many files have changed in this diff. Show more