mirror of
https://github.com/stalwartlabs/webui.git
synced 2026-12-06 16:04:38 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d48abb77f9 | ||
|
|
792530ab3c | ||
|
|
cb0af4334f | ||
|
|
6e76d2f9e9 | ||
|
|
51f47f0f81 | ||
|
|
64bebee21a | ||
|
|
337437bf31 | ||
|
|
a692e8a270 | ||
|
|
2ca40e9559 | ||
|
|
1a595c2121 | ||
|
|
6b8ad61b57 | ||
|
|
0e31addbbb | ||
|
|
e777b81fb8 | ||
|
|
44b3f914c6 | ||
|
|
03954f8052 | ||
|
|
db31e845ae | ||
|
|
f10408be22 | ||
|
|
f835f4fd62 | ||
|
|
0697f8a0f4 | ||
|
|
e5a3b29125 | ||
|
|
d87912c39b | ||
|
|
1461b17a75 | ||
|
|
9376af97c4 | ||
|
|
7988018fdd | ||
|
|
1b0ce53c17 | ||
|
|
dc462b137f | ||
|
|
b0b8e4e090 |
No files matched your search
@@ -3,7 +3,7 @@ name: Build and Release
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
- 'v*.*.*'
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -11,6 +11,9 @@ permissions:
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
major: ${{ steps.version.outputs.major }}
|
||||
prerelease: ${{ steps.version.outputs.prerelease }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
@@ -20,14 +23,33 @@ jobs:
|
||||
node-version: 22
|
||||
cache: npm
|
||||
|
||||
- name: Read package version
|
||||
id: version
|
||||
run: |
|
||||
version=$(node -p "require('./package.json').version")
|
||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||
echo "major=${version%%.*}" >> "$GITHUB_OUTPUT"
|
||||
case "$version" in
|
||||
*-*) echo "prerelease=true" >> "$GITHUB_OUTPUT" ;;
|
||||
*) echo "prerelease=false" >> "$GITHUB_OUTPUT" ;;
|
||||
esac
|
||||
|
||||
- name: Check tag matches package version
|
||||
env:
|
||||
TAG: ${{ github.ref_name }}
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
run: |
|
||||
if [ "${TAG#v}" != "$VERSION" ]; then
|
||||
echo "::error::Tag $TAG does not match package.json version $VERSION"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- run: npm ci
|
||||
|
||||
- run: npm run typecheck
|
||||
|
||||
- run: npx eslint src/
|
||||
|
||||
- run: npx vitest run
|
||||
|
||||
- run: npm run build
|
||||
|
||||
- name: Create webui.zip
|
||||
@@ -60,6 +82,45 @@ jobs:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: gh release edit "${{ github.ref_name }}" --draft=false --latest --repo "${{ github.repository }}"
|
||||
|
||||
rolling:
|
||||
name: Update rolling major release
|
||||
needs: [build, publish]
|
||||
if: needs.build.outputs.prerelease == 'false'
|
||||
runs-on: ubuntu-latest
|
||||
concurrency:
|
||||
group: rolling-v${{ needs.build.outputs.major }}
|
||||
cancel-in-progress: false
|
||||
permissions:
|
||||
contents: write
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
TAG: ${{ github.ref_name }}
|
||||
ROLLING_TAG: v${{ needs.build.outputs.major }}
|
||||
ASSET: webui.zip
|
||||
steps:
|
||||
- name: Download versioned asset
|
||||
run: gh release download "$TAG" --pattern "$ASSET"
|
||||
|
||||
- name: Move rolling tag
|
||||
run: |
|
||||
if gh api "repos/$GH_REPO/git/ref/tags/$ROLLING_TAG" --silent 2>/dev/null; then
|
||||
gh api -X PATCH "repos/$GH_REPO/git/refs/tags/$ROLLING_TAG" -f sha="$GITHUB_SHA" -F force=true --silent
|
||||
else
|
||||
gh api -X POST "repos/$GH_REPO/git/refs" -f ref="refs/tags/$ROLLING_TAG" -f sha="$GITHUB_SHA" --silent
|
||||
fi
|
||||
|
||||
- name: Publish rolling release
|
||||
run: |
|
||||
title="Stalwart WebUI ${ROLLING_TAG#v}.x"
|
||||
notes="Tracks the latest ${ROLLING_TAG#v}.x release."
|
||||
if gh release view "$ROLLING_TAG" >/dev/null 2>&1; then
|
||||
gh release edit "$ROLLING_TAG" --title "$title" --notes "$notes" --draft=false --prerelease=false --latest=false
|
||||
gh release upload "$ROLLING_TAG" "$ASSET" --clobber
|
||||
else
|
||||
gh release create "$ROLLING_TAG" "$ASSET" --verify-tag --title "$title" --notes "$notes" --latest=false
|
||||
fi
|
||||
|
||||
cleanup:
|
||||
name: Cleanup failed release
|
||||
needs: [build]
|
||||
|
||||
+135
@@ -2,6 +2,141 @@
|
||||
|
||||
All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/).
|
||||
|
||||
## [2.1.3] - 2026-12-03
|
||||
|
||||
### Fixed
|
||||
- Browser auto-translation (Chrome, Edge, Safari) is turned off for the web interface, which crashed with a `removeChild` error when the translator rewrote the page.
|
||||
- Forms: Save is enabled as soon as a field is edited, without leaving the field first, and the Delete, Cancel and Save buttons no longer move when the "Unsaved changes" label appears.
|
||||
|
||||
## [2.1.2] - 2026-11-29
|
||||
|
||||
### Fixed
|
||||
- Sign-in no longer sends `prompt=login`, so an existing single sign-on session at an external OpenID Connect provider is reused instead of asking for the login again.
|
||||
- Calendars, address books and mailboxes that still hold events, contacts or messages can be deleted. The delete confirmation says that their contents are deleted with them.
|
||||
- Dashboard:
|
||||
- Counter charts drop to zero in empty intervals instead of repeating the last value, so a short burst (for example the morning DMARC and TLS reports) no longer shows as hours of steady activity.
|
||||
- Pass, ham and other good series are drawn in teal and fail or spam in red, instead of the reverse.
|
||||
- Mail Rules editor: alternatives and exceptions keep their place. Adding an exception no longer moves the "Add alternative" button below it, and the add buttons are evenly spaced.
|
||||
|
||||
## [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
|
||||
|
||||
### Changed
|
||||
|
||||
### Fixed
|
||||
- Actions page hidden on Stalwart 1.0: create-only objects such as `x:Action` are now shown to accounts holding their Create permission (#27).
|
||||
|
||||
## [2.0.0] - 2026-10-26
|
||||
|
||||
### Added
|
||||
- CIMD support.
|
||||
|
||||
### Changed
|
||||
|
||||
### Fixed
|
||||
|
||||
## [1.0.11] - 2026-09-15
|
||||
|
||||
### Added
|
||||
- Sievepad integration.
|
||||
|
||||
### Changed
|
||||
|
||||
### Fixed
|
||||
|
||||
## [1.0.10] - 2026-09-04
|
||||
|
||||
### Added
|
||||
|
||||
### Changed
|
||||
|
||||
### Fixed
|
||||
- Re-added map entries and object list items are seeded with their schema defaults, including a value for every non-nullable boolean.
|
||||
|
||||
## [1.0.9] - 2026-08-24
|
||||
|
||||
### Added
|
||||
|
||||
+168
-105
@@ -1,213 +1,276 @@
|
||||
# Stalwart Enterprise License 2.0 (SELv2) Agreement
|
||||
# Stalwart Enterprise License 3.0 (SELv3) Agreement
|
||||
|
||||
*Last Update: March 29, 2026*
|
||||
*Last Update: December 5, 2026*
|
||||
|
||||
PLEASE CAREFULLY READ THIS STALWART ENTERPRISE LICENSE AGREEMENT ("AGREEMENT"). THIS AGREEMENT CONSTITUTES A LEGALLY BINDING AGREEMENT BETWEEN YOU AND STALWART LABS LLC AND GOVERNS YOUR USE OF THE SOFTWARE (DEFINED BELOW). IF YOU DO NOT AGREE WITH THIS AGREEMENT, YOU MAY NOT USE THE SOFTWARE. IF YOU ARE USING THE SOFTWARE ON BEHALF OF A LEGAL ENTITY, YOU REPRESENT AND WARRANT THAT YOU HAVE AUTHORITY TO AGREE TO THIS AGREEMENT ON BEHALF OF SUCH ENTITY. IF YOU DO NOT HAVE SUCH AUTHORITY, DO NOT USE THE SOFTWARE IN ANY MANNER.
|
||||
**Please read this Stalwart Enterprise License Agreement ("Agreement") carefully. It is a legally binding agreement between Stalwart Labs S.L. and the business, organization or professional that purchases a Subscription, and it governs the use of the Software (defined below). The Software is licensed only for business and professional purposes and is not offered to consumers. If you accept this Agreement on behalf of a legal entity, you represent that you have authority to bind that entity. If you do not agree with this Agreement, or do not have such authority, do not use the Software.**
|
||||
|
||||
This Agreement is entered into by and between Stalwart Labs LLC and you, or the legal entity on behalf of whom you are acting.
|
||||
This Agreement is entered into by and between Stalwart Labs S.L., a Spanish limited liability company (*sociedad limitada*) with its registered office at Pedro Asua Kalea 69, 01008 Vitoria-Gasteiz, Spain, tax identification number (NIF) B05835616, registered in the Commercial Registry (*Registro Mercantil*) on sheet VI-00023353, electronic folio (IRUS) 1000481890164, and the Licensee.
|
||||
|
||||
---
|
||||
|
||||
## 1. DEFINITIONS
|
||||
|
||||
1.1. "Software" refers to the Stalwart Server Enterprise Edition software, including all its versions, updates, modifications, accompanying documentation, and related materials. The Software is self-hosted by Licensee on its own infrastructure.
|
||||
1.1. "Software" refers to the Stalwart Server Enterprise Edition software, including all its versions, updates and modifications made by or for Licensor, accompanying documentation, and related materials. The Software is self-hosted by Licensee on infrastructure that Licensee operates or controls.
|
||||
|
||||
1.2. "Subscription" refers to the paid access to the Software provided by Licensor to Licensee, billed on a monthly or annual basis.
|
||||
|
||||
1.3. "Licensor" refers to Stalwart Labs LLC, the entity providing the Software.
|
||||
1.3. "Licensor" refers to Stalwart Labs S.L., the entity providing the Software.
|
||||
|
||||
1.4. "Licensee" refers to the individual or entity installing, accessing, or using the Software with a valid Subscription.
|
||||
1.4. "Licensee" refers to the legal entity, public body or individual acting for purposes relating to its trade, business, craft or profession that accepts this Agreement and holds a valid Subscription or a trial License Key, or that copies or modifies the Source Code under Section 5.5.
|
||||
|
||||
1.5. "License Key" refers to the unique code provided by Licensor upon purchasing a Subscription which activates the full features of the Software. Each License Key is bound to the domain name (including all subdomains) designated by Licensee at the time of purchase.
|
||||
1.5. "End User" refers to any individual who uses or accesses the Software through Licensee's deployment, including Licensee's employees, contractors and administrators, and the users of Mailboxes provisioned by Licensee for itself or for its tenants.
|
||||
|
||||
1.6. "Source Code" refers to the human-readable version of the Software's code, as opposed to the compiled machine-readable version.
|
||||
1.6. "License Key" refers to the unique code provided by Licensor upon purchasing a Subscription which activates the full features of the Software. Each License Key is bound to the domain name (including all subdomains) designated by Licensee at the time of purchase. A "trial License Key" is a License Key that Licensor issues, without a Subscription, for a limited period to evaluate the Software.
|
||||
|
||||
1.7. "Mailbox" refers to each individual user account or group account provisioned within the Software. The total number of Mailboxes across all domains and tenants hosted by Licensee determines the applicable Subscription tier.
|
||||
1.7. "Source Code" refers to the human-readable version of the Software's code, as opposed to the compiled machine-readable version.
|
||||
|
||||
1.8. "Confidential Information" refers to any non-public information disclosed by either party to the other in connection with this Agreement, whether in written, oral, electronic, or other form, that is designated as confidential or that a reasonable person would understand to be confidential given the nature of the information and circumstances of disclosure.
|
||||
1.8. "Mailbox" refers to each individual user account or group account provisioned within the Software. The total number of Mailboxes across all domains and tenants hosted by Licensee determines the applicable Subscription tier.
|
||||
|
||||
## 2. GRANT OF LICENSE
|
||||
1.9. "Confidential Information" refers to any non-public information disclosed by either party to the other in connection with this Agreement, whether in written, oral, electronic, or other form, that is designated as confidential or that a reasonable person would understand to be confidential given the nature of the information and circumstances of disclosure.
|
||||
|
||||
2.1. Licensor grants Licensee a non-exclusive, non-transferable, non-sublicensable, limited license to download, install, and use the Software during the Subscription term, subject to the terms and conditions of this Agreement.
|
||||
1.10. "Open Source Components" refers to software components included in or distributed with the Software that are licensed under an open source license.
|
||||
|
||||
2.2. The use of the Software is conditioned upon Licensee maintaining an active and valid paid Subscription with Licensor. The paid Subscription covers all versions of the Software and all updates and modifications released during the Subscription term.
|
||||
1.11. "Business Day" refers to any day other than a Saturday, a Sunday or a public holiday in Vitoria-Gasteiz, Spain.
|
||||
|
||||
2.3. This license grants Licensee the right to use the Software for both personal and commercial purposes. Licensee may install and operate the Software on an unlimited number of servers within its organization, host an unlimited number of domains, and host data for an unlimited number of external organizations (tenants) using the Software's multi-tenancy features. The Subscription tier is determined solely by the total number of Mailboxes provisioned. However, Licensee is expressly prohibited from reselling, leasing, sublicensing, or otherwise redistributing the Software itself.
|
||||
1.12. "Community Edition" refers to the edition of Stalwart Server that Licensor makes available under an open source license and that does not require a License Key.
|
||||
|
||||
2.4. This license is further governed by the terms and conditions set forth in any licensing agreements separately executed between Licensor and Licensee. In the event of any conflict between the terms of this Agreement and the terms of a signed licensing agreement, the terms of the signed licensing agreement shall control.
|
||||
## 2. ELIGIBILITY AND END USERS
|
||||
|
||||
2.5. You are not granted any other rights beyond what is expressly stated herein.
|
||||
2.1. The Software is licensed under this Agreement only to persons acting for purposes relating to their trade, business, craft or profession, and to public bodies. By accepting this Agreement, Licensee confirms that it is acquiring the Subscription for such purposes and not as a consumer. Licensor may require Licensee to provide its VAT number or another business tax identification number when purchasing a Subscription.
|
||||
|
||||
## 3. LICENSE KEYS
|
||||
2.2. Licensee may permit End Users to use the Software within the scope of the license granted in this Agreement. Licensee shall ensure that its End Users comply with the terms of this Agreement that apply to the use of the Software, including Sections 3, 4, 5, 6 and 15, and is responsible for the acts and omissions of its End Users as for its own.
|
||||
|
||||
3.1. The Software shall not be used without a valid License Key issued by Licensor.
|
||||
2.3. Any person who installs, operates or administers the Software on Licensee's behalf, including Licensee's contractors and service providers, does so on behalf of Licensee and subject to this Agreement.
|
||||
|
||||
3.2. Licensee is required to use valid License Keys issued by Licensor to run the Software, including any modified versions. Any attempts to bypass the License Key requirement is a violation of this Agreement.
|
||||
2.4. End Users acquire no license or other rights from Licensor under this Agreement beyond the use of the Software as made available to them by Licensee. Licensor's warranties, support and other obligations under this Agreement are owed to Licensee only.
|
||||
|
||||
3.3. Distribution or sharing of License Keys to third parties, not associated with Licensee, is strictly prohibited.
|
||||
## 3. GRANT OF LICENSE
|
||||
|
||||
3.4. License Keys are bound to the Subscription period. Should your Subscription expire or be cancelled, all License Keys will become invalid after fifteen (15) days from the Subscription expiration or cancellation date.
|
||||
3.1. Licensor grants Licensee a non-exclusive, non-transferable (except as permitted under Section 19), non-sublicensable, worldwide, limited license, for the duration of the Subscription term and the period set forth in Section 4.4, to download, install, reproduce, run and, as provided in Section 5, modify the Software for Licensee's business purposes, subject to the terms and conditions of this Agreement.
|
||||
|
||||
3.5. Any instance of the Software using such an expired key will revert to the Community Edition functionality after the aforementioned fifteen (15) day period.
|
||||
3.2. The use of the Software is conditioned upon Licensee maintaining an active and valid paid Subscription with Licensor. The paid Subscription covers all versions of the Software and all updates and modifications released during the Subscription term.
|
||||
|
||||
## 4. SOURCE CODE USAGE
|
||||
3.3. Licensee may install and operate the Software on an unlimited number of servers within its organization, host an unlimited number of domains, and host data for an unlimited number of external organizations (tenants) using the Software's multi-tenancy features. The Subscription tier is determined solely by the total number of Mailboxes provisioned. However, Licensee is expressly prohibited from reselling, leasing, sublicensing, or otherwise redistributing the Software itself.
|
||||
|
||||
4.1. Licensee is permitted to view, copy, and modify the Software's Source Code, as made available by Licensor, solely for Licensee's internal business use and in compliance with this Agreement's terms.
|
||||
3.4. This license is further governed by the terms and conditions set forth in any licensing agreements separately executed between Licensor and Licensee. In the event of any conflict between the terms of this Agreement and the terms of a signed licensing agreement, the terms of the signed licensing agreement shall control.
|
||||
|
||||
4.2. Any modifications to the Source Code do not grant Licensee any ownership rights to the original Software or any modifications. All rights, title, and interest to the Software and its Source Code remain exclusively with Licensor.
|
||||
3.5. Licensee is not granted any other rights beyond what is expressly stated herein.
|
||||
|
||||
4.3. Licensee is strictly prohibited from altering, removing, or in any way tampering with the License Key validation system within the Software. Any such unauthorized modifications will be considered a material breach of this Agreement and may result in legal action.
|
||||
## 4. LICENSE KEYS
|
||||
|
||||
4.4. Notwithstanding the availability of the Software's Source Code for review and limited modification, the Software and its Source Code are not open source and remain proprietary to Licensor. The provision of access to the Source Code does not confer any rights typically associated with open source software, including but not limited to the right to freely sublicense, or create derivative works for public distribution. All rights not expressly granted herein are reserved by Licensor.
|
||||
4.1. The Software shall not be used without a valid License Key issued by Licensor.
|
||||
|
||||
4.5. Notwithstanding the foregoing, you may copy the Source Code for development and testing purposes, without requiring a Subscription.
|
||||
4.2. Licensee is required to use valid License Keys issued by Licensor to run the Software, including any modified versions. Any attempt to bypass the License Key requirement is a violation of this Agreement.
|
||||
|
||||
## 5. INTELLECTUAL PROPERTY RIGHTS
|
||||
4.3. Distribution or sharing of License Keys to third parties, not associated with Licensee, is strictly prohibited.
|
||||
|
||||
5.1. The Licensor retains all rights, title, and interest in and to the Software, including all intellectual property rights therein. This Agreement does not transfer any ownership rights to the Licensee.
|
||||
4.4. License Keys are bound to the Subscription period. A License Key remains valid until five (5) days after the end of the paid Subscription term. If a renewal payment has not been received by the end of the term, the Subscription enters a grace period, the end date of which Licensor communicates to Licensee, and the License Key remains valid until five (5) days after the end of that grace period; a renewal paid during the grace period starts at the end of the previous term. Where Licensor has agreed that Licensee may pay within thirty (30) days under Section 7.6, the Subscription renews at the end of the term and payment is due as set forth in that Section. If payment is not received by the end of the grace period, the Subscription expires.
|
||||
|
||||
5.2. The Licensee must not remove, alter, or obscure any proprietary notices (including copyright and trademark notices) on the Software.
|
||||
4.5. Any instance of the Software using a License Key that is no longer valid will revert to the Community Edition functionality.
|
||||
|
||||
## 6. SUBSCRIPTION TERMS, RENEWAL, AND CANCELLATION
|
||||
4.6. The Software validates License Keys without connecting to Licensor. Licensee may optionally enable the automatic retrieval of renewed License Keys, in which case the Software connects to Licensor's licensing service and sends the licensed domain name and the credentials needed for that purpose. Licensee may instead obtain renewed License Keys from Licensor and install them manually.
|
||||
|
||||
6.1. Subscriptions are available on a monthly or annual basis. The applicable fees, Mailbox tier, and billing cycle will be as set forth at the time of purchase or as subsequently agreed in writing between the parties.
|
||||
## 5. SOURCE CODE USAGE
|
||||
|
||||
6.2. Where Licensee has provided a valid payment method (such as a credit card) on file, the Subscription will automatically renew at the end of each billing cycle at the then-current rate, unless Licensee removes the payment method or cancels the Subscription prior to the renewal date. No advance cancellation notice period is required; Licensee may cancel at any time by removing the payment method on file or by notifying Licensor.
|
||||
5.1. Licensee is permitted to view, copy, and modify the Software's Source Code, as made available by Licensor, solely for Licensee's own use of the Software under this Agreement and in compliance with its terms.
|
||||
|
||||
6.3. Where Licensee pays by invoice (bank transfer), the Subscription will not automatically renew. Licensor will issue an invoice notification prior to the end of the billing cycle, and the Subscription will renew only upon receipt of payment.
|
||||
5.2. Modifications to the Source Code do not grant Licensee any ownership rights in the Software. All rights, title, and interest in the Software and its Source Code remain exclusively with Licensor. Licensee retains its rights in the modifications it creates, subject to Licensor's rights in the underlying Software, and may use those modifications only together with the Software and in accordance with this Agreement.
|
||||
|
||||
6.4. Upon cancellation of a Subscription by Licensee prior to the end of a paid billing cycle, Licensee is entitled to a prorated refund for the unused portion of the then-current billing period. Refunds will be calculated from the effective date of cancellation through the end of the billing cycle and will be issued within thirty (30) days of the cancellation date.
|
||||
5.3. Licensee is strictly prohibited from altering, removing, or in any way tampering with the License Key validation system within the Software. Any such unauthorized modification is a material breach of this Agreement that is not capable of remedy for the purposes of Section 9.2.
|
||||
|
||||
6.5. Licensor reserves the right to modify Subscription fees upon renewal. Any fee changes will be communicated to Licensee at least thirty (30) days prior to the start of the next billing cycle.
|
||||
5.4. Notwithstanding the availability of the Software's Source Code for review and limited modification, the Software and its Source Code are not open source and remain proprietary to Licensor. The provision of access to the Source Code does not confer any rights typically associated with open source software, including but not limited to the right to freely sublicense, or create derivative works for public distribution. All rights not expressly granted herein are reserved by Licensor.
|
||||
|
||||
## 7. SUPPORT AND SERVICE LEVELS
|
||||
5.5. Notwithstanding Section 3.2, Licensee may, worldwide and for as long as it complies with this Agreement, copy and modify the Source Code for development and testing purposes without requiring a Subscription. Running the Software, including for development, testing or evaluation, requires a valid License Key, which may be a trial License Key. Use of the Software under a trial License Key is limited to evaluation during the trial period.
|
||||
|
||||
7.1. All Licensees with an active Subscription have access to standard community support resources, including documentation and community forums, as made available by Licensor.
|
||||
5.6. Nothing in this Agreement restricts the rights that a lawful user of the Software has under mandatory law, including the rights to make a back-up copy, to observe, study or test the functioning of the Software, and to decompile it to achieve interoperability, under Article 100 of the Spanish Intellectual Property Law (Royal Legislative Decree 1/1996) and Articles 5 and 6 of Directive 2009/24/EC.
|
||||
|
||||
7.2. Priority email support is available exclusively to Licensees whose Subscription covers one hundred fifty (150) or more Mailboxes. Priority email support inquiries will receive an initial response within forty-eight (48) hours of receipt during Licensor's standard business hours.
|
||||
5.7. Open Source Components are licensed under the terms of their respective open source licenses, which prevail over this Agreement with respect to those components to the extent required by those licenses. Nothing in this Agreement limits the rights that Licensee has under those licenses.
|
||||
|
||||
7.3. The forty-eight (48) hour response time set forth in Section 7.2 constitutes a service level commitment. In the event Licensor consistently fails to meet this commitment over a period of thirty (30) consecutive days, the affected Licensee's sole remedy shall be the right to terminate the Subscription and receive a prorated refund for the unused portion of the billing cycle.
|
||||
## 6. INTELLECTUAL PROPERTY RIGHTS
|
||||
|
||||
7.4. The Software is self-hosted by Licensee on Licensee's own infrastructure. Licensor does not provide hosting services and makes no guarantees regarding uptime, availability, or performance of Licensee's self-hosted deployment.
|
||||
6.1. Licensor retains all rights, title, and interest in and to the Software, including all intellectual property rights therein. This Agreement does not transfer any ownership rights to Licensee.
|
||||
|
||||
## 8. TERMINATION
|
||||
6.2. Licensee must not remove, alter, or obscure any proprietary notices (including copyright and trademark notices) on the Software.
|
||||
|
||||
8.1. Licensor may terminate this Agreement immediately upon written notice if Licensee commits a material breach of any term of this Agreement and fails to cure such breach within thirty (30) days of receiving written notice specifying the breach.
|
||||
6.3. If Licensee provides Licensor with suggestions, feedback, or code, patches or modifications that it chooses to submit to Licensor, Licensee grants Licensor, to the extent Licensee holds or can grant those rights, a non-exclusive, worldwide, royalty-free, irrevocable license, for the full term of protection of the rights concerned, to reproduce, modify, transform, distribute, publicly communicate and otherwise exploit them in any form and medium, including by incorporating them into Licensor's products and services and by sublicensing them to Licensor's customers, without any obligation to Licensee.
|
||||
|
||||
8.2. Licensor may terminate this Agreement for convenience upon thirty (30) days' written notice to Licensee. In such event, Licensee shall receive a prorated refund for the unused portion of any prepaid Subscription fees.
|
||||
## 7. SUBSCRIPTION, FEES AND PAYMENT
|
||||
|
||||
8.3. In the event of a termination, Licensee will be provided with written notice, sent to the email address used during Subscription registration, outlining the reasons for the termination.
|
||||
7.1. Subscriptions are available on a monthly or annual basis. The applicable fees, Mailbox tier, and billing cycle will be as set forth at the time of purchase or as subsequently agreed in writing between the parties. The fees for a billing cycle are fixed at the start of that billing cycle.
|
||||
|
||||
8.4. Upon termination, all rights granted to Licensee under this Agreement will cease, and Licensee must promptly cease all use of the Software and destroy or delete all copies in its possession, except that Licensee may retain copies of the Source Code obtained prior to termination solely for archival purposes, subject to the continuing obligations of confidentiality and intellectual property protection set forth herein.
|
||||
7.2. Where Licensee has saved a valid payment method (such as a credit card or a direct debit mandate) for automatic renewal, the Subscription will automatically renew at the end of each billing cycle at the then-current rate, and the renewal fee will be charged to that payment method. No advance cancellation notice period is required; Licensee may cancel the Subscription at any time through Licensor's customer portal or by notifying Licensor, and the cancellation takes effect at the end of the current billing cycle.
|
||||
|
||||
## 9. CONFIDENTIALITY
|
||||
7.3. Where Licensee pays by bank transfer or has not saved a payment method for automatic renewal, Licensor will send Licensee a payment request, together with a pro-forma invoice, before the end of the billing cycle, and the Subscription will renew only upon receipt of payment. If payment is not received by the end of the billing cycle, Section 4.4 applies.
|
||||
|
||||
9.1. Each party agrees to hold the other party's Confidential Information in strict confidence and not to disclose such information to any third party, except to employees, contractors, or agents who have a need to know and are bound by confidentiality obligations no less protective than those contained herein.
|
||||
7.4. Upon cancellation of a Subscription by Licensee, the Subscription and its License Keys remain active until the end of the paid billing cycle, and no further fees are charged. Fees already paid are not refunded, except as expressly provided in this Agreement.
|
||||
|
||||
9.2. Confidential Information does not include information that: (a) is or becomes publicly available through no fault of the receiving party; (b) was rightfully in the receiving party's possession prior to disclosure; (c) is independently developed by the receiving party without use of the disclosing party's Confidential Information; or (d) is rightfully obtained from a third party without restriction on disclosure.
|
||||
7.5. Licensor may modify Subscription fees upon renewal. Any fee change will be communicated to Licensee at least thirty (30) days prior to the start of the next billing cycle, and Licensee may cancel the Subscription under Section 7.2 before that billing cycle starts without being charged the new fee.
|
||||
|
||||
9.3. A receiving party may disclose Confidential Information to the extent required by applicable law, regulation, or court order, provided that the receiving party gives the disclosing party prompt written notice (where legally permissible) and cooperates with the disclosing party's efforts to seek protective treatment of such information.
|
||||
7.6. Fees are payable in advance, before the start of each billing cycle, unless Licensor has agreed in writing that Licensee may pay within thirty (30) days, in which case payment is due thirty (30) days from the date of the payment request. Licensor issues the tax invoice upon receipt of payment. Fees are exclusive of value added tax (VAT) and other applicable taxes. Licensor charges Spanish VAT to Licensees established in the Spanish VAT territory. Licensees established in another Member State of the European Union that provide a VAT identification number validated through the European Commission's VIES system at the time of the sale are invoiced without VAT under the reverse charge mechanism; where no such validated number is available, Licensor charges the VAT of Licensee's Member State under the One-Stop-Shop scheme where applicable. Licensees established outside the European Union, or in the Canary Islands, Ceuta or Melilla, are invoiced without Spanish VAT where the supply is not subject to it, and are responsible for any taxes due in their own jurisdiction. Late payments accrue the interest and the compensation for recovery costs provided for in the Spanish Late Payment Law (Law 3/2004 of 29 December).
|
||||
|
||||
9.4. The obligations of confidentiality set forth in this Section shall survive the termination or expiration of this Agreement for a period of three (3) years.
|
||||
7.7. Licensee shall keep accurate records of the number of Mailboxes provisioned and, upon Licensor's written request made no more than once in any twelve (12) month period, shall certify that number in writing. Where Licensor has reasonable grounds to believe that the certified number is inaccurate, Licensor may, on at least thirty (30) days' written notice, have an independent auditor bound by confidentiality obligations verify the number of Mailboxes, during normal business hours and without unreasonably disrupting Licensee's operations. Licensee shall pay any shortfall in fees revealed by the verification at Licensor's then-current rates, and shall bear the reasonable costs of the verification only if the shortfall exceeds five percent (5%) of the fees paid for the period verified.
|
||||
|
||||
## 10. LIMITATION OF LIABILITY
|
||||
7.8. Where Licensee purchases a Subscription through a reseller authorized by Licensor, Sections 7.2 to 7.6 do not apply to that Subscription: the fees, invoicing and payment terms are agreed between Licensee and the reseller, and the Subscription renews when Licensor receives the reseller's payment for the renewal. Any refund or service credit owed under this Agreement in respect of that Subscription is paid or applied by Licensor to the reseller, for the account of Licensee, based on the fees the reseller paid to Licensor for that Subscription.
|
||||
|
||||
10.1. In no event will the Licensor be liable for any indirect, incidental, special, consequential, or punitive damages, or any loss of profits or revenues, whether incurred directly or indirectly, or any loss of data, use, goodwill, or other intangible losses, resulting from (i) your use or inability to use the Software; (ii) any unauthorized access to or use of your servers and/or any personal information stored therein.
|
||||
## 8. SUPPORT AND SERVICE LEVELS
|
||||
|
||||
10.2. Except for liability arising from death or personal injury caused by negligence, fraud, willful misconduct, or a party's indemnification obligations under this Agreement, Licensor's total aggregate liability for any and all claims under this Agreement shall be limited to the total Subscription fees paid by Licensee to Licensor in the twelve (12) months immediately preceding the event giving rise to the claim.
|
||||
8.1. All Licensees with an active Subscription have access to standard community support resources, including documentation and community forums, as made available by Licensor.
|
||||
|
||||
## 11. INDEMNIFICATION
|
||||
8.2. Every Licensee with an active Subscription is entitled to Premium Support, which consists of (a) email support at the address designated by Licensor, and (b) access to the priority support area of Licensor's support portal, where requests are answered ahead of community requests. Premium Support is provided in English during Licensor's business hours (09:00 to 18:00 CET/CEST, Monday to Friday, excluding public holidays) and does not include any guaranteed response time.
|
||||
|
||||
11.1. Licensee agrees to indemnify, defend, and hold harmless Licensor, its officers, directors, employees, agents, licensors, suppliers, and any third-party information providers from and against all claims, losses, expenses, damages, and costs, including reasonable attorneys' fees, resulting from any violation of this Agreement or any activity related to Licensee's use or misuse of the Software (including negligent or wrongful conduct).
|
||||
8.3. Licensee may purchase, with a yearly Subscription, an incident pack ("Incident Pack") or a service-level agreement plan ("SLA Plan") that provides guaranteed initial response times. The scope, response times, severity definitions and hours of each Incident Pack and SLA Plan are those published on Licensor's support plans page at https://stalw.art/support on the date of purchase, which form part of this Agreement for the term of that purchase. Licensor will provide Licensee with a copy of those terms, in a form that Licensee can store and reproduce, at the time of purchase.
|
||||
|
||||
11.2. Licensor agrees to indemnify, defend, and hold harmless Licensee from and against any third-party claim that the Software, as provided by Licensor, infringes or misappropriates any patent, copyright, trademark, or trade secret of a third party, provided that Licensee: (a) gives Licensor prompt written notice of such claim; (b) grants Licensor sole control of the defense and settlement of such claim; and (c) provides reasonable cooperation at Licensor's expense.
|
||||
8.4. If Licensor fails to meet the initial response time of a Severity 1 or Severity 2 request under an SLA Plan, Licensee shall be entitled to a service credit equal to five percent (5%) of the annual fee of that SLA Plan for each such failure, up to a maximum of twenty-five percent (25%) of that fee per subscription year, applied to Licensee's next invoice. If Licensor fails to meet three (3) or more such response times within any period of twelve (12) consecutive months, Licensee may terminate the SLA Plan and receive a prorated refund of the unused portion of its fee. Without prejudice to Section 12.3, the service credits and the termination right set forth in this Section 8.4 are Licensee's sole and exclusive remedies for any failure to meet a response time.
|
||||
|
||||
11.3. If the Software becomes, or in Licensor's opinion is likely to become, the subject of an infringement claim, Licensor may at its option and expense: (a) procure for Licensee the right to continue using the Software; (b) modify or replace the Software to make it non-infringing while maintaining substantially equivalent functionality; or (c) if neither (a) nor (b) is commercially practicable, terminate this Agreement and provide Licensee with a prorated refund of any prepaid Subscription fees.
|
||||
8.5. Where Licensee purchased its Subscription through an authorized reseller that provides first-line support, Licensee shall direct its support requests to that reseller, and Licensor provides Premium Support and any Incident Pack or SLA Plan through that reseller.
|
||||
|
||||
11.4. Licensor shall have no obligation under this Section for any claim arising from: (a) modifications to the Software made by Licensee; (b) use of the Software in combination with products, services, or technologies not provided by Licensor, where the infringement would not have occurred but for such combination; or (c) Licensee's continued use of a version of the Software after being notified of the availability of a non-infringing update.
|
||||
8.6. The Software is self-hosted by Licensee. Licensor does not provide hosting services and makes no guarantees regarding uptime, availability, or performance of Licensee's self-hosted deployment.
|
||||
|
||||
## 12. DATA PROTECTION AND PRIVACY
|
||||
## 9. SUSPENSION AND TERMINATION
|
||||
|
||||
12.1. The Software is self-hosted by Licensee, and Licensee retains sole responsibility for all data stored and processed within its deployment of the Software, including any personal data of its users or tenants.
|
||||
9.1. If any amount due under this Agreement remains unpaid fifteen (15) days after Licensor has sent Licensee a written payment reminder, or where suspension is required to comply with Section 15, Licensor may suspend support services and the issuance and renewal of License Keys (with the effect described in Section 4.5) until the situation is remedied.
|
||||
|
||||
12.2. To the extent that Licensor processes any personal data on behalf of Licensee (for example, in connection with support services or license management), such processing shall be conducted in accordance with applicable data protection laws, including but not limited to the General Data Protection Regulation (GDPR) where applicable, the California Consumer Privacy Act (CCPA) where applicable, and any other relevant data protection legislation.
|
||||
9.2. Licensor may terminate this Agreement by written notice if Licensee commits a material breach of this Agreement and fails to remedy the breach within thirty (30) days of receiving written notice specifying it. Where the breach is not capable of remedy, including a breach of Section 5.3 or Section 15, Licensor may terminate this Agreement with immediate effect by written notice.
|
||||
|
||||
12.3. Where required by applicable data protection law, the parties shall enter into a separate Data Processing Agreement ("DPA") that sets forth the terms and conditions governing Licensor's processing of personal data on behalf of Licensee.
|
||||
9.3. Licensee may terminate this Agreement by written notice if Licensor commits a material breach of this Agreement and fails to remedy the breach within thirty (30) days of receiving written notice specifying it. In such event, Licensee shall receive a prorated refund for the unused portion of any prepaid Subscription fees.
|
||||
|
||||
12.4. In the event of a data breach affecting personal data processed by Licensor in connection with this Agreement, Licensor shall notify Licensee without undue delay and in any event within seventy-two (72) hours of becoming aware of the breach, and shall cooperate with Licensee in investigating and remediating the breach.
|
||||
9.4. Licensor may terminate this Agreement for convenience upon thirty (30) days' written notice to Licensee. In such event, Licensee shall receive a prorated refund for the unused portion of any prepaid Subscription fees.
|
||||
|
||||
12.5. Additional details regarding Licensor's data handling practices are outlined in Licensor's Privacy Policy, which can be accessed on Licensor's website.
|
||||
9.5. Notices of termination to Licensee shall be sent to the email address used during Subscription registration. A notice of termination for breach under Section 9.2 or 9.3 shall describe the breach.
|
||||
|
||||
## 13. EXPORT COMPLIANCE
|
||||
9.6. Upon termination, all rights granted to Licensee under this Agreement will cease, and Licensee must promptly cease all use of the Software and destroy or delete all copies in its possession, except that Licensee may retain copies of the Source Code obtained prior to termination solely for archival purposes, subject to the continuing obligations of confidentiality and intellectual property protection set forth herein. Nothing in this Section restricts Licensee's use of the Community Edition under the open source license that governs it.
|
||||
|
||||
13.1. The Software may be subject to export control and sanctions laws of the United States and other jurisdictions. Licensee agrees to comply with all applicable export control laws, including without limitation the U.S. Export Administration Regulations (EAR) and the regulations administered by the U.S. Department of the Treasury's Office of Foreign Assets Control (OFAC).
|
||||
9.7. This Agreement remains in force for as long as Licensee holds an active Subscription or a valid trial License Key, or copies or modifies the Source Code under Section 5.5, and expires when the Subscription expires or is cancelled without renewal, subject to Section 4.4 and Section 21.
|
||||
|
||||
13.2. Licensee represents and warrants that: (a) Licensee is not located in, organized under the laws of, or a resident of any country or territory subject to comprehensive U.S. sanctions (currently including Cuba, Iran, North Korea, Syria, and the Crimea, Donetsk, and Luhansk regions of Ukraine); (b) Licensee is not listed on any U.S. government restricted party list; and (c) Licensee will not export, re-export, or transfer the Software to any prohibited destination, entity, or individual without the required governmental authorizations.
|
||||
## 10. CONFIDENTIALITY
|
||||
|
||||
## 14. ANTI-CORRUPTION
|
||||
10.1. Each party agrees to hold the other party's Confidential Information in strict confidence and not to disclose such information to any third party, except to employees, contractors, or agents who have a need to know and are bound by confidentiality obligations no less protective than those contained herein.
|
||||
|
||||
14.1. Each party represents and warrants that it has not and will not, in connection with this Agreement, directly or indirectly offer, pay, promise to pay, or authorize the payment of any money or anything of value to any government official, political party, or candidate for political office for the purpose of influencing any act or decision, or securing any improper advantage.
|
||||
10.2. Confidential Information does not include information that: (a) is or becomes publicly available through no fault of the receiving party; (b) was rightfully in the receiving party's possession prior to disclosure; (c) is independently developed by the receiving party without use of the disclosing party's Confidential Information; or (d) is rightfully obtained from a third party without restriction on disclosure.
|
||||
|
||||
14.2. Each party shall comply with all applicable anti-corruption and anti-bribery laws, including without limitation the U.S. Foreign Corrupt Practices Act (FCPA) and the UK Bribery Act 2010.
|
||||
10.3. A receiving party may disclose Confidential Information to the extent required by applicable law, regulation, or court order, provided that the receiving party gives the disclosing party prompt written notice (where legally permissible) and cooperates with the disclosing party's efforts to seek protective treatment of such information.
|
||||
|
||||
## 15. GOVERNING LAW AND DISPUTE RESOLUTION
|
||||
10.4. The obligations of confidentiality set forth in this Section shall survive the termination or expiration of this Agreement for a period of three (3) years, except that obligations relating to Confidential Information that constitutes a trade secret, including the non-public parts of the Source Code, shall continue for as long as that information remains a trade secret under applicable law.
|
||||
|
||||
15.1. This Agreement shall be governed by and construed under the laws of the State of Wyoming, United States of America, without regard to its conflict of laws principles.
|
||||
## 11. WARRANTIES AND DISCLAIMERS
|
||||
|
||||
15.2. Any dispute, controversy, or claim arising out of or relating to this Agreement, or the breach, termination, or invalidity thereof, shall first be attempted to be resolved through good faith negotiation between the parties for a period of thirty (30) days following written notice of the dispute.
|
||||
11.1. Licensor warrants that it has the right to grant the licenses set forth in this Agreement.
|
||||
|
||||
15.3. If the dispute is not resolved through negotiation within the thirty (30) day period, it shall be finally resolved by binding arbitration administered by the American Arbitration Association ("AAA") in accordance with its Commercial Arbitration Rules. The arbitration shall be conducted in Sheridan, Wyoming, before a single arbitrator. The language of the arbitration shall be English.
|
||||
11.2. Licensor warrants that each version of the Software will perform substantially in accordance with the accompanying documentation for ninety (90) days from the date on which that version is first made available to Licensee. Without prejudice to Section 12.3, Licensee's sole remedy for breach of this warranty shall be, at Licensor's option, repair or replacement of the non-conforming Software, or a refund of the Subscription fees paid for the period during which the Software was non-conforming. This warranty does not apply to use of the Software under a trial License Key or under Section 5.5.
|
||||
|
||||
15.4. The arbitrator's award shall be final and binding and may be entered as a judgment in any court of competent jurisdiction. Each party shall bear its own costs and attorneys' fees in connection with the arbitration, unless the arbitrator determines otherwise.
|
||||
11.3. Except as expressly set forth in this Agreement, and to the maximum extent permitted by applicable law, the Software is provided "as is" and "as available", and Licensor excludes all other warranties and conditions, whether express, implied or statutory, including the statutory warranty against hidden defects (*saneamiento por vicios ocultos*) and any warranty of quality or fitness for a particular purpose. Third-party intellectual property claims are governed exclusively by Sections 11.1 and 13.2 to 13.5.
|
||||
|
||||
15.5. Notwithstanding the foregoing, either party may seek injunctive or other equitable relief in any court of competent jurisdiction to protect its intellectual property rights or Confidential Information without first submitting to arbitration.
|
||||
11.4. Licensor does not warrant that the Software will be error-free, that access thereto will be uninterrupted, or that defects will be corrected.
|
||||
|
||||
## 16. NOTICES
|
||||
## 12. LIMITATION OF LIABILITY
|
||||
|
||||
16.1. All notices required or permitted under this Agreement shall be in writing and shall be deemed effectively given: (a) upon personal delivery; (b) upon confirmed transmission by email; or (c) one (1) business day after deposit with a nationally recognized overnight courier service.
|
||||
12.1. Licensor shall not be liable for any loss of profits (*lucro cesante*), loss of revenue, business or goodwill, business interruption, loss or corruption of data, or cost of substitute goods or services, nor for any damage that was not foreseeable when this Agreement was entered into, in each case whether arising directly or indirectly, or for any damage resulting from any unauthorized access to or use of Licensee's servers or of any personal information stored therein. Licensee is responsible for maintaining adequate back-ups of the data processed with the Software.
|
||||
|
||||
16.2. Notices to Licensor shall be sent to the address and email set forth in Section 21 (Contact Information) of this Agreement. Notices to Licensee shall be sent to the email address provided during Subscription registration or as subsequently updated by Licensee in writing.
|
||||
12.2. Licensor's total aggregate liability arising out of or in connection with this Agreement, whether in contract, in tort or otherwise, and including amounts payable to Licensee or to third parties under Section 13.2 (but excluding Licensor's own costs of conducting the defense), shall be limited to the total Subscription fees paid by or on behalf of Licensee to Licensor, including fees paid by an authorized reseller for Licensee's Subscription, in the twelve (12) months immediately preceding the event giving rise to the claim.
|
||||
|
||||
## 17. ASSIGNMENT
|
||||
12.3. The limitations and exclusions in this Agreement do not apply to liability for (a) intentional misconduct (*dolo*) or fraud; (b) gross negligence (*culpa grave*); (c) death or personal injury; or (d) any other liability that cannot be limited or excluded under applicable law, including liability towards natural persons under Directive (EU) 2024/2853 on liability for defective products and the laws implementing it.
|
||||
|
||||
17.1. Licensee may not transfer or assign this Agreement or any rights or obligations hereunder without the prior written consent of Licensor, except that Licensee may assign this Agreement without consent in connection with a merger, acquisition, corporate reorganization, or sale of all or substantially all of its assets, provided that the assignee agrees in writing to be bound by the terms of this Agreement.
|
||||
## 13. INDEMNIFICATION
|
||||
|
||||
17.2. Licensor may assign this Agreement without restriction. Any assignment in violation of this Section shall be null and void.
|
||||
13.1. Licensee shall compensate Licensor for the damages and losses that Licensor actually suffers, including reasonable and documented legal costs and any amounts that Licensor is ordered to pay or pays under a settlement approved by Licensee, as a result of any third-party claim arising from (a) a breach of this Agreement by Licensee or its End Users, (b) the use of the Software by Licensee or its End Users in breach of applicable law or of the rights of third parties, or (c) any claim by an End User or tenant relating to the Software as deployed or made available by Licensee, except, in each case, to the extent the claim is covered by Section 13.2 or is caused by Licensor's intentional misconduct (*dolo*), fraud or gross negligence (*culpa grave*). Licensor shall notify Licensee of any such claim promptly. Licensee may assume the defense of the claim with counsel reasonably acceptable to Licensor, and may not settle it in a manner that imposes any obligation or admission on Licensor without Licensor's prior written consent.
|
||||
|
||||
## 18. DISCLAIMERS AND WARRANTIES
|
||||
13.2. Licensor shall defend Licensee against any claim brought by a third party alleging that the Software, as provided by Licensor, infringes that third party's patent, copyright, trademark or trade secret, and shall compensate Licensee for the damages and costs finally awarded against Licensee in respect of such claim, or agreed in a settlement approved in writing by Licensor, provided that Licensee: (a) notifies Licensor in writing of the claim promptly after becoming aware of it; (b) gives Licensor sole control of the defense and settlement of the claim, except that Licensor shall not agree to any settlement that imposes an obligation or admission on Licensee without Licensee's consent; and (c) provides reasonable cooperation, at Licensor's expense.
|
||||
|
||||
18.1. The Software is provided "AS IS" and "AS AVAILABLE", without warranty of any kind, either express or implied, including, without limitation, warranties of merchantability, fitness for a particular purpose, and non-infringement.
|
||||
13.3. If the Software becomes, or in Licensor's opinion is likely to become, the subject of a claim described in Section 13.2, Licensor may at its option and expense: (a) procure for Licensee the right to continue using the Software; (b) modify or replace the Software to make it non-infringing while maintaining substantially equivalent functionality; or (c) if neither (a) nor (b) is commercially practicable, terminate this Agreement and provide Licensee with a prorated refund of any prepaid Subscription fees.
|
||||
|
||||
18.2. Licensor does not warrant that the Software will be error-free, that access thereto will be uninterrupted, or that defects will be corrected.
|
||||
13.4. Licensor shall have no obligation under Sections 13.2 and 13.3 for any claim arising from: (a) modifications to the Software not made by Licensor; (b) use of the Software in combination with products, services, or technologies not provided by Licensor, where the infringement would not have occurred but for such combination; (c) Licensee's continued use of a version of the Software after being notified of the availability, at no additional charge, of an update that would have avoided the infringement; (d) Open Source Components or other third-party software; (e) use of the Software in breach of this Agreement; or (f) use of the Software under a trial License Key or without a Subscription under Section 5.5.
|
||||
|
||||
18.3. Licensor warrants that, as of the date of delivery, the Software will perform substantially in accordance with the accompanying documentation for a period of ninety (90) days. Licensee's sole remedy for breach of this warranty shall be, at Licensor's option, repair or replacement of the non-conforming Software, or a refund of the Subscription fees paid for the period during which the Software was non-conforming.
|
||||
13.5. Licensor's obligations under Sections 13.2 and 13.3 are subject to Sections 12.2 and 12.3; Section 12.1 does not limit the amounts finally awarded or agreed in settlement under Section 13.2. Without prejudice to Section 12.3, Sections 11.1, 13.2 and 13.3 state Licensor's entire liability and Licensee's sole and exclusive remedy for any third-party claim that the Software infringes intellectual property rights.
|
||||
|
||||
## 19. FORCE MAJEURE
|
||||
## 14. DATA PROTECTION AND PRIVACY
|
||||
|
||||
Neither party shall be in default or otherwise liable for any delay in or failure of its performance under this Agreement if such delay or failure arises by any reason of any event beyond the reasonable control of a party, including acts of God, the elements, earthquakes, floods, fires, epidemics, riots, failures or delays in transportation or communications, or any act or failure to act by the other party or such other party's officers, employees, agents, or contractors. The affected party shall give prompt notice to the other party and shall use commercially reasonable efforts to mitigate the effects of the force majeure event. If a force majeure event continues for more than ninety (90) days, either party may terminate this Agreement upon written notice, and Licensee shall receive a prorated refund of any prepaid Subscription fees.
|
||||
14.1. The Software is self-hosted by Licensee. As between the parties, Licensee, acting as controller or as processor on behalf of its tenants, is solely responsible for all data stored and processed within its deployment of the Software, including any personal data of its End Users or tenants. Licensor has no access to that data unless Licensee grants it.
|
||||
|
||||
## 20. SURVIVAL
|
||||
14.2. Licensor acts as controller of the personal data it collects to manage Subscriptions, License Keys, billing and support accounts, including the domain name, License Key credentials and IP address that the Software sends when Licensee enables the automatic retrieval of renewed License Keys. That processing is described in Licensor's Privacy Policy, available at https://stalw.art/legal/privacy.
|
||||
|
||||
The following Sections shall survive the termination or expiration of this Agreement: Section 1 (Definitions), Section 4.2 (Ownership of Modifications), Section 4.4 (Proprietary Nature of Software), Section 5 (Intellectual Property Rights), Section 9 (Confidentiality), Section 10 (Limitation of Liability), Section 11 (Indemnification), Section 12 (Data Protection and Privacy), Section 13 (Export Compliance), Section 15 (Governing Law and Dispute Resolution), and Section 20 (Survival).
|
||||
14.3. If Licensor processes personal data on behalf of Licensee, for example where Licensee grants Licensor access to its deployment for support purposes, Licensor acts as processor and the parties shall enter into a data processing agreement that meets the requirements of Article 28(3) of the General Data Protection Regulation (Regulation (EU) 2016/679, "GDPR") before that processing begins. Licensee shall not give Licensor access to personal data in its deployment until such an agreement is in place.
|
||||
|
||||
## 21. SEVERABILITY
|
||||
14.4. In the event of a personal data breach affecting personal data that Licensor processes on behalf of Licensee, Licensor shall notify Licensee without undue delay after becoming aware of the breach, and shall cooperate with Licensee in investigating and remediating the breach.
|
||||
|
||||
If any provision of this Agreement is held to be unenforceable or invalid for any reason, that provision shall be reformed to the extent necessary to make it enforceable and consistent with the intent of the parties, and the remaining provisions shall remain in full force and effect.
|
||||
14.5. Each party shall comply with the data protection laws that apply to it in connection with this Agreement, including the GDPR and the Spanish Organic Law 3/2018 on the Protection of Personal Data and Guarantee of Digital Rights.
|
||||
|
||||
## 22. ENTIRE AGREEMENT
|
||||
## 15. EXPORT CONTROL AND SANCTIONS
|
||||
|
||||
This Agreement constitutes the entire agreement between the Licensor and the Licensee with respect to the subject matter hereof and supersedes all prior or contemporaneous understandings regarding such subject matter. No amendment to or modification of this Agreement will be binding unless in writing and signed by the Licensor.
|
||||
15.1. Each party shall comply with the export control and sanctions laws of the European Union and of Spain that apply to the Software and to this Agreement, including Regulation (EU) 2021/821 (the EU Dual-Use Regulation), the restrictive measures adopted by the European Union (such as Council Regulations (EU) No 833/2014 and No 269/2014), and Spanish Law 53/2007 on the control of foreign trade in defense and dual-use material.
|
||||
|
||||
## 23. ACCEPTANCE
|
||||
15.2. Licensee represents and warrants that: (a) neither Licensee nor any person that owns or controls it is designated under, or subject to an asset freeze or a prohibition on making funds or economic resources available under, any restrictive measures adopted by the European Union; (b) Licensee is not established or resident in a country or territory to which the supply of the Software is prohibited by such restrictive measures; and (c) Licensee will not export, re-export, transfer or make the Software available to any person, entity, country or territory in breach of the laws referred to in Section 15.1.
|
||||
|
||||
By downloading, installing, or using the Software, even without explicitly clicking on an "I Agree" button or a similar mechanism, you acknowledge that you have read, understood, and agreed to be bound by the terms and conditions of this Agreement.
|
||||
15.3. Licensor may suspend its performance, or terminate this Agreement with immediate effect, where this is necessary to comply with the laws referred to in Section 15.1. In such event, Licensee shall receive a prorated refund for the unused portion of any prepaid Subscription fees, unless the refund itself is prohibited by those laws.
|
||||
|
||||
## 24. CONTACT INFORMATION
|
||||
## 16. ANTI-CORRUPTION
|
||||
|
||||
If you have any questions about this Agreement, please contact Stalwart Labs LLC at:
|
||||
16.1. Each party represents and warrants that it has not and will not, in connection with this Agreement, directly or indirectly offer, pay, promise, request or accept any money or anything of value, whether to or from a public official, a political party, a candidate for political office or any person in the private sector, for the purpose of improperly influencing any act or decision or securing any improper advantage.
|
||||
|
||||
Stalwart Labs LLC
|
||||
1309 Coffeen Avenue STE 1200
|
||||
Sheridan, Wyoming 82801
|
||||
USA
|
||||
16.2. Each party shall comply with all anti-corruption and anti-bribery laws that apply to it, including the Spanish Criminal Code.
|
||||
|
||||
## 17. GOVERNING LAW AND DISPUTE RESOLUTION
|
||||
|
||||
17.1. This Agreement, and any dispute or claim (including any non-contractual dispute or claim) arising out of or in connection with it, its subject matter or its formation, is governed by the laws of Spain, excluding its conflict of laws rules. The United Nations Convention on Contracts for the International Sale of Goods does not apply to this Agreement.
|
||||
|
||||
17.2. Except for applications under Section 17.6, before starting arbitration the party raising a dispute shall give the other party written notice describing the dispute, and the parties shall attempt to resolve it through good faith negotiation for a period of thirty (30) days following receipt of that notice.
|
||||
|
||||
17.3. If the dispute is not resolved within that period, any dispute, controversy or claim arising out of or in connection with this Agreement, including any question regarding its existence, validity, interpretation, performance or termination, shall be finally settled by arbitration administered by the Centro Internacional e Iberoamericano de Arbitraje de Madrid (CIIAM) in accordance with its Arbitration Rules in force on the date the request for arbitration is filed.
|
||||
|
||||
17.4. The seat of the arbitration shall be Madrid, Spain. The arbitral tribunal shall consist of a sole arbitrator, who shall decide in accordance with the law set forth in Section 17.1. The language of the arbitration shall be English. The parties do not exclude the abbreviated procedure (*procedimiento abreviado*) provided for in the applicable Arbitration Rules, which shall apply where its conditions are met.
|
||||
|
||||
17.5. If the dispute is not international within the meaning of the CIIAM Bylaws, the parties agree, including for the purposes of Additional Provision I of those Bylaws, that the arbitration shall be administered by the Madrid Court of Arbitration (Corte de Arbitraje de Madrid) of the Official Chamber of Commerce, Industry and Services of Madrid, in accordance with its Arbitration Rules in force on the date the request for arbitration is filed, with the seat, number of arbitrators and language set forth in Section 17.4. Either party may file the request for arbitration of such a dispute directly with the Madrid Court of Arbitration.
|
||||
|
||||
17.6. Nothing in this Section prevents either party from applying to any court of competent jurisdiction for interim or protective measures, including injunctive relief to protect its intellectual property rights or Confidential Information, before or during the arbitration.
|
||||
|
||||
17.7. If, notwithstanding Section 2.1, Licensee is considered a consumer under the mandatory law that applies to it, Sections 17.3 to 17.5 do not apply to Licensee, and nothing in this Agreement deprives Licensee of the protection afforded by the provisions of that law that cannot be derogated from by agreement.
|
||||
|
||||
17.8. Sections 17.3 to 17.5 do not apply where Licensee is a public sector entity that the law applicable to it prevents from agreeing to arbitration. In that case, disputes shall be resolved by the competent courts.
|
||||
|
||||
## 18. NOTICES
|
||||
|
||||
18.1. All notices required or permitted under this Agreement shall be in writing and shall be deemed effectively given: (a) upon personal delivery; (b) upon delivery by courier or *burofax* with proof of delivery; or (c) when sent by email to the address set forth in Section 18.2, unless the sender receives a notification that the email was not delivered. A notice received after 18:00 (Vitoria-Gasteiz time) or on a day that is not a Business Day is deemed given on the next Business Day.
|
||||
|
||||
18.2. Notices to Licensor shall be sent to the address and email set forth in Section 25 (Contact Information) of this Agreement. Notices to Licensee shall be sent to the email address provided during Subscription registration or as subsequently updated by Licensee in writing.
|
||||
|
||||
## 19. ASSIGNMENT
|
||||
|
||||
19.1. Licensee may not transfer or assign this Agreement or any rights or obligations hereunder without the prior written consent of Licensor, except that Licensee may assign this Agreement without consent in connection with a merger, acquisition, corporate reorganization, or sale of all or substantially all of its assets, provided that the assignee agrees in writing to be bound by the terms of this Agreement.
|
||||
|
||||
19.2. Licensor may assign this Agreement, by written notice to Licensee, to an affiliate or to a successor in connection with a merger, acquisition, corporate reorganization, or transfer of all or substantially all of the business to which this Agreement relates, provided that the assignee assumes all of Licensor's obligations under this Agreement. Any other assignment by Licensor requires Licensee's prior written consent. Any assignment in violation of this Section shall be null and void.
|
||||
|
||||
## 20. FORCE MAJEURE
|
||||
|
||||
Neither party shall be in default or otherwise liable for any delay in or failure of its performance under this Agreement, other than an obligation to pay money, to the extent the delay or failure is caused by an event beyond its reasonable control that could not have been foreseen or that, if foreseen, was unavoidable, such as natural disasters, fires, floods, epidemics, war, terrorism, riots, government action, or failures of public utilities, transportation or communications networks. The affected party shall give prompt notice to the other party and shall use commercially reasonable efforts to mitigate the effects of the force majeure event. If a force majeure event continues for more than ninety (90) days, either party may terminate this Agreement upon written notice, and Licensee shall receive a prorated refund of any prepaid Subscription fees.
|
||||
|
||||
## 21. SURVIVAL
|
||||
|
||||
The following Sections shall survive the termination or expiration of this Agreement: Section 1, Section 2.2, Section 5.2, Section 5.4, Section 6, Sections 7.4, 7.6 and 8.4 and any other refund or credit obligation, as to amounts accrued, Section 7.7 for twelve (12) months, Section 9.6, Section 10 for the periods set forth in Section 10.4, Sections 11.3 and 11.4, Section 12, Section 13, Section 14, Section 15, Section 17, Section 18, Section 21, Section 22 and Section 23.
|
||||
|
||||
## 22. SEVERABILITY
|
||||
|
||||
If any provision of this Agreement is held to be invalid or unenforceable, the remaining provisions shall remain in full force and effect, and this Agreement shall be integrated in accordance with Article 1258 of the Spanish Civil Code.
|
||||
|
||||
## 23. ENTIRE AGREEMENT, AMENDMENTS AND LANGUAGE
|
||||
|
||||
23.1. This Agreement constitutes the entire agreement between Licensor and Licensee with respect to the subject matter hereof and supersedes all prior or contemporaneous understandings regarding such subject matter. Except as provided in Section 23.2, no amendment to or modification of this Agreement will be binding unless made in writing and signed or electronically accepted by both parties.
|
||||
|
||||
23.2. Licensor may amend this Agreement with effect from the start of a billing cycle by giving Licensee at least thirty (30) days' notice. If Licensee does not accept the amendment, it may cancel the Subscription under Section 7.2 before that billing cycle starts, and the amendment will not apply to it.
|
||||
|
||||
23.3. This Agreement is concluded in English. Any translation is provided for convenience only, and the English version prevails in the event of any inconsistency.
|
||||
|
||||
## 24. ACCEPTANCE
|
||||
|
||||
24.1. Licensee accepts this Agreement by expressly accepting it when purchasing a Subscription, for example by ticking the acceptance box at checkout or by signing an order form. Before the purchase, Licensor makes this Agreement available for review and download. Licensor keeps a record of the acceptance and of the version of this Agreement accepted, and sends Licensee a copy of this Agreement, in a form that Licensee can store and reproduce, after the purchase.
|
||||
|
||||
24.2. A person requesting a trial License Key accepts this Agreement expressly when making the request. The copying and modification of the Source Code without a Subscription under Section 5.5 is also subject to this Agreement.
|
||||
|
||||
## 25. CONTACT INFORMATION
|
||||
|
||||
If you have any questions about this Agreement, please contact Stalwart Labs S.L. at:
|
||||
|
||||
Stalwart Labs S.L.
|
||||
Pedro Asua Kalea 69
|
||||
01008 Vitoria-Gasteiz
|
||||
Spain
|
||||
hello@stalw.art
|
||||
https://stalw.art/contact
|
||||
@@ -110,17 +110,7 @@ This starts Vite's development server with hot module replacement, typically at
|
||||
|
||||
## Testing
|
||||
|
||||
Run the unit tests (Vitest):
|
||||
|
||||
```
|
||||
npm test
|
||||
```
|
||||
|
||||
Run tests in watch mode:
|
||||
|
||||
```
|
||||
npm run test:watch
|
||||
```
|
||||
Unit and end-to-end tests are maintained in a separate repository.
|
||||
|
||||
## Building for production
|
||||
|
||||
@@ -142,14 +132,14 @@ npm run preview
|
||||
If you are having problems running Stalwart Mail Server, you found a bug or just have a question,
|
||||
do not hesitate to reach us on [Github Discussions](https://github.com/stalwartlabs/mail-server/discussions),
|
||||
[Reddit](https://www.reddit.com/r/stalwartlabs), [Discord](https://discord.gg/aVQr3jF8jd) or [Matrix](https://matrix.to/#/#stalwart:matrix.org).
|
||||
Additionally you may purchase a subscription to obtain priority support from Stalwart Labs LLC
|
||||
Additionally you may purchase a subscription to obtain priority support from Stalwart Labs S.L.
|
||||
|
||||
## License
|
||||
|
||||
This project is dual-licensed under the **GNU Affero General Public License v3.0** (AGPL-3.0; as published by the Free Software Foundation) and the **Stalwart Enterprise License v1 (SELv1)**:
|
||||
This project is dual-licensed under the **GNU Affero General Public License v3.0** (AGPL-3.0; as published by the Free Software Foundation) and the **Stalwart Enterprise License 3.0 (SELv3)**:
|
||||
|
||||
- The [GNU Affero General Public License v3.0](./LICENSES/AGPL-3.0-only.txt) is a free software license that ensures your freedom to use, modify, and distribute the software, with the condition that any modified versions of the software must also be distributed under the same license.
|
||||
- The [Stalwart Enterprise License v1 (SELv1)](./LICENSES/LicenseRef-SEL.txt) is a proprietary license designed for commercial use. It offers additional features and greater flexibility for businesses that do not wish to comply with the AGPL-3.0 license requirements.
|
||||
- The [Stalwart Enterprise License 3.0 (SELv3)](https://stalw.art/legal/license) is a proprietary license designed for commercial use. It offers additional features and greater flexibility for businesses that do not wish to comply with the AGPL-3.0 license requirements.
|
||||
|
||||
Each file in this project contains a license notice at the top, indicating the applicable license(s). The license notice follows the [REUSE guidelines](https://reuse.software/) to ensure clarity and consistency. The full text of each license is available in the [LICENSES](./LICENSES/) directory.
|
||||
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@ import prettierConfig from 'eslint-config-prettier'
|
||||
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
globalIgnores(['dist', '.ignore']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 446 KiB After Width: | Height: | Size: 577 KiB |
+3
-1
@@ -1,10 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<html lang="en" translate="no">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="google" content="notranslate" />
|
||||
<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>
|
||||
|
||||
Generated
+1471
-1211
File diff suppressed because it is too large.
Load diff
+53
-40
@@ -1,7 +1,10 @@
|
||||
{
|
||||
"name": "stalwart-webui",
|
||||
"private": true,
|
||||
"version": "1.0.9",
|
||||
"version": "2.1.3",
|
||||
"stalwart": {
|
||||
"minServerVersion": "1.0.0"
|
||||
},
|
||||
"description": "Stalwart WebUI",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
@@ -10,62 +13,72 @@
|
||||
"typecheck": "tsc -p tsconfig.app.json --noEmit",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"format": "prettier --write src/",
|
||||
"format:check": "prettier --check src/"
|
||||
},
|
||||
"dependencies": {
|
||||
"@daypicker/react": "^10.0.1",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.23",
|
||||
"@radix-ui/react-checkbox": "^1.3.11",
|
||||
"@radix-ui/react-collapsible": "^1.1.20",
|
||||
"@radix-ui/react-dialog": "^1.1.23",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.24",
|
||||
"@radix-ui/react-label": "^2.1.15",
|
||||
"@radix-ui/react-popover": "^1.1.23",
|
||||
"@radix-ui/react-scroll-area": "^1.2.18",
|
||||
"@radix-ui/react-select": "^2.3.7",
|
||||
"@radix-ui/react-separator": "^1.1.15",
|
||||
"@radix-ui/react-slot": "^1.3.3",
|
||||
"@radix-ui/react-switch": "^1.3.7",
|
||||
"@radix-ui/react-tabs": "^1.1.21",
|
||||
"@radix-ui/react-tooltip": "^1.2.16",
|
||||
"@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",
|
||||
"@radix-ui/react-collapsible": "^1.2.1",
|
||||
"@radix-ui/react-dialog": "^1.3.1",
|
||||
"@radix-ui/react-dropdown-menu": "^2.2.1",
|
||||
"@radix-ui/react-label": "^2.1.17",
|
||||
"@radix-ui/react-popover": "^1.3.1",
|
||||
"@radix-ui/react-scroll-area": "^1.4.0",
|
||||
"@radix-ui/react-select": "^2.4.1",
|
||||
"@radix-ui/react-separator": "^1.2.0",
|
||||
"@radix-ui/react-slot": "^1.5.0",
|
||||
"@radix-ui/react-switch": "^1.4.1",
|
||||
"@radix-ui/react-tabs": "^1.2.1",
|
||||
"@radix-ui/react-tooltip": "^1.4.1",
|
||||
"@tanstack/react-query": "^5.104.2",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.1.1",
|
||||
"i18next": "^26.3.6",
|
||||
"lucide-react": "^1.28.0",
|
||||
"otpauth": "^9.5.1",
|
||||
"i18next": "^26.4.4",
|
||||
"lucide-react": "^1.57.0",
|
||||
"otpauth": "^9.5.2",
|
||||
"qrcode": "^1.5.4",
|
||||
"react": "^19.2.8",
|
||||
"react-dom": "^19.2.8",
|
||||
"react-i18next": "^17.0.11",
|
||||
"react": "^19.3.0",
|
||||
"react-dom": "^19.3.0",
|
||||
"react-i18next": "^17.0.16",
|
||||
"react-markdown": "^10.1.0",
|
||||
"react-router-dom": "^7.18.2",
|
||||
"react-router-dom": "^7.18.4",
|
||||
"recharts": "^3.10.1",
|
||||
"tailwind-merge": "^3.6.0",
|
||||
"zustand": "^5.0.14"
|
||||
"tailwind-merge": "^3.7.0",
|
||||
"zustand": "^5.0.15"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.29.7",
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@rolldown/plugin-babel": "^0.2.4",
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"@types/node": "^26.1.2",
|
||||
"@types/react": "^19.2.17",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^6.0.5",
|
||||
"eslint": "^10.8.0",
|
||||
"@tanstack/react-query-devtools": "^5.104.2",
|
||||
"@types/babel__core": "^7.20.5",
|
||||
"@types/node": "^26.6.5",
|
||||
"@types/react": "^19.3.0",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"@vitejs/plugin-react": "^6.1.2",
|
||||
"babel-plugin-react-compiler": "^1.0.0",
|
||||
"eslint": "^10.12.0",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.3",
|
||||
"globals": "^17.8.0",
|
||||
"happy-dom": "^20.11.1",
|
||||
"prettier": "^3.9.6",
|
||||
"eslint-plugin-react-refresh": "^0.5.7",
|
||||
"globals": "^17.13.0",
|
||||
"prettier": "^3.9.10",
|
||||
"tailwindcss": "^4.3.3",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"typescript": "~6.0.3",
|
||||
"typescript-eslint": "^8.65.0",
|
||||
"vite": "^8.2.0",
|
||||
"vitest": "^4.1.10"
|
||||
"typescript-eslint": "^8.71.2",
|
||||
"vite": "^8.3.4"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg">
|
||||
<symbol id="bluesky-icon" viewBox="0 0 16 17">
|
||||
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
|
||||
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
|
||||
</symbol>
|
||||
<symbol id="discord-icon" viewBox="0 0 20 19">
|
||||
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
|
||||
</symbol>
|
||||
<symbol id="documentation-icon" viewBox="0 0 21 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
|
||||
</symbol>
|
||||
<symbol id="github-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
<symbol id="social-icon" viewBox="0 0 20 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
|
||||
</symbol>
|
||||
<symbol id="x-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 4.9 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="98.5 77.55 96.4 96.4" width="96" height="96"><path fill="#db2d54" d="M149.1 84.7h-4.8l-44.8 25.9v8.3l44.8 25.9h4.8l44.8-25.9v-8.3l-44.8-25.9zm32.9 30h-35.3V94.4l35.3 20.3zm-35.3 20.4-35.3-20.4 27-15.6v20.2l6.3 3.6h22.9l-20.9 12.2zM99.5 129.9v11l44.8 25.9h4.8l44.8-25.9v-11l-47.2 27.3zM187.3 166.8l6.6-3.8v-11l-25.7 14.8zM99.5 163l6.6 3.8h19.1L99.5 152z"/></svg>
|
||||
|
After Width: | Height: | Size: 411 B |
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"client_name": "Stalwart Web Interface",
|
||||
"client_uri": "https://stalw.art",
|
||||
"logo_uri": "logo.svg",
|
||||
"redirect_uris": ["oauth/callback"],
|
||||
"post_logout_redirect_uris": ["login"],
|
||||
"token_endpoint_auth_method": "none",
|
||||
"grant_types": ["authorization_code", "refresh_token"],
|
||||
"response_types": ["code"]
|
||||
}
|
||||
+7
-4
@@ -9,14 +9,17 @@ import { Outlet } from 'react-router-dom';
|
||||
import { ErrorBoundary } from '@/components/layout/ErrorBoundary';
|
||||
import { LoadingFallback } from '@/components/common/LoadingFallback';
|
||||
import { Toaster } from '@/components/ui/toaster';
|
||||
import { TooltipProvider } from '@/components/ui/tooltip';
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<ErrorBoundary>
|
||||
<Suspense fallback={<LoadingFallback fullScreen />}>
|
||||
<Outlet />
|
||||
</Suspense>
|
||||
<Toaster />
|
||||
<TooltipProvider>
|
||||
<Suspense fallback={<LoadingFallback fullScreen />}>
|
||||
<Outlet />
|
||||
</Suspense>
|
||||
<Toaster />
|
||||
</TooltipProvider>
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import type { ReactNode } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Check } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { CopyButton } from '@/components/common/CopyButton';
|
||||
import { DefaultLogo } from '@/components/common/Logo';
|
||||
import type { Fields } from '@/types/schema';
|
||||
|
||||
export function WizardShell({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col bg-background">
|
||||
<header className="sticky top-0 z-20 flex h-16 items-center bg-background/80 px-6 backdrop-blur-md">
|
||||
<DefaultLogo />
|
||||
</header>
|
||||
<main className="flex-1 overflow-auto px-4 pb-10 pt-4 sm:px-6">
|
||||
<div className="mx-auto max-w-3xl">{children}</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ProgressIndicator({ total, current }: { total: number; current: number }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div
|
||||
className="flex items-center gap-1.5"
|
||||
aria-label={t('bootstrap.stepOf', 'Step {{current}} of {{total}}', { current: current + 1, total })}
|
||||
>
|
||||
{Array.from({ length: total }, (_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className={cn(
|
||||
'h-1.5 rounded-full transition-all duration-300 ease-bento',
|
||||
i === current ? 'w-8 bg-primary' : i < current ? 'w-4 bg-primary/45' : 'w-4 bg-muted-strong',
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function SuccessScreen({
|
||||
extras,
|
||||
fields,
|
||||
labelsByName,
|
||||
}: {
|
||||
extras: Record<string, unknown>;
|
||||
fields: Fields;
|
||||
labelsByName: Map<string, string>;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const entries = Object.entries(extras).filter(([k, v]) => {
|
||||
if (k === 'id' || k === 'blobId' || k === '@type') return false;
|
||||
return typeof v === 'string' && v.length > 0;
|
||||
}) as [string, string][];
|
||||
|
||||
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>
|
||||
<h1 className="page-title">{t('bootstrap.complete', 'Setup complete')}</h1>
|
||||
<p className="mt-1.5 text-sm text-muted-foreground">
|
||||
{hasCredentials
|
||||
? t(
|
||||
'bootstrap.credentialsCreated',
|
||||
'Your administrator account has been created. Write these down now: the password will not be shown again.',
|
||||
)
|
||||
: t('bootstrap.configuredSuccessfully', 'Stalwart has been configured successfully.')}
|
||||
</p>
|
||||
</div>
|
||||
</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} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</section>
|
||||
)}
|
||||
|
||||
<div className="rounded-xl bg-info-soft p-4 text-info">
|
||||
<p className="text-sm">
|
||||
<span className="font-medium">{t('bootstrap.nextStepLabel', 'Next step:')}</span>{' '}
|
||||
{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.',
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -4,25 +4,26 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { ArrowLeft, ArrowRight, Check, Copy, Loader2, Rocket } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { ArrowLeft, ArrowRight, Loader2, Rocket } from 'lucide-react';
|
||||
|
||||
import { useSchemaStore } from '@/stores/schemaStore';
|
||||
import { FieldWidget } from '@/components/forms/FieldWidget';
|
||||
import { FormEditionContext } from '@/components/forms/FormEditionContext';
|
||||
import { DefaultLogo } from '@/components/common/Logo';
|
||||
import { toast } from '@/hooks/use-toast';
|
||||
import { FormProvider } from '@/components/forms/FormProvider';
|
||||
import { FieldRow } from '@/components/forms/FieldRow';
|
||||
import { mapSetError, validateRequired, type FieldErrors } from '@/components/forms/formLogic';
|
||||
import { ProgressIndicator, SuccessScreen, WizardShell } from '@/components/bootstrap/BootstrapScreens';
|
||||
import { resolveObject, resolveSchema, resolveForm, buildCreateDefaults, deepMerge } from '@/lib/schemaResolver';
|
||||
import { calculateJmapPatch } from '@/lib/jmapPatch';
|
||||
import { jmapGet, jmapSet, getAccountId } from '@/services/jmap/client';
|
||||
import { friendlySetError, validationErrorMessage } from '@/lib/jmapErrors';
|
||||
import { useJmapObject } from '@/data/objects';
|
||||
import { useJmapSet } from '@/data/mutations';
|
||||
import { errorMessage, friendlySetError, validationErrorMessage } from '@/lib/jmapErrors';
|
||||
|
||||
import type { Field, Fields, Form, FormField } from '@/types/schema';
|
||||
import type { JmapSetError, JmapSetResponse } from '@/types/jmap';
|
||||
import type { Field, Form, FormField } from '@/types/schema';
|
||||
import type { JmapSetError } from '@/types/jmap';
|
||||
|
||||
const BOOTSTRAP_VIEW = 'x:Bootstrap';
|
||||
|
||||
@@ -48,12 +49,10 @@ export function BootstrapWizard() {
|
||||
const [formData, setFormData] = useState<Record<string, unknown>>({});
|
||||
const [originalData, setOriginalData] = useState<Record<string, unknown>>({});
|
||||
const [currentPage, setCurrentPage] = useState(0);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
|
||||
const [generalError, setGeneralError] = useState<string | null>(null);
|
||||
const [successExtras, setSuccessExtras] = useState<Record<string, unknown> | null>(null);
|
||||
const [copied, setCopied] = useState<string | null>(null);
|
||||
|
||||
const sections = useMemo((): { title?: string; subtitle?: string; fields: RenderableField[] }[] => {
|
||||
if (!resolved) return [];
|
||||
@@ -83,39 +82,18 @@ export function BootstrapWizard() {
|
||||
return Array.from(set);
|
||||
}, [resolved, sections]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!schema || !resolved) return;
|
||||
const { obj, sch } = resolved;
|
||||
|
||||
const ctrl = new AbortController();
|
||||
|
||||
(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const accountId = getAccountId(obj.objectName);
|
||||
const responses = await jmapGet(obj.objectName, accountId, ['singleton'], fetchProperties, ctrl.signal);
|
||||
if (ctrl.signal.aborted) return;
|
||||
|
||||
const server = (responses[0]?.[1]?.list as Array<Record<string, unknown>> | undefined)?.[0] ?? {};
|
||||
const defaults = buildCreateDefaults(schema, obj, sch);
|
||||
const seeded = deepMerge(defaults, server);
|
||||
setFormData(seeded);
|
||||
setOriginalData({});
|
||||
} catch (err) {
|
||||
if (ctrl.signal.aborted) return;
|
||||
if (err instanceof DOMException && err.name === 'AbortError') return;
|
||||
setGeneralError(
|
||||
err instanceof Error ? err.message : t('bootstrap.failedToLoad', 'Failed to load bootstrap state.'),
|
||||
);
|
||||
} finally {
|
||||
if (!ctrl.signal.aborted) setLoading(false);
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
ctrl.abort();
|
||||
};
|
||||
}, [schema, resolved, fetchProperties, t]);
|
||||
const stateQuery = useJmapObject(resolved?.obj.objectName, 'singleton', fetchProperties, { staleTime: 0 });
|
||||
const setMutation = useJmapSet(resolved?.obj.objectName);
|
||||
const [seeded, setSeeded] = useState(false);
|
||||
if (!seeded && schema && resolved && stateQuery.isSuccess) {
|
||||
setSeeded(true);
|
||||
setFormData(deepMerge(buildCreateDefaults(schema, resolved.obj, resolved.sch), stateQuery.data ?? {}));
|
||||
setOriginalData({});
|
||||
}
|
||||
const loading = !seeded && !stateQuery.isError;
|
||||
const loadError = stateQuery.isError
|
||||
? errorMessage(stateQuery.error, t('bootstrap.failedToLoad', 'Failed to load bootstrap state.'))
|
||||
: null;
|
||||
|
||||
const handleFieldChange = useCallback((fieldName: string, value: unknown) => {
|
||||
setFormData((prev) => ({ ...prev, [fieldName]: value }));
|
||||
@@ -128,64 +106,34 @@ export function BootstrapWizard() {
|
||||
}, []);
|
||||
|
||||
const validateSectionRequired = useCallback(
|
||||
(sectionFields: RenderableField[], data: Record<string, unknown>): Record<string, string> => {
|
||||
const errors: Record<string, string> = {};
|
||||
for (const { formField, field } of sectionFields) {
|
||||
if (field.update === 'serverSet' || field.update === 'immutable') continue;
|
||||
const fieldType = field.type;
|
||||
const eligible =
|
||||
fieldType.type === 'string' ||
|
||||
fieldType.type === 'number' ||
|
||||
fieldType.type === 'utcDateTime' ||
|
||||
fieldType.type === 'enum' ||
|
||||
fieldType.type === 'blobId' ||
|
||||
fieldType.type === 'objectId';
|
||||
if (!eligible) continue;
|
||||
if ('nullable' in fieldType && fieldType.nullable) continue;
|
||||
const value = data[formField.name];
|
||||
const isEmpty = value === undefined || value === null || (typeof value === 'string' && value === '');
|
||||
if (isEmpty) errors[formField.name] = t('form.required', 'This field is required.');
|
||||
}
|
||||
return errors;
|
||||
(sectionFields: RenderableField[], data: Record<string, unknown>): FieldErrors => {
|
||||
const properties: Record<string, Field> = {};
|
||||
for (const { formField, field } of sectionFields) properties[formField.name] = field;
|
||||
return validateRequired(data, { properties }, 'edit', t('form.required', 'This field is required.'));
|
||||
},
|
||||
[t],
|
||||
);
|
||||
|
||||
const applySetError = useCallback(
|
||||
(error: JmapSetError): number | null => {
|
||||
setGeneralError(friendlySetError(error));
|
||||
|
||||
const fieldToPage = new Map<string, number>();
|
||||
sections.forEach((section, idx) => {
|
||||
for (const rf of section.fields) {
|
||||
if (!fieldToPage.has(rf.formField.name)) fieldToPage.set(rf.formField.name, idx);
|
||||
}
|
||||
});
|
||||
|
||||
const newErrors: Record<string, string> = {};
|
||||
const { general, fieldErrors: errors } = mapSetError(error, new Set(fieldToPage.keys()), {
|
||||
general: friendlySetError(error),
|
||||
invalidValue: t('form.invalidValue', 'Invalid value.'),
|
||||
validation: validationErrorMessage,
|
||||
});
|
||||
setGeneralError(general);
|
||||
if (Object.keys(errors).length > 0) setFieldErrors(errors);
|
||||
let earliest: number | null = null;
|
||||
const record = (topLevel: string, msg: string) => {
|
||||
if (!fieldToPage.has(topLevel)) return;
|
||||
newErrors[topLevel] = msg;
|
||||
const idx = fieldToPage.get(topLevel)!;
|
||||
if (earliest === null || idx < earliest) earliest = idx;
|
||||
};
|
||||
|
||||
if (error.properties) {
|
||||
for (const prop of error.properties) {
|
||||
const top = prop.split('/')[0];
|
||||
record(top, error.description ?? t('form.invalidValue', 'Invalid value.'));
|
||||
}
|
||||
for (const name of Object.keys(errors)) {
|
||||
const idx = fieldToPage.get(name);
|
||||
if (idx !== undefined && (earliest === null || idx < earliest)) earliest = idx;
|
||||
}
|
||||
if (error.validationErrors) {
|
||||
for (const ve of error.validationErrors) {
|
||||
const top = ve.property?.split('/')[0] ?? '';
|
||||
if (!top) continue;
|
||||
record(top, validationErrorMessage(ve));
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.keys(newErrors).length > 0) setFieldErrors(newErrors);
|
||||
return earliest;
|
||||
},
|
||||
[sections, t],
|
||||
@@ -216,7 +164,6 @@ export function BootstrapWizard() {
|
||||
|
||||
const handleSubmit = useCallback(async () => {
|
||||
if (!resolved) return;
|
||||
const { obj } = resolved;
|
||||
|
||||
let firstInvalid: number | null = null;
|
||||
const allErrors: Record<string, string> = {};
|
||||
@@ -241,11 +188,7 @@ export function BootstrapWizard() {
|
||||
try {
|
||||
const patch = calculateJmapPatch(originalData, formData);
|
||||
|
||||
const accountId = getAccountId(obj.objectName);
|
||||
const responses = await jmapSet(obj.objectName, accountId, {
|
||||
update: { singleton: patch },
|
||||
});
|
||||
const setResult = responses[responses.length - 1]?.[1] as unknown as JmapSetResponse;
|
||||
const setResult = await setMutation.mutateAsync({ update: { singleton: patch } });
|
||||
|
||||
if (setResult.updated && 'singleton' in setResult.updated) {
|
||||
setSuccessExtras(setResult.updated.singleton ?? {});
|
||||
@@ -256,36 +199,17 @@ export function BootstrapWizard() {
|
||||
setGeneralError(t('bootstrap.noConfirm', 'The server did not confirm the update.'));
|
||||
}
|
||||
} catch (err) {
|
||||
setGeneralError(
|
||||
err instanceof Error ? err.message : t('bootstrap.failedToComplete', 'Failed to complete setup.'),
|
||||
);
|
||||
setGeneralError(errorMessage(err, t('bootstrap.failedToComplete', 'Failed to complete setup.')));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}, [resolved, sections, formData, originalData, validateSectionRequired, applySetError, t]);
|
||||
|
||||
const handleCopy = useCallback(
|
||||
async (key: string, value: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(value);
|
||||
setCopied(key);
|
||||
setTimeout(() => setCopied((c) => (c === key ? null : c)), 1500);
|
||||
} catch {
|
||||
toast({
|
||||
title: t('bootstrap.copyFailed', 'Copy failed'),
|
||||
description: t('bootstrap.clipboardBlocked', 'Your browser blocked clipboard access.'),
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
},
|
||||
[t],
|
||||
);
|
||||
}, [resolved, sections, formData, originalData, validateSectionRequired, applySetError, setMutation, t]);
|
||||
|
||||
if (!schema || !resolved) {
|
||||
return (
|
||||
<WizardShell>
|
||||
<div className="flex items-center justify-center p-12 text-muted-foreground">
|
||||
<Loader2 className="h-6 w-6 animate-spin mr-2" />
|
||||
<div className="flex items-center justify-center p-12 text-muted-foreground" role="status">
|
||||
<Loader2 className="mr-2 h-6 w-6 animate-spin text-brand-text" aria-hidden="true" />
|
||||
{t('form.loadingSchema', 'Loading schema...')}
|
||||
</div>
|
||||
</WizardShell>
|
||||
@@ -295,14 +219,34 @@ export function BootstrapWizard() {
|
||||
if (loading) {
|
||||
return (
|
||||
<WizardShell>
|
||||
<div className="flex items-center justify-center p-12 text-muted-foreground">
|
||||
<Loader2 className="h-6 w-6 animate-spin mr-2" />
|
||||
<div className="flex items-center justify-center p-12 text-muted-foreground" role="status">
|
||||
<Loader2 className="mr-2 h-6 w-6 animate-spin text-brand-text" aria-hidden="true" />
|
||||
{t('bootstrap.loadingSetup', 'Loading setup...')}
|
||||
</div>
|
||||
</WizardShell>
|
||||
);
|
||||
}
|
||||
|
||||
if (loadError) {
|
||||
return (
|
||||
<WizardShell>
|
||||
<div className="mt-3 space-y-4 rounded-xl bg-destructive-soft p-4">
|
||||
<p className="text-sm text-destructive" role="alert">
|
||||
{loadError}
|
||||
</p>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => void stateQuery.refetch()}
|
||||
disabled={stateQuery.isFetching}
|
||||
>
|
||||
{t('common.retry', 'Retry')}
|
||||
</Button>
|
||||
</div>
|
||||
</WizardShell>
|
||||
);
|
||||
}
|
||||
|
||||
if (successExtras !== null) {
|
||||
return (
|
||||
<WizardShell>
|
||||
@@ -310,8 +254,6 @@ export function BootstrapWizard() {
|
||||
extras={successExtras}
|
||||
fields={resolved.fields}
|
||||
labelsByName={labelsByFieldName(resolved.form)}
|
||||
onCopy={handleCopy}
|
||||
copied={copied}
|
||||
/>
|
||||
</WizardShell>
|
||||
);
|
||||
@@ -320,7 +262,7 @@ export function BootstrapWizard() {
|
||||
if (sections.length === 0) {
|
||||
return (
|
||||
<WizardShell>
|
||||
<div className="rounded-md border border-destructive/20 bg-destructive/10 p-4 text-sm text-destructive">
|
||||
<div className="mt-3 rounded-xl bg-destructive-soft p-4 text-sm text-destructive">
|
||||
{t('bootstrap.emptyForm', 'Setup form is empty. The server did not return any bootstrap fields.')}
|
||||
</div>
|
||||
</WizardShell>
|
||||
@@ -331,54 +273,47 @@ export function BootstrapWizard() {
|
||||
|
||||
return (
|
||||
<WizardShell>
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold tracking-tight">{t('bootstrap.welcome', 'Welcome to Stalwart')}</h2>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{t('bootstrap.welcomeSubtitle', "Let's get your server set up.")}
|
||||
</p>
|
||||
<div className="space-y-3.5">
|
||||
<div className="flex flex-wrap items-end justify-between gap-4 px-1 pb-2 pt-3">
|
||||
<div>
|
||||
<h1 className="page-title">{t('bootstrap.welcome', 'Welcome to Stalwart')}</h1>
|
||||
<p className="mt-1.5 text-sm text-muted-foreground">
|
||||
{t('bootstrap.welcomeSubtitle', "Let's get your server set up.")}
|
||||
</p>
|
||||
</div>
|
||||
<ProgressIndicator total={sections.length} current={currentPage} />
|
||||
</div>
|
||||
|
||||
<ProgressIndicator total={sections.length} current={currentPage} />
|
||||
|
||||
{generalError && (
|
||||
<div className="rounded-md bg-destructive/10 border border-destructive/20 p-4">
|
||||
<p className="text-sm text-destructive whitespace-pre-line">{generalError}</p>
|
||||
<div className="rounded-xl bg-destructive-soft p-4" role="alert">
|
||||
<p className="whitespace-pre-line text-sm text-destructive">{generalError}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Card>
|
||||
{current.title && (
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">{current.title}</CardTitle>
|
||||
</CardHeader>
|
||||
)}
|
||||
<CardContent className={current.title ? '' : 'pt-6'}>
|
||||
<div className="space-y-6">
|
||||
<FormEditionContext.Provider value="oss">
|
||||
{current.fields.map(({ formField, field }) => (
|
||||
<FieldWidget
|
||||
key={formField.name}
|
||||
field={field}
|
||||
formField={formField}
|
||||
value={formData[formField.name]}
|
||||
onChange={(v) => handleFieldChange(formField.name, v)}
|
||||
readOnly={saving}
|
||||
error={fieldErrors[formField.name]}
|
||||
schema={schema}
|
||||
/>
|
||||
))}
|
||||
</FormEditionContext.Provider>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<section className="tile @container px-5 pb-1.5 sm:px-6">
|
||||
{current.title && <h2 className="section-title pb-1 pt-5">{current.title}</h2>}
|
||||
<fieldset disabled={saving} className={cn('min-w-0 divide-y divide-border', !current.title && 'pt-1')}>
|
||||
<FormProvider schema={schema} mode="create" hideEnterprise>
|
||||
{current.fields.map(({ formField, field }) => (
|
||||
<FieldRow
|
||||
key={formField.name}
|
||||
field={field}
|
||||
formField={formField}
|
||||
value={formData[formField.name]}
|
||||
onChange={(v) => handleFieldChange(formField.name, v)}
|
||||
error={fieldErrors[formField.name]}
|
||||
/>
|
||||
))}
|
||||
</FormProvider>
|
||||
</fieldset>
|
||||
</section>
|
||||
|
||||
<div className="flex items-center justify-between pt-2">
|
||||
<div className="flex items-center justify-between gap-3 pt-2">
|
||||
<Button type="button" variant="outline" onClick={handleBack} disabled={!canGoBack || saving}>
|
||||
<ArrowLeft className="h-4 w-4 mr-2" />
|
||||
<ArrowLeft aria-hidden="true" />
|
||||
{t('common.back', 'Back')}
|
||||
</Button>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
<div className="text-xs font-medium text-dim">
|
||||
{t('bootstrap.stepOf', 'Step {{current}} of {{total}}', {
|
||||
current: currentPage + 1,
|
||||
total: sections.length,
|
||||
@@ -386,13 +321,13 @@ export function BootstrapWizard() {
|
||||
</div>
|
||||
{isLastPage ? (
|
||||
<Button type="button" onClick={handleSubmit} disabled={saving}>
|
||||
{saving ? <Loader2 className="h-4 w-4 mr-2 animate-spin" /> : <Rocket className="h-4 w-4 mr-2" />}
|
||||
{saving ? <Loader2 className="animate-spin" aria-hidden="true" /> : <Rocket aria-hidden="true" />}
|
||||
{t('bootstrap.finishSetup', 'Finish setup')}
|
||||
</Button>
|
||||
) : (
|
||||
<Button type="button" onClick={handleNext} disabled={saving}>
|
||||
{t('common.next', 'Next')}
|
||||
<ArrowRight className="h-4 w-4 ml-2" />
|
||||
<ArrowRight aria-hidden="true" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
@@ -401,113 +336,6 @@ export function BootstrapWizard() {
|
||||
);
|
||||
}
|
||||
|
||||
function WizardShell({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col bg-content-background">
|
||||
<header className="flex items-center px-6 py-4 border-b bg-background">
|
||||
<DefaultLogo />
|
||||
</header>
|
||||
<main className="flex-1 overflow-auto p-6">
|
||||
<div className="mx-auto max-w-3xl">{children}</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ProgressIndicator({ total, current }: { total: number; current: number }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div
|
||||
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={`h-2 w-2 rounded-full transition-colors ${
|
||||
i < current ? 'bg-primary' : i === current ? 'bg-primary' : 'bg-muted-foreground/20'
|
||||
}`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SuccessScreen({
|
||||
extras,
|
||||
fields,
|
||||
labelsByName,
|
||||
onCopy,
|
||||
copied,
|
||||
}: {
|
||||
extras: Record<string, unknown>;
|
||||
fields: Fields;
|
||||
labelsByName: Map<string, string>;
|
||||
onCopy: (key: string, value: string) => void;
|
||||
copied: string | null;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const entries = Object.entries(extras).filter(([k, v]) => {
|
||||
if (k === 'id' || k === 'blobId' || k === '@type') return false;
|
||||
return typeof v === 'string' && v.length > 0;
|
||||
}) as [string, string][];
|
||||
|
||||
const hasCredentials = entries.length > 0;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-col items-start gap-3">
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary/10">
|
||||
<Check className="h-5 w-5 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<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',
|
||||
'Your administrator account has been created. Write these down now: the password will not be shown again.',
|
||||
)
|
||||
: t('bootstrap.configuredSuccessfully', 'Stalwart has been configured successfully.')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{hasCredentials && (
|
||||
<Card>
|
||||
<CardContent className="pt-6 space-y-4">
|
||||
{entries.map(([key, value]) => {
|
||||
const field = fields.properties[key];
|
||||
const label = labelsByName.get(key) ?? field?.description?.split('\n')[0] ?? key;
|
||||
return (
|
||||
<div key={key} className="space-y-1.5">
|
||||
<div className="text-sm font-medium">{label}</div>
|
||||
<div className="flex gap-2">
|
||||
<code className="flex-1 rounded bg-muted p-2 text-sm break-all select-all">{value}</code>
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => onCopy(key, value)}>
|
||||
{copied === key ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<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>{' '}
|
||||
{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>
|
||||
);
|
||||
}
|
||||
|
||||
function labelsByFieldName(form: Form | null): Map<string, string> {
|
||||
const map = new Map<string, string>();
|
||||
if (!form) return map;
|
||||
|
||||
@@ -11,6 +11,15 @@ import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, Command
|
||||
import { friendlyName, getActionInfo, getObjectKind, useGlobalSearch } from '@/hooks/useGlobalSearch';
|
||||
import type { SearchIndexEntry } from '@/stores/schemaStore';
|
||||
|
||||
function uniqueEntries(entries: SearchIndexEntry[]): Array<[string, SearchIndexEntry]> {
|
||||
const seen = new Map<string, SearchIndexEntry>();
|
||||
for (const entry of entries) {
|
||||
const key = [entry.type, entry.section, entry.viewName, entry.breadcrumb, entry.text].join('|');
|
||||
if (!seen.has(key)) seen.set(key, entry);
|
||||
}
|
||||
return Array.from(seen);
|
||||
}
|
||||
|
||||
interface CommandPaletteProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
@@ -19,7 +28,7 @@ interface CommandPaletteProps {
|
||||
export function CommandPalette({ open, onOpenChange }: CommandPaletteProps) {
|
||||
const { t } = useTranslation();
|
||||
const closePalette = useCallback(() => onOpenChange(false), [onOpenChange]);
|
||||
const { query, setQuery, debouncedQuery, groups, selectEntry, reset, schema } = useGlobalSearch(closePalette);
|
||||
const { query, setQuery, deferredQuery, groups, selectEntry, reset, schema } = useGlobalSearch(closePalette);
|
||||
|
||||
const groupLabels: Record<SearchIndexEntry['type'], string> = useMemo(
|
||||
() => ({
|
||||
@@ -41,39 +50,43 @@ export function CommandPalette({ open, onOpenChange }: CommandPaletteProps) {
|
||||
<Command
|
||||
shouldFilter={false}
|
||||
loop
|
||||
className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5"
|
||||
className="[&_[cmdk-group-heading]]:px-2.5 [&_[cmdk-group-heading]]:pt-2.5 [&_[cmdk-group-heading]]:text-[11px] [&_[cmdk-group-heading]]:font-semibold [&_[cmdk-group-heading]]:uppercase [&_[cmdk-group-heading]]:tracking-wider [&_[cmdk-group-heading]]:text-dim [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-14 [&_[cmdk-item]]:gap-3 [&_[cmdk-item]]:rounded-xl [&_[cmdk-item]]:px-2.5 [&_[cmdk-item]]:py-2 [&_[cmdk-item][data-selected=true]]:bg-muted [&_[cmdk-item]_svg]:h-4 [&_[cmdk-item]_svg]:w-4 [&_[cmdk-list]]:max-h-[min(60vh,420px)] [&_[cmdk-list]]:pb-2"
|
||||
>
|
||||
<CommandInput
|
||||
placeholder={t('globalSearch.placeholder', 'Search pages, fields, settings...')}
|
||||
value={query}
|
||||
onValueChange={setQuery}
|
||||
trailing={
|
||||
<kbd 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">
|
||||
<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"
|
||||
>
|
||||
ESC
|
||||
</kbd>
|
||||
}
|
||||
/>
|
||||
<CommandList>
|
||||
<CommandEmpty>
|
||||
{debouncedQuery.trim()
|
||||
{deferredQuery.trim()
|
||||
? t('globalSearch.noResults', 'No results found.')
|
||||
: t('globalSearch.typeToSearch', 'Type to search the admin panel.')}
|
||||
</CommandEmpty>
|
||||
{Array.from(groups.entries()).map(([type, entries]) => (
|
||||
<CommandGroup key={type} heading={groupLabels[type]}>
|
||||
{entries.map((entry, idx) => {
|
||||
{uniqueEntries(entries).map(([itemValue, entry]) => {
|
||||
const objectKind = schema ? getObjectKind(schema, entry.viewName) : null;
|
||||
const { label: actionLabel, Icon: ActionIcon } = getActionInfo(entry.type, objectKind, t);
|
||||
const itemValue = `${type}-${idx}-${entry.viewName}`;
|
||||
|
||||
return (
|
||||
<CommandItem key={itemValue} value={itemValue} onSelect={() => selectEntry(entry)}>
|
||||
<ActionIcon className="mr-2 h-4 w-4 shrink-0 text-muted-foreground" />
|
||||
<span className="grid size-8 shrink-0 place-items-center rounded-[10px] bg-highlight text-highlight-foreground">
|
||||
<ActionIcon aria-hidden="true" className="h-4 w-4" />
|
||||
</span>
|
||||
<div className="flex flex-1 flex-col overflow-hidden">
|
||||
<span className="truncate font-medium">{friendlyName(entry.text)}</span>
|
||||
<span className="truncate text-xs text-muted-foreground">{entry.breadcrumb}</span>
|
||||
<span className="truncate text-xs text-dim">{entry.breadcrumb}</span>
|
||||
</div>
|
||||
<span className="ml-auto shrink-0 pl-2 text-xs text-muted-foreground">{actionLabel}</span>
|
||||
<span className="ml-auto shrink-0 pl-2 text-xs font-medium text-dim">{actionLabel}</span>
|
||||
</CommandItem>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useState, type ReactNode } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
export interface ConfirmDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
title: ReactNode;
|
||||
description?: ReactNode;
|
||||
children?: ReactNode;
|
||||
confirmLabel?: ReactNode;
|
||||
cancelLabel?: ReactNode;
|
||||
variant?: 'default' | 'destructive';
|
||||
onConfirm: () => unknown;
|
||||
onCancel?: () => void;
|
||||
}
|
||||
|
||||
function isPromiseLike(value: unknown): value is PromiseLike<unknown> {
|
||||
return typeof value === 'object' && value !== null && typeof (value as { then?: unknown }).then === 'function';
|
||||
}
|
||||
|
||||
export function ConfirmDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
title,
|
||||
description,
|
||||
children,
|
||||
confirmLabel,
|
||||
cancelLabel,
|
||||
variant = 'default',
|
||||
onConfirm,
|
||||
onCancel,
|
||||
}: ConfirmDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const [pending, setPending] = useState(false);
|
||||
|
||||
const dismiss = () => {
|
||||
if (pending) return;
|
||||
onCancel?.();
|
||||
onOpenChange?.(false);
|
||||
};
|
||||
|
||||
const confirm = async () => {
|
||||
if (pending) return;
|
||||
let result: unknown;
|
||||
try {
|
||||
result = onConfirm();
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
return;
|
||||
}
|
||||
if (!isPromiseLike(result)) {
|
||||
onOpenChange?.(false);
|
||||
return;
|
||||
}
|
||||
setPending(true);
|
||||
try {
|
||||
await result;
|
||||
onOpenChange?.(false);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
return;
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<AlertDialog
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
if (!next) dismiss();
|
||||
}}
|
||||
>
|
||||
<AlertDialogContent onEscapeKeyDown={(e) => pending && e.preventDefault()}>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{title}</AlertDialogTitle>
|
||||
{description !== undefined && <AlertDialogDescription>{description}</AlertDialogDescription>}
|
||||
</AlertDialogHeader>
|
||||
{children}
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={pending}>{cancelLabel ?? t('common.cancel', 'Cancel')}</AlertDialogCancel>
|
||||
<Button
|
||||
type="button"
|
||||
variant={variant === 'destructive' ? 'destructive' : 'default'}
|
||||
onClick={() => void confirm()}
|
||||
disabled={pending}
|
||||
aria-busy={pending || undefined}
|
||||
>
|
||||
{pending && <Loader2 className="animate-spin" />}
|
||||
{confirmLabel ??
|
||||
(variant === 'destructive' ? t('common.delete', 'Delete') : t('common.confirm', 'Confirm'))}
|
||||
</Button>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* 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 { Check, Copy } from 'lucide-react';
|
||||
import { Button, type ButtonProps } from '@/components/ui/button';
|
||||
import { useCopyToClipboard } from '@/hooks/useCopyToClipboard';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export interface CopyButtonProps extends Omit<ButtonProps, 'onClick' | 'children' | 'value'> {
|
||||
value: string;
|
||||
label?: string;
|
||||
showText?: boolean;
|
||||
}
|
||||
|
||||
export function CopyButton({
|
||||
value,
|
||||
label,
|
||||
showText = false,
|
||||
variant = 'outline',
|
||||
size,
|
||||
className,
|
||||
...props
|
||||
}: CopyButtonProps) {
|
||||
const { t } = useTranslation();
|
||||
const { copy, isCopied } = useCopyToClipboard();
|
||||
const copied = isCopied();
|
||||
const actionLabel = label ? t('common.copyValue', 'Copy {{name}}', { name: label }) : t('common.copy', 'Copy');
|
||||
const text = copied ? t('common.copied', 'Copied') : actionLabel;
|
||||
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
variant={variant}
|
||||
size={size ?? (showText ? 'sm' : 'icon')}
|
||||
className={cn('shrink-0', className)}
|
||||
onClick={() => void copy(value)}
|
||||
aria-label={showText ? undefined : text}
|
||||
title={showText ? undefined : actionLabel}
|
||||
{...props}
|
||||
>
|
||||
{copied ? <Check /> : <Copy />}
|
||||
{showText && <span>{text}</span>}
|
||||
<span className="sr-only" aria-live="polite">
|
||||
{copied ? t('common.copied', 'Copied') : ''}
|
||||
</span>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { createElement } from 'react';
|
||||
import { Circle, type LucideIcon } from 'lucide-react';
|
||||
import { ICONS } from '@/components/common/icons.generated';
|
||||
|
||||
const warned = new Set<string>();
|
||||
|
||||
function iconKey(name: string): string {
|
||||
const trimmed = name.trim();
|
||||
if (!/[A-Z]/.test(trimmed)) return trimmed;
|
||||
return trimmed.replace(/([a-z])([A-Z0-9])/g, '$1-$2').toLowerCase();
|
||||
}
|
||||
|
||||
interface DynamicIconProps {
|
||||
name: string;
|
||||
className?: string;
|
||||
fallback?: LucideIcon;
|
||||
}
|
||||
|
||||
export function DynamicIcon({ name, className, fallback = Circle }: DynamicIconProps) {
|
||||
const key = iconKey(name);
|
||||
const icon = Object.hasOwn(ICONS, key) ? ICONS[key] : undefined;
|
||||
if (!icon && import.meta.env.DEV && !warned.has(key)) {
|
||||
warned.add(key);
|
||||
console.warn(`Unknown icon name "${name}": run npm run generate:icons after schema changes`);
|
||||
}
|
||||
return createElement(icon ?? fallback, { 'aria-hidden': true, className });
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
*/
|
||||
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Sparkles } from 'lucide-react';
|
||||
|
||||
import {
|
||||
Dialog,
|
||||
@@ -26,12 +27,26 @@ export function EnterpriseUpsell({ open, onClose }: EnterpriseUpsellProps) {
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(isOpen) => !isOpen && onClose()}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<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>
|
||||
<DialogFooter>
|
||||
<DialogFooter className="gap-2 sm:items-center">
|
||||
<a
|
||||
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"
|
||||
>
|
||||
{t('enterprise.whyNotFree')}
|
||||
</a>
|
||||
<Button variant="outline" onClick={onClose}>
|
||||
{t('common.close')}
|
||||
</Button>
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
export function FloatingActionBar({ label, children }: { label?: string; children: ReactNode }) {
|
||||
return (
|
||||
<div className="pointer-events-none sticky bottom-4 z-20 flex justify-center pt-2">
|
||||
<div
|
||||
role={label ? 'group' : undefined}
|
||||
aria-label={label}
|
||||
className="pointer-events-auto flex max-w-full items-center gap-1.5 rounded-full bg-ink p-1.5 text-ink-foreground shadow-ink"
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function FloatingActionDivider() {
|
||||
return <span className="mx-0.5 h-5 w-px bg-ink-foreground/15" aria-hidden="true" />;
|
||||
}
|
||||
|
||||
export function FloatingActionDot() {
|
||||
return <span className="h-2 w-2 shrink-0 rounded-full bg-ink-accent" aria-hidden="true" />;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* 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 { HelpCircle, type LucideIcon } from 'lucide-react';
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import { Markdown } from '@/components/common/Markdown';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export interface HelpTooltipProps {
|
||||
content: string;
|
||||
label?: string;
|
||||
side?: 'top' | 'right' | 'bottom' | 'left';
|
||||
icon?: LucideIcon;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function HelpTooltip({ content, label, side = 'top', icon: Icon = HelpCircle, className }: HelpTooltipProps) {
|
||||
const { t } = useTranslation();
|
||||
const ariaLabel = label
|
||||
? t('common.helpFor', 'Help: {{name}}', { name: label })
|
||||
: t('common.moreInfo', 'More information');
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
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',
|
||||
className,
|
||||
)}
|
||||
onClick={(e) => e.preventDefault()}
|
||||
>
|
||||
<Icon className="h-3.5 w-3.5" aria-hidden="true" />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side={side} className="max-w-xs">
|
||||
<Markdown source={content} className="text-xs" />
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
@@ -11,9 +11,14 @@ import { cn } from '@/lib/utils';
|
||||
export function LoadingFallback({ fullScreen = false }: { fullScreen?: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className={cn('flex flex-col items-center justify-center gap-3', fullScreen ? 'min-h-screen' : 'p-8')}>
|
||||
<Loader2 className="h-8 w-8 animate-spin text-primary" />
|
||||
<p className="text-muted-foreground">{t('common.loading')}</p>
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-col items-center justify-center gap-3',
|
||||
fullScreen ? 'min-h-screen bg-background' : 'p-8',
|
||||
)}
|
||||
>
|
||||
<Loader2 className="h-7 w-7 animate-spin text-brand-text" aria-hidden="true" />
|
||||
<p className="text-sm text-muted-foreground">{t('common.loading')}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* 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 { cn } from '@/lib/utils';
|
||||
|
||||
const MarkdownRenderer = lazy(() => import('@/components/common/MarkdownRenderer'));
|
||||
|
||||
export interface MarkdownProps {
|
||||
source: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function Markdown({ source, className }: MarkdownProps) {
|
||||
const text = source.replace(/\\n/g, '\n');
|
||||
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',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<Suspense fallback={<p className="whitespace-pre-line">{text}</p>}>
|
||||
<MarkdownRenderer source={text} />
|
||||
</Suspense>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import ReactMarkdown from 'react-markdown';
|
||||
|
||||
export default function MarkdownRenderer({ source }: { source: string }) {
|
||||
return <ReactMarkdown>{source}</ReactMarkdown>;
|
||||
}
|
||||
@@ -4,53 +4,46 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Loader2, Search, X } from 'lucide-react';
|
||||
import { Loader2, X } from 'lucide-react';
|
||||
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
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, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
|
||||
import { useObjectList, useObjectLabel, useNoPermissionMessage } from '@/lib/objectOptions';
|
||||
import { ObjectFieldFrame, ObjectSearchPopover } from '@/components/common/ObjectSearchPopover';
|
||||
import { useNoPermissionMessage } from '@/lib/objectOptions';
|
||||
import { useObjectOptions, useDisplayName } from '@/data/objectOptions';
|
||||
import type { Schema } from '@/types/schema';
|
||||
|
||||
interface ObjectPickerProps {
|
||||
schema: Schema;
|
||||
objectName: string;
|
||||
label: string;
|
||||
value: string;
|
||||
onChange: (id: string) => void;
|
||||
onClear?: () => void;
|
||||
placeholder?: string;
|
||||
}
|
||||
|
||||
export function ObjectPicker({ schema, objectName, value, onChange, onClear, placeholder }: ObjectPickerProps) {
|
||||
export function ObjectPicker({ schema, objectName, label, value, onChange, onClear, placeholder }: ObjectPickerProps) {
|
||||
const { t } = useTranslation();
|
||||
const list = useObjectList(objectName, schema);
|
||||
const list = useObjectOptions(objectName, schema);
|
||||
const fromList = list.options.find((o) => o.id === value)?.label;
|
||||
const { label: cheapLabel, loading: labelLoading } = useObjectLabel(
|
||||
const { label: cheapLabel, loading: labelLoading } = useDisplayName(
|
||||
objectName,
|
||||
fromList ? null : value || null,
|
||||
schema,
|
||||
);
|
||||
const display = fromList ?? cheapLabel;
|
||||
const [open, setOpen] = useState(false);
|
||||
const [tooltipOpen, setTooltipOpen] = useState(false);
|
||||
const noPermissionMessage = useNoPermissionMessage(schema, objectName);
|
||||
|
||||
const handleOpenChange = (next: boolean) => {
|
||||
setOpen(next);
|
||||
if (next) void list.ensureLoaded();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<ObjectFieldFrame disabled={!!noPermissionMessage} single>
|
||||
{value && (
|
||||
<Badge variant="secondary" className="gap-1 pr-1.5 text-sm max-w-xs">
|
||||
<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"
|
||||
>
|
||||
{labelLoading ? (
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
<Loader2 className="h-3 w-3 animate-spin" aria-hidden="true" />
|
||||
) : (
|
||||
<span className="truncate" title={display ?? value}>
|
||||
{display ?? value}
|
||||
@@ -60,84 +53,24 @@ export function ObjectPicker({ schema, objectName, value, onChange, onClear, pla
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClear}
|
||||
className="ml-1 rounded-full hover:bg-muted-foreground/20 p-0.5"
|
||||
aria-label={t('common.clear', 'Clear')}
|
||||
className="grid size-5 shrink-0 place-items-center rounded-full bg-card text-muted-foreground transition-colors hover:bg-highlight hover:text-highlight-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
aria-label={t('field.clearValue', 'Clear {{name}}', { name: label })}
|
||||
>
|
||||
<X className="h-3 w-3" />
|
||||
<X className="h-3 w-3" aria-hidden="true" />
|
||||
</button>
|
||||
)}
|
||||
</Badge>
|
||||
)}
|
||||
{!value && placeholder && <span className="text-sm text-muted-foreground">{placeholder}</span>}
|
||||
{noPermissionMessage ? (
|
||||
<TooltipProvider>
|
||||
<Tooltip open={tooltipOpen} onOpenChange={setTooltipOpen}>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7 cursor-not-allowed opacity-60"
|
||||
aria-label={t('common.search', 'Search')}
|
||||
aria-disabled="true"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setTooltipOpen(true);
|
||||
}}
|
||||
>
|
||||
<Search className="h-4 w-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{noPermissionMessage}</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
) : (
|
||||
<Popover open={open} onOpenChange={handleOpenChange}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7"
|
||||
aria-label={t('common.search', 'Search')}
|
||||
>
|
||||
<Search className="h-4 w-4" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="p-0 w-72" align="start">
|
||||
<Command>
|
||||
<CommandInput placeholder={t('common.searchPlaceholder', 'Search...')} />
|
||||
<CommandList>
|
||||
{list.loading && (
|
||||
<div className="flex items-center justify-center py-6 text-sm text-muted-foreground">
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
{t('common.loading', 'Loading...')}
|
||||
</div>
|
||||
)}
|
||||
{!list.loading && <CommandEmpty>{t('common.noResultsDot', 'No results.')}</CommandEmpty>}
|
||||
<CommandGroup>
|
||||
{list.options.map((opt) => (
|
||||
<CommandItem
|
||||
key={opt.id}
|
||||
value={opt.id}
|
||||
keywords={[opt.label]}
|
||||
onSelect={() => {
|
||||
onChange(opt.id);
|
||||
setOpen(false);
|
||||
}}
|
||||
>
|
||||
<span className="truncate" title={opt.label}>
|
||||
{opt.label}
|
||||
</span>
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)}
|
||||
</div>
|
||||
<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}
|
||||
ensureLoaded={list.ensureLoaded}
|
||||
onSelect={onChange}
|
||||
disabledMessage={noPermissionMessage}
|
||||
/>
|
||||
</ObjectFieldFrame>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
/*
|
||||
* 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 type { ReactNode } from 'react';
|
||||
import { ChevronsUpDown, Loader2, Search } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from '@/components/ui/command';
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import { errorMessage } from '@/lib/jmapErrors';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { ObjectOption } from '@/data/objectOptions';
|
||||
import type { ControlProps } from '@/components/forms/widgets/types';
|
||||
|
||||
export interface ObjectSearchPopoverProps {
|
||||
options: ObjectOption[];
|
||||
loading: boolean;
|
||||
error: Error | null;
|
||||
ensureLoaded: () => void | Promise<void>;
|
||||
onSelect: (id: string) => void;
|
||||
disabledMessage?: string | null;
|
||||
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({
|
||||
options,
|
||||
loading,
|
||||
error,
|
||||
ensureLoaded,
|
||||
onSelect,
|
||||
disabledMessage,
|
||||
disabled,
|
||||
label,
|
||||
control,
|
||||
placeholder,
|
||||
}: ObjectSearchPopoverProps) {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [tooltipOpen, setTooltipOpen] = useState(false);
|
||||
|
||||
if (disabledMessage) {
|
||||
return (
|
||||
<Tooltip open={tooltipOpen} onOpenChange={setTooltipOpen}>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
{...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),
|
||||
)}
|
||||
aria-label={label}
|
||||
aria-disabled="true"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setTooltipOpen(true);
|
||||
}}
|
||||
>
|
||||
<TriggerContent placeholder={placeholder} />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{disabledMessage}</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Popover
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
setOpen(next);
|
||||
if (next) void ensureLoaded();
|
||||
}}
|
||||
>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
{...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)
|
||||
}
|
||||
aria-label={label}
|
||||
disabled={disabled}
|
||||
>
|
||||
<TriggerContent placeholder={placeholder} />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-72 overflow-hidden p-0" align="start">
|
||||
<Command>
|
||||
<CommandInput placeholder={t('common.searchPlaceholder', 'Search...')} />
|
||||
<CommandList>
|
||||
{loading && (
|
||||
<div className="flex items-center justify-center py-6 text-sm text-muted-foreground">
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden="true" />
|
||||
{t('common.loading', 'Loading...')}
|
||||
</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">
|
||||
<p className="text-destructive">
|
||||
{errorMessage(error, t('field.optionsLoadFailed', 'Failed to load options.'))}
|
||||
</p>
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => void ensureLoaded()}>
|
||||
{t('common.retry', 'Retry')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{!loading && !error && <CommandEmpty>{t('common.noResultsDot', 'No results.')}</CommandEmpty>}
|
||||
<CommandGroup>
|
||||
{options.map((opt) => (
|
||||
<CommandItem
|
||||
key={opt.id}
|
||||
value={opt.id}
|
||||
keywords={[opt.label]}
|
||||
onSelect={() => {
|
||||
onSelect(opt.id);
|
||||
setOpen(false);
|
||||
}}
|
||||
>
|
||||
<span className="truncate" title={opt.label}>
|
||||
{opt.label}
|
||||
</span>
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</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" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* 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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import {
|
||||
ActivityIcon,
|
||||
AlarmClockIcon,
|
||||
AppWindowIcon,
|
||||
ArchiveIcon,
|
||||
BanIcon,
|
||||
BoxesIcon,
|
||||
BrainIcon,
|
||||
Building2Icon,
|
||||
CableIcon,
|
||||
CalendarIcon,
|
||||
ChartLineIcon,
|
||||
CircleUserIcon,
|
||||
CircleXIcon,
|
||||
ClockIcon,
|
||||
ContactIcon,
|
||||
DatabaseIcon,
|
||||
DownloadIcon,
|
||||
FileCheckIcon,
|
||||
FileCodeIcon,
|
||||
FileTextIcon,
|
||||
FilterIcon,
|
||||
FingerprintIcon,
|
||||
FolderIcon,
|
||||
GaugeIcon,
|
||||
GlobeIcon,
|
||||
HardDriveIcon,
|
||||
HourglassIcon,
|
||||
InboxIcon,
|
||||
KeyRoundIcon,
|
||||
KeySquareIcon,
|
||||
LayersIcon,
|
||||
LayoutDashboardIcon,
|
||||
ListChecksIcon,
|
||||
ListOrderedIcon,
|
||||
ListTodoIcon,
|
||||
ListTreeIcon,
|
||||
LockIcon,
|
||||
LockKeyholeIcon,
|
||||
MailIcon,
|
||||
MailMinusIcon,
|
||||
MailXIcon,
|
||||
MemoryStickIcon,
|
||||
MonitorIcon,
|
||||
NetworkIcon,
|
||||
PhoneIcon,
|
||||
PlaneIcon,
|
||||
RotateCwIcon,
|
||||
RouteIcon,
|
||||
ScissorsIcon,
|
||||
SearchCodeIcon,
|
||||
SearchIcon,
|
||||
SearchXIcon,
|
||||
SendIcon,
|
||||
ServerIcon,
|
||||
SettingsIcon,
|
||||
ShieldAlertIcon,
|
||||
ShieldCheckIcon,
|
||||
ShieldXIcon,
|
||||
SlidersHorizontalIcon,
|
||||
TimerIcon,
|
||||
TimerOffIcon,
|
||||
Trash2Icon,
|
||||
TriangleAlertIcon,
|
||||
UnlockIcon,
|
||||
UploadIcon,
|
||||
UsersIcon,
|
||||
ZapIcon,
|
||||
type LucideIcon,
|
||||
} from 'lucide-react';
|
||||
|
||||
export const ICONS: Readonly<Record<string, LucideIcon>> = {
|
||||
activity: ActivityIcon,
|
||||
'alarm-clock': AlarmClockIcon,
|
||||
'app-window': AppWindowIcon,
|
||||
archive: ArchiveIcon,
|
||||
ban: BanIcon,
|
||||
boxes: BoxesIcon,
|
||||
brain: BrainIcon,
|
||||
'building-2': Building2Icon,
|
||||
cable: CableIcon,
|
||||
calendar: CalendarIcon,
|
||||
'chart-line': ChartLineIcon,
|
||||
'circle-user': CircleUserIcon,
|
||||
'circle-x': CircleXIcon,
|
||||
clock: ClockIcon,
|
||||
contact: ContactIcon,
|
||||
database: DatabaseIcon,
|
||||
download: DownloadIcon,
|
||||
'file-check': FileCheckIcon,
|
||||
'file-code': FileCodeIcon,
|
||||
'file-text': FileTextIcon,
|
||||
filter: FilterIcon,
|
||||
fingerprint: FingerprintIcon,
|
||||
folder: FolderIcon,
|
||||
gauge: GaugeIcon,
|
||||
globe: GlobeIcon,
|
||||
'hard-drive': HardDriveIcon,
|
||||
hourglass: HourglassIcon,
|
||||
inbox: InboxIcon,
|
||||
'key-round': KeyRoundIcon,
|
||||
'key-square': KeySquareIcon,
|
||||
layers: LayersIcon,
|
||||
'layout-dashboard': LayoutDashboardIcon,
|
||||
'list-checks': ListChecksIcon,
|
||||
'list-ordered': ListOrderedIcon,
|
||||
'list-todo': ListTodoIcon,
|
||||
'list-tree': ListTreeIcon,
|
||||
lock: LockIcon,
|
||||
'lock-keyhole': LockKeyholeIcon,
|
||||
mail: MailIcon,
|
||||
'mail-minus': MailMinusIcon,
|
||||
'mail-x': MailXIcon,
|
||||
'memory-stick': MemoryStickIcon,
|
||||
monitor: MonitorIcon,
|
||||
network: NetworkIcon,
|
||||
phone: PhoneIcon,
|
||||
plane: PlaneIcon,
|
||||
'rotate-cw': RotateCwIcon,
|
||||
route: RouteIcon,
|
||||
scissors: ScissorsIcon,
|
||||
search: SearchIcon,
|
||||
'search-code': SearchCodeIcon,
|
||||
'search-x': SearchXIcon,
|
||||
send: SendIcon,
|
||||
server: ServerIcon,
|
||||
settings: SettingsIcon,
|
||||
'shield-alert': ShieldAlertIcon,
|
||||
'shield-check': ShieldCheckIcon,
|
||||
'shield-x': ShieldXIcon,
|
||||
'sliders-horizontal': SlidersHorizontalIcon,
|
||||
timer: TimerIcon,
|
||||
'timer-off': TimerOffIcon,
|
||||
'trash-2': Trash2Icon,
|
||||
'triangle-alert': TriangleAlertIcon,
|
||||
unlock: UnlockIcon,
|
||||
upload: UploadIcon,
|
||||
users: UsersIcon,
|
||||
zap: ZapIcon,
|
||||
};
|
||||
@@ -10,7 +10,7 @@ import { useBufferedValue } from '@/hooks/useBufferedValue';
|
||||
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
import { X, Plus } from 'lucide-react';
|
||||
|
||||
@@ -41,16 +41,25 @@ function BufferedExprInput({
|
||||
);
|
||||
}
|
||||
|
||||
interface ExpressionEditorProps {
|
||||
value: {
|
||||
match: Record<string, { if: string; then: string }>;
|
||||
else: string;
|
||||
};
|
||||
onChange: (value: { match: Record<string, { if: string; then: string }>; else: string }) => void;
|
||||
readOnly?: boolean;
|
||||
export interface ExpressionValue {
|
||||
match: Record<string, { if: string; then: string }>;
|
||||
else: string;
|
||||
}
|
||||
|
||||
export function ExpressionEditor({ value, onChange, readOnly = false }: ExpressionEditorProps) {
|
||||
interface ExpressionEditorProps {
|
||||
value: ExpressionValue;
|
||||
onChange: (value: ExpressionValue) => void;
|
||||
readOnly?: boolean;
|
||||
label?: string;
|
||||
control?: {
|
||||
id?: string;
|
||||
'aria-invalid'?: boolean;
|
||||
'aria-describedby'?: string;
|
||||
'aria-labelledby'?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export function ExpressionEditor({ value, onChange, readOnly = false, label, control }: ExpressionEditorProps) {
|
||||
const { t } = useTranslation();
|
||||
const [nextIndex, setNextIndex] = useState(() => {
|
||||
const keys = Object.keys(value.match).map(Number).filter(Number.isFinite);
|
||||
@@ -89,48 +98,50 @@ export function ExpressionEditor({ value, onChange, readOnly = false }: Expressi
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border bg-card p-4 space-y-3">
|
||||
<div className="space-y-2.5 rounded-xl bg-muted p-3">
|
||||
{matchEntries.map(([key, entry], index) => (
|
||||
<div key={key}>
|
||||
<div className="rounded-md border bg-muted/30 p-3 space-y-2">
|
||||
<div className="space-y-2 rounded-lg bg-card p-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground w-12 shrink-0">
|
||||
<span className="w-12 shrink-0 text-[11px] font-semibold uppercase tracking-wider text-dim">
|
||||
{t('expression.if', 'IF')}
|
||||
</span>
|
||||
<BufferedExprInput
|
||||
value={entry.if}
|
||||
onCommit={(v) => handleConditionChange(key, 'if', v)}
|
||||
disabled={readOnly}
|
||||
aria-label={t('expression.conditionN', 'Condition {{n}}', { n: index + 1 })}
|
||||
placeholder={t('expression.condition', 'Condition')}
|
||||
className="flex-1"
|
||||
/>
|
||||
{!readOnly && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive"
|
||||
variant="ghost-danger"
|
||||
size="icon-sm"
|
||||
className="shrink-0"
|
||||
onClick={() => handleRemove(key)}
|
||||
aria-label={t('expression.removeCondition', 'Remove condition {{n}}', { n: index + 1 })}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
<X aria-hidden="true" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground w-12 shrink-0">
|
||||
<span className="w-12 shrink-0 text-[11px] font-semibold uppercase tracking-wider text-dim">
|
||||
{t('expression.then', 'THEN')}
|
||||
</span>
|
||||
<BufferedExprInput
|
||||
value={entry.then}
|
||||
onCommit={(v) => handleConditionChange(key, 'then', v)}
|
||||
disabled={readOnly}
|
||||
aria-label={t('expression.resultN', 'Result {{n}}', { n: index + 1 })}
|
||||
placeholder={t('expression.result', 'Result')}
|
||||
className="flex-1"
|
||||
/>
|
||||
{!readOnly && <div className="w-8 shrink-0" />}
|
||||
</div>
|
||||
</div>
|
||||
{index < matchEntries.length - 1 && <Separator className="my-3" />}
|
||||
</div>
|
||||
))}
|
||||
|
||||
@@ -141,18 +152,17 @@ export function ExpressionEditor({ value, onChange, readOnly = false }: Expressi
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={handleAdd}
|
||||
className="h-7 gap-1 px-2 text-xs text-muted-foreground hover:text-foreground"
|
||||
className="h-7 gap-1 px-3 text-xs hover:bg-card"
|
||||
>
|
||||
<Plus className="h-3 w-3" />
|
||||
<Plus className="!size-3.5" aria-hidden="true" />
|
||||
{t('expression.addCondition', 'Add condition')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{matchEntries.length > 0 && <Separator />}
|
||||
<div className="flex items-center gap-2">
|
||||
<div className={cn('flex items-center gap-2', matchEntries.length > 0 && 'border-t border-border pt-2.5')}>
|
||||
{matchEntries.length > 0 && (
|
||||
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground w-12 shrink-0">
|
||||
<span className="w-12 shrink-0 text-[11px] font-semibold uppercase tracking-wider text-dim">
|
||||
{t('expression.else', 'ELSE')}
|
||||
</span>
|
||||
)}
|
||||
@@ -160,6 +170,13 @@ export function ExpressionEditor({ value, onChange, readOnly = false }: Expressi
|
||||
value={value.else}
|
||||
onCommit={handleElseChange}
|
||||
disabled={readOnly}
|
||||
id={control?.id}
|
||||
aria-invalid={control?.['aria-invalid']}
|
||||
aria-label={
|
||||
matchEntries.length > 0
|
||||
? t('expression.defaultValue', 'Default value')
|
||||
: (label ?? t('expression.value', 'Value'))
|
||||
}
|
||||
placeholder={
|
||||
matchEntries.length > 0 ? t('expression.defaultValue', 'Default value') : t('expression.value', 'Value')
|
||||
}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* 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 { Button } from '@/components/ui/button';
|
||||
import { CopyButton } from '@/components/common/CopyButton';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
|
||||
interface CreatedValuesDialogProps {
|
||||
values: Record<string, unknown> | null;
|
||||
labels: Map<string, string>;
|
||||
onContinue: () => void;
|
||||
}
|
||||
|
||||
function displayValue(value: unknown): string {
|
||||
if (typeof value === 'string') return value;
|
||||
if (value === null || value === undefined) return '';
|
||||
if (typeof value === 'object') return JSON.stringify(value);
|
||||
return String(value);
|
||||
}
|
||||
|
||||
export function CreatedValuesDialog({ values, labels, onContinue }: CreatedValuesDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Dialog open={values !== null}>
|
||||
<DialogContent
|
||||
showCloseButton={false}
|
||||
onInteractOutside={(e) => e.preventDefault()}
|
||||
onEscapeKeyDown={(e) => e.preventDefault()}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('form.createdSuccess', 'Created successfully')}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{t(
|
||||
'form.createdServerGenerated',
|
||||
'The following values were generated by the server. Please save them now, they may not be retrievable later.',
|
||||
)}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-1 divide-y divide-border rounded-xl bg-muted px-4 py-1">
|
||||
{values &&
|
||||
Object.entries(values).map(([key, value]) => {
|
||||
const text = displayValue(value);
|
||||
const label = labels.get(key) ?? key;
|
||||
return (
|
||||
<div key={key} className="flex flex-col gap-1.5 py-3">
|
||||
<span className="text-[13px] font-semibold text-muted-foreground">{label}</span>
|
||||
<div className="flex items-start gap-2">
|
||||
<code className="flex-1 select-all break-all rounded-lg bg-card px-3 py-2 font-mono text-sm">
|
||||
{text}
|
||||
</code>
|
||||
<CopyButton value={text} label={label} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="button" onClick={onContinue}>
|
||||
{t('common.continue', 'Continue')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
+295
-1071
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,171 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import type { ReactNode } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Lock } from 'lucide-react';
|
||||
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 { FieldScopeProvider } from '@/components/forms/FormProvider';
|
||||
import { FieldControl } from '@/components/forms/widgets/FieldControl';
|
||||
import { resolveWidget } from '@/extensions/widgets';
|
||||
import { fieldIds, isEnterpriseLockedIn, useFieldScope, useFormContext } from '@/components/forms/formContext';
|
||||
import { requiredMarker } from '@/components/forms/formLogic';
|
||||
import { resolveObject } from '@/lib/schemaResolver';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { ControlProps } from '@/components/forms/widgets/types';
|
||||
import type { Field, FormField } from '@/types/schema';
|
||||
|
||||
const ARIA_REQUIRED_TYPES = new Set(['string', 'number', 'enum', 'blobId']);
|
||||
|
||||
export interface FieldRowProps {
|
||||
field: Field;
|
||||
formField: FormField;
|
||||
value: unknown;
|
||||
onChange: (value: unknown) => void;
|
||||
error?: string;
|
||||
readOnly?: boolean;
|
||||
}
|
||||
|
||||
interface FieldLabelProps {
|
||||
id: string;
|
||||
htmlFor?: string;
|
||||
label: string;
|
||||
marker: 'required' | 'optional' | null;
|
||||
locked: boolean;
|
||||
}
|
||||
|
||||
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">
|
||||
{label}
|
||||
{marker === 'required' && (
|
||||
<span className="ml-1 text-brand-text" aria-hidden="true">
|
||||
*
|
||||
</span>
|
||||
)}
|
||||
{marker === 'optional' && (
|
||||
<span className="ml-1.5 text-xs font-normal text-dim">{t('field.optional', '(optional)')}</span>
|
||||
)}
|
||||
</Label>
|
||||
{locked && (
|
||||
<HelpTooltip
|
||||
icon={Lock}
|
||||
label={label}
|
||||
content={t('enterprise.featureDisabled', 'This feature requires an Enterprise license.')}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function FieldError({ id, error }: { id: string; error?: string }) {
|
||||
if (!error) return null;
|
||||
return (
|
||||
<p id={id} className="text-xs font-medium text-destructive">
|
||||
{error}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
export function FieldRow({ field, formField, value, onChange, error, readOnly: forceReadOnly = false }: FieldRowProps) {
|
||||
const ctx = useFormContext();
|
||||
const scope = useFieldScope();
|
||||
if (field.enterprise && ctx.hideEnterprise) return null;
|
||||
|
||||
const ft = field.type;
|
||||
const ids = fieldIds(ctx.idPrefix, [...scope.path, formField.name]);
|
||||
const topLevel = scope.path.length === 0;
|
||||
const referencesLocked =
|
||||
ft.type === 'objectId' && ctx.isCommunity && !!resolveObject(ctx.schema, ft.objectName)?.enterprise;
|
||||
const locked = isEnterpriseLockedIn(ctx, field.enterprise);
|
||||
const readOnly =
|
||||
scope.readOnly ||
|
||||
forceReadOnly ||
|
||||
locked ||
|
||||
referencesLocked ||
|
||||
field.update === 'serverSet' ||
|
||||
(topLevel && ctx.mode === 'edit' && field.update === 'immutable');
|
||||
const { traits, RowAddon } = resolveWidget(ft);
|
||||
const asValue = readOnly && traits.readOnlyAsValue;
|
||||
const marker = requiredMarker(field, readOnly);
|
||||
const describedBy =
|
||||
[field.description ? ids.descriptionId : null, error ? ids.errorId : null].filter(Boolean).join(' ') || undefined;
|
||||
const control: ControlProps = {
|
||||
id: ids.inputId,
|
||||
'aria-invalid': error ? true : undefined,
|
||||
'aria-describedby': describedBy,
|
||||
'aria-labelledby': traits.labelMode === 'group' ? ids.labelId : undefined,
|
||||
'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} />
|
||||
</FieldScopeProvider>
|
||||
);
|
||||
if (!asValue && traits.labelMode === 'group') {
|
||||
body = (
|
||||
<div role="group" aria-labelledby={ids.labelId} aria-describedby={describedBy}>
|
||||
{body}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (traits.labelMode === 'none') {
|
||||
return (
|
||||
<div data-slot="field-row" className="space-y-1.5 py-4">
|
||||
{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>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,18 +0,0 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { createContext, useContext } from 'react';
|
||||
import { useAccountStore } from '@/stores/accountStore';
|
||||
|
||||
export type EditionValue = 'enterprise' | 'community' | 'oss';
|
||||
|
||||
export const FormEditionContext = createContext<EditionValue | null>(null);
|
||||
|
||||
export function useEffectiveEdition(): EditionValue {
|
||||
const override = useContext(FormEditionContext);
|
||||
const storeEdition = useAccountStore((s) => s.edition);
|
||||
return override ?? storeEdition;
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useId, type ReactNode } from 'react';
|
||||
import { useIsCommunity } from '@/hooks/usePermissions';
|
||||
import {
|
||||
FieldScopeContext,
|
||||
FormContext,
|
||||
useFieldScope,
|
||||
type FieldScope,
|
||||
type FormContextValue,
|
||||
type FormMode,
|
||||
} from '@/components/forms/formContext';
|
||||
import type { Schema } from '@/types/schema';
|
||||
|
||||
interface FormProviderProps {
|
||||
schema: Schema;
|
||||
mode?: FormMode;
|
||||
readOnly?: boolean;
|
||||
hideEnterprise?: boolean;
|
||||
recordLabel?: string;
|
||||
baseline?: unknown;
|
||||
tenantId?: string | null;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function FormProvider({
|
||||
schema,
|
||||
mode = 'edit',
|
||||
readOnly = false,
|
||||
hideEnterprise = false,
|
||||
recordLabel = '',
|
||||
baseline = null,
|
||||
tenantId = null,
|
||||
children,
|
||||
}: FormProviderProps) {
|
||||
const isCommunity = useIsCommunity();
|
||||
const idPrefix = `f${useId().replace(/[^A-Za-z0-9_-]/g, '')}`;
|
||||
const value: FormContextValue = {
|
||||
schema,
|
||||
mode,
|
||||
readOnly,
|
||||
hideEnterprise,
|
||||
isCommunity,
|
||||
idPrefix,
|
||||
recordLabel,
|
||||
baseline,
|
||||
tenantId,
|
||||
};
|
||||
const scope: FieldScope = { path: [], readOnly };
|
||||
return (
|
||||
<FormContext.Provider value={value}>
|
||||
<FieldScopeContext.Provider value={scope}>{children}</FieldScopeContext.Provider>
|
||||
</FormContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function FieldScopeProvider({
|
||||
name,
|
||||
readOnly,
|
||||
children,
|
||||
}: {
|
||||
name: string;
|
||||
readOnly: boolean;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const outer = useFieldScope();
|
||||
const scope: FieldScope = { path: [...outer.path, name], readOnly };
|
||||
return <FieldScopeContext.Provider value={scope}>{children}</FieldScopeContext.Provider>;
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import type { ReactNode } from 'react';
|
||||
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[];
|
||||
value: string;
|
||||
onChange: (variant: string) => void;
|
||||
}
|
||||
|
||||
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) {
|
||||
return (
|
||||
<>
|
||||
{sections.map((section) => (
|
||||
<FormSectionCard key={section.key} id={sectionId?.(section.key)} title={section.title}>
|
||||
{section.fields.map(({ formField, field }) => {
|
||||
if (!field) {
|
||||
if (!variant) return null;
|
||||
return (
|
||||
<VariantSelect
|
||||
key={formField.name}
|
||||
label={formField.label}
|
||||
variants={variant.variants}
|
||||
value={variant.value}
|
||||
onChange={variant.onChange}
|
||||
readOnly={readOnly}
|
||||
/>
|
||||
);
|
||||
}
|
||||
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}
|
||||
field={field}
|
||||
formField={formField}
|
||||
value={data[formField.name]}
|
||||
onChange={(v) => onFieldChange(formField.name, v)}
|
||||
error={errors[formField.name]}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</FormSectionCard>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function FormSectionCard({ id, title, children }: { id?: string; 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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
* 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 { Bug } from 'lucide-react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
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;
|
||||
source: string;
|
||||
}
|
||||
|
||||
export function SievepadButton({ scriptName, source }: SievepadButtonProps) {
|
||||
const { t } = useTranslation();
|
||||
const [warningOpen, setWarningOpen] = useState(false);
|
||||
const [dontShowAgain, setDontShowAgain] = useState(false);
|
||||
|
||||
const open = () => {
|
||||
openInSievepad(scriptName || t('sievepad.defaultName', 'Sieve script'), source).catch(() => {
|
||||
toast({ title: t('sievepad.failed', 'Failed to open Sievepad.'), variant: 'destructive' });
|
||||
});
|
||||
};
|
||||
|
||||
const handleClick = () => {
|
||||
if (isSievepadWarningDismissed()) {
|
||||
open();
|
||||
} else {
|
||||
setDontShowAgain(false);
|
||||
setWarningOpen(true);
|
||||
}
|
||||
};
|
||||
|
||||
const handleContinue = () => {
|
||||
if (dontShowAgain) dismissSievepadWarning();
|
||||
open();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex justify-end">
|
||||
<Button type="button" variant="secondary" size="sm" onClick={handleClick} disabled={!source.trim()}>
|
||||
<Bug aria-hidden="true" />
|
||||
{t('sievepad.debug', 'Debug')}
|
||||
</Button>
|
||||
</div>
|
||||
<ConfirmDialog
|
||||
open={warningOpen}
|
||||
onOpenChange={setWarningOpen}
|
||||
title={t('sievepad.warningTitle', 'Debug in Sievepad')}
|
||||
description={t(
|
||||
'sievepad.warningDescription',
|
||||
'A new tab will open sievepad.com with a copy of this script. Sievepad compiles and runs the script entirely in your browser: nothing is uploaded to or stored on any server.',
|
||||
)}
|
||||
confirmLabel={t('common.continue')}
|
||||
onConfirm={handleContinue}
|
||||
>
|
||||
<div className="flex items-center gap-2.5 rounded-xl bg-muted px-3.5 py-3">
|
||||
<Checkbox
|
||||
id="sievepad-dont-show-again"
|
||||
checked={dontShowAgain}
|
||||
onCheckedChange={(checked) => setDontShowAgain(checked === true)}
|
||||
/>
|
||||
<Label htmlFor="sievepad-dont-show-again" className="text-sm font-normal">
|
||||
{t('sievepad.dontShowAgain', "Don't show this again")}
|
||||
</Label>
|
||||
</div>
|
||||
</ConfirmDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function SievepadRowAddon({ value }: WidgetProps) {
|
||||
const { recordLabel } = useFormContext();
|
||||
return <SievepadButton scriptName={recordLabel} source={typeof value === 'string' ? value : ''} />;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* 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 type { Blocker } from 'react-router-dom';
|
||||
import { ConfirmDialog } from '@/components/common/ConfirmDialog';
|
||||
|
||||
export function UnsavedChangesDialog({ blocker }: { blocker: Blocker }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<ConfirmDialog
|
||||
open={blocker.state === 'blocked'}
|
||||
title={t('form.unsavedChangesTitle', 'Unsaved changes')}
|
||||
description={t('form.unsavedChanges', 'You have unsaved changes. Are you sure you want to leave?')}
|
||||
cancelLabel={t('form.stay', 'Stay')}
|
||||
confirmLabel={t('form.leave', 'Leave')}
|
||||
onCancel={() => blocker.reset?.()}
|
||||
onConfirm={() => blocker.proceed?.()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* 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 { 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;
|
||||
labelledBy?: string;
|
||||
ariaLabel?: string;
|
||||
variants: readonly EmbeddedVariant[];
|
||||
value: string;
|
||||
onChange: (variant: string) => void;
|
||||
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,
|
||||
ariaLabel,
|
||||
variants,
|
||||
value,
|
||||
onChange,
|
||||
readOnly,
|
||||
}: VariantSelectProps) {
|
||||
const { t } = useTranslation();
|
||||
const ctx = useFormContext();
|
||||
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">
|
||||
<FieldLabel
|
||||
id={ids.labelId}
|
||||
htmlFor={segmented ? undefined : 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>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { createContext, useContext } from 'react';
|
||||
import type { Schema } from '@/types/schema';
|
||||
|
||||
export type FormMode = 'create' | 'edit';
|
||||
|
||||
export interface FormContextValue {
|
||||
schema: Schema;
|
||||
mode: FormMode;
|
||||
readOnly: boolean;
|
||||
hideEnterprise: boolean;
|
||||
isCommunity: boolean;
|
||||
idPrefix: string;
|
||||
recordLabel: string;
|
||||
baseline: unknown;
|
||||
tenantId: string | null;
|
||||
}
|
||||
|
||||
export interface FieldScope {
|
||||
path: readonly string[];
|
||||
readOnly: boolean;
|
||||
}
|
||||
|
||||
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');
|
||||
return ctx;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
export function fieldDomId(idPrefix: string, path: readonly string[]): string {
|
||||
const suffix = path.map((p) => p.replace(/[^A-Za-z0-9_-]/g, '_')).join('-');
|
||||
return suffix ? `${idPrefix}-${suffix}` : idPrefix;
|
||||
}
|
||||
|
||||
export interface FieldIds {
|
||||
inputId: string;
|
||||
labelId: string;
|
||||
descriptionId: string;
|
||||
errorId: string;
|
||||
}
|
||||
|
||||
export function fieldIds(idPrefix: string, path: readonly string[]): FieldIds {
|
||||
const base = fieldDomId(idPrefix, path);
|
||||
return {
|
||||
inputId: base,
|
||||
labelId: `${base}-label`,
|
||||
descriptionId: `${base}-description`,
|
||||
errorId: `${base}-error`,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,532 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { calculateJmapPatch } from '@/lib/jmapPatch';
|
||||
import { deepMerge, resolveForm, resolveObject, type ResolvedView } from '@/lib/schemaResolver';
|
||||
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 { FormMode } from '@/components/forms/formContext';
|
||||
|
||||
export type FieldValues = Record<string, unknown>;
|
||||
export type FieldErrors = Record<string, string>;
|
||||
|
||||
export function valuesEqual(a: unknown, b: unknown): boolean {
|
||||
if (Object.is(a, b)) return true;
|
||||
if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;
|
||||
if (Array.isArray(a) !== Array.isArray(b)) return false;
|
||||
if (Array.isArray(a) && Array.isArray(b)) {
|
||||
if (a.length !== b.length) return false;
|
||||
for (let i = 0; i < a.length; i++) if (!valuesEqual(a[i], b[i])) return false;
|
||||
return true;
|
||||
}
|
||||
const ar = a as Record<string, unknown>;
|
||||
const br = b as Record<string, unknown>;
|
||||
const aKeys = Object.keys(ar);
|
||||
if (aKeys.length !== Object.keys(br).length) return false;
|
||||
for (const key of aKeys) {
|
||||
if (!Object.prototype.hasOwnProperty.call(br, key) || !valuesEqual(ar[key], br[key])) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function changedKeys(original: FieldValues, current: FieldValues): Set<string> {
|
||||
const changed = new Set<string>();
|
||||
for (const key of new Set([...Object.keys(original), ...Object.keys(current)])) {
|
||||
if (!valuesEqual(original[key], current[key])) changed.add(key);
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
export function isRequiredEligible(type: FieldType): boolean {
|
||||
switch (type.type) {
|
||||
case 'string':
|
||||
case 'number':
|
||||
case 'utcDateTime':
|
||||
case 'enum':
|
||||
case 'blobId':
|
||||
case 'objectId':
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isNullable(type: FieldType): boolean {
|
||||
return 'nullable' in type && !!type.nullable;
|
||||
}
|
||||
|
||||
export function requiredMarker(field: Field, readOnly: boolean): 'required' | 'optional' | null {
|
||||
if (readOnly || field.update === 'serverSet' || !isRequiredEligible(field.type)) return null;
|
||||
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;
|
||||
}
|
||||
|
||||
export function validateRequired(
|
||||
data: FieldValues,
|
||||
fields: Fields,
|
||||
mode: FormMode,
|
||||
messages: RequiredMessages | 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 (!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;
|
||||
}
|
||||
|
||||
export function isOtpAuthValid(data: unknown): boolean {
|
||||
if (!isRecord(data)) return true;
|
||||
for (const key of Object.keys(data)) {
|
||||
if (!isOtpAuthValid(data[key])) return false;
|
||||
}
|
||||
if (!('otpUrl' in data) || !('otpCode' in data)) return true;
|
||||
if (data.otpUrl == null || data.otpUrl === '') return true;
|
||||
return !(data.otpCode == null || data.otpCode === '' || data.otpCode === SECRET_MASK);
|
||||
}
|
||||
|
||||
export function buildCreatePayload(
|
||||
data: FieldValues,
|
||||
fields: Fields | null,
|
||||
options: { filtersStatic?: Record<string, unknown>; variant?: string } = {},
|
||||
): FieldValues {
|
||||
const validKeys = new Set<string>(['@type', ...Object.keys(fields?.properties ?? {})]);
|
||||
const base: FieldValues = {};
|
||||
for (const [key, value] of Object.entries(options.filtersStatic ?? {})) {
|
||||
if (validKeys.has(key)) base[key] = value;
|
||||
}
|
||||
const input: FieldValues = {};
|
||||
if (options.variant) input['@type'] = options.variant;
|
||||
for (const [name, field] of Object.entries(fields?.properties ?? {})) {
|
||||
if (field.update === 'serverSet' || !(name in data)) continue;
|
||||
if (isUnchangedSecret(field, data[name])) continue;
|
||||
input[name] = data[name];
|
||||
}
|
||||
return deepMerge(base, input);
|
||||
}
|
||||
|
||||
function withoutMaskedSecrets(value: unknown): unknown {
|
||||
if (Array.isArray(value)) return value.map(withoutMaskedSecrets);
|
||||
if (!isRecord(value)) return value;
|
||||
const result: Record<string, unknown> = {};
|
||||
for (const [key, nested] of Object.entries(value)) {
|
||||
if (nested !== SECRET_MASK) result[key] = withoutMaskedSecrets(nested);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function buildUpdatePatch(original: FieldValues, data: FieldValues, fields: Fields | null): FieldValues {
|
||||
const patch: FieldValues = {};
|
||||
if (original[VARIANT_FIELD] !== data[VARIANT_FIELD]) {
|
||||
for (const [key, value] of Object.entries(data)) {
|
||||
if (key === 'id') continue;
|
||||
const field = fields?.properties[key];
|
||||
if (field?.update === 'serverSet') continue;
|
||||
if (field && isUnchangedSecret(field, value)) continue;
|
||||
patch[key] = value === undefined ? null : withoutMaskedSecrets(value);
|
||||
}
|
||||
return patch;
|
||||
}
|
||||
for (const [key, value] of Object.entries(calculateJmapPatch(original, data))) {
|
||||
const field = fields?.properties[key.split('/')[0]];
|
||||
if (field && (field.update === 'immutable' || field.update === 'serverSet')) continue;
|
||||
if (field && isUnchangedSecret(field, value)) continue;
|
||||
if (key.includes('/') && value === SECRET_MASK) continue;
|
||||
patch[key] = withoutMaskedSecrets(value);
|
||||
}
|
||||
return patch;
|
||||
}
|
||||
|
||||
export function collectBlobUploads(
|
||||
payload: FieldValues,
|
||||
fields: Fields | null,
|
||||
original?: FieldValues,
|
||||
): { blobs: Record<string, BlobUpload>; payload: FieldValues } {
|
||||
const blobs: Record<string, BlobUpload> = {};
|
||||
if (!fields) return { blobs, payload };
|
||||
const next: FieldValues = { ...payload };
|
||||
let index = 0;
|
||||
for (const [key, value] of Object.entries(payload)) {
|
||||
if (fields.properties[key.split('/')[0]]?.type.type !== 'blobId') continue;
|
||||
if (typeof value !== 'string' || !value) continue;
|
||||
if (original && value === original[key]) continue;
|
||||
const tag = `temp-blob-${index++}`;
|
||||
blobs[tag] = { data: value };
|
||||
next[key] = `#${tag}`;
|
||||
}
|
||||
return { blobs, payload: next };
|
||||
}
|
||||
|
||||
export interface SetErrorMessages {
|
||||
general: string;
|
||||
invalidValue: string;
|
||||
validation: (ve: ValidationError) => string;
|
||||
}
|
||||
|
||||
export function mapSetError(
|
||||
error: JmapSetError,
|
||||
knownFields: ReadonlySet<string>,
|
||||
messages: SetErrorMessages,
|
||||
): { 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;
|
||||
const top = ve.property.split('/')[0];
|
||||
if (knownFields.has(top)) {
|
||||
fieldErrors[top] = messages.validation(ve);
|
||||
} else {
|
||||
extra.push(`${ve.property}: ${ve.value && ve.value.length > 0 ? ve.value : ve.type}`);
|
||||
}
|
||||
}
|
||||
return { general: [messages.general, ...extra].join('\n'), fieldErrors };
|
||||
}
|
||||
|
||||
export function combineForms(parent: Form | null, variant: Form | null): Form | null {
|
||||
const sections = [...(parent?.sections ?? []), ...(variant?.sections ?? [])];
|
||||
if (sections.length === 0) return null;
|
||||
return {
|
||||
title: parent?.title ?? variant?.title,
|
||||
subtitle: parent?.subtitle ?? variant?.subtitle,
|
||||
sections,
|
||||
};
|
||||
}
|
||||
|
||||
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) {
|
||||
for (const section of form?.sections ?? []) {
|
||||
for (const ff of section.fields) names.add(ff.name);
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
export function formFieldLabels(...forms: (Form | null | undefined)[]): Map<string, string> {
|
||||
const labels = new Map<string, string>();
|
||||
for (const form of forms) {
|
||||
for (const section of form?.sections ?? []) {
|
||||
for (const ff of section.fields) labels.set(ff.name, ff.label);
|
||||
}
|
||||
}
|
||||
return labels;
|
||||
}
|
||||
|
||||
export function referencedObjectNames(type: FieldType): string[] {
|
||||
switch (type.type) {
|
||||
case 'objectId':
|
||||
case 'object':
|
||||
case 'objectList':
|
||||
return [type.objectName];
|
||||
case 'set':
|
||||
return type.class.type === 'objectId' ? [type.class.objectName] : [];
|
||||
case 'map': {
|
||||
const names: string[] = [];
|
||||
if (type.keyClass.type === 'objectId') names.push(type.keyClass.objectName);
|
||||
if (type.valueClass.type === 'object') names.push(type.valueClass.objectName);
|
||||
return names;
|
||||
}
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function filterAccessibleFields(
|
||||
fields: Fields | null,
|
||||
schema: Schema,
|
||||
canGet: (permissionPrefix: string) => boolean,
|
||||
): Fields | null {
|
||||
if (!fields) return null;
|
||||
const properties: Record<string, Field> = {};
|
||||
for (const [name, field] of Object.entries(fields.properties)) {
|
||||
const blocked = referencedObjectNames(field.type).some((objectName) => {
|
||||
const resolved = resolveObject(schema, objectName);
|
||||
return resolved ? !canGet(resolved.permissionPrefix) : false;
|
||||
});
|
||||
if (!blocked) properties[name] = field;
|
||||
}
|
||||
return { ...fields, properties };
|
||||
}
|
||||
|
||||
export const VARIANT_FIELD = '@type';
|
||||
|
||||
export interface RenderableField {
|
||||
formField: FormField;
|
||||
field: Field | null;
|
||||
}
|
||||
|
||||
export interface RenderableSection {
|
||||
key: string;
|
||||
title?: string;
|
||||
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;
|
||||
if (!form) {
|
||||
if (!fields) return [];
|
||||
const all = Object.entries(fields.properties)
|
||||
.filter(([name, field]) => !hidden.has(name) && visible(field))
|
||||
.map(([name, field]) => ({ formField: { name, label: name }, field }));
|
||||
return all.length > 0 ? [{ key: 'section-0', fields: all }] : [];
|
||||
}
|
||||
const sections: RenderableSection[] = [];
|
||||
form.sections.forEach((section, index) => {
|
||||
const rendered: RenderableField[] = [];
|
||||
for (const ff of section.fields) {
|
||||
if (ff.name === VARIANT_FIELD) {
|
||||
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 });
|
||||
}
|
||||
if (rendered.length > 0) sections.push({ key: `section-${index}`, title: section.title, fields: rendered });
|
||||
});
|
||||
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']);
|
||||
const add = (form: Form | null | undefined) => {
|
||||
for (const section of form?.sections ?? []) {
|
||||
for (const ff of section.fields) {
|
||||
if (ff.name && ff.name !== VARIANT_FIELD) names.add(ff.name);
|
||||
}
|
||||
}
|
||||
};
|
||||
if (resolvedSchema.type === 'multiple') {
|
||||
names.add(VARIANT_FIELD);
|
||||
add(schema.forms[viewName] ?? schema.forms[object.objectName]);
|
||||
for (const variant of resolvedSchema.variants) {
|
||||
if (variant.schemaName) add(schema.forms[variant.schemaName]);
|
||||
}
|
||||
} else {
|
||||
const form = resolveForm(schema, viewName, object.objectName, resolvedSchema.schemaName);
|
||||
if (form) add(form);
|
||||
else for (const name of Object.keys(resolvedSchema.fields.properties)) names.add(name);
|
||||
}
|
||||
return Array.from(names);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { changedKeys, valuesEqual, type FieldErrors, type FieldValues } from '@/components/forms/formLogic';
|
||||
|
||||
export interface CreatedResult {
|
||||
id: string;
|
||||
values: FieldValues;
|
||||
}
|
||||
|
||||
export interface FormState {
|
||||
data: FieldValues;
|
||||
original: FieldValues;
|
||||
variant: string;
|
||||
dirty: ReadonlySet<string>;
|
||||
fieldErrors: FieldErrors;
|
||||
generalError: string | null;
|
||||
created: CreatedResult | null;
|
||||
source: unknown;
|
||||
}
|
||||
|
||||
export type FormAction =
|
||||
| { type: 'load'; data: FieldValues; variant: string; source: unknown }
|
||||
| { type: 'setField'; name: string; value: unknown }
|
||||
| { type: 'setVariant'; variant: string; data: FieldValues }
|
||||
| { type: 'setErrors'; generalError: string | null; fieldErrors?: FieldErrors }
|
||||
| { type: 'commit' }
|
||||
| { type: 'created'; result: CreatedResult };
|
||||
|
||||
const NO_ERRORS: FieldErrors = {};
|
||||
const CLEAN: ReadonlySet<string> = new Set();
|
||||
|
||||
export function initialFormState(data: FieldValues = {}, variant = '', source: unknown = null): FormState {
|
||||
return {
|
||||
data,
|
||||
original: data,
|
||||
variant,
|
||||
dirty: CLEAN,
|
||||
fieldErrors: NO_ERRORS,
|
||||
generalError: null,
|
||||
created: null,
|
||||
source,
|
||||
};
|
||||
}
|
||||
|
||||
export function formReducer(state: FormState, action: FormAction): FormState {
|
||||
switch (action.type) {
|
||||
case 'load':
|
||||
return initialFormState(action.data, action.variant, action.source);
|
||||
case 'setField': {
|
||||
const data = { ...state.data, [action.name]: action.value };
|
||||
const isChanged = !valuesEqual(state.original[action.name], action.value);
|
||||
let dirty = state.dirty;
|
||||
if (isChanged !== dirty.has(action.name)) {
|
||||
const next = new Set(dirty);
|
||||
if (isChanged) next.add(action.name);
|
||||
else next.delete(action.name);
|
||||
dirty = next;
|
||||
}
|
||||
let fieldErrors = state.fieldErrors;
|
||||
if (action.name in fieldErrors) {
|
||||
fieldErrors = { ...fieldErrors };
|
||||
delete fieldErrors[action.name];
|
||||
}
|
||||
return { ...state, data, dirty, fieldErrors };
|
||||
}
|
||||
case 'setVariant':
|
||||
return {
|
||||
...state,
|
||||
variant: action.variant,
|
||||
data: action.data,
|
||||
dirty: changedKeys(state.original, action.data),
|
||||
fieldErrors: NO_ERRORS,
|
||||
};
|
||||
case 'setErrors':
|
||||
return { ...state, generalError: action.generalError, fieldErrors: action.fieldErrors ?? NO_ERRORS };
|
||||
case 'commit':
|
||||
return { ...state, original: state.data, dirty: CLEAN, created: null };
|
||||
case 'created':
|
||||
return { ...state, original: state.data, dirty: CLEAN, created: action.result };
|
||||
}
|
||||
}
|
||||
|
||||
export function isFormDirty(state: FormState): boolean {
|
||||
return state.dirty.size > 0;
|
||||
}
|
||||
@@ -0,0 +1,404 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useEffect, useReducer, type ComponentType } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useSchemaStore } from '@/stores/schemaStore';
|
||||
import { usePermissionCheckers } from '@/hooks/usePermissions';
|
||||
import { useResolvedView } from '@/hooks/useResolvedView';
|
||||
import { toast } from '@/hooks/use-toast';
|
||||
import {
|
||||
buildCreateDefaults,
|
||||
buildEmbeddedDefaults,
|
||||
deepMerge,
|
||||
getDisplayProperty,
|
||||
resolveForm,
|
||||
resolveVariantForm,
|
||||
type ResolvedView,
|
||||
} from '@/lib/schemaResolver';
|
||||
import { coerceLabel } from '@/lib/objectOptions';
|
||||
import { layoutViewFor } from '@/lib/layout';
|
||||
import { switchVariantValues } from '@/lib/embeddedSchema';
|
||||
import { errorMessage, friendlySetError, validationErrorMessage } from '@/lib/jmapErrors';
|
||||
import { logFormChange } from '@/lib/debug';
|
||||
import { useJmapObject } from '@/data/objects';
|
||||
import { useJmapSet } from '@/data/mutations';
|
||||
import {
|
||||
buildCreatePayload,
|
||||
buildSections,
|
||||
buildUpdatePatch,
|
||||
collectBlobUploads,
|
||||
collectFetchProperties,
|
||||
combineForms,
|
||||
filterAccessibleFields,
|
||||
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';
|
||||
|
||||
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;
|
||||
if (variant) data[VARIANT_FIELD] = variant;
|
||||
return data;
|
||||
}
|
||||
|
||||
function initialCreateVariant(view: ResolvedView): string | undefined {
|
||||
const { resolvedSchema, list } = view;
|
||||
if (resolvedSchema.type !== 'multiple') return undefined;
|
||||
const fromFilter = list?.filtersStatic?.[VARIANT_FIELD];
|
||||
return typeof fromFilter === 'string' ? fromFilter : (resolvedSchema.variants[0]?.name ?? '');
|
||||
}
|
||||
|
||||
function initialState(
|
||||
schema: Schema | null,
|
||||
view: ResolvedView | null,
|
||||
mode: FormMode,
|
||||
createValues: FieldValues | undefined,
|
||||
): FormState {
|
||||
if (mode !== 'create' || !schema || !view) return initialFormState();
|
||||
const variant = initialCreateVariant(view);
|
||||
return initialFormState(createDefaults(schema, view, variant, createValues), variant ?? '', view);
|
||||
}
|
||||
|
||||
function loadedVariant(view: ResolvedView, data: FieldValues): string {
|
||||
if (view.resolvedSchema.type !== 'multiple') return '';
|
||||
const type = data[VARIANT_FIELD];
|
||||
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 = {},
|
||||
) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const schema = useSchemaStore((s) => s.schema);
|
||||
const viewToSection = useSchemaStore((s) => s.viewToSection);
|
||||
const { canGet } = usePermissionCheckers();
|
||||
const resolved = useResolvedView(viewName);
|
||||
const mode: FormMode = objectId === null ? 'create' : 'edit';
|
||||
const isSingleton = resolved?.object.objectType.type === 'singleton';
|
||||
const objectName = resolved?.object.objectName;
|
||||
|
||||
const [state, dispatch] = useReducer(formReducer, null, () => initialState(schema, resolved, mode, createValues));
|
||||
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),
|
||||
variant: variant ?? '',
|
||||
source: resolved,
|
||||
});
|
||||
}
|
||||
|
||||
const objectQuery = useJmapObject(
|
||||
objectName,
|
||||
mode === 'create' ? null : isSingleton ? 'singleton' : objectId,
|
||||
schema && resolved ? collectFetchProperties(schema, resolved, viewName) : ['id'],
|
||||
{ staleTime: 0, refetchOnMount: 'always', accountId },
|
||||
);
|
||||
if (objectQuery.data && objectQuery.data !== state.source && !isDirty && resolved) {
|
||||
dispatch({
|
||||
type: 'load',
|
||||
data: { ...objectQuery.data },
|
||||
variant: loadedVariant(resolved, objectQuery.data),
|
||||
source: objectQuery.data,
|
||||
});
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
logFormChange(`${viewName}${objectId ? ` (${objectId})` : ' (new)'}`, state.data);
|
||||
}, [state.data, viewName, objectId]);
|
||||
|
||||
const setMutation = useJmapSet(objectName);
|
||||
const saving = setMutation.isPending;
|
||||
const guard = useUnsavedChangesGuard(isDirty && !saving);
|
||||
|
||||
const sch = resolved?.resolvedSchema ?? null;
|
||||
const variant = sch?.type === 'multiple' ? sch.variants.find((v) => v.name === state.variant) : undefined;
|
||||
const rawFields: Fields | null = !sch ? null : sch.type === 'single' ? sch.fields : (variant?.fields ?? null);
|
||||
const fields = schema ? filterAccessibleFields(rawFields, schema, canGet) : null;
|
||||
|
||||
let parentForm: Form | null = null;
|
||||
let variantForm: Form | null = null;
|
||||
if (schema && resolved && sch) {
|
||||
if (sch.type === 'single') {
|
||||
variantForm = resolveForm(schema, viewName, resolved.object.objectName, sch.schemaName);
|
||||
} else {
|
||||
parentForm = schema.forms[viewName] ?? schema.forms[resolved.object.objectName] ?? null;
|
||||
variantForm = variant
|
||||
? resolveVariantForm(schema, viewName, resolved.object.objectName, variant.schemaName)
|
||||
: null;
|
||||
}
|
||||
}
|
||||
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 loading = mode === 'edit' && objectQuery.fetchStatus !== 'idle' && !objectQuery.isFetchedAfterMount;
|
||||
const loadError =
|
||||
mode === 'create'
|
||||
? null
|
||||
: objectQuery.isError
|
||||
? errorMessage(objectQuery.error, t('form.failedToLoadData', 'Failed to load data.'))
|
||||
: objectQuery.isSuccess && !objectQuery.data
|
||||
? t('form.objectNotFound', 'Object not found.')
|
||||
: null;
|
||||
const loadFailed = mode === 'edit' && loadError !== null && !objectQuery.data;
|
||||
const retryLoad = () => void objectQuery.refetch();
|
||||
|
||||
const labelProperty = schema ? (resolved?.list?.labelProperty ?? getDisplayProperty(schema, viewName)) : undefined;
|
||||
const recordLabel = labelProperty ? coerceLabel(state.data[labelProperty], '') : '';
|
||||
|
||||
const listView = schema ? layoutViewFor(schema, viewToSection, viewName) : null;
|
||||
const listPath = listView ? `/${viewToSection[listView]}/${listView}` : '/';
|
||||
const leaveToList = () => {
|
||||
guard.allowNextNavigation();
|
||||
navigate(listPath);
|
||||
};
|
||||
|
||||
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, {
|
||||
general: friendlySetError(error),
|
||||
invalidValue: t('form.invalidValue', 'Invalid value.'),
|
||||
validation: validationErrorMessage,
|
||||
});
|
||||
dispatch({ type: 'setErrors', generalError: general, fieldErrors });
|
||||
};
|
||||
|
||||
const notConfirmed = () =>
|
||||
dispatch({ type: 'setErrors', generalError: t('form.notConfirmed', 'The server did not confirm the change.') });
|
||||
|
||||
const setField = (name: string, value: unknown) => dispatch({ type: 'setField', name, value });
|
||||
|
||||
const setVariant = (next: string) => {
|
||||
if (!schema || !resolved || resolved.resolvedSchema.type !== 'multiple') return;
|
||||
const { variants } = resolved.resolvedSchema;
|
||||
const defaults =
|
||||
mode === 'create'
|
||||
? createDefaults(schema, resolved, next, createValues)
|
||||
: buildEmbeddedDefaults(schema, resolved.object.objectName, {}, next);
|
||||
const data = switchVariantValues(
|
||||
variants.find((v) => v.name === state.variant)?.fields,
|
||||
variants.find((v) => v.name === next)?.fields,
|
||||
state.data,
|
||||
defaults,
|
||||
mode === 'edit' ? state.original : undefined,
|
||||
);
|
||||
dispatch({ type: 'setVariant', variant: next, data });
|
||||
};
|
||||
|
||||
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,
|
||||
)
|
||||
: {},
|
||||
);
|
||||
if (Object.keys(errors).length > 0) {
|
||||
dispatch({
|
||||
type: 'setErrors',
|
||||
generalError: t('form.correctErrorsBelow', 'Please correct the errors below.'),
|
||||
fieldErrors: errors,
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!isOtpAuthValid(state.data)) {
|
||||
dispatch({
|
||||
type: 'setErrors',
|
||||
generalError: t('form.otpCodeRequired', 'Enter your current authenticator code to authorise this change.'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
dispatch({ type: 'setErrors', generalError: null });
|
||||
|
||||
try {
|
||||
if (mode === 'create') {
|
||||
const { blobs, payload } = collectBlobUploads(
|
||||
buildCreatePayload(state.data, fields, {
|
||||
filtersStatic: resolved.list?.filtersStatic,
|
||||
variant: resolved.resolvedSchema.type === 'multiple' ? state.variant : undefined,
|
||||
}),
|
||||
fields,
|
||||
);
|
||||
const result = await setMutation.mutateAsync({ create: { [CREATE_ID]: payload }, blobs, accountId });
|
||||
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) {
|
||||
dispatch({ type: 'created', result: { id: String(created.id), values: extras } });
|
||||
} else {
|
||||
toast({ title: t('form.createdSuccess', 'Created successfully'), variant: 'success' });
|
||||
dispatch({ type: 'commit' });
|
||||
leaveToList();
|
||||
}
|
||||
} else if (result.notCreated?.[CREATE_ID]) {
|
||||
applySetError(result.notCreated[CREATE_ID]);
|
||||
} else {
|
||||
notConfirmed();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const patch = buildUpdatePatch(state.original, state.data, fields);
|
||||
if (Object.keys(patch).length === 0) {
|
||||
toast({ title: t('form.noChangesToSave', 'No changes to save'), variant: 'default' });
|
||||
return;
|
||||
}
|
||||
const { blobs, payload } = collectBlobUploads(patch, fields, state.original);
|
||||
const updateId = isSingleton ? 'singleton' : objectId!;
|
||||
const result = await setMutation.mutateAsync({ update: { [updateId]: payload }, blobs, accountId });
|
||||
if (result.updated && updateId in result.updated) {
|
||||
toast({ title: t('form.savedSuccess', 'Saved successfully'), variant: 'success' });
|
||||
dispatch({ type: 'commit' });
|
||||
if (!isSingleton) leaveToList();
|
||||
} else if (result.notUpdated?.[updateId]) {
|
||||
applySetError(result.notUpdated[updateId]);
|
||||
} else {
|
||||
notConfirmed();
|
||||
}
|
||||
} catch (err) {
|
||||
dispatch({ type: 'setErrors', generalError: errorMessage(err, t('form.failedToSave', 'Failed to save.')) });
|
||||
}
|
||||
};
|
||||
|
||||
const remove = async () => {
|
||||
if (!resolved || !objectId) return;
|
||||
dispatch({ type: 'setErrors', generalError: null });
|
||||
try {
|
||||
const result = await setMutation.mutateAsync({ destroy: [objectId], accountId });
|
||||
if (result.destroyed?.includes(objectId)) {
|
||||
const label = resolved.list?.singularName ?? resolved.object.objectType.description;
|
||||
toast({
|
||||
title: t('form.deletedSuccess', '{{name}} deleted successfully', {
|
||||
name: label.charAt(0).toUpperCase() + label.slice(1),
|
||||
}),
|
||||
variant: 'success',
|
||||
});
|
||||
dispatch({ type: 'commit' });
|
||||
leaveToList();
|
||||
} else if (result.notDestroyed?.[objectId]) {
|
||||
dispatch({ type: 'setErrors', generalError: friendlySetError(result.notDestroyed[objectId]) });
|
||||
} else {
|
||||
notConfirmed();
|
||||
}
|
||||
} catch (err) {
|
||||
dispatch({ type: 'setErrors', generalError: errorMessage(err, t('form.failedToDelete', 'Failed to delete.')) });
|
||||
}
|
||||
};
|
||||
|
||||
const continueAfterCreate = () => {
|
||||
dispatch({ type: 'commit' });
|
||||
leaveToList();
|
||||
};
|
||||
|
||||
return {
|
||||
schema,
|
||||
resolved,
|
||||
mode,
|
||||
isSingleton,
|
||||
state,
|
||||
isDirty,
|
||||
saving,
|
||||
loading,
|
||||
loadError,
|
||||
loadFailed,
|
||||
retryLoad,
|
||||
fields,
|
||||
parentForm,
|
||||
variantForm,
|
||||
form,
|
||||
sections,
|
||||
recordLabel,
|
||||
guard,
|
||||
setField,
|
||||
setVariant,
|
||||
save,
|
||||
remove,
|
||||
continueAfterCreate,
|
||||
};
|
||||
}
|
||||
|
||||
export type DynamicFormModel = ReturnType<typeof useDynamicForm>;
|
||||
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useBlocker, type Blocker } from 'react-router-dom';
|
||||
|
||||
export interface UnsavedChangesGuard {
|
||||
blocker: Blocker;
|
||||
allowNextNavigation: () => void;
|
||||
}
|
||||
|
||||
export function useUnsavedChangesGuard(when: boolean): UnsavedChangesGuard {
|
||||
const bypass = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!when) return;
|
||||
const handler = (e: BeforeUnloadEvent) => {
|
||||
e.preventDefault();
|
||||
};
|
||||
window.addEventListener('beforeunload', handler);
|
||||
return () => window.removeEventListener('beforeunload', handler);
|
||||
}, [when]);
|
||||
|
||||
const blocker = useBlocker(() => when && !bypass.current);
|
||||
|
||||
return {
|
||||
blocker,
|
||||
allowNextNavigation: () => {
|
||||
bypass.current = true;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
* 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 { Loader2 } from 'lucide-react';
|
||||
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>) {
|
||||
const { t } = useTranslation();
|
||||
const { recordLabel } = useFormContext();
|
||||
const [edited, setEdited] = useState<string | null>(null);
|
||||
if (edited !== null && value !== edited) {
|
||||
setEdited(null);
|
||||
}
|
||||
const isOwnEdit = edited !== null && value === edited;
|
||||
const blobId = !isOwnEdit && typeof value === 'string' && value.length > 0 ? value : null;
|
||||
const blob = useBlobText(blobId);
|
||||
|
||||
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" />
|
||||
{t('field.loadingContent', 'Loading content...')}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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">
|
||||
<p className="text-sm text-destructive" role="alert">
|
||||
{blob.isError
|
||||
? errorMessage(blob.error, t('field.blobLoadFailed', 'Failed to load content.'))
|
||||
: t('field.blobNotFound', 'The stored content could not be found.')}
|
||||
</p>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="shrink-0"
|
||||
onClick={() => void blob.refetch()}
|
||||
disabled={blob.isFetching}
|
||||
>
|
||||
{t('common.retry', 'Retry')}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const text = edited ?? blob.data ?? '';
|
||||
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
<BufferedTextarea
|
||||
{...control}
|
||||
value={text}
|
||||
onCommit={(text) => {
|
||||
setEdited(text);
|
||||
onChange(text);
|
||||
}}
|
||||
disabled={readOnly}
|
||||
rows={8}
|
||||
className="font-mono text-xs"
|
||||
/>
|
||||
{isOwnEdit && (
|
||||
<p className="text-xs font-medium text-warning">
|
||||
{t('field.contentModified', 'Content modified (will be saved as a new blob)')}
|
||||
</p>
|
||||
)}
|
||||
{type.format === 'sieve' && <SievepadButton scriptName={recordLabel} source={text} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
import type { FieldTypeBoolean } from '@/types/schema';
|
||||
|
||||
export function BooleanWidget({ value, onChange, readOnly, control }: WidgetProps<FieldTypeBoolean>) {
|
||||
return (
|
||||
<Switch
|
||||
{...control}
|
||||
checked={value === true}
|
||||
disabled={readOnly}
|
||||
onCheckedChange={(checked) => onChange(checked)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import type { InputHTMLAttributes, TextareaHTMLAttributes } from 'react';
|
||||
import { useBufferedValue } from '@/hooks/useBufferedValue';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import type { NumberFormat } from '@/types/schema';
|
||||
|
||||
interface BufferedInputProps extends Omit<InputHTMLAttributes<HTMLInputElement>, 'onChange' | 'value'> {
|
||||
value: string;
|
||||
onCommit: (v: string) => void;
|
||||
}
|
||||
|
||||
export function BufferedInput({ value, onCommit, onBlur, onKeyDown, ...rest }: BufferedInputProps) {
|
||||
const [local, setLocal] = useBufferedValue(value);
|
||||
|
||||
const commit = () => {
|
||||
if (local !== value) onCommit(local);
|
||||
};
|
||||
|
||||
return (
|
||||
<Input
|
||||
{...rest}
|
||||
value={local}
|
||||
onChange={(e) => setLocal(e.target.value)}
|
||||
onBlur={(e) => {
|
||||
commit();
|
||||
onBlur?.(e);
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') commit();
|
||||
onKeyDown?.(e);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
interface BufferedTextareaProps extends Omit<TextareaHTMLAttributes<HTMLTextAreaElement>, 'onChange' | 'value'> {
|
||||
variant?: 'field' | 'bare';
|
||||
value: string;
|
||||
onCommit: (v: string) => void;
|
||||
}
|
||||
|
||||
export function BufferedTextarea({ value, onCommit, onBlur, ...rest }: BufferedTextareaProps) {
|
||||
const [local, setLocal] = useBufferedValue(value);
|
||||
|
||||
return (
|
||||
<Textarea
|
||||
{...rest}
|
||||
value={local}
|
||||
onChange={(e) => setLocal(e.target.value)}
|
||||
onBlur={(e) => {
|
||||
if (local !== value) onCommit(local);
|
||||
onBlur?.(e);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
interface BufferedNumberInputProps extends Omit<
|
||||
InputHTMLAttributes<HTMLInputElement>,
|
||||
'onChange' | 'value' | 'type' | 'min' | 'max' | 'step'
|
||||
> {
|
||||
value: number | null;
|
||||
format: NumberFormat;
|
||||
min?: number;
|
||||
max?: number;
|
||||
nullable?: boolean;
|
||||
onCommit: (value: number | null | undefined) => void;
|
||||
}
|
||||
|
||||
export function BufferedNumberInput({
|
||||
value,
|
||||
format,
|
||||
min,
|
||||
max,
|
||||
nullable,
|
||||
onCommit,
|
||||
...rest
|
||||
}: BufferedNumberInputProps) {
|
||||
const [local, setLocal] = useBufferedValue(value, (v) => (v != null ? String(v) : ''));
|
||||
|
||||
const commit = () => {
|
||||
if (local === '') {
|
||||
const next = nullable ? null : undefined;
|
||||
if (next !== value) onCommit(next);
|
||||
return;
|
||||
}
|
||||
const n = format === 'float' ? parseFloat(local) : parseInt(local, 10);
|
||||
if (!Number.isNaN(n) && n !== value) onCommit(n);
|
||||
};
|
||||
|
||||
return (
|
||||
<Input
|
||||
{...rest}
|
||||
type="number"
|
||||
value={local}
|
||||
onChange={(e) => setLocal(e.target.value)}
|
||||
onBlur={commit}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') commit();
|
||||
}}
|
||||
step={format === 'float' ? 0.01 : 1}
|
||||
min={format === 'unsignedInteger' ? Math.max(min ?? 0, 0) : min}
|
||||
max={max}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
/*
|
||||
* 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 { useTranslation } from 'react-i18next';
|
||||
import { Calendar as CalendarIcon, Loader2, X } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { formatDateTime } from '@/lib/format';
|
||||
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 })));
|
||||
|
||||
export 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" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function parseDate(value: unknown): Date | null {
|
||||
if (typeof value !== 'string' || !value) return null;
|
||||
const d = new Date(value);
|
||||
return Number.isNaN(d.getTime()) ? null : d;
|
||||
}
|
||||
|
||||
export function DateTimeWidget({ type, value, onChange, readOnly, control }: WidgetProps<FieldTypeUtcDateTime>) {
|
||||
const { t } = useTranslation();
|
||||
const selected = parseDate(value);
|
||||
const localTime = (selected ?? new Date()).toTimeString().slice(0, 5);
|
||||
|
||||
const commit = (day: Date, time: string) => {
|
||||
const [hours, minutes] = time.split(':').map(Number);
|
||||
const next = new Date(day);
|
||||
next.setHours(hours || 0, minutes || 0, 0, 0);
|
||||
onChange(next.toISOString());
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
{...control}
|
||||
type="button"
|
||||
variant="field"
|
||||
disabled={readOnly}
|
||||
className={cn('flex-1 justify-start px-3 text-left', !selected && 'text-dim')}
|
||||
>
|
||||
<CalendarIcon className="text-dim" aria-hidden="true" />
|
||||
{selected ? formatDateTime(selected) : 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 ?? undefined}
|
||||
defaultMonth={selected ?? undefined}
|
||||
autoFocus
|
||||
onSelect={(day) => {
|
||||
if (day) commit(day, localTime);
|
||||
}}
|
||||
/>
|
||||
</Suspense>
|
||||
<div className="border-t border-border bg-muted/60 p-3">
|
||||
<Input
|
||||
type="time"
|
||||
value={localTime}
|
||||
disabled={!selected}
|
||||
onChange={(e) => {
|
||||
if (selected && e.target.value) commit(selected, e.target.value);
|
||||
}}
|
||||
aria-label={t('field.time', 'Time')}
|
||||
/>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
{type.nullable && selected && !readOnly && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-9 w-9 shrink-0"
|
||||
onClick={() => onChange(null)}
|
||||
aria-label={t('common.clear', 'Clear')}
|
||||
>
|
||||
<X aria-hidden="true" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
/*
|
||||
* 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 { FieldRow } from '@/components/forms/FieldRow';
|
||||
import { VariantSelect } from '@/components/forms/VariantSelect';
|
||||
import { EnclosingSchemaContext, PanelContext, useFormContext, useInPanel } from '@/components/forms/formContext';
|
||||
import { buildEmbeddedDefaults } from '@/lib/schemaResolver';
|
||||
import { embeddedEntries, isRecord, resolveEmbedded, switchVariantValues } from '@/lib/embeddedSchema';
|
||||
import type { ControlProps, WidgetProps } from '@/components/forms/widgets/types';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { FieldTypeObject } from '@/types/schema';
|
||||
|
||||
interface EmbeddedObjectEditorProps {
|
||||
objectName: string;
|
||||
control?: ControlProps;
|
||||
value: unknown;
|
||||
onChange: (value: unknown) => void;
|
||||
readOnly: boolean;
|
||||
bare?: boolean;
|
||||
}
|
||||
|
||||
export function EmbeddedObjectEditor({
|
||||
objectName,
|
||||
control,
|
||||
value,
|
||||
onChange,
|
||||
readOnly,
|
||||
bare = false,
|
||||
}: EmbeddedObjectEditorProps) {
|
||||
const { t } = useTranslation();
|
||||
const { schema, mode, baseline } = useFormContext();
|
||||
const inPanel = useInPanel();
|
||||
const [initial, setInitial] = useState({ baseline, value });
|
||||
if (initial.baseline !== baseline) setInitial({ baseline, value });
|
||||
const resolved = resolveEmbedded(schema, objectName, value);
|
||||
|
||||
if (!resolved) {
|
||||
return (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('field.unknownObjectType', 'Unknown object type: {{name}}', { name: objectName })}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
const obj = isRecord(value) ? value : {};
|
||||
const changeVariant = (next: string) => {
|
||||
const defaults = buildEmbeddedDefaults(schema, objectName, {}, next);
|
||||
const target = resolveEmbedded(schema, objectName, defaults);
|
||||
const original = mode === 'edit' ? initial.value : undefined;
|
||||
onChange(switchVariantValues(resolved.fields, target?.fields, value, defaults, original));
|
||||
};
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
export function EmbeddedObjectWidget({ type, value, onChange, readOnly, control }: WidgetProps<FieldTypeObject>) {
|
||||
return (
|
||||
<EmbeddedObjectEditor
|
||||
objectName={type.objectName}
|
||||
control={control}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
readOnly={readOnly}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
/*
|
||||
* 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 { Search } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Combobox, type ComboboxOption } from '@/components/ui/combobox';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { HelpTooltip } from '@/components/common/HelpTooltip';
|
||||
import { usePermissionCheckers } from '@/hooks/usePermissions';
|
||||
import { getEnum } from '@/lib/schemaResolver';
|
||||
import { useFormContext } from '@/components/forms/formContext';
|
||||
import { RemovablePill } from '@/components/forms/widgets/RemovablePill';
|
||||
import type { ControlProps, WidgetProps } from '@/components/forms/widgets/types';
|
||||
import type { EnumVariant, FieldTypeEnum } from '@/types/schema';
|
||||
|
||||
function ColorDot({ color, size = 'h-2.5 w-2.5' }: { color?: string; size?: string }) {
|
||||
if (!color) return null;
|
||||
return (
|
||||
<span
|
||||
className={`inline-block shrink-0 rounded-full ${size}`}
|
||||
style={{ backgroundColor: color }}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function useEnumVariants(enumName: string): readonly EnumVariant[] {
|
||||
const { schema } = useFormContext();
|
||||
const { hasPermission } = usePermissionCheckers();
|
||||
const variants = getEnum(schema, enumName);
|
||||
return enumName === 'Permission' ? variants.filter((v) => hasPermission(v.name)) : variants;
|
||||
}
|
||||
|
||||
export function EnumWidget({ type, value, onChange, readOnly, control }: WidgetProps<FieldTypeEnum>) {
|
||||
const { t } = useTranslation();
|
||||
const variants = useEnumVariants(type.enumName);
|
||||
const options: ComboboxOption[] = variants.map((v) => ({
|
||||
value: v.name,
|
||||
label: v.label,
|
||||
description: v.explanation || undefined,
|
||||
keywords: [v.name],
|
||||
marker: v.color ? <ColorDot color={v.color} /> : undefined,
|
||||
}));
|
||||
|
||||
return (
|
||||
<Combobox
|
||||
{...control}
|
||||
options={options}
|
||||
value={typeof value === 'string' ? value : ''}
|
||||
onValueChange={(v) => onChange(v === '' ? null : v)}
|
||||
placeholder={t('field.selectEllipsis', 'Select...')}
|
||||
searchPlaceholder={t('common.searchPlaceholder', 'Search...')}
|
||||
emptyText={t('field.noMatches', 'No matches')}
|
||||
nullLabel={t('field.none', 'None')}
|
||||
nullable={type.nullable}
|
||||
disabled={readOnly}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
interface EnumMultiSelectProps {
|
||||
enumName: string;
|
||||
items: string[];
|
||||
onChange: (items: string[]) => void;
|
||||
readOnly: boolean;
|
||||
minItems?: number;
|
||||
control: ControlProps;
|
||||
}
|
||||
|
||||
const SEARCHABLE_THRESHOLD = 10;
|
||||
const GRID_THRESHOLD = 3;
|
||||
|
||||
export function EnumMultiSelect({ enumName, items, onChange, readOnly, minItems, control }: EnumMultiSelectProps) {
|
||||
const { t } = useTranslation();
|
||||
const variants = useEnumVariants(enumName);
|
||||
const baseId = control.id ?? `enum-${enumName}`;
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [open, setOpen] = useState(false);
|
||||
const atMinimum = minItems != null && items.length <= minItems;
|
||||
|
||||
const toggle = (name: string) => {
|
||||
if (items.includes(name)) {
|
||||
if (atMinimum) return;
|
||||
onChange(items.filter((i) => i !== name));
|
||||
} else {
|
||||
onChange([...items, name]);
|
||||
}
|
||||
};
|
||||
|
||||
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">
|
||||
<Checkbox
|
||||
id={id}
|
||||
checked={items.includes(v.name)}
|
||||
onCheckedChange={() => toggle(v.name)}
|
||||
disabled={readOnly || (items.includes(v.name) && atMinimum)}
|
||||
/>
|
||||
<Label htmlFor={id} className="flex flex-1 cursor-pointer items-center gap-2 text-sm font-normal">
|
||||
<ColorDot color={v.color} />
|
||||
{v.label}
|
||||
</Label>
|
||||
{v.explanation && <HelpTooltip content={v.explanation} label={v.label} />}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
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'
|
||||
}
|
||||
>
|
||||
{variants.map((v) => checkboxItem(v, baseId))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const query = searchQuery.toLowerCase();
|
||||
const filtered = query
|
||||
? variants.filter((v) => v.label.toLowerCase().includes(query) || v.name.toLowerCase().includes(query))
|
||||
: variants;
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{items.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{items.map((name) => {
|
||||
const variant = variants.find((v) => v.name === name);
|
||||
const label = variant?.label ?? name;
|
||||
return (
|
||||
<RemovablePill
|
||||
key={name}
|
||||
label={label}
|
||||
onRemove={readOnly ? undefined : () => toggle(name)}
|
||||
removeDisabled={atMinimum}
|
||||
>
|
||||
<ColorDot color={variant?.color} size="h-2 w-2" />
|
||||
{label}
|
||||
</RemovablePill>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button {...control} type="button" variant="secondary" size="sm" disabled={readOnly}>
|
||||
<Search aria-hidden="true" />
|
||||
{t('field.selectOptions', 'Select options...')}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-72 overflow-hidden p-0" align="start">
|
||||
<div className="p-2 pb-1">
|
||||
<Input
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
placeholder={t('common.searchPlaceholder', 'Search...')}
|
||||
aria-label={t('common.search', 'Search')}
|
||||
variant="pill"
|
||||
className="h-8 px-3.5"
|
||||
/>
|
||||
</div>
|
||||
<div className="max-h-60 space-y-0.5 overflow-y-auto p-1.5">
|
||||
{filtered.length === 0 && (
|
||||
<p className="py-2 text-center text-sm text-muted-foreground">{t('field.noMatches', 'No matches')}</p>
|
||||
)}
|
||||
{filtered.map((v) => checkboxItem(v, `${baseId}-dd`))}
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { ExpressionEditor, type ExpressionValue } from '@/components/expression/ExpressionEditor';
|
||||
import { isRecord } from '@/lib/embeddedSchema';
|
||||
import type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
import type { FieldTypeObject } from '@/types/schema';
|
||||
|
||||
function toExpression(value: unknown): ExpressionValue {
|
||||
const obj = isRecord(value) ? value : {};
|
||||
return {
|
||||
match: isRecord(obj.match) ? (obj.match as ExpressionValue['match']) : {},
|
||||
else: typeof obj.else === 'string' ? obj.else : '',
|
||||
};
|
||||
}
|
||||
|
||||
export function ExpressionWidget({ formField, value, onChange, readOnly, control }: WidgetProps<FieldTypeObject>) {
|
||||
return (
|
||||
<ExpressionEditor
|
||||
value={toExpression(value)}
|
||||
onChange={onChange}
|
||||
readOnly={readOnly}
|
||||
label={formField.label}
|
||||
control={control}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { resolveWidget } from '@/extensions/widgets';
|
||||
import type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
|
||||
export function FieldControl(props: WidgetProps) {
|
||||
const { Edit } = resolveWidget(props.type);
|
||||
return <Edit {...props} />;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* 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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
* 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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* 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>;
|
||||
}
|
||||
@@ -0,0 +1,468 @@
|
||||
/*
|
||||
* 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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useId, useState, type KeyboardEvent } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ChevronRight, Loader2, Plus, Trash2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
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 { 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 { 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';
|
||||
|
||||
function defaultMapValue(valueClass: MapValueType, newObject: (objectName: string) => unknown): unknown {
|
||||
switch (valueClass.type) {
|
||||
case 'number':
|
||||
return 0;
|
||||
case 'object':
|
||||
return newObject(valueClass.objectName);
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
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('');
|
||||
const [expanded, setExpanded] = useState<ReadonlySet<string>>(() => new Set());
|
||||
const canAdd = type.maxItems == null || entries.length < type.maxItems;
|
||||
const canRemove = type.minItems == null || entries.length > type.minItems;
|
||||
const trimmedKey = newKey.trim();
|
||||
const valueField: Field = { description: '', type: type.valueClass as FieldType, update: 'mutable' };
|
||||
|
||||
const setOpen = (key: string, open: boolean) =>
|
||||
setExpanded((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (open) next.add(key);
|
||||
else next.delete(key);
|
||||
return next;
|
||||
});
|
||||
|
||||
const addEntry = () => {
|
||||
if (!trimmedKey || Object.hasOwn(map, trimmedKey) || !canAdd) return;
|
||||
onChange({
|
||||
...map,
|
||||
[trimmedKey]: defaultMapValue(type.valueClass, (name) => buildNewObjectValue(schema, name)),
|
||||
});
|
||||
setOpen(trimmedKey, true);
|
||||
setNewKey('');
|
||||
};
|
||||
|
||||
const removeEntry = (key: string) => {
|
||||
const copy = { ...map };
|
||||
delete copy[key];
|
||||
onChange(copy);
|
||||
setOpen(key, false);
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
addEntry();
|
||||
}
|
||||
};
|
||||
|
||||
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">
|
||||
<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"
|
||||
>
|
||||
<ChevronRight
|
||||
className={cn(
|
||||
'h-4 w-4 shrink-0 text-dim transition-transform duration-200',
|
||||
expanded.has(key) && 'rotate-90',
|
||||
)}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span className="truncate">
|
||||
<MapKeyLabel keyClass={type.keyClass} keyValue={key} />
|
||||
</span>
|
||||
</button>
|
||||
{removeButton(key)}
|
||||
</div>
|
||||
{expanded.has(key) && (
|
||||
<div id={`${baseId}-${key}`} className="border-t border-border px-4">
|
||||
{valueControl(key, val)}
|
||||
</div>
|
||||
)}
|
||||
</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>
|
||||
</div>
|
||||
)}
|
||||
{readOnly && entries.length === 0 && (
|
||||
<p className="px-2.5 py-2 text-sm text-muted-foreground">{t('field.none', 'None')}</p>
|
||||
)}
|
||||
</div>
|
||||
</PanelContext>
|
||||
);
|
||||
}
|
||||
|
||||
function MapKeyLabel({ keyClass, keyValue }: { keyClass: ScalarType; keyValue: string }) {
|
||||
const { schema } = useFormContext();
|
||||
if (keyClass.type === 'enum') return <>{getEnumVariant(schema, keyClass.enumName, keyValue)?.label ?? keyValue}</>;
|
||||
if (keyClass.type === 'objectId') return <ObjectIdKeyLabel objectName={keyClass.objectName} id={keyValue} />;
|
||||
return <>{keyValue}</>;
|
||||
}
|
||||
|
||||
function ObjectIdKeyLabel({ objectName, id }: { objectName: string; id: string }) {
|
||||
const { schema } = useFormContext();
|
||||
const { label, loading } = useDisplayName(objectName, id, schema);
|
||||
if (loading && !label) return <Loader2 className="h-3 w-3 animate-spin text-muted-foreground" aria-hidden="true" />;
|
||||
return <>{label ?? id}</>;
|
||||
}
|
||||
|
||||
interface MapKeyInputProps {
|
||||
keyClass: ScalarType;
|
||||
label: string;
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
onKeyDown: (e: KeyboardEvent<HTMLInputElement>) => void;
|
||||
existingKeys: Record<string, unknown>;
|
||||
}
|
||||
|
||||
function MapKeyInput({ keyClass, label, value, onChange, onKeyDown, existingKeys }: MapKeyInputProps) {
|
||||
const { t } = useTranslation();
|
||||
const { schema } = useFormContext();
|
||||
switch (keyClass.type) {
|
||||
case 'enum': {
|
||||
const variants = getEnum(schema, keyClass.enumName).filter((v) => !Object.hasOwn(existingKeys, v.name));
|
||||
return (
|
||||
<Select value={value} onValueChange={onChange}>
|
||||
<SelectTrigger className="flex-1" aria-label={label}>
|
||||
<SelectValue placeholder={t('field.selectKey', 'Select key...')} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{variants.map((v) => (
|
||||
<SelectItem key={v.name} value={v.name}>
|
||||
{v.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
);
|
||||
}
|
||||
case 'objectId':
|
||||
return (
|
||||
<MapKeyObjectIdInput
|
||||
objectName={keyClass.objectName}
|
||||
label={label}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
existingKeys={existingKeys}
|
||||
/>
|
||||
);
|
||||
default:
|
||||
return (
|
||||
<Input
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
onKeyDown={onKeyDown}
|
||||
aria-label={label}
|
||||
placeholder={
|
||||
(keyClass.type === 'string' ? formatPlaceholder(keyClass.format) : undefined) ?? t('field.key', 'Key...')
|
||||
}
|
||||
className="flex-1"
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function MapKeyObjectIdInput({
|
||||
objectName,
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
existingKeys,
|
||||
}: {
|
||||
objectName: string;
|
||||
label: string;
|
||||
value: string;
|
||||
onChange: (v: string) => void;
|
||||
existingKeys: Record<string, unknown>;
|
||||
}) {
|
||||
const { schema, tenantId } = useFormContext();
|
||||
const list = useObjectOptions(objectName, schema, tenantId);
|
||||
const noPermissionMessage = useNoPermissionMessage(schema, objectName);
|
||||
return (
|
||||
<div className="flex flex-1 items-center gap-2">
|
||||
{value && (
|
||||
<span className="text-sm">
|
||||
<ObjectIdKeyLabel objectName={objectName} id={value} />
|
||||
</span>
|
||||
)}
|
||||
<ObjectSearchPopover
|
||||
label={label}
|
||||
options={list.options.filter((o) => !Object.hasOwn(existingKeys, o.id))}
|
||||
loading={list.loading}
|
||||
error={list.error}
|
||||
ensureLoaded={list.ensureLoaded}
|
||||
onSelect={onChange}
|
||||
disabledMessage={noPermissionMessage}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
/*
|
||||
* 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 { X } from 'lucide-react';
|
||||
import { useResetOnChange } from '@/hooks/useBufferedValue';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { bytesToHuman, humanToBytes, msToHuman, humanToMs, SIZE_UNITS, DURATION_UNITS } from '@/lib/durationFormat';
|
||||
import { BufferedNumberInput } from '@/components/forms/widgets/BufferedInputs';
|
||||
import { useDurationUnitLabel } from '@/components/forms/widgets/useDurationUnitLabel';
|
||||
import type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
import type { FieldTypeNumber } from '@/types/schema';
|
||||
|
||||
export function NumberWidget({ type, value, onChange, readOnly, control }: WidgetProps<FieldTypeNumber>) {
|
||||
return (
|
||||
<BufferedNumberInput
|
||||
{...control}
|
||||
value={typeof value === 'number' ? value : null}
|
||||
format={type.format}
|
||||
min={type.min}
|
||||
max={type.max}
|
||||
nullable={type.nullable}
|
||||
disabled={readOnly}
|
||||
onCommit={(v) => onChange(v)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
interface UnitConversion {
|
||||
units: readonly string[];
|
||||
toHuman: (raw: number) => { value: number; unit: string };
|
||||
fromHuman: (value: number, unit: string) => number;
|
||||
triggerClass: string;
|
||||
}
|
||||
|
||||
const SIZE_CONVERSION: UnitConversion = {
|
||||
units: SIZE_UNITS,
|
||||
toHuman: bytesToHuman,
|
||||
fromHuman: humanToBytes,
|
||||
triggerClass: 'w-24',
|
||||
};
|
||||
|
||||
const DURATION_CONVERSION: UnitConversion = {
|
||||
units: DURATION_UNITS,
|
||||
toHuman: msToHuman,
|
||||
fromHuman: humanToMs,
|
||||
triggerClass: 'w-32',
|
||||
};
|
||||
|
||||
export function SizeWidget(props: WidgetProps<FieldTypeNumber>) {
|
||||
return <UnitNumberWidget {...props} conversion={SIZE_CONVERSION} />;
|
||||
}
|
||||
|
||||
export function DurationWidget(props: WidgetProps<FieldTypeNumber>) {
|
||||
return <UnitNumberWidget {...props} conversion={DURATION_CONVERSION} />;
|
||||
}
|
||||
|
||||
function UnitNumberWidget({
|
||||
type,
|
||||
value,
|
||||
onChange,
|
||||
readOnly,
|
||||
control,
|
||||
conversion,
|
||||
}: WidgetProps<FieldTypeNumber> & { conversion: UnitConversion }) {
|
||||
const { t } = useTranslation();
|
||||
const durationLabel = useDurationUnitLabel();
|
||||
const isDuration = conversion === DURATION_CONVERSION;
|
||||
const unitLabel = (u: string) => (isDuration ? durationLabel(u) : u);
|
||||
const isNull = value == null;
|
||||
const initial = conversion.toHuman(typeof value === 'number' ? value : 0);
|
||||
const [unit, setUnit] = useState(initial.unit);
|
||||
const [localStr, setLocalStr] = useState<string>(isNull ? '' : String(initial.value));
|
||||
|
||||
useResetOnChange(value, () => {
|
||||
const h = conversion.toHuman(typeof value === 'number' ? value : 0);
|
||||
setUnit(h.unit);
|
||||
setLocalStr(value == null ? '' : String(h.value));
|
||||
});
|
||||
|
||||
const commit = () => {
|
||||
if (localStr === '') {
|
||||
onChange(type.nullable ? null : 0);
|
||||
return;
|
||||
}
|
||||
const n = parseFloat(localStr);
|
||||
if (Number.isNaN(n)) return;
|
||||
const next = conversion.fromHuman(n, unit);
|
||||
if (next !== value) onChange(next);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
{...control}
|
||||
type="number"
|
||||
value={localStr}
|
||||
placeholder={type.nullable ? t('field.notSet', 'Not set') : '0'}
|
||||
onChange={(e) => setLocalStr(e.target.value)}
|
||||
onBlur={commit}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') commit();
|
||||
}}
|
||||
disabled={readOnly}
|
||||
min={0}
|
||||
step={1}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Select
|
||||
value={unit}
|
||||
disabled={readOnly}
|
||||
onValueChange={(u) => {
|
||||
setUnit(u);
|
||||
if (localStr !== '') {
|
||||
const n = parseFloat(localStr);
|
||||
if (!Number.isNaN(n)) onChange(conversion.fromHuman(n, u));
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className={conversion.triggerClass} aria-label={t('field.unit', 'Unit')}>
|
||||
<SelectValue>{unitLabel(unit)}</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{conversion.units.map((u) => (
|
||||
<SelectItem key={u} value={u}>
|
||||
{unitLabel(u)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{type.nullable && !isNull && !readOnly && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-9 w-9 shrink-0"
|
||||
onClick={() => onChange(null)}
|
||||
aria-label={t('common.clear', 'Clear')}
|
||||
>
|
||||
<X aria-hidden="true" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
/*
|
||||
* 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 { Loader2 } from 'lucide-react';
|
||||
import { ObjectFieldFrame, ObjectSearchPopover } from '@/components/common/ObjectSearchPopover';
|
||||
import { useNoPermissionMessage } from '@/lib/objectOptions';
|
||||
import { useObjectOptions, useDisplayName, type ObjectOption } from '@/data/objectOptions';
|
||||
import { useFormContext } from '@/components/forms/formContext';
|
||||
import { RemovablePill } from '@/components/forms/widgets/RemovablePill';
|
||||
import type { ControlProps, WidgetProps } from '@/components/forms/widgets/types';
|
||||
import type { FieldTypeObjectId } from '@/types/schema';
|
||||
|
||||
function ObjectIdPill({
|
||||
objectName,
|
||||
id,
|
||||
options,
|
||||
onRemove,
|
||||
removeDisabled,
|
||||
}: {
|
||||
objectName: string;
|
||||
id: string;
|
||||
options: ObjectOption[];
|
||||
onRemove?: () => void;
|
||||
removeDisabled?: boolean;
|
||||
}) {
|
||||
const { schema } = useFormContext();
|
||||
const fromList = options.find((o) => o.id === id)?.label;
|
||||
const { label, loading } = useDisplayName(objectName, fromList ? null : id, schema);
|
||||
const display = fromList ?? label ?? id;
|
||||
return (
|
||||
<RemovablePill label={display} onRemove={onRemove} removeDisabled={removeDisabled}>
|
||||
{loading ? <Loader2 className="h-3 w-3 animate-spin" aria-hidden="true" /> : display}
|
||||
</RemovablePill>
|
||||
);
|
||||
}
|
||||
|
||||
export function ObjectIdWidget({
|
||||
type,
|
||||
formField,
|
||||
value,
|
||||
onChange,
|
||||
readOnly,
|
||||
control,
|
||||
}: WidgetProps<FieldTypeObjectId>) {
|
||||
const { t } = useTranslation();
|
||||
const { schema, tenantId } = useFormContext();
|
||||
const id = typeof value === 'string' ? value : '';
|
||||
const list = useObjectOptions(type.objectName, schema, tenantId);
|
||||
const noPermissionMessage = useNoPermissionMessage(schema, type.objectName);
|
||||
|
||||
const pill = id ? (
|
||||
<ObjectIdPill
|
||||
objectName={type.objectName}
|
||||
id={id}
|
||||
options={list.options}
|
||||
onRemove={!readOnly && type.nullable ? () => onChange(null) : undefined}
|
||||
/>
|
||||
) : null;
|
||||
|
||||
if (readOnly) {
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{pill ?? <span className="text-sm text-dim">{t('field.none', 'None')}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<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>
|
||||
);
|
||||
}
|
||||
|
||||
interface ObjectIdMultiSelectProps {
|
||||
objectName: string;
|
||||
label: string;
|
||||
items: string[];
|
||||
onChange: (items: string[]) => void;
|
||||
readOnly: boolean;
|
||||
minItems?: number;
|
||||
control: ControlProps;
|
||||
}
|
||||
|
||||
export function ObjectIdMultiSelect({
|
||||
objectName,
|
||||
label,
|
||||
items,
|
||||
onChange,
|
||||
readOnly,
|
||||
minItems,
|
||||
control,
|
||||
}: ObjectIdMultiSelectProps) {
|
||||
const { t } = useTranslation();
|
||||
const { schema, tenantId } = useFormContext();
|
||||
const list = useObjectOptions(objectName, schema, tenantId);
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* 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 { Button } from '@/components/ui/button';
|
||||
import { FieldScopeProvider } from '@/components/forms/FormProvider';
|
||||
import { PanelContext, useFormContext, useInPanel } from '@/components/forms/formContext';
|
||||
import { FieldControl } from '@/components/forms/widgets/FieldControl';
|
||||
import { EmbeddedObjectEditor } from '@/components/forms/widgets/EmbeddedObjectWidget';
|
||||
import { widgetKey } from '@/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 type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
import type { Field, FieldTypeObject, FieldTypeObjectList } from '@/types/schema';
|
||||
|
||||
export function ObjectListWidget({
|
||||
type,
|
||||
field,
|
||||
formField,
|
||||
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) });
|
||||
};
|
||||
|
||||
const removeItem = (key: string) => {
|
||||
const copy = { ...items };
|
||||
delete copy[key];
|
||||
onChange(copy);
|
||||
if (collapsed.has(key)) toggle(key);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{entries.map(([key, item], position) => {
|
||||
const itemLabel = t('field.itemN', '{{label}} {{n}}', { label: formField.label, n: position + 1 });
|
||||
const summary = embeddedSummary(schema, type.objectName, item);
|
||||
const open = !!control['aria-invalid'] || !collapsed.has(key);
|
||||
const bodyId = `${baseId}-${key}`;
|
||||
return (
|
||||
<div
|
||||
key={key}
|
||||
data-slot="object-list-item"
|
||||
className={cn('overflow-hidden rounded-xl', inPanel ? 'bg-card shadow-tile' : 'bg-muted')}
|
||||
>
|
||||
<div className="flex items-center gap-1 py-1.5 pl-1.5 pr-1.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggle(key)}
|
||||
aria-expanded={open}
|
||||
aria-controls={bodyId}
|
||||
className="flex min-w-0 flex-1 items-center gap-2.5 rounded-lg px-1.5 py-1 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
<ChevronRight
|
||||
className={cn('h-4 w-4 shrink-0 text-dim transition-transform duration-200', open && 'rotate-90')}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span className="flex min-w-0 flex-col">
|
||||
<span className="truncate text-[13.5px] font-semibold">{summary.variantLabel ?? itemLabel}</span>
|
||||
{summary.summary && (
|
||||
<span className="truncate text-[12.5px] text-muted-foreground">
|
||||
{summary.summary.type ? (
|
||||
<FieldValue
|
||||
schema={schema}
|
||||
type={summary.summary.type}
|
||||
value={summary.summary.value}
|
||||
variant="compact"
|
||||
/>
|
||||
) : (
|
||||
String(summary.summary.value)
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
{!readOnly && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost-danger"
|
||||
size="icon-sm"
|
||||
className="shrink-0"
|
||||
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" />
|
||||
</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>
|
||||
);
|
||||
})}
|
||||
{!readOnly && canAdd && (
|
||||
<Button type="button" variant="secondary" size="sm" onClick={addItem}>
|
||||
<Plus className="h-4 w-4" aria-hidden="true" />
|
||||
{t('field.addItem', 'Add item')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+38
-51
@@ -4,29 +4,25 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useEffect, useId, useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import * as OTPAuth from 'otpauth';
|
||||
import QRCode from 'qrcode';
|
||||
import { Check, Copy, Loader2, ShieldCheck, ShieldOff } from 'lucide-react';
|
||||
import { Loader2, ShieldCheck, ShieldOff } from 'lucide-react';
|
||||
import { CopyButton } from '@/components/common/CopyButton';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { toast } from '@/hooks/use-toast';
|
||||
import { SECRET_MASK } from '@/lib/jmapUtils';
|
||||
import type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
import type { FieldTypeObject } from '@/types/schema';
|
||||
|
||||
interface OtpAuthValue {
|
||||
otpUrl?: string | null;
|
||||
otpCode?: string | null;
|
||||
}
|
||||
|
||||
interface OtpAuthFieldProps {
|
||||
value: unknown;
|
||||
onChange: (value: unknown) => void;
|
||||
readOnly: boolean;
|
||||
}
|
||||
|
||||
const STALWART_IMAGE_URL = 'https://stalw.art/img/favicon-32x32.png';
|
||||
|
||||
function buildOtpAuthUrl(totp: OTPAuth.TOTP): string {
|
||||
@@ -47,8 +43,9 @@ function generateTotp(): { totp: OTPAuth.TOTP; url: string } {
|
||||
return { totp, url: buildOtpAuthUrl(totp) };
|
||||
}
|
||||
|
||||
export function OtpAuthField({ value, onChange, readOnly }: OtpAuthFieldProps) {
|
||||
export function OtpAuthField({ value, onChange, readOnly }: WidgetProps<FieldTypeObject>) {
|
||||
const { t } = useTranslation();
|
||||
const codeId = useId();
|
||||
const objValue = (value as OtpAuthValue | null | undefined) ?? {};
|
||||
const isConfigured = objValue.otpUrl != null && objValue.otpUrl !== '';
|
||||
|
||||
@@ -57,28 +54,12 @@ export function OtpAuthField({ value, onChange, readOnly }: OtpAuthFieldProps) {
|
||||
const [qrDataUrl, setQrDataUrl] = useState<string | null>(null);
|
||||
const [setupCode, setSetupCode] = useState('');
|
||||
const [setupError, setSetupError] = useState<string | null>(null);
|
||||
const [secretCopied, setSecretCopied] = useState(false);
|
||||
|
||||
const setupSecret = useMemo(() => {
|
||||
if (!setupTotp) return null;
|
||||
return setupTotp.secret.base32.replace(/(.{4})/g, '$1 ').trim();
|
||||
}, [setupTotp]);
|
||||
|
||||
const copySecret = async () => {
|
||||
if (!setupTotp) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(setupTotp.secret.base32);
|
||||
setSecretCopied(true);
|
||||
setTimeout(() => setSecretCopied(false), 1500);
|
||||
} catch {
|
||||
toast({
|
||||
title: t('otp.copyFailed', 'Copy failed'),
|
||||
description: t('otp.clipboardBlocked', 'Your browser blocked clipboard access.'),
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!setupUrl) return;
|
||||
let cancelled = false;
|
||||
@@ -118,7 +99,6 @@ export function OtpAuthField({ value, onChange, readOnly }: OtpAuthFieldProps) {
|
||||
setSetupTotp(null);
|
||||
setSetupUrl(null);
|
||||
setSetupCode('');
|
||||
setSecretCopied(false);
|
||||
};
|
||||
|
||||
const cancelSetup = () => {
|
||||
@@ -126,7 +106,6 @@ export function OtpAuthField({ value, onChange, readOnly }: OtpAuthFieldProps) {
|
||||
setSetupUrl(null);
|
||||
setSetupCode('');
|
||||
setSetupError(null);
|
||||
setSecretCopied(false);
|
||||
};
|
||||
|
||||
const otpCodeValue = useMemo(
|
||||
@@ -154,7 +133,7 @@ export function OtpAuthField({ value, onChange, readOnly }: OtpAuthFieldProps) {
|
||||
|
||||
if (!isConfigured && setupUrl) {
|
||||
return (
|
||||
<div className="rounded-md border bg-muted/30 p-4 space-y-4">
|
||||
<div className="space-y-4 rounded-xl bg-muted p-4">
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm font-medium">{t('otp.scanPrompt', 'Scan with your authenticator app')}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
@@ -171,11 +150,11 @@ export function OtpAuthField({ value, onChange, readOnly }: OtpAuthFieldProps) {
|
||||
alt={t('otp.qrCodeAlt', 'TOTP QR code')}
|
||||
width={220}
|
||||
height={220}
|
||||
className="rounded-md border bg-white p-2"
|
||||
className="rounded-xl bg-white p-2 shadow-tile"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-[220px] w-[220px] items-center justify-center text-muted-foreground">
|
||||
<Loader2 className="h-6 w-6 animate-spin" />
|
||||
<Loader2 className="h-6 w-6 animate-spin text-brand-text" aria-hidden="true" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -189,22 +168,21 @@ export function OtpAuthField({ value, onChange, readOnly }: OtpAuthFieldProps) {
|
||||
)}
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<code className="flex-1 rounded bg-muted p-2 text-sm font-mono break-all select-all">{setupSecret}</code>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={copySecret}
|
||||
aria-label={t('otp.copySecret', 'Copy secret')}
|
||||
>
|
||||
{secretCopied ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
|
||||
</Button>
|
||||
<code className="flex-1 select-all break-all rounded-lg bg-card px-3 py-2 font-mono text-sm">
|
||||
{setupSecret}
|
||||
</code>
|
||||
{setupTotp && <CopyButton value={setupTotp.secret.base32} label={t('otp.secret', 'secret')} />}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-sm font-medium">{t('otp.confirmationCodeLabel', 'Confirmation code')}</Label>
|
||||
<Label htmlFor={codeId} className="text-sm font-medium">
|
||||
{t('otp.confirmationCodeLabel', 'Confirmation code')}
|
||||
</Label>
|
||||
<Input
|
||||
id={codeId}
|
||||
aria-invalid={setupError ? true : undefined}
|
||||
aria-describedby={setupError ? `${codeId}-error` : undefined}
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
@@ -214,14 +192,18 @@ export function OtpAuthField({ value, onChange, readOnly }: OtpAuthFieldProps) {
|
||||
maxLength={10}
|
||||
className="font-mono tracking-widest text-center max-w-[12rem]"
|
||||
/>
|
||||
{setupError && <p className="text-xs text-destructive">{setupError}</p>}
|
||||
{setupError && (
|
||||
<p id={`${codeId}-error`} className="text-xs text-destructive">
|
||||
{setupError}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<Button type="button" variant="outline" size="sm" onClick={cancelSetup}>
|
||||
<Button type="button" variant="ghost" size="sm" onClick={cancelSetup}>
|
||||
{t('common.cancel', 'Cancel')}
|
||||
</Button>
|
||||
<Button type="button" size="sm" onClick={confirmSetup}>
|
||||
<ShieldCheck className="mr-2 h-4 w-4" />
|
||||
<ShieldCheck aria-hidden="true" />
|
||||
{t('common.confirm', 'Confirm')}
|
||||
</Button>
|
||||
</div>
|
||||
@@ -235,8 +217,8 @@ export function OtpAuthField({ value, onChange, readOnly }: OtpAuthFieldProps) {
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t('otp.statusDisabled', 'Two-factor authentication is not enabled.')}
|
||||
</span>
|
||||
<Button type="button" variant="outline" size="sm" onClick={startSetup}>
|
||||
<ShieldCheck className="mr-2 h-4 w-4" />
|
||||
<Button type="button" variant="secondary" size="sm" onClick={startSetup}>
|
||||
<ShieldCheck aria-hidden="true" />
|
||||
{t('otp.setUp', 'Set up TOTP')}
|
||||
</Button>
|
||||
</div>
|
||||
@@ -244,9 +226,11 @@ export function OtpAuthField({ value, onChange, readOnly }: OtpAuthFieldProps) {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-md border bg-muted/30 p-4 space-y-3">
|
||||
<div className="space-y-3 rounded-xl bg-muted p-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<ShieldCheck className="h-4 w-4 text-green-600" />
|
||||
<span className="grid size-7 place-items-center rounded-[9px] bg-success-soft text-success">
|
||||
<ShieldCheck className="h-4 w-4" aria-hidden="true" />
|
||||
</span>
|
||||
<span className="text-sm font-medium">{t('otp.statusEnabled', 'Two-factor authentication is enabled.')}</span>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
@@ -256,8 +240,11 @@ export function OtpAuthField({ value, onChange, readOnly }: OtpAuthFieldProps) {
|
||||
)}
|
||||
</p>
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-sm font-medium">{t('otp.currentCodeLabel', 'Current code')}</Label>
|
||||
<Label htmlFor={codeId} className="text-sm font-medium">
|
||||
{t('otp.currentCodeLabel', 'Current code')}
|
||||
</Label>
|
||||
<Input
|
||||
id={codeId}
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
@@ -270,7 +257,7 @@ export function OtpAuthField({ value, onChange, readOnly }: OtpAuthFieldProps) {
|
||||
</div>
|
||||
<div className="flex items-center justify-end">
|
||||
<Button type="button" variant="destructive" size="sm" onClick={handleDisable} disabled={!otpCodeValue.trim()}>
|
||||
<ShieldOff className="mr-2 h-4 w-4" />
|
||||
<ShieldOff aria-hidden="true" />
|
||||
{t('otp.disable', 'Disable')}
|
||||
</Button>
|
||||
</div>
|
||||
@@ -0,0 +1,251 @@
|
||||
/*
|
||||
* 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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
/*
|
||||
* 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 { Plus, X } from 'lucide-react';
|
||||
import { useResetOnChange } from '@/hooks/useBufferedValue';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { DURATION_UNITS, humanToMs, msToHuman } from '@/lib/durationFormat';
|
||||
import { formatDuration, formatNumber } from '@/lib/format';
|
||||
import { useDurationUnitLabel } from '@/components/forms/widgets/useDurationUnitLabel';
|
||||
import type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
import type { FieldTypeObject } from '@/types/schema';
|
||||
|
||||
interface RateValue {
|
||||
count?: number;
|
||||
period?: number;
|
||||
}
|
||||
|
||||
export function RateWidget({ type, value, onChange, readOnly, control }: WidgetProps<FieldTypeObject>) {
|
||||
const { t } = useTranslation();
|
||||
const durationLabel = useDurationUnitLabel();
|
||||
const rate = value as RateValue | null | undefined;
|
||||
const isNull = rate == null;
|
||||
const count = typeof rate?.count === 'number' ? rate.count : 0;
|
||||
const periodMs = typeof rate?.period === 'number' ? rate.period : 0;
|
||||
const human = msToHuman(periodMs);
|
||||
|
||||
const [localCount, setLocalCount] = useState(String(count));
|
||||
const [localPeriod, setLocalPeriod] = useState(String(human.value));
|
||||
useResetOnChange(count, () => setLocalCount(String(count)));
|
||||
useResetOnChange(human.value, () => setLocalPeriod(String(human.value)));
|
||||
|
||||
const commitCount = () => {
|
||||
const n = parseInt(localCount, 10);
|
||||
const next = !localCount || Number.isNaN(n) ? 0 : n;
|
||||
if (next !== count) onChange({ count: next, period: periodMs });
|
||||
};
|
||||
const commitPeriod = () => {
|
||||
const n = parseFloat(localPeriod);
|
||||
const next = !localPeriod || Number.isNaN(n) ? 0 : n;
|
||||
if (next !== human.value) onChange({ count, period: humanToMs(next, human.unit) });
|
||||
};
|
||||
|
||||
if (readOnly) {
|
||||
if (isNull) return <span className="text-sm italic text-dim">{t('field.notSet', 'Not set')}</span>;
|
||||
return (
|
||||
<span className="text-sm">
|
||||
{t('rate.summary', '{{amount}} per {{period}}', {
|
||||
amount: formatNumber(count),
|
||||
period: formatDuration(periodMs),
|
||||
})}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
if (isNull) {
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm italic text-dim">{t('field.notSet', 'Not set')}</span>
|
||||
<Button
|
||||
{...control}
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => onChange({ count: 1, period: 1000 })}
|
||||
>
|
||||
<Plus aria-hidden="true" />
|
||||
{t('field.enable', 'Enable')}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Input
|
||||
{...control}
|
||||
type="number"
|
||||
min={1}
|
||||
step={1}
|
||||
value={localCount}
|
||||
className="w-24"
|
||||
aria-label={t('rate.count', 'Count')}
|
||||
onChange={(e) => setLocalCount(e.target.value)}
|
||||
onBlur={commitCount}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') commitCount();
|
||||
}}
|
||||
/>
|
||||
<span className="shrink-0 text-sm text-muted-foreground">{t('rate.per', 'per')}</span>
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
step={1}
|
||||
value={localPeriod}
|
||||
className="w-24"
|
||||
aria-label={t('rate.periodValue', 'Period value')}
|
||||
onChange={(e) => setLocalPeriod(e.target.value)}
|
||||
onBlur={commitPeriod}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') commitPeriod();
|
||||
}}
|
||||
/>
|
||||
<Select value={human.unit} onValueChange={(u) => onChange({ count, period: humanToMs(human.value, u) })}>
|
||||
<SelectTrigger className="w-32" aria-label={t('field.unit', 'Unit')}>
|
||||
<SelectValue>{durationLabel(human.unit)}</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{DURATION_UNITS.map((u) => (
|
||||
<SelectItem key={u} value={u}>
|
||||
{durationLabel(u)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{type.nullable && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-9 w-9 shrink-0"
|
||||
onClick={() => onChange(null)}
|
||||
aria-label={t('common.clear', 'Clear')}
|
||||
>
|
||||
<X aria-hidden="true" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
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;
|
||||
onRemove?: () => void;
|
||||
removeDisabled?: boolean;
|
||||
children?: ReactNode;
|
||||
}
|
||||
|
||||
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>
|
||||
{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"
|
||||
>
|
||||
<X className="h-3 w-3" aria-hidden="true" />
|
||||
</button>
|
||||
)}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useId, useState, type ClipboardEvent } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Plus } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { EnumMultiSelect } from '@/components/forms/widgets/EnumWidgets';
|
||||
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';
|
||||
|
||||
function toSetObject(items: string[]): Record<string, true> {
|
||||
const obj: Record<string, true> = {};
|
||||
for (const item of items) obj[item] = true;
|
||||
return obj;
|
||||
}
|
||||
|
||||
export function SetWidget({ type, formField, value, onChange, readOnly, control }: WidgetProps<FieldTypeSet>) {
|
||||
const items = isRecord(value) ? Object.keys(value) : [];
|
||||
const commit = (next: string[]) => onChange(toSetObject(next));
|
||||
const scalar = type.class;
|
||||
|
||||
switch (scalar.type) {
|
||||
case 'string':
|
||||
return (
|
||||
<TagInput
|
||||
type={scalar}
|
||||
label={formField.label}
|
||||
items={items}
|
||||
onChange={commit}
|
||||
readOnly={readOnly}
|
||||
minItems={type.minItems}
|
||||
maxItems={type.maxItems}
|
||||
placeholder={formField.placeholder ?? formatPlaceholder(scalar.format)}
|
||||
control={control}
|
||||
/>
|
||||
);
|
||||
case 'enum':
|
||||
return (
|
||||
<EnumMultiSelect
|
||||
enumName={scalar.enumName}
|
||||
items={items}
|
||||
onChange={commit}
|
||||
readOnly={readOnly}
|
||||
minItems={type.minItems}
|
||||
control={control}
|
||||
/>
|
||||
);
|
||||
case 'objectId':
|
||||
return (
|
||||
<ObjectIdMultiSelect
|
||||
objectName={scalar.objectName}
|
||||
label={formField.label}
|
||||
items={items}
|
||||
onChange={commit}
|
||||
readOnly={readOnly}
|
||||
minItems={type.minItems}
|
||||
control={control}
|
||||
/>
|
||||
);
|
||||
default: {
|
||||
const unknownScalar: never = scalar;
|
||||
void unknownScalar;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface TagInputProps {
|
||||
type: ScalarTypeString;
|
||||
label: string;
|
||||
items: string[];
|
||||
onChange: (items: string[]) => void;
|
||||
readOnly: boolean;
|
||||
minItems?: number;
|
||||
maxItems?: number;
|
||||
placeholder?: string;
|
||||
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) {
|
||||
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 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"
|
||||
/>
|
||||
<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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useState, type CSSProperties } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Eye, EyeOff } from 'lucide-react';
|
||||
import { useResetOnChange } from '@/hooks/useBufferedValue';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { SECRET_MASK } from '@/lib/jmapUtils';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { BufferedInput, BufferedTextarea } from '@/components/forms/widgets/BufferedInputs';
|
||||
import { formatPlaceholder, inputTypeFor } from '@/components/forms/widgets/placeholders';
|
||||
import type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
import type { FieldTypeString } from '@/types/schema';
|
||||
|
||||
function stringCommitter({ type, onChange }: WidgetProps<FieldTypeString>) {
|
||||
return (v: string) => onChange(type.nullable && v === '' ? null : v);
|
||||
}
|
||||
|
||||
function stringValue(value: unknown): string {
|
||||
return typeof value === 'string' ? value : '';
|
||||
}
|
||||
|
||||
export function TextWidget(props: WidgetProps<FieldTypeString>) {
|
||||
const { type, formField, value, readOnly, control } = props;
|
||||
const commit = stringCommitter(props);
|
||||
return (
|
||||
<BufferedInput
|
||||
{...control}
|
||||
type={inputTypeFor(type.format)}
|
||||
value={stringValue(value)}
|
||||
onCommit={commit}
|
||||
disabled={readOnly}
|
||||
placeholder={formField.placeholder ?? formatPlaceholder(type.format)}
|
||||
minLength={type.minLength}
|
||||
maxLength={type.maxLength}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function MultilineWidget(props: WidgetProps<FieldTypeString>) {
|
||||
const { type, formField, value, readOnly, control } = props;
|
||||
const commit = stringCommitter(props);
|
||||
const common = {
|
||||
...control,
|
||||
value: stringValue(value),
|
||||
onCommit: commit,
|
||||
disabled: readOnly,
|
||||
placeholder: formField.placeholder,
|
||||
minLength: type.minLength,
|
||||
maxLength: type.maxLength,
|
||||
};
|
||||
|
||||
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">
|
||||
<span className="font-mono">HTML</span>
|
||||
</div>
|
||||
<BufferedTextarea
|
||||
{...common}
|
||||
rows={10}
|
||||
spellCheck={false}
|
||||
variant="bare"
|
||||
className="resize-y font-mono text-xs"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
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;
|
||||
const commit = stringCommitter(props);
|
||||
const str = stringValue(value);
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
value={str || '#000000'}
|
||||
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"
|
||||
/>
|
||||
<BufferedInput
|
||||
{...control}
|
||||
value={str}
|
||||
onCommit={commit}
|
||||
disabled={readOnly}
|
||||
placeholder="#000000"
|
||||
className="max-w-[10rem]"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function SecretWidget(props: WidgetProps<FieldTypeString>) {
|
||||
const { t } = useTranslation();
|
||||
const { type, formField, value, readOnly, control } = props;
|
||||
const commitValue = stringCommitter(props);
|
||||
const strValue = stringValue(value);
|
||||
const multiline = type.format === 'secretText';
|
||||
|
||||
const [visible, setVisible] = useState(false);
|
||||
const [localValue, setLocalValue] = useState(() => (strValue === SECRET_MASK ? '' : strValue));
|
||||
const [isMasked, setIsMasked] = useState(() => strValue === SECRET_MASK);
|
||||
|
||||
useResetOnChange(strValue, () => {
|
||||
setLocalValue(strValue === SECRET_MASK ? '' : strValue);
|
||||
setIsMasked(strValue === SECRET_MASK);
|
||||
});
|
||||
|
||||
const handleLocalChange = (v: string) => {
|
||||
setLocalValue(v);
|
||||
setIsMasked(false);
|
||||
};
|
||||
|
||||
const commit = () => {
|
||||
if (isMasked && localValue === '') return;
|
||||
if (localValue !== strValue) commitValue(localValue);
|
||||
};
|
||||
|
||||
const displayValue = isMasked && !visible ? '' : localValue;
|
||||
const placeholder = isMasked ? SECRET_MASK : formField.placeholder;
|
||||
const managerIgnore = { 'data-1p-ignore': true, 'data-lpignore': 'true', 'data-bwignore': true };
|
||||
|
||||
const toggle = (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className="shrink-0"
|
||||
onClick={() => setVisible((p) => !p)}
|
||||
aria-label={visible ? t('field.hideValue', 'Hide value') : t('field.showValue', 'Show value')}
|
||||
aria-pressed={visible}
|
||||
tabIndex={-1}
|
||||
>
|
||||
{visible ? <EyeOff aria-hidden="true" /> : <Eye aria-hidden="true" />}
|
||||
</Button>
|
||||
);
|
||||
|
||||
if (multiline) {
|
||||
return (
|
||||
<div className="relative">
|
||||
<Textarea
|
||||
{...control}
|
||||
{...managerIgnore}
|
||||
value={displayValue}
|
||||
onChange={(e) => handleLocalChange(e.target.value)}
|
||||
onBlur={commit}
|
||||
disabled={readOnly}
|
||||
placeholder={placeholder}
|
||||
minLength={type.minLength}
|
||||
maxLength={type.maxLength}
|
||||
rows={4}
|
||||
autoComplete="off"
|
||||
className={cn(!visible && 'tracking-widest')}
|
||||
style={visible ? undefined : ({ WebkitTextSecurity: 'disc' } as CSSProperties)}
|
||||
/>
|
||||
<div className="absolute right-1 top-1">{toggle}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1">
|
||||
<Input
|
||||
{...control}
|
||||
{...managerIgnore}
|
||||
type={visible ? 'text' : 'password'}
|
||||
value={displayValue}
|
||||
onChange={(e) => handleLocalChange(e.target.value)}
|
||||
onBlur={commit}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') commit();
|
||||
}}
|
||||
disabled={readOnly}
|
||||
placeholder={placeholder}
|
||||
minLength={type.minLength}
|
||||
maxLength={type.maxLength}
|
||||
autoComplete="off"
|
||||
className="flex-1"
|
||||
/>
|
||||
{toggle}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
/*
|
||||
* 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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
/*
|
||||
* 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 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">
|
||||
{t('field.unsupportedType', 'Unsupported field type: {{type}}', { type: (type as { type?: string }).type ?? '' })}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
/*
|
||||
* 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}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import type { StringFormat } from '@/types/schema';
|
||||
|
||||
export function formatPlaceholder(format: StringFormat): string | undefined {
|
||||
switch (format) {
|
||||
case 'ipAddress':
|
||||
return '192.168.1.1';
|
||||
case 'ipNetwork':
|
||||
return '192.168.1.0/24';
|
||||
case 'socketAddress':
|
||||
return '127.0.0.1:8080';
|
||||
case 'emailAddress':
|
||||
return 'user@example.com';
|
||||
case 'uri':
|
||||
return 'https://example.com';
|
||||
case 'localTime':
|
||||
return 'HH:MM';
|
||||
case 'localDate':
|
||||
return 'YYYY-MM-DD';
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function inputTypeFor(format: StringFormat): 'email' | 'url' | 'text' {
|
||||
return format === 'emailAddress' ? 'email' : format === 'uri' ? 'url' : 'text';
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import type { Field, FieldType, FormField } from '@/types/schema';
|
||||
|
||||
export interface ControlProps {
|
||||
id?: string;
|
||||
'aria-invalid'?: boolean;
|
||||
'aria-describedby'?: string;
|
||||
'aria-labelledby'?: string;
|
||||
'aria-required'?: boolean;
|
||||
'aria-label'?: string;
|
||||
}
|
||||
|
||||
export interface WidgetProps<T extends FieldType = FieldType> {
|
||||
type: T;
|
||||
field: Field;
|
||||
formField: FormField;
|
||||
value: unknown;
|
||||
onChange: (value: unknown) => void;
|
||||
readOnly: boolean;
|
||||
control: ControlProps;
|
||||
error?: string;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
export function useDurationUnitLabel(): (unit: string) => string {
|
||||
const { t } = useTranslation();
|
||||
return (unit: string) => {
|
||||
switch (unit) {
|
||||
case 'ms':
|
||||
return t('duration.milliseconds', 'Milliseconds');
|
||||
case 's':
|
||||
return t('duration.seconds', 'Seconds');
|
||||
case 'min':
|
||||
return t('duration.minutes', 'Minutes');
|
||||
case 'h':
|
||||
return t('duration.hours', 'Hours');
|
||||
case 'd':
|
||||
return t('duration.days', 'Days');
|
||||
default:
|
||||
return unit;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -5,12 +5,14 @@
|
||||
*/
|
||||
|
||||
import { Component, type ErrorInfo, type ReactNode } from 'react';
|
||||
import { TriangleAlert } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import i18n from '@/i18n';
|
||||
|
||||
interface ErrorBoundaryProps {
|
||||
children: ReactNode;
|
||||
fallback?: ReactNode;
|
||||
resetKey?: unknown;
|
||||
}
|
||||
|
||||
interface ErrorBoundaryState {
|
||||
@@ -32,6 +34,12 @@ export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundarySt
|
||||
console.error('[ErrorBoundary] Caught error:', error, errorInfo);
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps: ErrorBoundaryProps) {
|
||||
if (this.state.hasError && !Object.is(prevProps.resetKey, this.props.resetKey)) {
|
||||
this.handleReset();
|
||||
}
|
||||
}
|
||||
|
||||
handleReset = () => {
|
||||
this.setState({ hasError: false, error: null });
|
||||
};
|
||||
@@ -43,11 +51,12 @@ export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundarySt
|
||||
}
|
||||
|
||||
return (
|
||||
<div role="alert" className="flex flex-col items-center justify-center gap-4 p-8">
|
||||
<div className="text-destructive text-lg font-semibold">
|
||||
{i18n.t('errorBoundary.title', 'Something went wrong')}
|
||||
</div>
|
||||
<p className="text-muted-foreground text-sm max-w-md text-center">
|
||||
<div role="alert" className="mx-auto mt-6 flex max-w-lg flex-col items-center gap-4 tile p-8 text-center">
|
||||
<span className="grid size-11 place-items-center rounded-[13px] bg-destructive-soft text-destructive">
|
||||
<TriangleAlert className="h-5 w-5" aria-hidden="true" />
|
||||
</span>
|
||||
<div className="section-title text-lg">{i18n.t('errorBoundary.title', 'Something went wrong')}</div>
|
||||
<p className="max-w-md text-sm text-muted-foreground">
|
||||
{this.state.error?.message ?? i18n.t('errors.unexpectedError', 'An unexpected error occurred.')}
|
||||
</p>
|
||||
<Button variant="outline" onClick={this.handleReset}>
|
||||
|
||||
@@ -4,41 +4,17 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { lazy, Suspense, useEffect, type ComponentType, type ReactNode } from 'react';
|
||||
import { Suspense, type ReactNode } from 'react';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useSchemaStore } from '@/stores/schemaStore';
|
||||
import { useCacheStore } from '@/stores/cacheStore';
|
||||
import { useAccountStore } from '@/stores/accountStore';
|
||||
import { resolveObject } from '@/lib/schemaResolver';
|
||||
import { usePermissionCheckers } from '@/hooks/usePermissions';
|
||||
import { pageObjectId, resolvePage, type PageTarget } from '@/extensions/pages';
|
||||
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 DashboardView = lazyFeature(
|
||||
() => import('@/features/dashboard/components/DashboardView'),
|
||||
(m) => m.DashboardView,
|
||||
);
|
||||
const DeliveryTracePage = lazyFeature(
|
||||
() => import('@/features/troubleshoot/DeliveryTracePage'),
|
||||
(m) => m.DeliveryTracePage,
|
||||
);
|
||||
const LiveTracingPage = lazyFeature(
|
||||
() => import('@/features/tracing/components/LiveTracingPage'),
|
||||
(m) => m.LiveTracingPage,
|
||||
);
|
||||
const TraceDetailView = lazyFeature(
|
||||
() => import('@/features/tracing/components/TraceDetailView'),
|
||||
(m) => m.TraceDetailView,
|
||||
);
|
||||
const ActionPage = lazyFeature(
|
||||
() => import('@/features/actions/ActionPage'),
|
||||
(m) => m.ActionPage,
|
||||
);
|
||||
|
||||
interface MainContentProps {
|
||||
viewName?: string;
|
||||
@@ -46,77 +22,68 @@ interface MainContentProps {
|
||||
section?: string;
|
||||
}
|
||||
|
||||
export function MainContent({ viewName, id, section }: MainContentProps) {
|
||||
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) {
|
||||
const schema = useSchemaStore((s) => s.schema);
|
||||
const invalidateAllObjectLists = useCacheStore((s) => s.invalidateAllObjectLists);
|
||||
const permissions = usePermissionCheckers();
|
||||
const location = useLocation();
|
||||
const { t } = useTranslation();
|
||||
const page = resolvePage(schema, viewName, id, permissions);
|
||||
|
||||
useEffect(() => {
|
||||
invalidateAllObjectLists();
|
||||
}, [viewName, invalidateAllObjectLists]);
|
||||
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 <Suspense fallback={<LoadingFallback />}>{renderView(schema, viewName, id, section)}</Suspense>;
|
||||
}
|
||||
|
||||
function renderView(schema: Schema | null, viewName?: string, id?: string, section?: string): ReactNode {
|
||||
if (!viewName) {
|
||||
return <LoadingFallback />;
|
||||
}
|
||||
|
||||
if (viewName.startsWith('Dashboard/')) {
|
||||
const dashboardId = viewName.slice('Dashboard/'.length);
|
||||
return <DashboardView dashboardId={dashboardId} section={section ?? ''} />;
|
||||
}
|
||||
|
||||
if (viewName.startsWith('CustomComponent/')) {
|
||||
const componentName = viewName.slice('CustomComponent/'.length);
|
||||
if (componentName === 'Dashboard') {
|
||||
const firstId = schema?.dashboards?.[0]?.id ?? 'overview';
|
||||
return <DashboardView dashboardId={firstId} section={section ?? ''} />;
|
||||
}
|
||||
if (componentName === 'LiveDelivery') {
|
||||
return <DeliveryTracePage />;
|
||||
}
|
||||
if (componentName === 'LiveTracing') {
|
||||
return <LiveTracingPage />;
|
||||
}
|
||||
return (
|
||||
<div className="rounded-lg border border-dashed p-12 text-center text-muted-foreground">
|
||||
Unknown component: {componentName}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!schema) {
|
||||
return <div className="flex items-center justify-center p-8 text-muted-foreground">Loading...</div>;
|
||||
}
|
||||
|
||||
const resolved = resolveObject(schema, viewName);
|
||||
if (!resolved) {
|
||||
return <div className="flex items-center justify-center p-8 text-destructive">Unknown view: {viewName}</div>;
|
||||
}
|
||||
|
||||
if (resolved.objectName === 'x:Action') {
|
||||
return <ActionPage viewName={viewName} />;
|
||||
}
|
||||
|
||||
if (resolved.objectType.type === 'singleton') {
|
||||
return <DynamicForm viewName={viewName} objectId="singleton" />;
|
||||
}
|
||||
|
||||
if (id === 'new') {
|
||||
return <DynamicForm viewName={viewName} objectId={null} />;
|
||||
}
|
||||
|
||||
if (id) {
|
||||
if (resolved.objectName === 'x:Trace') {
|
||||
return <TraceDetailView viewName={viewName} objectId={id} />;
|
||||
}
|
||||
const canUpdate = useAccountStore.getState().hasObjectPermission(resolved.permissionPrefix, 'Update');
|
||||
if (!canUpdate) {
|
||||
return <DynamicViewPage viewName={viewName} objectId={id} />;
|
||||
}
|
||||
return <DynamicForm viewName={viewName} objectId={id} />;
|
||||
}
|
||||
|
||||
return <DynamicList viewName={viewName} />;
|
||||
return (
|
||||
<ErrorBoundary resetKey={location.pathname}>
|
||||
<Suspense fallback={<LoadingFallback />}>{content}</Suspense>
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
@@ -9,9 +9,8 @@ import { useAuthStore } from '@/stores/authStore';
|
||||
|
||||
export function ProtectedRoute({ children }: { children: React.ReactNode }) {
|
||||
const authenticated = useAuthStore((s) => s.isAuthenticated());
|
||||
const bypassToken = import.meta.env.VITE_ACCESS_TOKEN;
|
||||
const location = useLocation();
|
||||
if (!authenticated && !bypassToken) {
|
||||
if (!authenticated) {
|
||||
const originalPath = location.pathname + location.search;
|
||||
return <Navigate to="/login" replace state={{ from: originalPath }} />;
|
||||
}
|
||||
|
||||
+158
-343
@@ -4,400 +4,215 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useLocation, useNavigate } from 'react-router-dom';
|
||||
import * as LucideIcons from 'lucide-react';
|
||||
const { ChevronDown, Lock } = LucideIcons;
|
||||
import { useEffect, useId, useRef, useState } from 'react';
|
||||
import { Link, useLocation, useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ChevronRight, Lock } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { DynamicIcon } from '@/components/common/DynamicIcon';
|
||||
import { EnterpriseUpsell } from '@/components/common/EnterpriseUpsell';
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import { useUIStore } from '@/stores/uiStore';
|
||||
import { useAccountStore } from '@/stores/accountStore';
|
||||
import { useSchemaStore } from '@/stores/schemaStore';
|
||||
import { visibleLayouts, isLinkEnterprise, isLinkVisible } from '@/lib/layout';
|
||||
import { sectionLandingLink } from '@/lib/lastVisited';
|
||||
import type { Layout, LayoutItem, LayoutSubItem } from '@/types/schema';
|
||||
import type { Layout } from '@/types/schema';
|
||||
import { activeViewName, layoutNavNodes, navNodeKey, someLink, viewPath, type NavNode } from './navTree';
|
||||
import { SIDEBAR_ID, SidebarNavContext, useSidebarNav } from './sidebarContext';
|
||||
import { useLayoutNavigation } from './useLayoutNavigation';
|
||||
|
||||
function LucideIcon({ name, className }: { name: string; className?: string }) {
|
||||
const formatted = name
|
||||
.split('-')
|
||||
.map((s) => s[0].toUpperCase() + s.slice(1))
|
||||
.join('');
|
||||
const IconComp = (LucideIcons as Record<string, unknown>)[formatted] as LucideIcons.LucideIcon | undefined;
|
||||
if (!IconComp) return <LucideIcons.Circle className={className} />;
|
||||
return <IconComp className={className} />;
|
||||
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 resolveViewPath(sectionName: string, viewName: string): string {
|
||||
return `/${sectionName}/${viewName}`;
|
||||
}
|
||||
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;
|
||||
|
||||
function pathMatchesView(currentPath: string, sectionName: string, viewName: string): boolean {
|
||||
const base = `/${sectionName}/${viewName}`;
|
||||
if (currentPath === base || currentPath.startsWith(`${base}/`)) return true;
|
||||
if (viewName === 'CustomComponent/Dashboard') {
|
||||
const dashBase = `/${sectionName}/Dashboard/`;
|
||||
return currentPath.startsWith(dashBase);
|
||||
useEffect(() => {
|
||||
if (isActive) ref.current?.scrollIntoView?.({ block: 'nearest' });
|
||||
}, [isActive]);
|
||||
|
||||
if (!nav.isVisible(node.viewName)) return null;
|
||||
|
||||
const label = node.name || t('sidebar.overview', 'Overview');
|
||||
const content = (
|
||||
<>
|
||||
{node.icon && <DynamicIcon name={node.icon} className="h-4 w-4 shrink-0" />}
|
||||
<span className="truncate">{label}</span>
|
||||
</>
|
||||
);
|
||||
const className = cn(itemClass, itemSize(depth));
|
||||
|
||||
if (nav.isLocked(node.viewName)) {
|
||||
return (
|
||||
<button type="button" className={className} onClick={nav.openUpsell} aria-describedby={nav.lockedHintId}>
|
||||
{content}
|
||||
<Lock aria-hidden="true" className="ml-auto h-3 w-3 text-muted-foreground" />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
return false;
|
||||
|
||||
return (
|
||||
<Link
|
||||
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',
|
||||
)}
|
||||
>
|
||||
{content}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
function subtreeContainsActive(items: LayoutSubItem[], currentPath: string, sectionName: string): boolean {
|
||||
for (const item of items) {
|
||||
if (item.type === 'link') {
|
||||
if (pathMatchesView(currentPath, sectionName, item.viewName)) return true;
|
||||
} else if (item.type === 'container') {
|
||||
if (subtreeContainsActive(item.items, currentPath, sectionName)) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function subtreeHasVisibleLink(items: LayoutSubItem[], edition: string): boolean {
|
||||
for (const item of items) {
|
||||
if (item.type === 'link') {
|
||||
if (!checkLinkVisible(item.viewName)) continue;
|
||||
const enterprise = checkIsEnterprise(item.viewName);
|
||||
if (enterprise && edition === 'oss') continue;
|
||||
return true;
|
||||
} else if (item.type === 'container') {
|
||||
if (subtreeHasVisibleLink(item.items, edition)) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
interface AutoOpenCollapsibleProps {
|
||||
containsActive: boolean;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
function AutoOpenCollapsible({ containsActive, children }: AutoOpenCollapsibleProps) {
|
||||
function NavContainer({ node, depth }: { node: Extract<NavNode, { kind: 'container' }>; depth: number }) {
|
||||
const nav = useSidebarNav();
|
||||
const containsActive = someLink(node.children, (viewName) => viewName === nav.activeViewName);
|
||||
const [open, setOpen] = useState(containsActive);
|
||||
const [prevContainsActive, setPrevContainsActive] = useState(containsActive);
|
||||
if (containsActive !== prevContainsActive) {
|
||||
setPrevContainsActive(containsActive);
|
||||
if (containsActive) setOpen(true);
|
||||
}
|
||||
|
||||
if (!someLink(node.children, nav.isVisible)) return null;
|
||||
|
||||
return (
|
||||
<Collapsible open={open} onOpenChange={setOpen}>
|
||||
{children}
|
||||
<CollapsibleTrigger asChild>
|
||||
<button type="button" className={cn(itemClass, itemSize(depth))}>
|
||||
{node.icon && <DynamicIcon name={node.icon} className="h-4 w-4 shrink-0" />}
|
||||
<span className="truncate">{node.name}</span>
|
||||
<ChevronRight
|
||||
aria-hidden="true"
|
||||
className="ml-auto h-3.5 w-3.5 shrink-0 opacity-60 transition-transform duration-200 [[data-state=open]>&]:rotate-90"
|
||||
/>
|
||||
</button>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<div className="my-0.5 ml-[18px] flex flex-col gap-0.5 border-l border-input pl-2">
|
||||
<NavNodes nodes={node.children} depth={depth + 1} />
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
);
|
||||
}
|
||||
|
||||
function checkLinkVisible(viewName: string): boolean {
|
||||
const schema = useSchemaStore.getState().schema;
|
||||
if (!schema) return true;
|
||||
|
||||
const accountStore = useAccountStore.getState();
|
||||
return isLinkVisible(
|
||||
schema,
|
||||
viewName,
|
||||
accountStore.edition,
|
||||
(prefix: string) => accountStore.hasObjectPermission(prefix, 'Get'),
|
||||
(perm: string) => accountStore.hasPermission(perm),
|
||||
function NavNodes({ nodes, depth }: { nodes: NavNode[]; depth: number }) {
|
||||
return nodes.map((node) =>
|
||||
node.kind === 'link' ? (
|
||||
<NavLink key={navNodeKey(node)} node={node} depth={depth} />
|
||||
) : (
|
||||
<NavContainer key={navNodeKey(node)} node={node} depth={depth} />
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function checkIsEnterprise(viewName: string): boolean {
|
||||
const schema = useSchemaStore.getState().schema;
|
||||
if (!schema) return false;
|
||||
const edition = useAccountStore.getState().edition;
|
||||
return isLinkEnterprise(schema, viewName, edition);
|
||||
}
|
||||
function SectionSwitcher({ layouts, activeSection }: { layouts: Layout[]; activeSection: string }) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const setActiveSection = useUIStore((s) => s.setActiveSection);
|
||||
const { landingPath } = useLayoutNavigation();
|
||||
|
||||
type ActiveItemRef = (el: HTMLButtonElement | null) => void;
|
||||
|
||||
interface SidebarSubItemProps {
|
||||
item: LayoutSubItem;
|
||||
depth: number;
|
||||
sectionName: string;
|
||||
currentPath: string;
|
||||
navigate: ReturnType<typeof useNavigate>;
|
||||
edition: string;
|
||||
onUpsell: () => void;
|
||||
activeItemRef: ActiveItemRef;
|
||||
}
|
||||
|
||||
function SidebarSubItem({
|
||||
item,
|
||||
depth,
|
||||
sectionName,
|
||||
currentPath,
|
||||
navigate,
|
||||
edition,
|
||||
onUpsell,
|
||||
activeItemRef,
|
||||
}: SidebarSubItemProps) {
|
||||
if (item.type === 'link') {
|
||||
if (!checkLinkVisible(item.viewName)) return null;
|
||||
|
||||
const path = resolveViewPath(sectionName, item.viewName);
|
||||
const isActive = pathMatchesView(currentPath, sectionName, item.viewName);
|
||||
const enterprise = checkIsEnterprise(item.viewName);
|
||||
const isLocked = enterprise && edition === 'community';
|
||||
const isHidden = enterprise && edition === 'oss';
|
||||
|
||||
if (isHidden) return null;
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
ref={isActive ? activeItemRef : undefined}
|
||||
className={cn(
|
||||
'w-full justify-start gap-2 font-normal',
|
||||
isActive && 'bg-accent text-accent-foreground',
|
||||
depth > 0 && 'text-sm',
|
||||
)}
|
||||
style={{ paddingLeft: `${(depth + 1) * 12 + 8}px` }}
|
||||
onClick={() => {
|
||||
if (isLocked) {
|
||||
onUpsell();
|
||||
} else {
|
||||
navigate(path);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span className="truncate">{item.name || 'Overview'}</span>
|
||||
{isLocked && <Lock className="ml-auto h-3 w-3 text-muted-foreground" />}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
if (item.type === 'container') {
|
||||
if (!subtreeHasVisibleLink(item.items, edition)) return null;
|
||||
|
||||
const containsActive = subtreeContainsActive(item.items, currentPath, sectionName);
|
||||
return (
|
||||
<AutoOpenCollapsible containsActive={containsActive}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="w-full justify-start gap-2 font-normal text-sm"
|
||||
style={{ paddingLeft: `${(depth + 1) * 12 + 8}px` }}
|
||||
>
|
||||
<ChevronDown className="h-3 w-3 shrink-0 transition-transform duration-200 [[data-state=closed]>&]:rotate-[-90deg]" />
|
||||
<span className="truncate">{item.name}</span>
|
||||
</Button>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
{item.items.map((sub) => (
|
||||
<SidebarSubItem
|
||||
key={sub.type === 'link' ? sub.viewName : sub.name}
|
||||
item={sub}
|
||||
depth={depth + 1}
|
||||
sectionName={sectionName}
|
||||
currentPath={currentPath}
|
||||
navigate={navigate}
|
||||
edition={edition}
|
||||
onUpsell={onUpsell}
|
||||
activeItemRef={activeItemRef}
|
||||
/>
|
||||
))}
|
||||
</CollapsibleContent>
|
||||
</AutoOpenCollapsible>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
interface SidebarTopItemProps {
|
||||
item: LayoutItem;
|
||||
sectionName: string;
|
||||
currentPath: string;
|
||||
navigate: ReturnType<typeof useNavigate>;
|
||||
edition: string;
|
||||
onUpsell: () => void;
|
||||
activeItemRef: ActiveItemRef;
|
||||
}
|
||||
|
||||
function SidebarTopItem({
|
||||
item,
|
||||
sectionName,
|
||||
currentPath,
|
||||
navigate,
|
||||
edition,
|
||||
onUpsell,
|
||||
activeItemRef,
|
||||
}: SidebarTopItemProps) {
|
||||
if ('link' in item) {
|
||||
const { name, icon, viewName } = item.link;
|
||||
|
||||
if (!checkLinkVisible(viewName)) return null;
|
||||
|
||||
const path = resolveViewPath(sectionName, viewName);
|
||||
const isActive = pathMatchesView(currentPath, sectionName, viewName);
|
||||
const enterprise = checkIsEnterprise(viewName);
|
||||
const isLocked = enterprise && edition === 'community';
|
||||
const isHidden = enterprise && edition === 'oss';
|
||||
|
||||
if (isHidden) return null;
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
ref={isActive ? activeItemRef : undefined}
|
||||
className={cn('w-full justify-start gap-2 font-normal', isActive && 'bg-accent text-accent-foreground')}
|
||||
onClick={() => {
|
||||
if (isLocked) {
|
||||
onUpsell();
|
||||
} else {
|
||||
navigate(path);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<LucideIcon name={icon} className="h-4 w-4 shrink-0" />
|
||||
<span className="truncate">{name}</span>
|
||||
{isLocked && <Lock className="ml-auto h-3 w-3 text-muted-foreground" />}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
if ('container' in item) {
|
||||
const { name, icon, items } = item.container;
|
||||
if (!subtreeHasVisibleLink(items, edition)) return null;
|
||||
|
||||
const containsActive = subtreeContainsActive(items, currentPath, sectionName);
|
||||
|
||||
return (
|
||||
<AutoOpenCollapsible containsActive={containsActive}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<Button variant="ghost" className="w-full justify-start gap-2 font-normal">
|
||||
<LucideIcon name={icon} className="h-4 w-4 shrink-0" />
|
||||
<span className="truncate">{name}</span>
|
||||
<ChevronDown className="ml-auto h-3 w-3 shrink-0 transition-transform duration-200 [[data-state=closed]>&]:rotate-[-90deg]" />
|
||||
</Button>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
{items.map((sub) => (
|
||||
<SidebarSubItem
|
||||
key={sub.type === 'link' ? sub.viewName : sub.name}
|
||||
item={sub}
|
||||
depth={1}
|
||||
sectionName={sectionName}
|
||||
currentPath={currentPath}
|
||||
navigate={navigate}
|
||||
edition={edition}
|
||||
onUpsell={onUpsell}
|
||||
activeItemRef={activeItemRef}
|
||||
/>
|
||||
))}
|
||||
</CollapsibleContent>
|
||||
</AutoOpenCollapsible>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
return (
|
||||
<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"
|
||||
>
|
||||
{layouts.map((target) => {
|
||||
const isActive = target.name === activeSection;
|
||||
return (
|
||||
<Tooltip key={target.name}>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label={target.name}
|
||||
aria-pressed={isActive}
|
||||
onClick={() => {
|
||||
setActiveSection(target.name);
|
||||
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',
|
||||
)}
|
||||
>
|
||||
<DynamicIcon name={target.icon} className="h-4 w-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top">{target.name}</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Sidebar() {
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const { t } = useTranslation();
|
||||
const { pathname } = useLocation();
|
||||
const activeSection = useUIStore((s) => s.activeSection);
|
||||
const setActiveSection = useUIStore((s) => s.setActiveSection);
|
||||
const sidebarOpen = useUIStore((s) => s.sidebarOpen);
|
||||
const setSidebarOpen = useUIStore((s) => s.setSidebarOpen);
|
||||
const schema = useSchemaStore((s) => s.schema);
|
||||
const edition = useAccountStore((s) => s.edition);
|
||||
const permissions = useAccountStore((s) => s.permissions);
|
||||
const hasPermission = useAccountStore((s) => s.hasPermission);
|
||||
const { layouts, isVisible, isLocked } = useLayoutNavigation();
|
||||
const [upsellOpen, setUpsellOpen] = useState(false);
|
||||
const activeItem = useRef<HTMLButtonElement | null>(null);
|
||||
const activeItemRef = useCallback<ActiveItemRef>((el) => {
|
||||
activeItem.current = el;
|
||||
}, []);
|
||||
|
||||
const layouts = useMemo(() => {
|
||||
if (!schema) return [];
|
||||
const canGet = (prefix: string) => permissions.includes(`${prefix}Get`);
|
||||
return visibleLayouts(schema, edition, canGet, hasPermission);
|
||||
}, [schema, edition, permissions, hasPermission]);
|
||||
const lockedHintId = useId();
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === 'undefined') return;
|
||||
if (window.matchMedia('(max-width: 767px)').matches) {
|
||||
setSidebarOpen(false);
|
||||
}
|
||||
}, [location.pathname, setSidebarOpen]);
|
||||
if (window.matchMedia('(max-width: 767px)').matches) setSidebarOpen(false);
|
||||
}, [pathname, setSidebarOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
activeItem.current?.scrollIntoView({ block: 'nearest' });
|
||||
}, [location.pathname, activeSection]);
|
||||
|
||||
if (!sidebarOpen || !schema) return null;
|
||||
|
||||
const layout: Layout | undefined = layouts.find((l) => l.name === activeSection);
|
||||
if (!sidebarOpen) return null;
|
||||
const layout = layouts.find((l) => l.name === activeSection);
|
||||
if (!layout) return null;
|
||||
|
||||
const handleSectionClick = (target: Layout) => {
|
||||
setActiveSection(target.name);
|
||||
const canGet = (prefix: string) => permissions.includes(`${prefix}Get`);
|
||||
const first = sectionLandingLink(schema, target, edition, canGet, hasPermission);
|
||||
if (first) navigate(`/${target.name}/${first}`);
|
||||
const nodes = layoutNavNodes(layout);
|
||||
const nav = {
|
||||
sectionName: layout.name,
|
||||
pathname,
|
||||
activeViewName: activeViewName(nodes, pathname, layout.name),
|
||||
isVisible,
|
||||
isLocked,
|
||||
openUpsell: () => setUpsellOpen(true),
|
||||
lockedHintId,
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="fixed inset-0 top-14 z-20 bg-black/40 md:hidden"
|
||||
className="fixed inset-0 top-16 z-20 bg-overlay md:hidden"
|
||||
onClick={() => setSidebarOpen(false)}
|
||||
/>
|
||||
<aside className="fixed top-14 left-0 bottom-0 z-30 flex w-64 flex-col border-r bg-background">
|
||||
<div className="flex-1 overflow-y-auto py-2 [scrollbar-width:thin]">
|
||||
<nav className="flex flex-col gap-0.5 px-2">
|
||||
{layout.items.map((item) => (
|
||||
<SidebarTopItem
|
||||
key={'link' in item ? item.link.viewName : item.container.name}
|
||||
item={item}
|
||||
sectionName={layout.name}
|
||||
currentPath={location.pathname}
|
||||
navigate={navigate}
|
||||
edition={edition}
|
||||
onUpsell={() => setUpsellOpen(true)}
|
||||
activeItemRef={activeItemRef}
|
||||
/>
|
||||
))}
|
||||
<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"
|
||||
>
|
||||
<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">
|
||||
<SidebarNavContext value={nav}>
|
||||
<NavNodes nodes={nodes} depth={0} />
|
||||
</SidebarNavContext>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
{layouts.length > 1 && (
|
||||
<TooltipProvider>
|
||||
<div className="flex items-center justify-around border-t bg-background px-2 py-2">
|
||||
{layouts.map((target) => {
|
||||
const Icon = (LucideIcons as Record<string, unknown>)[
|
||||
target.icon
|
||||
.split('-')
|
||||
.map((s) => s[0].toUpperCase() + s.slice(1))
|
||||
.join('')
|
||||
] as LucideIcons.LucideIcon | undefined;
|
||||
const isActive = target.name === activeSection;
|
||||
return (
|
||||
<Tooltip key={target.name}>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label={target.name}
|
||||
aria-current={isActive ? 'page' : undefined}
|
||||
onClick={() => handleSectionClick(target)}
|
||||
className={cn('h-9 w-9', isActive && 'bg-accent text-accent-foreground')}
|
||||
>
|
||||
{Icon ? <Icon className="h-4 w-4" /> : <LucideIcons.Circle className="h-4 w-4" />}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top">{target.name}</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
{layouts.length > 1 && <SectionSwitcher layouts={layouts} activeSection={activeSection} />}
|
||||
|
||||
<EnterpriseUpsell open={upsellOpen} onClose={() => setUpsellOpen(false)} />
|
||||
</aside>
|
||||
|
||||
@@ -6,8 +6,7 @@
|
||||
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import * as LucideIcons from 'lucide-react';
|
||||
const { Sun, Moon, User, LogOut, Check, Menu, Sparkles, Search } = LucideIcons;
|
||||
import { LogOut, Menu, Moon, Search, Sparkles, Sun, User } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { CommandPalette } from '@/components/common/CommandPalette';
|
||||
import {
|
||||
@@ -16,31 +15,25 @@ import {
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuRadioGroup,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import Logo from '@/components/common/Logo';
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import { EnterpriseUpsell } from '@/components/common/EnterpriseUpsell';
|
||||
import { visibleLayouts } from '@/lib/layout';
|
||||
import { sectionLandingLink } from '@/lib/lastVisited';
|
||||
import { DynamicIcon } from '@/components/common/DynamicIcon';
|
||||
import { useUIStore } from '@/stores/uiStore';
|
||||
import { useAuthStore } from '@/stores/authStore';
|
||||
import { buildEndSessionUrl, getPostLogoutRedirectUri } from '@/services/auth/oauth';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useAccountStore } from '@/stores/accountStore';
|
||||
import { useSchemaStore } from '@/stores/schemaStore';
|
||||
import { useIsCommunity } from '@/hooks/usePermissions';
|
||||
import { SIDEBAR_ID } from './sidebarContext';
|
||||
import { useLayoutNavigation } from './useLayoutNavigation';
|
||||
|
||||
const IS_MAC = /Mac|iPhone|iPad|iPod/.test(navigator.userAgent);
|
||||
|
||||
function getIcon(name: string): LucideIcons.LucideIcon {
|
||||
const formatted = name
|
||||
.split('-')
|
||||
.map((s) => s[0].toUpperCase() + s.slice(1))
|
||||
.join('');
|
||||
return ((LucideIcons as Record<string, unknown>)[formatted] as LucideIcons.LucideIcon) || LucideIcons.Circle;
|
||||
}
|
||||
|
||||
export function TopBar() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
@@ -52,10 +45,9 @@ export function TopBar() {
|
||||
const activeAccountId = useAuthStore((s) => s.activeAccountId);
|
||||
const switchAccount = useAuthStore((s) => s.switchAccount);
|
||||
const logout = useAuthStore((s) => s.logout);
|
||||
const edition = useAccountStore((s) => s.edition);
|
||||
const hasObjectPermission = useAccountStore((s) => s.hasObjectPermission);
|
||||
const hasPermission = useAccountStore((s) => s.hasPermission);
|
||||
const schema = useSchemaStore((s) => s.schema);
|
||||
const sidebarOpen = useUIStore((s) => s.sidebarOpen);
|
||||
const isCommunity = useIsCommunity();
|
||||
const { layouts: navigableLayouts, landingPath } = useLayoutNavigation();
|
||||
const [upsellOpen, setUpsellOpen] = useState(false);
|
||||
const [paletteOpen, setPaletteOpen] = useState(false);
|
||||
|
||||
@@ -70,92 +62,95 @@ export function TopBar() {
|
||||
return () => document.removeEventListener('keydown', handleGlobalKeyDown);
|
||||
}, []);
|
||||
|
||||
const navigableLayouts = schema
|
||||
? visibleLayouts(schema, edition, (prefix) => hasObjectPermission(prefix, 'Get'), hasPermission)
|
||||
: [];
|
||||
|
||||
return (
|
||||
<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" onClick={toggleSidebar} className="md:hidden">
|
||||
<Menu className="h-4 w-4" />
|
||||
<header className="sticky top-0 z-40 flex h-16 items-center gap-4 bg-background/80 px-4 backdrop-blur-xl backdrop-saturate-150 sm:px-5">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={toggleSidebar}
|
||||
className="md:hidden"
|
||||
aria-label={t('sidebar.toggle', 'Toggle navigation')}
|
||||
aria-expanded={sidebarOpen}
|
||||
aria-controls={SIDEBAR_ID}
|
||||
>
|
||||
<Menu aria-hidden="true" className="h-4 w-4" />
|
||||
</Button>
|
||||
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Link to="/" className="flex shrink-0 items-center">
|
||||
<Logo />
|
||||
</Link>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">
|
||||
{t('version.label', 'Stalwart WebUI v{{version}}', { version: __APP_VERSION__ })}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Link to="/" className="flex shrink-0 items-center md:w-[228px]">
|
||||
<Logo />
|
||||
</Link>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">
|
||||
{t('version.label', 'Stalwart WebUI v{{version}}', { version: __APP_VERSION__ })}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
|
||||
<div className="hidden min-w-0 flex-1 items-center justify-center px-4 md:flex">
|
||||
<div className="hidden min-w-0 flex-1 items-center md:flex">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPaletteOpen(true)}
|
||||
className="flex h-9 w-full max-w-md items-center gap-2 rounded-md border border-input bg-transparent px-3 text-sm text-muted-foreground shadow-sm transition-colors hover:bg-accent"
|
||||
className="flex h-10 w-full max-w-md items-center gap-2.5 rounded-full bg-card pl-4 pr-2 text-sm text-dim shadow-tile transition-shadow duration-200 hover:shadow-lift"
|
||||
>
|
||||
<Search className="h-4 w-4" />
|
||||
<Search aria-hidden="true" className="h-4 w-4" />
|
||||
<span className="flex-1 text-left">{t('globalSearch.placeholder', 'Search pages, fields, settings...')}</span>
|
||||
<kbd className="pointer-events-none flex h-5 select-none items-center rounded border bg-muted px-1.5 font-mono text-[10px] font-medium">
|
||||
<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"
|
||||
>
|
||||
{IS_MAC ? '⌘K' : 'Ctrl K'}
|
||||
</kbd>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="ml-auto flex items-center gap-2 md:ml-0">
|
||||
{edition !== 'enterprise' && <EnterpriseUpsell open={upsellOpen} onClose={() => setUpsellOpen(false)} />}
|
||||
<div className="ml-auto flex items-center gap-1.5">
|
||||
{isCommunity && <EnterpriseUpsell open={upsellOpen} onClose={() => setUpsellOpen(false)} />}
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="md:hidden"
|
||||
onClick={() => setPaletteOpen(true)}
|
||||
aria-label={t('search', 'Search')}
|
||||
aria-label={t('common.search', 'Search')}
|
||||
>
|
||||
<Search className="h-4 w-4" />
|
||||
<Search aria-hidden="true" className="h-4 w-4" />
|
||||
</Button>
|
||||
|
||||
<CommandPalette open={paletteOpen} onOpenChange={setPaletteOpen} />
|
||||
|
||||
<Button variant="ghost" size="icon" onClick={toggleTheme} aria-label={t('toggleTheme', 'Toggle theme')}>
|
||||
{theme === 'light' ? <Moon className="h-4 w-4" /> : <Sun className="h-4 w-4" />}
|
||||
{theme === 'light' ? (
|
||||
<Moon aria-hidden="true" className="h-4 w-4" />
|
||||
) : (
|
||||
<Sun aria-hidden="true" className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" aria-label={t('userMenu', 'User menu')}>
|
||||
<User className="h-4 w-4" />
|
||||
<Button variant="outline" size="icon-lg" aria-label={t('userMenu', 'User menu')}>
|
||||
<User aria-hidden="true" className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-56">
|
||||
{schema && navigableLayouts.length > 0 && (
|
||||
{navigableLayouts.length > 0 && (
|
||||
<>
|
||||
<DropdownMenuLabel>{t('sections', 'Sections')}</DropdownMenuLabel>
|
||||
<DropdownMenuGroup>
|
||||
{navigableLayouts.map((layout) => {
|
||||
const Icon = getIcon(layout.icon);
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={layout.name}
|
||||
onClick={() => {
|
||||
setActiveSection(layout.name);
|
||||
const canGet = (prefix: string) => hasObjectPermission(prefix, 'Get');
|
||||
const firstLink = sectionLandingLink(schema, layout, edition, canGet, hasPermission);
|
||||
if (firstLink) {
|
||||
navigate(`/${layout.name}/${firstLink}`);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Icon className="mr-2 h-4 w-4" />
|
||||
{layout.name}
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
})}
|
||||
{navigableLayouts.map((layout) => (
|
||||
<DropdownMenuItem
|
||||
key={layout.name}
|
||||
onClick={() => {
|
||||
setActiveSection(layout.name);
|
||||
const path = landingPath(layout);
|
||||
if (path) navigate(path);
|
||||
}}
|
||||
>
|
||||
<DynamicIcon name={layout.icon} className="mr-2 h-4 w-4" />
|
||||
{layout.name}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator />
|
||||
</>
|
||||
@@ -164,22 +159,21 @@ export function TopBar() {
|
||||
{Object.keys(accounts).length > 0 && (
|
||||
<>
|
||||
<DropdownMenuLabel>{t('accounts', 'Accounts')}</DropdownMenuLabel>
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuRadioGroup value={activeAccountId ?? ''} onValueChange={switchAccount}>
|
||||
{Object.entries(accounts).map(([id, info]) => (
|
||||
<DropdownMenuItem key={id} onClick={() => switchAccount(id)}>
|
||||
{id === activeAccountId && <Check className="mr-2 h-4 w-4" />}
|
||||
<span className={id !== activeAccountId ? 'ml-6' : ''}>{info.name || id}</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuRadioItem key={id} value={id}>
|
||||
{info.name || id}
|
||||
</DropdownMenuRadioItem>
|
||||
))}
|
||||
</DropdownMenuGroup>
|
||||
</DropdownMenuRadioGroup>
|
||||
<DropdownMenuSeparator />
|
||||
</>
|
||||
)}
|
||||
|
||||
{edition !== 'enterprise' && (
|
||||
{isCommunity && (
|
||||
<>
|
||||
<DropdownMenuItem onClick={() => setUpsellOpen(true)}>
|
||||
<Sparkles className="mr-2 h-4 w-4" />
|
||||
<Sparkles aria-hidden="true" className="mr-2 h-4 w-4" />
|
||||
{t('tryEnterprise', 'Try Enterprise')}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
@@ -189,15 +183,18 @@ export function TopBar() {
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
const endSessionEndpoint = useAuthStore.getState().endSessionEndpoint;
|
||||
const endSessionUrl = endSessionEndpoint
|
||||
? buildEndSessionUrl(endSessionEndpoint, getPostLogoutRedirectUri())
|
||||
: null;
|
||||
logout();
|
||||
if (endSessionEndpoint) {
|
||||
window.location.href = buildEndSessionUrl(endSessionEndpoint, getPostLogoutRedirectUri());
|
||||
if (endSessionUrl) {
|
||||
window.location.href = endSessionUrl;
|
||||
} else {
|
||||
navigate('/login');
|
||||
}
|
||||
}}
|
||||
>
|
||||
<LogOut className="mr-2 h-4 w-4" />
|
||||
<LogOut aria-hidden="true" className="mr-2 h-4 w-4" />
|
||||
{t('logout', 'Logout')}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import type { Layout, LayoutItem, LayoutSubItem } from '@/types/schema';
|
||||
|
||||
export type NavNode =
|
||||
| { kind: 'link'; name: string; icon?: string; viewName: string }
|
||||
| { kind: 'container'; name: string; icon?: string; children: NavNode[] };
|
||||
|
||||
function fromSubItem(item: LayoutSubItem): NavNode | null {
|
||||
if (item.type === 'link') return { kind: 'link', name: item.name, viewName: item.viewName };
|
||||
if (item.type === 'container') return { kind: 'container', name: item.name, children: fromSubItems(item.items) };
|
||||
return null;
|
||||
}
|
||||
|
||||
function fromSubItems(items: LayoutSubItem[]): NavNode[] {
|
||||
return items.map(fromSubItem).filter((n): n is NavNode => n !== null);
|
||||
}
|
||||
|
||||
function fromItem(item: LayoutItem): NavNode | null {
|
||||
if ('link' in item) return { kind: 'link', ...item.link };
|
||||
if ('container' in item) {
|
||||
const { name, icon, items } = item.container;
|
||||
return { kind: 'container', name, icon, children: fromSubItems(items) };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function layoutNavNodes(layout: Layout): NavNode[] {
|
||||
return layout.items.map(fromItem).filter((n): n is NavNode => n !== null);
|
||||
}
|
||||
|
||||
export function navNodeKey(node: NavNode): string {
|
||||
return node.kind === 'link' ? `link:${node.viewName}` : `container:${node.name}`;
|
||||
}
|
||||
|
||||
export function viewPath(sectionName: string, viewName: string): string {
|
||||
return `/${sectionName}/${viewName}`;
|
||||
}
|
||||
|
||||
export function pathMatchesView(pathname: string, sectionName: string, viewName: string): boolean {
|
||||
const base = viewPath(sectionName, viewName);
|
||||
if (pathname === base || pathname.startsWith(`${base}/`)) return true;
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
if (viewName === 'CustomComponent/Dashboard' && pathname.startsWith(`/${sectionName}/Dashboard/`)) return true;
|
||||
// SPDX-SnippetEnd
|
||||
return false;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { createContext, useContext } from 'react';
|
||||
|
||||
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;
|
||||
lockedHintId: string;
|
||||
}
|
||||
|
||||
export const SidebarNavContext = createContext<SidebarNavContextValue | null>(null);
|
||||
|
||||
export function useSidebarNav(): SidebarNavContextValue {
|
||||
const ctx = useContext(SidebarNavContext);
|
||||
if (!ctx) throw new Error('useSidebarNav must be used inside SidebarNavContext');
|
||||
return ctx;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useAccountStore } from '@/stores/accountStore';
|
||||
import { useSchemaStore } from '@/stores/schemaStore';
|
||||
import { useIsCommunity, usePermissionCheckers } from '@/hooks/usePermissions';
|
||||
import { isLinkEnterprise, isLinkVisible, visibleLayouts } from '@/lib/layout';
|
||||
import { sectionLandingLink } from '@/lib/lastVisited';
|
||||
import type { Layout } from '@/types/schema';
|
||||
import { viewPath } from './navTree';
|
||||
|
||||
export function useLayoutNavigation() {
|
||||
const schema = useSchemaStore((s) => s.schema);
|
||||
const edition = useAccountStore((s) => s.edition);
|
||||
const isCommunity = useIsCommunity();
|
||||
const { canGet, hasPermission } = usePermissionCheckers();
|
||||
|
||||
const layouts = schema ? visibleLayouts(schema, canGet, hasPermission) : [];
|
||||
|
||||
return {
|
||||
layouts,
|
||||
isVisible: (viewName: string) => !schema || isLinkVisible(schema, viewName, canGet, hasPermission),
|
||||
isLocked: (viewName: string) => isCommunity && !!schema && isLinkEnterprise(schema, viewName),
|
||||
landingPath: (layout: Layout): string | null => {
|
||||
if (!schema) return null;
|
||||
const link = sectionLandingLink(schema, layout, edition, canGet, hasPermission);
|
||||
return link ? viewPath(layout.name, link) : null;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* 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 { 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;
|
||||
sort: ListSort | null;
|
||||
onSort: (field: string) => void;
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
if (!sortable) {
|
||||
return (
|
||||
<th scope="col" className={className}>
|
||||
{column.label}
|
||||
</th>
|
||||
);
|
||||
}
|
||||
|
||||
const hint =
|
||||
direction === 'none'
|
||||
? t('list.sortAscending', 'Sort ascending')
|
||||
: direction === 'ascending'
|
||||
? t('list.sortDescending', 'Sort descending')
|
||||
: t('list.sortClear', 'Clear sort');
|
||||
|
||||
return (
|
||||
<th scope="col" aria-sort={direction} className={className}>
|
||||
<button
|
||||
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"
|
||||
>
|
||||
{column.label}
|
||||
{direction === 'ascending' ? (
|
||||
<ChevronUp className="h-3.5 w-3.5" aria-hidden />
|
||||
) : direction === 'descending' ? (
|
||||
<ChevronDown className="h-3.5 w-3.5" aria-hidden />
|
||||
) : (
|
||||
<ArrowUpDown className="h-3 w-3" aria-hidden />
|
||||
)}
|
||||
</button>
|
||||
</th>
|
||||
);
|
||||
}
|
||||
+264
-1330
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,122 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useId, useState, type FormEvent } from 'react';
|
||||
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';
|
||||
import { FilterField } from './FilterFields';
|
||||
|
||||
interface FilterBarProps {
|
||||
schema: Schema;
|
||||
filters: Filter[];
|
||||
applied: Record<string, string>;
|
||||
isXPrefixed: boolean;
|
||||
disabled: boolean;
|
||||
onApply: (values: Record<string, string>) => void;
|
||||
onReset: () => void;
|
||||
}
|
||||
|
||||
export function FilterBar({ schema, filters, applied, isXPrefixed, disabled, onApply, onReset }: FilterBarProps) {
|
||||
const { t } = useTranslation();
|
||||
const panelId = useId();
|
||||
const appliedKey = filtersKey(applied);
|
||||
const [open, setOpen] = useState(() => Object.keys(applied).length > 0);
|
||||
const [draft, setDraft] = useState<Record<string, string> | null>(null);
|
||||
const [draftKey, setDraftKey] = useState(appliedKey);
|
||||
if (draftKey !== appliedKey) {
|
||||
setDraftKey(appliedKey);
|
||||
setDraft(null);
|
||||
}
|
||||
const values = draft ?? applied;
|
||||
|
||||
const setValue = (field: string, value: string) => setDraft({ ...values, [field]: value });
|
||||
|
||||
const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
setDraft(null);
|
||||
onApply(values);
|
||||
};
|
||||
|
||||
const handleReset = () => {
|
||||
setDraft(null);
|
||||
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>
|
||||
<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"
|
||||
>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{filters.map((filter) => (
|
||||
<FilterField
|
||||
key={filter.field}
|
||||
schema={schema}
|
||||
filter={filter}
|
||||
values={values}
|
||||
isXPrefixed={isXPrefixed}
|
||||
onChange={setValue}
|
||||
onCommit={(field, value) => onApply({ ...applied, [field]: value })}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-4 flex items-center justify-end gap-2">
|
||||
<Button type="button" variant="ghost" size="sm" onClick={handleReset} disabled={disabled}>
|
||||
<RotateCcw aria-hidden />
|
||||
{t('list.resetFilters', 'Reset')}
|
||||
</Button>
|
||||
<Button type="submit" size="sm" disabled={disabled}>
|
||||
<Search aria-hidden />
|
||||
{t('list.searchFilters', 'Search')}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useId, type ReactNode } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
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';
|
||||
|
||||
const ENUM_FILTER_COMBOBOX_THRESHOLD = 15;
|
||||
const ALL_VALUE = '__all__';
|
||||
const DEFAULT_OP = 'eq';
|
||||
|
||||
interface FilterFieldProps<F extends Filter> {
|
||||
schema: Schema;
|
||||
filter: F;
|
||||
values: Record<string, string>;
|
||||
isXPrefixed: boolean;
|
||||
onChange: (field: string, value: string) => void;
|
||||
onCommit: (field: string, value: string) => void;
|
||||
}
|
||||
|
||||
function opField(filter: Filter): string {
|
||||
return `${filter.field}Op`;
|
||||
}
|
||||
|
||||
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">
|
||||
{label}
|
||||
</label>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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">
|
||||
{label}
|
||||
</span>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TextFilter({ filter, values, onChange }: FilterFieldProps<FilterText>) {
|
||||
const { t } = useTranslation();
|
||||
const id = useId();
|
||||
return (
|
||||
<LabelledField id={id} label={filter.label}>
|
||||
<SearchInput
|
||||
id={id}
|
||||
placeholder={t('list.filterPlaceholder', 'Search {{label}}...', { label: filter.label.toLowerCase() })}
|
||||
value={values[filter.field] ?? ''}
|
||||
onValueChange={(next) => onChange(filter.field, next)}
|
||||
/>
|
||||
</LabelledField>
|
||||
);
|
||||
}
|
||||
|
||||
function EnumFilter({ schema, filter, values, onChange }: FilterFieldProps<FilterEnum>) {
|
||||
const { t } = useTranslation();
|
||||
const id = useId();
|
||||
const variants = getEnum(schema, filter.enumName);
|
||||
const value = values[filter.field] || ALL_VALUE;
|
||||
const handleChange = (next: string) => onChange(filter.field, next === ALL_VALUE ? '' : next);
|
||||
|
||||
if (variants.length > ENUM_FILTER_COMBOBOX_THRESHOLD) {
|
||||
return (
|
||||
<GroupField label={filter.label}>
|
||||
<Combobox
|
||||
options={[
|
||||
{ value: ALL_VALUE, label: t('filters.all', 'All') },
|
||||
...variants.map((v) => ({ value: v.name, label: v.label })),
|
||||
]}
|
||||
value={value}
|
||||
onValueChange={handleChange}
|
||||
searchPlaceholder={t('common.searchPlaceholder', 'Search...')}
|
||||
emptyText={t('field.noMatches', 'No matches')}
|
||||
/>
|
||||
</GroupField>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<LabelledField id={id} label={filter.label}>
|
||||
<Select value={value} onValueChange={handleChange}>
|
||||
<SelectTrigger id={id}>
|
||||
<SelectValue placeholder={filter.label} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={ALL_VALUE}>{t('filters.all', 'All')}</SelectItem>
|
||||
{variants.map((v) => (
|
||||
<SelectItem key={v.name} value={v.name}>
|
||||
{v.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</LabelledField>
|
||||
);
|
||||
}
|
||||
|
||||
interface OperatorOption {
|
||||
value: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
function ComparisonFilter({
|
||||
filter,
|
||||
values,
|
||||
isXPrefixed,
|
||||
onChange,
|
||||
inputType,
|
||||
operators,
|
||||
operatorWidth,
|
||||
}: FilterFieldProps<FilterInteger | FilterDate> & {
|
||||
inputType: 'number' | 'date';
|
||||
operators: OperatorOption[];
|
||||
operatorWidth: string;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const id = useId();
|
||||
const input = (
|
||||
<Input
|
||||
id={id}
|
||||
type={inputType}
|
||||
placeholder={inputType === 'number' ? filter.label : undefined}
|
||||
value={values[filter.field] ?? ''}
|
||||
onChange={(e) => onChange(filter.field, e.target.value)}
|
||||
className={isXPrefixed ? 'flex-1' : undefined}
|
||||
/>
|
||||
);
|
||||
|
||||
if (!isXPrefixed) {
|
||||
return (
|
||||
<LabelledField id={id} label={filter.label}>
|
||||
{input}
|
||||
</LabelledField>
|
||||
);
|
||||
}
|
||||
|
||||
const op = opField(filter);
|
||||
return (
|
||||
<LabelledField id={id} label={filter.label}>
|
||||
<div className="flex gap-2">
|
||||
<Select value={values[op] || DEFAULT_OP} onValueChange={(v) => onChange(op, v)}>
|
||||
<SelectTrigger
|
||||
className={`${operatorWidth} shrink-0`}
|
||||
aria-label={t('list.filterOperator', '{{label}} comparison', { label: filter.label })}
|
||||
>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{operators.map((o) => (
|
||||
<SelectItem key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{input}
|
||||
</div>
|
||||
</LabelledField>
|
||||
);
|
||||
}
|
||||
|
||||
const INTEGER_OPERATORS: OperatorOption[] = [
|
||||
{ value: 'eq', label: '=' },
|
||||
{ value: 'gt', label: '>' },
|
||||
{ value: 'lt', label: '<' },
|
||||
{ value: 'gte', label: '>=' },
|
||||
{ value: 'lte', label: '<=' },
|
||||
];
|
||||
|
||||
function IntegerFilter(props: FilterFieldProps<FilterInteger>) {
|
||||
return <ComparisonFilter {...props} inputType="number" operators={INTEGER_OPERATORS} operatorWidth="w-20" />;
|
||||
}
|
||||
|
||||
function DateFilter(props: FilterFieldProps<FilterDate>) {
|
||||
const { t } = useTranslation();
|
||||
const operators = [
|
||||
{ value: 'eq', label: t('filters.on', 'On') },
|
||||
{ value: 'gt', label: t('filters.after', 'After') },
|
||||
{ value: 'lt', label: t('filters.before', 'Before') },
|
||||
];
|
||||
return <ComparisonFilter {...props} inputType="date" operators={operators} operatorWidth="w-24" />;
|
||||
}
|
||||
|
||||
function ObjectIdFilter({ schema, filter, values, onCommit }: FilterFieldProps<FilterObjectId>) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<GroupField label={filter.label}>
|
||||
<ObjectPicker
|
||||
schema={schema}
|
||||
objectName={filter.objectName}
|
||||
label={filter.label}
|
||||
value={values[filter.field] ?? ''}
|
||||
onChange={(id) => onCommit(filter.field, id)}
|
||||
onClear={() => onCommit(filter.field, '')}
|
||||
placeholder={t('list.selectFilterPlaceholder', 'Select {{label}}...', {
|
||||
label: filter.label.toLowerCase(),
|
||||
})}
|
||||
/>
|
||||
</GroupField>
|
||||
);
|
||||
}
|
||||
|
||||
export function FilterField(props: FilterFieldProps<Filter>) {
|
||||
const { filter } = props;
|
||||
switch (filter.type) {
|
||||
case 'text':
|
||||
return <TextFilter {...props} filter={filter} />;
|
||||
case 'enum':
|
||||
return <EnumFilter {...props} filter={filter} />;
|
||||
case 'integer':
|
||||
return <IntegerFilter {...props} filter={filter} />;
|
||||
case 'date':
|
||||
return <DateFilter {...props} filter={filter} />;
|
||||
case 'objectId':
|
||||
return <ObjectIdFilter {...props} filter={filter} />;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { FieldValue, VariantValue } from '@/components/values/FieldValue';
|
||||
import { EmptyValue } from '@/components/values/ScalarValues';
|
||||
import type { Field, Schema } from '@/types/schema';
|
||||
import { scalarText } from './listQuery';
|
||||
|
||||
interface ListCellProps {
|
||||
schema: Schema;
|
||||
objectName: string;
|
||||
column: string;
|
||||
field: Field | undefined;
|
||||
value: unknown;
|
||||
}
|
||||
|
||||
export function ListCell({ schema, objectName, column, field, value }: ListCellProps) {
|
||||
if (field) return <FieldValue schema={schema} type={field.type} value={value} variant="compact" />;
|
||||
if (column === '@type' && typeof value === 'string' && value) {
|
||||
return <VariantValue schema={schema} objectName={objectName} value={value} />;
|
||||
}
|
||||
const text = scalarText(value);
|
||||
return text ? <>{text}</> : <EmptyValue variant="compact" />;
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import type { ReactNode } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Loader2, X } from 'lucide-react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
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 />
|
||||
<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>;
|
||||
}
|
||||
|
||||
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">
|
||||
{children}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
}
|
||||
|
||||
export function ListError({
|
||||
message,
|
||||
onRetry,
|
||||
onDismiss,
|
||||
}: {
|
||||
message: string;
|
||||
onRetry?: () => void;
|
||||
onDismiss?: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div
|
||||
role="alert"
|
||||
className="flex items-start justify-between gap-3 rounded-xl bg-destructive-soft p-4 text-sm text-destructive"
|
||||
>
|
||||
<span className="whitespace-pre-line">{message}</span>
|
||||
<div className="flex shrink-0 items-center gap-1">
|
||||
{onRetry && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 text-destructive hover:bg-destructive/10 hover:text-destructive"
|
||||
onClick={onRetry}
|
||||
>
|
||||
{t('common.retry', 'Retry')}
|
||||
</Button>
|
||||
)}
|
||||
{onDismiss && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7 text-destructive hover:bg-destructive/10 hover:text-destructive"
|
||||
onClick={onDismiss}
|
||||
aria-label={t('common.close', 'Close')}
|
||||
>
|
||||
<X className="h-4 w-4" aria-hidden />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import type { MouseEvent, ReactNode } from 'react';
|
||||
import { Link, useNavigate } 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 { ListSpinner, ListTableMessage } from './ListStates';
|
||||
import { itemId, type ListItem } from './listQuery';
|
||||
import type { ListSort } from './listUrlState';
|
||||
import type { ListSelection } from './useListSelection';
|
||||
|
||||
interface ListTableProps {
|
||||
caption: string;
|
||||
columns: Column[];
|
||||
fields: Record<string, Field>;
|
||||
items: ListItem[];
|
||||
schema: Schema;
|
||||
objectName: string;
|
||||
sort: ListSort | null;
|
||||
sortable: ReadonlySet<string>;
|
||||
onSort: (field: string) => void;
|
||||
selection: ListSelection | null;
|
||||
rowHref: (id: string) => string | null;
|
||||
rowLabel: (item: ListItem) => string;
|
||||
renderRowActions: ((item: ListItem, id: string, label: string) => ReactNode) | null;
|
||||
loading: boolean;
|
||||
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
|
||||
);
|
||||
}
|
||||
|
||||
export function ListTable({
|
||||
caption,
|
||||
columns,
|
||||
fields,
|
||||
items,
|
||||
schema,
|
||||
objectName,
|
||||
sort,
|
||||
sortable,
|
||||
onSort,
|
||||
selection,
|
||||
rowHref,
|
||||
rowLabel,
|
||||
renderRowActions,
|
||||
loading,
|
||||
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);
|
||||
return id ? [{ item, id }] : [];
|
||||
});
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<td key={col.name} className={BODY_CELL}>
|
||||
{content}
|
||||
</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>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
* 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 { ChevronUp, X } from 'lucide-react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { FloatingActionBar, FloatingActionDivider, FloatingActionDot } from '@/components/common/FloatingActionBar';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import type { MassAction } from '@/types/schema';
|
||||
|
||||
export type RunnableMassAction = Exclude<MassAction, { type: 'separator' }>;
|
||||
|
||||
interface MassActionBarProps {
|
||||
actions: { key: string; action: MassAction }[];
|
||||
count: number;
|
||||
disabled: boolean;
|
||||
onSelect: (action: RunnableMassAction) => void;
|
||||
onClear: () => void;
|
||||
}
|
||||
|
||||
export function MassActionBar({ actions, count, disabled, onSelect, onClear }: 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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* 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 { ChevronLeft, ChevronRight } from 'lucide-react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import type { PageRange } from './listQuery';
|
||||
|
||||
interface PaginationProps {
|
||||
range: PageRange;
|
||||
total: number | null;
|
||||
count: number;
|
||||
pluralName: string;
|
||||
disabled: boolean;
|
||||
onPrev: () => void;
|
||||
onNext: () => void;
|
||||
}
|
||||
|
||||
export function Pagination({ range, total, count, pluralName, disabled, onPrev, onNext }: PaginationProps) {
|
||||
const { t } = useTranslation();
|
||||
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"
|
||||
>
|
||||
<p aria-live="polite">
|
||||
{total !== null
|
||||
? t('list.showing', 'Showing {{from}}-{{to}} of {{total}} {{name}}', {
|
||||
from: range.from,
|
||||
to: range.to,
|
||||
total,
|
||||
name: pluralName,
|
||||
})
|
||||
: 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 />
|
||||
{t('list.previous', 'Previous')}
|
||||
</Button>
|
||||
<Button variant="secondary" size="sm" disabled={!range.hasNext || disabled} onClick={onNext}>
|
||||
{t('list.next', 'Next')}
|
||||
<ChevronRight aria-hidden />
|
||||
</Button>
|
||||
</div>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { Link } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Lock, MoreHorizontal } from 'lucide-react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import type { ResolvedItemAction } from './listActions';
|
||||
|
||||
type NavigateAction = Extract<ResolvedItemAction, { kind: 'navigate' }>;
|
||||
type MutationAction = Extract<ResolvedItemAction, { kind: 'mutation' }>;
|
||||
|
||||
interface RowActionsProps {
|
||||
actions: ResolvedItemAction[];
|
||||
label: string;
|
||||
hrefFor: (action: NavigateAction) => string | null;
|
||||
onMutation: (action: MutationAction) => void;
|
||||
onLocked: () => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export function RowActions({ actions, label, hrefFor, onMutation, onLocked, disabled = false }: RowActionsProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
disabled={disabled}
|
||||
aria-label={t('list.actionsFor', 'Actions for {{label}}', { label })}
|
||||
>
|
||||
<MoreHorizontal className="h-4 w-4" aria-hidden />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{actions.map((entry) => {
|
||||
if (entry.kind === 'separator') return <DropdownMenuSeparator key={entry.key} />;
|
||||
if (entry.kind === 'mutation') {
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={entry.key}
|
||||
className={
|
||||
entry.action.type === 'delete'
|
||||
? 'text-destructive focus:bg-destructive-soft focus:text-destructive'
|
||||
: undefined
|
||||
}
|
||||
onSelect={() => onMutation(entry)}
|
||||
>
|
||||
{entry.action.label}
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
}
|
||||
if (entry.locked) {
|
||||
return (
|
||||
<DropdownMenuItem key={entry.key} onSelect={onLocked}>
|
||||
{entry.label}
|
||||
<Lock className="ml-auto h-3 w-3 text-dim" aria-hidden />
|
||||
<span className="sr-only">
|
||||
{t('enterprise.featureDisabled', 'This feature requires an Enterprise license.')}
|
||||
</span>
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
}
|
||||
const href = hrefFor(entry);
|
||||
if (!href) return null;
|
||||
return (
|
||||
<DropdownMenuItem key={entry.key} asChild>
|
||||
<Link to={href}>{entry.label}</Link>
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
})}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
interface SelectionBannerProps {
|
||||
allMatching: boolean;
|
||||
pageCount: number;
|
||||
total: number | null;
|
||||
pluralName: string;
|
||||
onSelectAllMatching: () => void;
|
||||
onClear: () => void;
|
||||
}
|
||||
|
||||
export function SelectionBanner({
|
||||
allMatching,
|
||||
pageCount,
|
||||
total,
|
||||
pluralName,
|
||||
onSelectAllMatching,
|
||||
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';
|
||||
|
||||
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]"
|
||||
>
|
||||
{t('list.allMatchingSelected', 'All {{total}} {{name}} matching the current filters are selected.', {
|
||||
total: total ?? 0,
|
||||
name: pluralName,
|
||||
})}{' '}
|
||||
<button type="button" className={linkClass} onClick={onClear}>
|
||||
{t('list.clearSelection', 'Clear selection')}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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]"
|
||||
>
|
||||
{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', {
|
||||
total,
|
||||
name: pluralName,
|
||||
})}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { resolveObject } from '@/lib/schemaResolver';
|
||||
import type { ObjectAction } from '@/lib/permissions';
|
||||
import type { ItemAction, MassAction, Schema } from '@/types/schema';
|
||||
import { filteredListSearch } from './listUrlState';
|
||||
|
||||
export interface ActionPermissions {
|
||||
hasObjectPermission: (permissionPrefix: string, action: ObjectAction) => boolean;
|
||||
isCommunity: boolean;
|
||||
}
|
||||
|
||||
export type ResolvedItemAction =
|
||||
| { key: string; kind: 'separator' }
|
||||
| { key: string; kind: 'navigate'; label: string; objectName: string; fieldName?: string; locked: boolean }
|
||||
| { key: string; kind: 'mutation'; action: Extract<ItemAction, { type: 'delete' | 'setProperty' }> };
|
||||
|
||||
function actionIdentity(action: ItemAction | MassAction): string {
|
||||
switch (action.type) {
|
||||
case 'separator':
|
||||
return 'separator';
|
||||
case 'view':
|
||||
return `view:${action.objectName}:${action.label}`;
|
||||
case 'query':
|
||||
return `query:${action.objectName}:${action.fieldName}:${action.label}`;
|
||||
default:
|
||||
return `${action.type}:${action.label}`;
|
||||
}
|
||||
}
|
||||
|
||||
export function withStableKeys<T extends ItemAction | MassAction>(actions: readonly T[]): { key: string; action: T }[] {
|
||||
const seen = new Map<string, number>();
|
||||
return actions.map((action) => {
|
||||
const base = actionIdentity(action);
|
||||
const count = seen.get(base) ?? 0;
|
||||
seen.set(base, count + 1);
|
||||
return { key: count === 0 ? base : `${base}#${count}`, action };
|
||||
});
|
||||
}
|
||||
|
||||
export function trimSeparators<T>(entries: T[], isSep: (entry: T) => boolean): T[] {
|
||||
const out: T[] = [];
|
||||
for (const entry of entries) {
|
||||
if (isSep(entry) && (out.length === 0 || isSep(out[out.length - 1]))) continue;
|
||||
out.push(entry);
|
||||
}
|
||||
while (out.length > 0 && isSep(out[out.length - 1])) out.pop();
|
||||
return out;
|
||||
}
|
||||
|
||||
export function resolveItemActions(
|
||||
schema: Schema,
|
||||
actions: readonly ItemAction[] | undefined,
|
||||
permissionPrefix: string,
|
||||
perms: ActionPermissions,
|
||||
): ResolvedItemAction[] {
|
||||
if (!actions || actions.length === 0) return [];
|
||||
const out: ResolvedItemAction[] = [];
|
||||
for (const { key, action } of withStableKeys(actions)) {
|
||||
switch (action.type) {
|
||||
case 'separator':
|
||||
out.push({ key, kind: 'separator' });
|
||||
break;
|
||||
case 'delete':
|
||||
if (perms.hasObjectPermission(permissionPrefix, 'Destroy')) out.push({ key, kind: 'mutation', action });
|
||||
break;
|
||||
case 'setProperty':
|
||||
if (perms.hasObjectPermission(permissionPrefix, 'Update')) out.push({ key, kind: 'mutation', action });
|
||||
break;
|
||||
case 'view':
|
||||
case 'query': {
|
||||
const target = resolveObject(schema, action.objectName);
|
||||
if (!target) break;
|
||||
const locked = !!target.enterprise && perms.isCommunity;
|
||||
if (!locked && !perms.hasObjectPermission(target.permissionPrefix, 'Get')) break;
|
||||
out.push({
|
||||
key,
|
||||
kind: 'navigate',
|
||||
label: action.label,
|
||||
objectName: action.objectName,
|
||||
fieldName: action.type === 'query' ? action.fieldName : undefined,
|
||||
locked,
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return trimSeparators(out, (entry) => entry.kind === 'separator');
|
||||
}
|
||||
|
||||
export function itemActionHref(
|
||||
action: Extract<ResolvedItemAction, { kind: 'navigate' }>,
|
||||
itemId: string,
|
||||
sectionFor: (viewName: string) => string | undefined,
|
||||
fallbackSection: string | undefined,
|
||||
viewFor: (objectName: string) => string | null = () => null,
|
||||
): string | null {
|
||||
const target = viewFor(action.objectName) ?? action.objectName;
|
||||
const section = sectionFor(target) ?? fallbackSection;
|
||||
if (!section) return null;
|
||||
if (action.fieldName === undefined) return `/${section}/${target}/${itemId}`;
|
||||
return `/${section}/${target}?${filteredListSearch(action.fieldName, itemId)}`;
|
||||
}
|
||||
|
||||
export interface ObjectKindInfo {
|
||||
isObject: boolean;
|
||||
permissionPrefix: string;
|
||||
}
|
||||
|
||||
export function resolveMassActions(
|
||||
actions: readonly MassAction[] | undefined,
|
||||
info: ObjectKindInfo,
|
||||
perms: Pick<ActionPermissions, 'hasObjectPermission'>,
|
||||
defaultDeleteLabel: string,
|
||||
): { key: string; action: MassAction }[] {
|
||||
const canDestroy = info.isObject && perms.hasObjectPermission(info.permissionPrefix, 'Destroy');
|
||||
const canUpdate = perms.hasObjectPermission(info.permissionPrefix, 'Update');
|
||||
const base = [...(actions ?? [])];
|
||||
if (canDestroy && !base.some((a) => a.type === 'delete')) {
|
||||
base.push({ type: 'delete', label: defaultDeleteLabel });
|
||||
}
|
||||
const allowed = withStableKeys(base).filter(({ action }) => {
|
||||
if (action.type === 'delete') return canDestroy;
|
||||
if (action.type === 'setProperty') return canUpdate;
|
||||
return true;
|
||||
});
|
||||
return trimSeparators(allowed, (entry) => entry.action.type === 'separator');
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { buildJmapFilter } from '@/lib/listFilter';
|
||||
import type { ListPageParams } from '@/data/keys';
|
||||
import type { ResolvedSchema } from '@/lib/schemaResolver';
|
||||
import type { Field, List } from '@/types/schema';
|
||||
import type { ListSort, ListUrlState } from './listUrlState';
|
||||
|
||||
export const LIST_PAGE_SIZE = 25;
|
||||
|
||||
export type ListItem = Record<string, unknown>;
|
||||
|
||||
export function getListFields(resolvedSchema: ResolvedSchema): Record<string, Field> {
|
||||
if (resolvedSchema.type === 'single') return resolvedSchema.fields.properties;
|
||||
const merged: Record<string, Field> = {};
|
||||
for (const variant of resolvedSchema.variants) {
|
||||
if (variant.fields) Object.assign(merged, variant.fields.properties);
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
export function buildListFilter(
|
||||
filters: Record<string, string>,
|
||||
list: Pick<List, 'filters' | 'filtersStatic'>,
|
||||
objectName: string,
|
||||
): Record<string, unknown> | undefined {
|
||||
const filter = buildJmapFilter({
|
||||
appliedFilters: filters,
|
||||
filters: list.filters,
|
||||
filtersStatic: list.filtersStatic,
|
||||
isXPrefixed: objectName.startsWith('x:'),
|
||||
});
|
||||
return Object.keys(filter).length > 0 ? filter : undefined;
|
||||
}
|
||||
|
||||
export function effectiveSort(sort: ListSort | null, list: Pick<List, 'sort'>): ListSort | null {
|
||||
return sort && list.sort?.includes(sort.field) ? sort : null;
|
||||
}
|
||||
|
||||
export function buildListSort(sort: ListSort | null): Record<string, unknown>[] | undefined {
|
||||
return sort ? [{ property: sort.field, isAscending: sort.ascending }] : undefined;
|
||||
}
|
||||
|
||||
export function buildListPageParams(
|
||||
state: ListUrlState,
|
||||
list: Pick<List, 'filters' | 'filtersStatic' | 'columns' | 'sort'>,
|
||||
objectName: string,
|
||||
pageSize = LIST_PAGE_SIZE,
|
||||
labelProperty?: string,
|
||||
): ListPageParams {
|
||||
const properties = ['id', ...list.columns.map((c) => c.name)];
|
||||
if (labelProperty && !properties.includes(labelProperty)) properties.push(labelProperty);
|
||||
const params: ListPageParams = {
|
||||
filter: buildListFilter(state.filters, list, objectName),
|
||||
sort: buildListSort(effectiveSort(state.sort, list)),
|
||||
limit: pageSize,
|
||||
calculateTotal: true,
|
||||
properties,
|
||||
};
|
||||
const anchor = state.anchors[state.anchors.length - 1];
|
||||
if (anchor === undefined) {
|
||||
params.position = 0;
|
||||
} else {
|
||||
params.anchor = anchor;
|
||||
params.anchorOffset = 1;
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
export function isStrandedPage(anchors: number, count: number, settled: boolean): boolean {
|
||||
return settled && count === 0 && anchors > 0;
|
||||
}
|
||||
|
||||
export function scalarText(value: unknown): string | null {
|
||||
if (typeof value === 'string') return value || null;
|
||||
if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') return String(value);
|
||||
return null;
|
||||
}
|
||||
|
||||
export function itemId(item: ListItem): string | null {
|
||||
return typeof item.id === 'string' && item.id ? item.id : null;
|
||||
}
|
||||
|
||||
export function itemLabel(item: ListItem, labelProperty: string): string {
|
||||
const value = item[labelProperty];
|
||||
if (typeof value === 'string' && value) return value;
|
||||
if (typeof value === 'number') return String(value);
|
||||
return itemId(item) ?? '';
|
||||
}
|
||||
|
||||
export interface PageRange {
|
||||
from: number;
|
||||
to: number;
|
||||
hasPrev: boolean;
|
||||
hasNext: boolean;
|
||||
}
|
||||
|
||||
export function pageRange(
|
||||
position: number,
|
||||
count: number,
|
||||
total: number | null,
|
||||
anchors: number,
|
||||
pageSize = LIST_PAGE_SIZE,
|
||||
): PageRange {
|
||||
const start = position > 0 || anchors === 0 ? position : anchors * pageSize;
|
||||
return {
|
||||
from: count > 0 ? start + 1 : 0,
|
||||
to: start + count,
|
||||
hasPrev: anchors > 0,
|
||||
hasNext: total !== null ? start + count < total : count >= pageSize,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { isFilterOp } from '@/lib/listFilter';
|
||||
|
||||
export interface ListSort {
|
||||
field: string;
|
||||
ascending: boolean;
|
||||
}
|
||||
|
||||
export interface ListUrlState {
|
||||
filters: Record<string, string>;
|
||||
sort: ListSort | null;
|
||||
anchors: string[];
|
||||
}
|
||||
|
||||
export const FILTER_PARAM_PREFIX = 'f.';
|
||||
export const SORT_PARAM = 'sort';
|
||||
export const SORT_DIR_PARAM = 'sortDir';
|
||||
export const ANCHORS_PARAM = 'after';
|
||||
const ANCHOR_SEPARATOR = ',';
|
||||
const OP_SUFFIX = 'Op';
|
||||
const DEFAULT_OP = 'eq';
|
||||
|
||||
export function normalizeFilters(values: Record<string, string>): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
for (const [key, value] of Object.entries(values)) {
|
||||
if (value === '' || value == null) continue;
|
||||
if (key.endsWith(OP_SUFFIX)) {
|
||||
const base = key.slice(0, -OP_SUFFIX.length);
|
||||
if (value === DEFAULT_OP || !isFilterOp(value) || !Object.hasOwn(values, base) || !values[base]) continue;
|
||||
}
|
||||
out[key] = value;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function parseListSearch(params: URLSearchParams): ListUrlState {
|
||||
const filters: Record<string, string> = {};
|
||||
params.forEach((value, key) => {
|
||||
if (key.startsWith(FILTER_PARAM_PREFIX) && key.length > FILTER_PARAM_PREFIX.length) {
|
||||
filters[key.slice(FILTER_PARAM_PREFIX.length)] = value;
|
||||
}
|
||||
});
|
||||
const sortField = params.get(SORT_PARAM);
|
||||
const sort = sortField ? { field: sortField, ascending: params.get(SORT_DIR_PARAM) !== 'desc' } : null;
|
||||
const anchors = (params.get(ANCHORS_PARAM) ?? '').split(ANCHOR_SEPARATOR).filter((id) => id.length > 0);
|
||||
return { filters: normalizeFilters(filters), sort, anchors };
|
||||
}
|
||||
|
||||
export function serializeListSearch(state: ListUrlState): URLSearchParams {
|
||||
const params = new URLSearchParams();
|
||||
for (const [key, value] of Object.entries(normalizeFilters(state.filters))) {
|
||||
params.set(`${FILTER_PARAM_PREFIX}${key}`, value);
|
||||
}
|
||||
if (state.sort) {
|
||||
params.set(SORT_PARAM, state.sort.field);
|
||||
params.set(SORT_DIR_PARAM, state.sort.ascending ? 'asc' : 'desc');
|
||||
}
|
||||
if (state.anchors.length > 0) {
|
||||
params.set(ANCHORS_PARAM, state.anchors.join(ANCHOR_SEPARATOR));
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
export function listStateKey(state: ListUrlState): string {
|
||||
return serializeListSearch(state).toString();
|
||||
}
|
||||
|
||||
export function filtersKey(filters: Record<string, string>): string {
|
||||
return serializeListSearch({ filters, sort: null, anchors: [] }).toString();
|
||||
}
|
||||
|
||||
export function nextSort(current: ListSort | null, field: string): ListSort | null {
|
||||
if (current?.field !== field) return { field, ascending: true };
|
||||
if (current.ascending) return { field, ascending: false };
|
||||
return null;
|
||||
}
|
||||
|
||||
export function filteredListSearch(field: string, value: string): string {
|
||||
return serializeListSearch({ filters: { [field]: value }, sort: null, anchors: [] }).toString();
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useEffect } from 'react';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
|
||||
import { useJmapList } from '@/data/objects';
|
||||
import { errorMessage } from '@/lib/jmapErrors';
|
||||
import { JmapMethodError } from '@/services/errors';
|
||||
import type { List } from '@/types/schema';
|
||||
import {
|
||||
LIST_PAGE_SIZE,
|
||||
buildListFilter,
|
||||
buildListPageParams,
|
||||
buildListSort,
|
||||
effectiveSort,
|
||||
isStrandedPage,
|
||||
itemId,
|
||||
pageRange,
|
||||
type ListItem,
|
||||
type PageRange,
|
||||
} from './listQuery';
|
||||
import { listStateKey, nextSort, parseListSearch, serializeListSearch, type ListUrlState } from './listUrlState';
|
||||
|
||||
const EMPTY_ITEMS: ListItem[] = [];
|
||||
const EMPTY_LIST: Pick<List, 'filters' | 'filtersStatic' | 'columns' | 'sort'> = { columns: [] };
|
||||
|
||||
export interface DynamicListState {
|
||||
state: ListUrlState;
|
||||
stateKey: string;
|
||||
items: ListItem[];
|
||||
total: number | null;
|
||||
range: PageRange;
|
||||
jmapFilter: Record<string, unknown> | undefined;
|
||||
jmapSort: Record<string, unknown>[] | undefined;
|
||||
isLoading: boolean;
|
||||
isFetching: boolean;
|
||||
error: string | null;
|
||||
applyFilters: (filters: Record<string, string>) => void;
|
||||
resetFilters: () => void;
|
||||
toggleSort: (field: string) => void;
|
||||
nextPage: () => void;
|
||||
prevPage: () => void;
|
||||
refetch: () => void;
|
||||
}
|
||||
|
||||
export function useDynamicList(
|
||||
objectName: string | undefined,
|
||||
list: List | null | undefined,
|
||||
labelProperty?: string,
|
||||
): DynamicListState {
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const state = parseListSearch(searchParams);
|
||||
const stateKey = listStateKey(state);
|
||||
const effectiveList = list ?? EMPTY_LIST;
|
||||
const enabledObject = list && objectName ? objectName : null;
|
||||
|
||||
const query = useJmapList(
|
||||
enabledObject,
|
||||
buildListPageParams(state, effectiveList, objectName ?? '', LIST_PAGE_SIZE, labelProperty),
|
||||
{ keepPrevious: true },
|
||||
);
|
||||
|
||||
const anchorLost =
|
||||
state.anchors.length > 0 &&
|
||||
query.error instanceof JmapMethodError &&
|
||||
query.error.type === 'anchorNotFound' &&
|
||||
!query.isFetching;
|
||||
|
||||
const stranded = isStrandedPage(
|
||||
state.anchors.length,
|
||||
query.data?.list.length ?? 0,
|
||||
query.isSuccess && !query.isPlaceholderData && !query.isFetching,
|
||||
);
|
||||
const recovery = anchorLost ? 'reset' : stranded ? 'back' : null;
|
||||
|
||||
useEffect(() => {
|
||||
if (!recovery) return;
|
||||
const current = parseListSearch(searchParams);
|
||||
const anchors = recovery === 'reset' ? [] : current.anchors.slice(0, -1);
|
||||
setSearchParams(serializeListSearch({ ...current, anchors }), { replace: true });
|
||||
}, [recovery, searchParams, setSearchParams]);
|
||||
|
||||
const navigateTo = (next: ListUrlState) => {
|
||||
const params = serializeListSearch(next);
|
||||
if (params.toString() === stateKey) void query.refetch();
|
||||
else setSearchParams(params);
|
||||
};
|
||||
|
||||
const items = query.data?.list ?? EMPTY_ITEMS;
|
||||
const total = query.data?.total ?? null;
|
||||
const position = query.data?.position ?? 0;
|
||||
|
||||
return {
|
||||
state,
|
||||
stateKey,
|
||||
items,
|
||||
total,
|
||||
range: pageRange(position, items.length, total, state.anchors.length, LIST_PAGE_SIZE),
|
||||
jmapFilter: buildListFilter(state.filters, effectiveList, objectName ?? ''),
|
||||
jmapSort: buildListSort(effectiveSort(state.sort, effectiveList)),
|
||||
isLoading: query.isPending && query.fetchStatus !== 'idle',
|
||||
isFetching: query.isFetching,
|
||||
error: query.isError && !anchorLost ? errorMessage(query.error) : null,
|
||||
applyFilters: (filters) => navigateTo({ filters, sort: state.sort, anchors: [] }),
|
||||
resetFilters: () => navigateTo({ filters: {}, sort: null, anchors: [] }),
|
||||
toggleSort: (field) => navigateTo({ filters: state.filters, sort: nextSort(state.sort, field), anchors: [] }),
|
||||
nextPage: () => {
|
||||
const last = items.length > 0 ? itemId(items[items.length - 1]) : null;
|
||||
if (last) navigateTo({ ...state, anchors: [...state.anchors, last] });
|
||||
},
|
||||
prevPage: () => {
|
||||
if (state.anchors.length > 0) navigateTo({ ...state, anchors: state.anchors.slice(0, -1) });
|
||||
},
|
||||
refetch: () => void query.refetch(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
/*
|
||||
* 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 { useJmapBulkSet, useJmapSet, type BulkTarget } from '@/data/mutations';
|
||||
import { toast } from '@/hooks/use-toast';
|
||||
import {
|
||||
bulkResultSummary,
|
||||
destroyedOutcome,
|
||||
errorMessage,
|
||||
friendlySetError,
|
||||
updatedOutcome,
|
||||
type SetOutcome,
|
||||
} from '@/lib/jmapErrors';
|
||||
import type { ItemAction } from '@/types/schema';
|
||||
import type { RunnableMassAction } from './MassActionBar';
|
||||
|
||||
type MutationItemAction = Extract<ItemAction, { type: 'delete' | 'setProperty' }>;
|
||||
|
||||
export interface MassActionTarget {
|
||||
ids: string[];
|
||||
allMatching: boolean;
|
||||
filter: Record<string, unknown> | undefined;
|
||||
sort: Record<string, unknown>[] | undefined;
|
||||
}
|
||||
|
||||
export interface ListActions {
|
||||
error: string | null;
|
||||
pending: boolean;
|
||||
clearError: () => void;
|
||||
runItemAction: (action: MutationItemAction, id: string) => Promise<boolean>;
|
||||
runMassAction: (action: RunnableMassAction, target: MassActionTarget) => Promise<boolean>;
|
||||
}
|
||||
|
||||
function reportOutcome(outcome: SetOutcome, kind: 'delete' | 'update') {
|
||||
const failures = Object.keys(outcome.failed).length > 0 ? outcome.failed : null;
|
||||
const summary = bulkResultSummary(outcome.succeeded.length, failures, kind);
|
||||
if (summary) toast({ title: summary.title, description: summary.description, variant: summary.variant });
|
||||
}
|
||||
|
||||
export function useListActions(objectName: string | undefined): ListActions {
|
||||
const { t } = useTranslation();
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const setMutation = useJmapSet(objectName);
|
||||
const bulkMutation = useJmapBulkSet(objectName);
|
||||
|
||||
const runItemAction = async (action: MutationItemAction, id: string): Promise<boolean> => {
|
||||
setError(null);
|
||||
try {
|
||||
if (action.type === 'delete') {
|
||||
const outcome = destroyedOutcome(await setMutation.mutateAsync({ destroy: [id] }));
|
||||
const failure = outcome.failed[id];
|
||||
if (failure) {
|
||||
setError(friendlySetError(failure));
|
||||
return false;
|
||||
}
|
||||
if (!outcome.succeeded.includes(id)) {
|
||||
setError(t('list.deleteNotConfirmed', 'Delete failed: item was not confirmed as destroyed by the server.'));
|
||||
return false;
|
||||
}
|
||||
reportOutcome(outcome, 'delete');
|
||||
return true;
|
||||
}
|
||||
const outcome = updatedOutcome(await setMutation.mutateAsync({ update: { [id]: action.properties } }));
|
||||
const failure = outcome.failed[id];
|
||||
if (failure) {
|
||||
setError(friendlySetError(failure));
|
||||
return false;
|
||||
}
|
||||
reportOutcome(outcome, 'update');
|
||||
return true;
|
||||
} catch (err) {
|
||||
setError(errorMessage(err));
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const runMassAction = async (action: RunnableMassAction, target: MassActionTarget): Promise<boolean> => {
|
||||
setError(null);
|
||||
const bulkTarget: BulkTarget = target.allMatching
|
||||
? { query: { filter: target.filter, sort: target.sort } }
|
||||
: { ids: target.ids };
|
||||
try {
|
||||
const outcome =
|
||||
action.type === 'delete'
|
||||
? await bulkMutation.mutateAsync({ ...bulkTarget, action: 'destroy' })
|
||||
: await bulkMutation.mutateAsync({ ...bulkTarget, action: 'update', patch: action.properties });
|
||||
reportOutcome(outcome, action.type === 'delete' ? 'delete' : 'update');
|
||||
return Object.keys(outcome.failed).length === 0;
|
||||
} catch (err) {
|
||||
setError(errorMessage(err));
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
error,
|
||||
pending: setMutation.isPending || bulkMutation.isPending,
|
||||
clearError: () => setError(null),
|
||||
runItemAction,
|
||||
runMassAction,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useState } from 'react';
|
||||
|
||||
interface SelectionState {
|
||||
scope: string;
|
||||
ids: ReadonlySet<string>;
|
||||
allMatching: boolean;
|
||||
}
|
||||
|
||||
export type PageSelectionState = 'none' | 'some' | 'all';
|
||||
|
||||
export interface ListSelection {
|
||||
selectedIds: string[];
|
||||
allMatching: boolean;
|
||||
pageState: PageSelectionState;
|
||||
isSelected: (id: string) => boolean;
|
||||
toggle: (id: string) => void;
|
||||
togglePage: () => void;
|
||||
selectAllMatching: () => void;
|
||||
clear: () => void;
|
||||
deselect: (id: string) => void;
|
||||
}
|
||||
|
||||
const EMPTY_IDS: ReadonlySet<string> = new Set();
|
||||
|
||||
export function useListSelection(scope: string, pageIds: readonly string[]): ListSelection {
|
||||
const [raw, setRaw] = useState<SelectionState>({ scope, ids: EMPTY_IDS, allMatching: false });
|
||||
const current = raw.scope === scope ? raw : { scope, ids: EMPTY_IDS, allMatching: false };
|
||||
|
||||
const selectedIds = pageIds.filter((id) => current.ids.has(id));
|
||||
const pageState: PageSelectionState =
|
||||
selectedIds.length === 0 ? 'none' : selectedIds.length === pageIds.length ? 'all' : 'some';
|
||||
|
||||
const update = (fn: (prev: SelectionState) => SelectionState) =>
|
||||
setRaw((prev) => fn(prev.scope === scope ? prev : { scope, ids: EMPTY_IDS, allMatching: false }));
|
||||
|
||||
return {
|
||||
selectedIds,
|
||||
allMatching: current.allMatching && pageState === 'all',
|
||||
pageState,
|
||||
isSelected: (id) => current.ids.has(id),
|
||||
toggle: (id) =>
|
||||
update((prev) => {
|
||||
const ids = new Set(prev.ids);
|
||||
if (ids.has(id)) ids.delete(id);
|
||||
else ids.add(id);
|
||||
return { scope, ids, allMatching: false };
|
||||
}),
|
||||
togglePage: () =>
|
||||
update(() => ({
|
||||
scope,
|
||||
ids: pageState === 'all' ? EMPTY_IDS : new Set(pageIds),
|
||||
allMatching: false,
|
||||
})),
|
||||
selectAllMatching: () => update(() => ({ scope, ids: new Set(pageIds), allMatching: true })),
|
||||
clear: () => update(() => ({ scope, ids: EMPTY_IDS, allMatching: false })),
|
||||
deselect: (id) =>
|
||||
update((prev) => {
|
||||
if (!prev.ids.has(id)) return prev;
|
||||
const ids = new Set(prev.ids);
|
||||
ids.delete(id);
|
||||
return { scope, ids, allMatching: false };
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -10,90 +10,103 @@ import * as AlertDialogPrimitive from '@radix-ui/react-alert-dialog';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { buttonVariants } from '@/components/ui/button';
|
||||
|
||||
const AlertDialog = AlertDialogPrimitive.Root;
|
||||
function AlertDialog(props: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
|
||||
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />;
|
||||
}
|
||||
|
||||
const AlertDialogTrigger = AlertDialogPrimitive.Trigger;
|
||||
function AlertDialogTrigger(props: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
|
||||
return <AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />;
|
||||
}
|
||||
|
||||
const AlertDialogPortal = AlertDialogPrimitive.Portal;
|
||||
function AlertDialogPortal(props: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
|
||||
return <AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />;
|
||||
}
|
||||
|
||||
const AlertDialogOverlay = React.forwardRef<
|
||||
React.ComponentRef<typeof AlertDialogPrimitive.Overlay>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Overlay
|
||||
className={cn(
|
||||
'fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
ref={ref}
|
||||
/>
|
||||
));
|
||||
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName;
|
||||
|
||||
const AlertDialogContent = React.forwardRef<
|
||||
React.ComponentRef<typeof AlertDialogPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPortal>
|
||||
<AlertDialogOverlay />
|
||||
<AlertDialogPrimitive.Content
|
||||
ref={ref}
|
||||
function AlertDialogOverlay({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Overlay
|
||||
data-slot="alert-dialog-overlay"
|
||||
className={cn(
|
||||
'fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg',
|
||||
'fixed inset-0 z-50 bg-overlay data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</AlertDialogPortal>
|
||||
));
|
||||
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName;
|
||||
);
|
||||
}
|
||||
|
||||
const AlertDialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div className={cn('flex flex-col space-y-2 text-center sm:text-left', className)} {...props} />
|
||||
);
|
||||
AlertDialogHeader.displayName = 'AlertDialogHeader';
|
||||
function AlertDialogContent({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {
|
||||
return (
|
||||
<AlertDialogPortal>
|
||||
<AlertDialogOverlay>
|
||||
<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',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</AlertDialogOverlay>
|
||||
</AlertDialogPortal>
|
||||
);
|
||||
}
|
||||
|
||||
const AlertDialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div className={cn('flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2', className)} {...props} />
|
||||
);
|
||||
AlertDialogFooter.displayName = 'AlertDialogFooter';
|
||||
function AlertDialogHeader({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-dialog-header"
|
||||
className={cn('flex flex-col space-y-2 text-center sm:text-left', className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const AlertDialogTitle = React.forwardRef<
|
||||
React.ComponentRef<typeof AlertDialogPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Title ref={ref} className={cn('text-lg font-semibold', className)} {...props} />
|
||||
));
|
||||
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName;
|
||||
function AlertDialogFooter({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-dialog-footer"
|
||||
className={cn('flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2', className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const AlertDialogDescription = React.forwardRef<
|
||||
React.ComponentRef<typeof AlertDialogPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Description ref={ref} className={cn('text-sm text-muted-foreground', className)} {...props} />
|
||||
));
|
||||
AlertDialogDescription.displayName = AlertDialogPrimitive.Description.displayName;
|
||||
function AlertDialogTitle({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Title
|
||||
data-slot="alert-dialog-title"
|
||||
className={cn('font-display text-lg font-bold tracking-[-0.015em]', className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const AlertDialogAction = React.forwardRef<
|
||||
React.ComponentRef<typeof AlertDialogPrimitive.Action>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Action ref={ref} className={cn(buttonVariants(), className)} {...props} />
|
||||
));
|
||||
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName;
|
||||
function AlertDialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Description
|
||||
data-slot="alert-dialog-description"
|
||||
className={cn('text-sm text-muted-foreground', className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const AlertDialogCancel = React.forwardRef<
|
||||
React.ComponentRef<typeof AlertDialogPrimitive.Cancel>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Cancel
|
||||
ref={ref}
|
||||
className={cn(buttonVariants({ variant: 'outline' }), 'mt-2 sm:mt-0', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName;
|
||||
function AlertDialogAction({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {
|
||||
return <AlertDialogPrimitive.Action className={cn(buttonVariants(), className)} {...props} />;
|
||||
}
|
||||
|
||||
function AlertDialogCancel({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Cancel
|
||||
className={cn(buttonVariants({ variant: 'outline' }), 'mt-2 sm:mt-0', className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
AlertDialog,
|
||||
|
||||
@@ -10,14 +10,14 @@ import { cva, type VariantProps } from 'class-variance-authority';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const badgeVariants = cva(
|
||||
'inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
|
||||
'inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80',
|
||||
secondary: 'border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80',
|
||||
destructive: 'border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80',
|
||||
outline: 'text-foreground',
|
||||
default: 'border-transparent bg-highlight text-highlight-foreground',
|
||||
secondary: 'border-transparent bg-secondary text-secondary-foreground',
|
||||
destructive: 'border-transparent bg-destructive-soft text-destructive',
|
||||
outline: 'border-input text-foreground',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
|
||||
Loaded 100 of 261 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user