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 |
No files matched your search
@@ -2,6 +2,96 @@
|
||||
|
||||
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
|
||||
|
||||
+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
|
||||
@@ -132,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.
|
||||
|
||||
|
||||
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
+88
-2
@@ -1,14 +1,20 @@
|
||||
{
|
||||
"name": "stalwart-webui",
|
||||
"version": "2.0.2",
|
||||
"version": "2.1.3",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "stalwart-webui",
|
||||
"version": "2.0.2",
|
||||
"version": "2.1.3",
|
||||
"dependencies": {
|
||||
"@daypicker/react": "^10.0.2",
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@fontsource-variable/inter": "^5.3.0",
|
||||
"@fontsource-variable/jetbrains-mono": "^5.3.0",
|
||||
"@fontsource-variable/plus-jakarta-sans": "^5.3.0",
|
||||
"@noble/hashes": "^2.4.0",
|
||||
"@radix-ui/react-alert-dialog": "^1.2.1",
|
||||
"@radix-ui/react-checkbox": "^1.4.1",
|
||||
@@ -384,6 +390,59 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@dnd-kit/accessibility": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/accessibility/-/accessibility-3.1.1.tgz",
|
||||
"integrity": "sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tslib": "^2.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@dnd-kit/core": {
|
||||
"version": "6.3.1",
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz",
|
||||
"integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@dnd-kit/accessibility": "^3.1.1",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"tslib": "^2.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.8.0",
|
||||
"react-dom": ">=16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@dnd-kit/sortable": {
|
||||
"version": "10.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/sortable/-/sortable-10.0.0.tgz",
|
||||
"integrity": "sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"tslib": "^2.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@dnd-kit/core": "^6.3.0",
|
||||
"react": ">=16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@dnd-kit/utilities": {
|
||||
"version": "3.2.2",
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/utilities/-/utilities-3.2.2.tgz",
|
||||
"integrity": "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tslib": "^2.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@emnapi/core": {
|
||||
"version": "1.11.1",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.1.tgz",
|
||||
@@ -584,6 +643,33 @@
|
||||
"integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@fontsource-variable/inter": {
|
||||
"version": "5.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@fontsource-variable/inter/-/inter-5.3.0.tgz",
|
||||
"integrity": "sha512-OupL48va4JNofb97w6NYeF9S7W/kHNKM0Er8Dem5nqi4jeOLrVJDoE8tZEpnMJmtkvNbB1EIPPwHcdkF6b1oUA==",
|
||||
"license": "OFL-1.1",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ayuhito"
|
||||
}
|
||||
},
|
||||
"node_modules/@fontsource-variable/jetbrains-mono": {
|
||||
"version": "5.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@fontsource-variable/jetbrains-mono/-/jetbrains-mono-5.3.0.tgz",
|
||||
"integrity": "sha512-F32xpS2NsGYoQi2ADSkKTgpJj7ozajsGgDJ8woTnqjmIB+dxDIqImjl4pXZVEExu8UFZ2ndhmX18EBS/hdz3Lw==",
|
||||
"license": "OFL-1.1",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ayuhito"
|
||||
}
|
||||
},
|
||||
"node_modules/@fontsource-variable/plus-jakarta-sans": {
|
||||
"version": "5.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@fontsource-variable/plus-jakarta-sans/-/plus-jakarta-sans-5.3.0.tgz",
|
||||
"integrity": "sha512-/l/4r0yyWK9JzAlmA0LiYgGgmJe/Gswt4jTJEzr5QhJfwMbvJZDmYWyW0M4X7yCK69BajMVlV/Lx8g7WDc1+sw==",
|
||||
"license": "OFL-1.1",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ayuhito"
|
||||
}
|
||||
},
|
||||
"node_modules/@humanfs/core": {
|
||||
"version": "0.19.2",
|
||||
"resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz",
|
||||
|
||||
+7
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "stalwart-webui",
|
||||
"private": true,
|
||||
"version": "2.0.2",
|
||||
"version": "2.1.3",
|
||||
"stalwart": {
|
||||
"minServerVersion": "1.0.0"
|
||||
},
|
||||
@@ -18,6 +18,12 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@daypicker/react": "^10.0.2",
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@fontsource-variable/inter": "^5.3.0",
|
||||
"@fontsource-variable/jetbrains-mono": "^5.3.0",
|
||||
"@fontsource-variable/plus-jakarta-sans": "^5.3.0",
|
||||
"@noble/hashes": "^2.4.0",
|
||||
"@radix-ui/react-alert-dialog": "^1.2.1",
|
||||
"@radix-ui/react-checkbox": "^1.4.1",
|
||||
|
||||
@@ -7,18 +7,18 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Check } from 'lucide-react';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { CopyButton } from '@/components/common/CopyButton';
|
||||
import { DefaultLogo } from '@/components/common/Logo';
|
||||
import type { Fields } from '@/types/schema';
|
||||
|
||||
export function WizardShell({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col bg-content-background">
|
||||
<header className="flex items-center px-6 py-4 border-b bg-background">
|
||||
<div className="flex min-h-screen flex-col bg-background">
|
||||
<header className="sticky top-0 z-20 flex h-16 items-center bg-background/80 px-6 backdrop-blur-md">
|
||||
<DefaultLogo />
|
||||
</header>
|
||||
<main className="flex-1 overflow-auto p-6">
|
||||
<main className="flex-1 overflow-auto px-4 pb-10 pt-4 sm:px-6">
|
||||
<div className="mx-auto max-w-3xl">{children}</div>
|
||||
</main>
|
||||
</div>
|
||||
@@ -29,15 +29,16 @@ export function ProgressIndicator({ total, current }: { total: number; current:
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div
|
||||
className="flex items-center gap-2"
|
||||
className="flex items-center gap-1.5"
|
||||
aria-label={t('bootstrap.stepOf', 'Step {{current}} of {{total}}', { current: current + 1, total })}
|
||||
>
|
||||
{Array.from({ length: total }, (_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className={`h-2 w-2 rounded-full transition-colors ${
|
||||
i < current ? 'bg-primary' : i === current ? 'bg-primary' : 'bg-muted-foreground/20'
|
||||
}`}
|
||||
className={cn(
|
||||
'h-1.5 rounded-full transition-all duration-300 ease-bento',
|
||||
i === current ? 'w-8 bg-primary' : i < current ? 'w-4 bg-primary/45' : 'w-4 bg-muted-strong',
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -62,14 +63,14 @@ export function SuccessScreen({
|
||||
const hasCredentials = entries.length > 0;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-col items-start gap-3">
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary/10">
|
||||
<Check className="h-5 w-5 text-primary" />
|
||||
</div>
|
||||
<div className="space-y-3.5">
|
||||
<div className="flex flex-col items-start gap-4 px-1 pb-2 pt-3">
|
||||
<span className="grid size-11 place-items-center rounded-[13px] bg-success-soft text-success">
|
||||
<Check className="h-5 w-5" aria-hidden="true" />
|
||||
</span>
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold tracking-tight">{t('bootstrap.complete', 'Setup complete')}</h2>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
<h1 className="page-title">{t('bootstrap.complete', 'Setup complete')}</h1>
|
||||
<p className="mt-1.5 text-sm text-muted-foreground">
|
||||
{hasCredentials
|
||||
? t(
|
||||
'bootstrap.credentialsCreated',
|
||||
@@ -81,32 +82,37 @@ export function SuccessScreen({
|
||||
</div>
|
||||
|
||||
{hasCredentials && (
|
||||
<Card>
|
||||
<CardContent className="pt-6 space-y-4">
|
||||
{entries.map(([key, value]) => {
|
||||
const field = fields.properties[key];
|
||||
const label = labelsByName.get(key) ?? field?.description?.split('\n')[0] ?? key;
|
||||
return (
|
||||
<div key={key} className="space-y-1.5">
|
||||
<div className="text-sm font-medium">{label}</div>
|
||||
<div className="flex gap-2">
|
||||
<code className="flex-1 rounded bg-muted p-2 text-sm break-all select-all">{value}</code>
|
||||
<CopyButton value={value} label={label} />
|
||||
</div>
|
||||
<section className="tile divide-y divide-border px-5 sm:px-6">
|
||||
{entries.map(([key, value]) => {
|
||||
const field = fields.properties[key];
|
||||
const label = labelsByName.get(key) ?? field?.description?.split('\n')[0] ?? key;
|
||||
return (
|
||||
<div key={key} className="space-y-2 py-4">
|
||||
<div className="text-[13.5px] font-semibold">{label}</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<code className="flex-1 select-all break-all rounded-xl bg-muted px-3 py-2.5 font-mono text-sm">
|
||||
{value}
|
||||
</code>
|
||||
<CopyButton value={value} label={label} />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</section>
|
||||
)}
|
||||
|
||||
<div className="rounded-md border border-primary/20 bg-primary/5 p-4">
|
||||
<div className="rounded-xl bg-info-soft p-4 text-info">
|
||||
<p className="text-sm">
|
||||
<span className="font-medium">{t('bootstrap.nextStepLabel', 'Next step:')}</span>{' '}
|
||||
{t(
|
||||
'bootstrap.nextStepBody',
|
||||
'restart Stalwart for the new configuration to take effect. Once restarted, sign in with the credentials above to continue administering your server.',
|
||||
)}
|
||||
{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>
|
||||
|
||||
@@ -8,7 +8,7 @@ import { useCallback, useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { ArrowLeft, ArrowRight, Loader2, Rocket } from 'lucide-react';
|
||||
|
||||
import { useSchemaStore } from '@/stores/schemaStore';
|
||||
@@ -208,8 +208,8 @@ export function BootstrapWizard() {
|
||||
if (!schema || !resolved) {
|
||||
return (
|
||||
<WizardShell>
|
||||
<div className="flex items-center justify-center p-12 text-muted-foreground">
|
||||
<Loader2 className="h-6 w-6 animate-spin mr-2" />
|
||||
<div className="flex items-center justify-center p-12 text-muted-foreground" role="status">
|
||||
<Loader2 className="mr-2 h-6 w-6 animate-spin text-brand-text" aria-hidden="true" />
|
||||
{t('form.loadingSchema', 'Loading schema...')}
|
||||
</div>
|
||||
</WizardShell>
|
||||
@@ -219,8 +219,8 @@ export function BootstrapWizard() {
|
||||
if (loading) {
|
||||
return (
|
||||
<WizardShell>
|
||||
<div className="flex items-center justify-center p-12 text-muted-foreground">
|
||||
<Loader2 className="h-6 w-6 animate-spin mr-2" />
|
||||
<div className="flex items-center justify-center p-12 text-muted-foreground" role="status">
|
||||
<Loader2 className="mr-2 h-6 w-6 animate-spin text-brand-text" aria-hidden="true" />
|
||||
{t('bootstrap.loadingSetup', 'Loading setup...')}
|
||||
</div>
|
||||
</WizardShell>
|
||||
@@ -230,7 +230,7 @@ export function BootstrapWizard() {
|
||||
if (loadError) {
|
||||
return (
|
||||
<WizardShell>
|
||||
<div className="space-y-4 rounded-md border border-destructive/20 bg-destructive/10 p-4">
|
||||
<div className="mt-3 space-y-4 rounded-xl bg-destructive-soft p-4">
|
||||
<p className="text-sm text-destructive" role="alert">
|
||||
{loadError}
|
||||
</p>
|
||||
@@ -262,7 +262,7 @@ export function BootstrapWizard() {
|
||||
if (sections.length === 0) {
|
||||
return (
|
||||
<WizardShell>
|
||||
<div className="rounded-md border border-destructive/20 bg-destructive/10 p-4 text-sm text-destructive">
|
||||
<div className="mt-3 rounded-xl bg-destructive-soft p-4 text-sm text-destructive">
|
||||
{t('bootstrap.emptyForm', 'Setup form is empty. The server did not return any bootstrap fields.')}
|
||||
</div>
|
||||
</WizardShell>
|
||||
@@ -273,52 +273,47 @@ export function BootstrapWizard() {
|
||||
|
||||
return (
|
||||
<WizardShell>
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold tracking-tight">{t('bootstrap.welcome', 'Welcome to Stalwart')}</h2>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{t('bootstrap.welcomeSubtitle', "Let's get your server set up.")}
|
||||
</p>
|
||||
<div className="space-y-3.5">
|
||||
<div className="flex flex-wrap items-end justify-between gap-4 px-1 pb-2 pt-3">
|
||||
<div>
|
||||
<h1 className="page-title">{t('bootstrap.welcome', 'Welcome to Stalwart')}</h1>
|
||||
<p className="mt-1.5 text-sm text-muted-foreground">
|
||||
{t('bootstrap.welcomeSubtitle', "Let's get your server set up.")}
|
||||
</p>
|
||||
</div>
|
||||
<ProgressIndicator total={sections.length} current={currentPage} />
|
||||
</div>
|
||||
|
||||
<ProgressIndicator total={sections.length} current={currentPage} />
|
||||
|
||||
{generalError && (
|
||||
<div className="rounded-md bg-destructive/10 border border-destructive/20 p-4">
|
||||
<p className="text-sm text-destructive whitespace-pre-line">{generalError}</p>
|
||||
<div className="rounded-xl bg-destructive-soft p-4" role="alert">
|
||||
<p className="whitespace-pre-line text-sm text-destructive">{generalError}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Card>
|
||||
{current.title && (
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">{current.title}</CardTitle>
|
||||
</CardHeader>
|
||||
)}
|
||||
<CardContent className={current.title ? '' : 'pt-6'}>
|
||||
<fieldset disabled={saving} className="min-w-0 space-y-6">
|
||||
<FormProvider schema={schema} mode="create" hideEnterprise>
|
||||
{current.fields.map(({ formField, field }) => (
|
||||
<FieldRow
|
||||
key={formField.name}
|
||||
field={field}
|
||||
formField={formField}
|
||||
value={formData[formField.name]}
|
||||
onChange={(v) => handleFieldChange(formField.name, v)}
|
||||
error={fieldErrors[formField.name]}
|
||||
/>
|
||||
))}
|
||||
</FormProvider>
|
||||
</fieldset>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<section className="tile @container px-5 pb-1.5 sm:px-6">
|
||||
{current.title && <h2 className="section-title pb-1 pt-5">{current.title}</h2>}
|
||||
<fieldset disabled={saving} className={cn('min-w-0 divide-y divide-border', !current.title && 'pt-1')}>
|
||||
<FormProvider schema={schema} mode="create" hideEnterprise>
|
||||
{current.fields.map(({ formField, field }) => (
|
||||
<FieldRow
|
||||
key={formField.name}
|
||||
field={field}
|
||||
formField={formField}
|
||||
value={formData[formField.name]}
|
||||
onChange={(v) => handleFieldChange(formField.name, v)}
|
||||
error={fieldErrors[formField.name]}
|
||||
/>
|
||||
))}
|
||||
</FormProvider>
|
||||
</fieldset>
|
||||
</section>
|
||||
|
||||
<div className="flex items-center justify-between pt-2">
|
||||
<div className="flex items-center justify-between gap-3 pt-2">
|
||||
<Button type="button" variant="outline" onClick={handleBack} disabled={!canGoBack || saving}>
|
||||
<ArrowLeft className="h-4 w-4 mr-2" />
|
||||
<ArrowLeft aria-hidden="true" />
|
||||
{t('common.back', 'Back')}
|
||||
</Button>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
<div className="text-xs font-medium text-dim">
|
||||
{t('bootstrap.stepOf', 'Step {{current}} of {{total}}', {
|
||||
current: currentPage + 1,
|
||||
total: sections.length,
|
||||
@@ -326,13 +321,13 @@ export function BootstrapWizard() {
|
||||
</div>
|
||||
{isLastPage ? (
|
||||
<Button type="button" onClick={handleSubmit} disabled={saving}>
|
||||
{saving ? <Loader2 className="h-4 w-4 mr-2 animate-spin" /> : <Rocket className="h-4 w-4 mr-2" />}
|
||||
{saving ? <Loader2 className="animate-spin" aria-hidden="true" /> : <Rocket aria-hidden="true" />}
|
||||
{t('bootstrap.finishSetup', 'Finish setup')}
|
||||
</Button>
|
||||
) : (
|
||||
<Button type="button" onClick={handleNext} disabled={saving}>
|
||||
{t('common.next', 'Next')}
|
||||
<ArrowRight className="h-4 w-4 ml-2" />
|
||||
<ArrowRight aria-hidden="true" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -50,7 +50,7 @@ export function CommandPalette({ open, onOpenChange }: CommandPaletteProps) {
|
||||
<Command
|
||||
shouldFilter={false}
|
||||
loop
|
||||
className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5"
|
||||
className="[&_[cmdk-group-heading]]:px-2.5 [&_[cmdk-group-heading]]:pt-2.5 [&_[cmdk-group-heading]]:text-[11px] [&_[cmdk-group-heading]]:font-semibold [&_[cmdk-group-heading]]:uppercase [&_[cmdk-group-heading]]:tracking-wider [&_[cmdk-group-heading]]:text-dim [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-14 [&_[cmdk-item]]:gap-3 [&_[cmdk-item]]:rounded-xl [&_[cmdk-item]]:px-2.5 [&_[cmdk-item]]:py-2 [&_[cmdk-item][data-selected=true]]:bg-muted [&_[cmdk-item]_svg]:h-4 [&_[cmdk-item]_svg]:w-4 [&_[cmdk-list]]:max-h-[min(60vh,420px)] [&_[cmdk-list]]:pb-2"
|
||||
>
|
||||
<CommandInput
|
||||
placeholder={t('globalSearch.placeholder', 'Search pages, fields, settings...')}
|
||||
@@ -59,7 +59,7 @@ export function CommandPalette({ open, onOpenChange }: CommandPaletteProps) {
|
||||
trailing={
|
||||
<kbd
|
||||
aria-hidden="true"
|
||||
className="pointer-events-none ml-2 inline-flex h-5 shrink-0 select-none items-center rounded-md border bg-muted px-1.5 font-mono text-[10px] font-medium text-muted-foreground"
|
||||
className="pointer-events-none ml-2 inline-flex h-5 shrink-0 select-none items-center rounded-md bg-muted px-1.5 font-mono text-[10px] font-medium text-dim"
|
||||
>
|
||||
ESC
|
||||
</kbd>
|
||||
@@ -79,12 +79,14 @@ export function CommandPalette({ open, onOpenChange }: CommandPaletteProps) {
|
||||
|
||||
return (
|
||||
<CommandItem key={itemValue} value={itemValue} onSelect={() => selectEntry(entry)}>
|
||||
<ActionIcon aria-hidden="true" className="mr-2 h-4 w-4 shrink-0 text-muted-foreground" />
|
||||
<span className="grid size-8 shrink-0 place-items-center rounded-[10px] bg-highlight text-highlight-foreground">
|
||||
<ActionIcon aria-hidden="true" className="h-4 w-4" />
|
||||
</span>
|
||||
<div className="flex flex-1 flex-col overflow-hidden">
|
||||
<span className="truncate font-medium">{friendlyName(entry.text)}</span>
|
||||
<span className="truncate text-xs text-muted-foreground">{entry.breadcrumb}</span>
|
||||
<span className="truncate text-xs text-dim">{entry.breadcrumb}</span>
|
||||
</div>
|
||||
<span className="ml-auto shrink-0 pl-2 text-xs text-muted-foreground">{actionLabel}</span>
|
||||
<span className="ml-auto shrink-0 pl-2 text-xs font-medium text-dim">{actionLabel}</span>
|
||||
</CommandItem>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
*/
|
||||
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Sparkles } from 'lucide-react';
|
||||
|
||||
import {
|
||||
Dialog,
|
||||
@@ -28,6 +29,12 @@ export function EnterpriseUpsell({ open, onClose }: EnterpriseUpsellProps) {
|
||||
<Dialog open={open} onOpenChange={(isOpen) => !isOpen && onClose()}>
|
||||
<DialogContent className="gap-6">
|
||||
<DialogHeader className="space-y-4">
|
||||
<span
|
||||
className="grid size-11 place-items-center rounded-[13px] bg-highlight text-highlight-foreground max-sm:mx-auto"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<Sparkles className="h-5 w-5" />
|
||||
</span>
|
||||
<DialogTitle>{t('enterprise.trialTitle')}</DialogTitle>
|
||||
<DialogDescription>{t('enterprise.trialDescription')}</DialogDescription>
|
||||
</DialogHeader>
|
||||
@@ -36,7 +43,7 @@ export function EnterpriseUpsell({ open, onClose }: EnterpriseUpsellProps) {
|
||||
href="https://stalw.art/compare#why-isnt-feature-x-open-source"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-center text-xs text-muted-foreground underline-offset-4 hover:underline sm:mr-auto sm:text-left"
|
||||
className="text-center text-xs font-medium text-muted-foreground underline-offset-4 hover:text-brand-text hover:underline sm:mr-auto sm:text-left"
|
||||
>
|
||||
{t('enterprise.whyNotFree')}
|
||||
</a>
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
export function FloatingActionBar({ label, children }: { label?: string; children: ReactNode }) {
|
||||
return (
|
||||
<div className="pointer-events-none sticky bottom-4 z-20 flex justify-center pt-2">
|
||||
<div
|
||||
role={label ? 'group' : undefined}
|
||||
aria-label={label}
|
||||
className="pointer-events-auto flex max-w-full items-center gap-1.5 rounded-full bg-ink p-1.5 text-ink-foreground shadow-ink"
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function FloatingActionDivider() {
|
||||
return <span className="mx-0.5 h-5 w-px bg-ink-foreground/15" aria-hidden="true" />;
|
||||
}
|
||||
|
||||
export function FloatingActionDot() {
|
||||
return <span className="h-2 w-2 shrink-0 rounded-full bg-ink-accent" aria-hidden="true" />;
|
||||
}
|
||||
@@ -31,7 +31,7 @@ export function HelpTooltip({ content, label, side = 'top', icon: Icon = HelpCir
|
||||
type="button"
|
||||
aria-label={ariaLabel}
|
||||
className={cn(
|
||||
'inline-flex shrink-0 cursor-help items-center rounded-sm text-muted-foreground/60 hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring',
|
||||
'inline-flex shrink-0 cursor-help items-center rounded-full text-dim transition-colors hover:text-brand-text focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
|
||||
className,
|
||||
)}
|
||||
onClick={(e) => e.preventDefault()}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -19,7 +19,7 @@ export function Markdown({ source, className }: MarkdownProps) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'[&_a]:underline [&_code]:font-mono [&_ol]:list-decimal [&_ol]:pl-4 [&_p+p]:mt-1 [&_ul]:list-disc [&_ul]:pl-4',
|
||||
'[&_a]:font-medium [&_a]:underline [&_a]:underline-offset-2 [&_code]:rounded [&_code]:bg-current/10 [&_code]:px-1 [&_code]:py-px [&_code]:font-mono [&_code]:text-[0.92em] [&_ol]:list-decimal [&_ol]:pl-4 [&_p+p]:mt-1 [&_ul]:list-disc [&_ul]:pl-4',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
|
||||
@@ -8,7 +8,7 @@ import { useTranslation } from 'react-i18next';
|
||||
import { Loader2, X } from 'lucide-react';
|
||||
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { ObjectSearchPopover } from '@/components/common/ObjectSearchPopover';
|
||||
import { ObjectFieldFrame, ObjectSearchPopover } from '@/components/common/ObjectSearchPopover';
|
||||
import { useNoPermissionMessage } from '@/lib/objectOptions';
|
||||
import { useObjectOptions, useDisplayName } from '@/data/objectOptions';
|
||||
import type { Schema } from '@/types/schema';
|
||||
@@ -36,11 +36,14 @@ export function ObjectPicker({ schema, objectName, label, value, onChange, onCle
|
||||
const noPermissionMessage = useNoPermissionMessage(schema, objectName);
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<ObjectFieldFrame disabled={!!noPermissionMessage} 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}
|
||||
@@ -50,17 +53,17 @@ export function ObjectPicker({ schema, objectName, label, value, onChange, onCle
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClear}
|
||||
className="ml-1 rounded-full hover:bg-muted-foreground/20 p-0.5"
|
||||
className="grid size-5 shrink-0 place-items-center rounded-full bg-card text-muted-foreground transition-colors hover:bg-highlight hover:text-highlight-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
aria-label={t('field.clearValue', 'Clear {{name}}', { name: label })}
|
||||
>
|
||||
<X className="h-3 w-3" />
|
||||
<X className="h-3 w-3" aria-hidden="true" />
|
||||
</button>
|
||||
)}
|
||||
</Badge>
|
||||
)}
|
||||
{!value && placeholder && <span className="text-sm text-muted-foreground">{placeholder}</span>}
|
||||
<ObjectSearchPopover
|
||||
label={t('field.chooseValue', 'Choose {{name}}', { name: label })}
|
||||
placeholder={value ? '' : (placeholder ?? t('field.selectEllipsis', 'Select...'))}
|
||||
options={list.options}
|
||||
loading={list.loading}
|
||||
error={list.error}
|
||||
@@ -68,6 +71,6 @@ export function ObjectPicker({ schema, objectName, label, value, onChange, onCle
|
||||
onSelect={onChange}
|
||||
disabledMessage={noPermissionMessage}
|
||||
/>
|
||||
</div>
|
||||
</ObjectFieldFrame>
|
||||
);
|
||||
}
|
||||
@@ -6,12 +6,14 @@
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Loader2, Search } from 'lucide-react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { ChevronsUpDown, Loader2, Search } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from '@/components/ui/command';
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import { errorMessage } from '@/lib/jmapErrors';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { ObjectOption } from '@/data/objectOptions';
|
||||
import type { ControlProps } from '@/components/forms/widgets/types';
|
||||
|
||||
@@ -25,6 +27,37 @@ export interface ObjectSearchPopoverProps {
|
||||
disabled?: boolean;
|
||||
label: string;
|
||||
control?: ControlProps;
|
||||
placeholder?: string;
|
||||
}
|
||||
|
||||
export function ObjectFieldFrame({
|
||||
disabled,
|
||||
single,
|
||||
children,
|
||||
}: {
|
||||
disabled?: boolean;
|
||||
single?: boolean;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
data-slot="object-field"
|
||||
className={cn(
|
||||
'field-surface flex min-h-9 w-full items-center gap-1.5 rounded-lg p-1',
|
||||
single ? 'flex-nowrap' : 'flex-wrap',
|
||||
disabled && 'opacity-60',
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const INLINE_TRIGGER =
|
||||
'h-7 flex-1 justify-between gap-2 rounded-md px-2 text-sm font-normal text-dim shadow-none hover:bg-transparent hover:text-foreground focus-visible:ring-0 focus-visible:ring-offset-0';
|
||||
|
||||
function inlineTrigger(placeholder: string): string {
|
||||
return cn(INLINE_TRIGGER, placeholder ? 'min-w-[6rem]' : 'min-w-8 justify-end');
|
||||
}
|
||||
|
||||
export function ObjectSearchPopover({
|
||||
@@ -37,6 +70,7 @@ export function ObjectSearchPopover({
|
||||
disabled,
|
||||
label,
|
||||
control,
|
||||
placeholder,
|
||||
}: ObjectSearchPopoverProps) {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
@@ -50,8 +84,11 @@ export function ObjectSearchPopover({
|
||||
{...control}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7 cursor-not-allowed opacity-60"
|
||||
size={placeholder === undefined ? 'icon' : 'sm'}
|
||||
className={cn(
|
||||
'cursor-not-allowed',
|
||||
placeholder === undefined ? 'h-8 w-8 bg-muted opacity-60' : inlineTrigger(placeholder),
|
||||
)}
|
||||
aria-label={label}
|
||||
aria-disabled="true"
|
||||
onClick={(e) => {
|
||||
@@ -60,7 +97,7 @@ export function ObjectSearchPopover({
|
||||
setTooltipOpen(true);
|
||||
}}
|
||||
>
|
||||
<Search className="h-4 w-4" aria-hidden="true" />
|
||||
<TriggerContent placeholder={placeholder} />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{disabledMessage}</TooltipContent>
|
||||
@@ -81,15 +118,19 @@ export function ObjectSearchPopover({
|
||||
{...control}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7"
|
||||
size={placeholder === undefined ? 'icon' : 'sm'}
|
||||
className={
|
||||
placeholder === undefined
|
||||
? 'h-8 w-8 bg-muted hover:bg-highlight hover:text-highlight-foreground'
|
||||
: inlineTrigger(placeholder)
|
||||
}
|
||||
aria-label={label}
|
||||
disabled={disabled}
|
||||
>
|
||||
<Search className="h-4 w-4" aria-hidden="true" />
|
||||
<TriggerContent placeholder={placeholder} />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-72 p-0" align="start">
|
||||
<PopoverContent className="w-72 overflow-hidden p-0" align="start">
|
||||
<Command>
|
||||
<CommandInput placeholder={t('common.searchPlaceholder', 'Search...')} />
|
||||
<CommandList>
|
||||
@@ -100,7 +141,7 @@ export function ObjectSearchPopover({
|
||||
</div>
|
||||
)}
|
||||
{!loading && error && (
|
||||
<div className="space-y-2 px-3 py-4 text-center text-sm" role="alert">
|
||||
<div className="m-2 space-y-2 rounded-xl bg-destructive-soft px-3 py-4 text-center text-sm" role="alert">
|
||||
<p className="text-destructive">
|
||||
{errorMessage(error, t('field.optionsLoadFailed', 'Failed to load options.'))}
|
||||
</p>
|
||||
@@ -133,3 +174,13 @@ export function ObjectSearchPopover({
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
function TriggerContent({ placeholder }: { placeholder?: string }) {
|
||||
if (placeholder === undefined) return <Search className="h-4 w-4" aria-hidden="true" />;
|
||||
return (
|
||||
<>
|
||||
<span className="truncate">{placeholder}</span>
|
||||
<ChevronsUpDown className="h-4 w-4 shrink-0 opacity-60" aria-hidden="true" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -42,6 +42,7 @@ import {
|
||||
ListTodoIcon,
|
||||
ListTreeIcon,
|
||||
LockIcon,
|
||||
LockKeyholeIcon,
|
||||
MailIcon,
|
||||
MailMinusIcon,
|
||||
MailXIcon,
|
||||
@@ -112,6 +113,7 @@ export const ICONS: Readonly<Record<string, LucideIcon>> = {
|
||||
'list-todo': ListTodoIcon,
|
||||
'list-tree': ListTreeIcon,
|
||||
lock: LockIcon,
|
||||
'lock-keyhole': LockKeyholeIcon,
|
||||
mail: MailIcon,
|
||||
'mail-minus': MailMinusIcon,
|
||||
'mail-x': MailXIcon,
|
||||
|
||||
@@ -10,7 +10,7 @@ import { useBufferedValue } from '@/hooks/useBufferedValue';
|
||||
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
import { X, Plus } from 'lucide-react';
|
||||
|
||||
@@ -98,12 +98,12 @@ export function ExpressionEditor({ value, onChange, readOnly = false, label, con
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border bg-card p-4 space-y-3">
|
||||
<div className="space-y-2.5 rounded-xl bg-muted p-3">
|
||||
{matchEntries.map(([key, entry], index) => (
|
||||
<div key={key}>
|
||||
<div className="rounded-md border bg-muted/30 p-3 space-y-2">
|
||||
<div className="space-y-2 rounded-lg bg-card p-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground w-12 shrink-0">
|
||||
<span className="w-12 shrink-0 text-[11px] font-semibold uppercase tracking-wider text-dim">
|
||||
{t('expression.if', 'IF')}
|
||||
</span>
|
||||
<BufferedExprInput
|
||||
@@ -117,18 +117,18 @@ export function ExpressionEditor({ value, onChange, readOnly = false, label, con
|
||||
{!readOnly && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive"
|
||||
variant="ghost-danger"
|
||||
size="icon-sm"
|
||||
className="shrink-0"
|
||||
onClick={() => handleRemove(key)}
|
||||
aria-label={t('expression.removeCondition', 'Remove condition {{n}}', { n: index + 1 })}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
<X aria-hidden="true" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground w-12 shrink-0">
|
||||
<span className="w-12 shrink-0 text-[11px] font-semibold uppercase tracking-wider text-dim">
|
||||
{t('expression.then', 'THEN')}
|
||||
</span>
|
||||
<BufferedExprInput
|
||||
@@ -142,7 +142,6 @@ export function ExpressionEditor({ value, onChange, readOnly = false, label, con
|
||||
{!readOnly && <div className="w-8 shrink-0" />}
|
||||
</div>
|
||||
</div>
|
||||
{index < matchEntries.length - 1 && <Separator className="my-3" />}
|
||||
</div>
|
||||
))}
|
||||
|
||||
@@ -153,18 +152,17 @@ export function ExpressionEditor({ value, onChange, readOnly = false, label, con
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={handleAdd}
|
||||
className="h-7 gap-1 px-2 text-xs text-muted-foreground hover:text-foreground"
|
||||
className="h-7 gap-1 px-3 text-xs hover:bg-card"
|
||||
>
|
||||
<Plus className="h-3 w-3" />
|
||||
<Plus className="!size-3.5" aria-hidden="true" />
|
||||
{t('expression.addCondition', 'Add condition')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{matchEntries.length > 0 && <Separator />}
|
||||
<div className="flex items-center gap-2">
|
||||
<div className={cn('flex items-center gap-2', matchEntries.length > 0 && 'border-t border-border pt-2.5')}>
|
||||
{matchEntries.length > 0 && (
|
||||
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground w-12 shrink-0">
|
||||
<span className="w-12 shrink-0 text-[11px] font-semibold uppercase tracking-wider text-dim">
|
||||
{t('expression.else', 'ELSE')}
|
||||
</span>
|
||||
)}
|
||||
|
||||
@@ -48,16 +48,18 @@ export function CreatedValuesDialog({ values, labels, onContinue }: CreatedValue
|
||||
)}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-3 py-2">
|
||||
<div className="space-y-1 divide-y divide-border rounded-xl bg-muted px-4 py-1">
|
||||
{values &&
|
||||
Object.entries(values).map(([key, value]) => {
|
||||
const text = displayValue(value);
|
||||
const label = labels.get(key) ?? key;
|
||||
return (
|
||||
<div key={key} className="flex flex-col gap-1">
|
||||
<span className="text-sm font-medium">{label}</span>
|
||||
<div key={key} className="flex flex-col gap-1.5 py-3">
|
||||
<span className="text-[13px] font-semibold text-muted-foreground">{label}</span>
|
||||
<div className="flex items-start gap-2">
|
||||
<code className="flex-1 rounded bg-muted p-2 text-sm break-all select-all">{text}</code>
|
||||
<code className="flex-1 select-all break-all rounded-lg bg-card px-3 py-2 font-mono text-sm">
|
||||
{text}
|
||||
</code>
|
||||
<CopyButton value={text} label={label} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -4,12 +4,13 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useEffect, useId, useState, useSyncExternalStore, type ComponentType } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ArrowLeft, Loader2, RefreshCw, Save, Trash2 } from 'lucide-react';
|
||||
import { ArrowLeft, Check, Loader2, RefreshCw, Trash2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ConfirmDialog } from '@/components/common/ConfirmDialog';
|
||||
import { FloatingActionBar, FloatingActionDivider, FloatingActionDot } from '@/components/common/FloatingActionBar';
|
||||
import { useCanAccess } from '@/hooks/usePermissions';
|
||||
import { coerceLabel } from '@/lib/objectOptions';
|
||||
import { TENANT_PROPERTY } from '@/lib/schemaResolver';
|
||||
@@ -18,11 +19,22 @@ import { FormProvider } from '@/components/forms/FormProvider';
|
||||
import { FormSections } from '@/components/forms/FormSections';
|
||||
import { UnsavedChangesDialog } from '@/components/forms/UnsavedChangesDialog';
|
||||
import { formFieldLabels } from '@/components/forms/formLogic';
|
||||
import { useDynamicForm, type DynamicFormModel } from '@/components/forms/useDynamicForm';
|
||||
import { useDynamicForm, type DynamicFormModel, type DynamicFormOptions } from '@/components/forms/useDynamicForm';
|
||||
import type { FieldValues, RenderableSection } from '@/components/forms/formLogic';
|
||||
import { withDestroyContentsNotice } from '@/lib/destroyContents';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface DynamicFormProps {
|
||||
const SECTION_INDEX_MIN = 3;
|
||||
|
||||
export interface AfterSectionsProps {
|
||||
data: FieldValues;
|
||||
readOnly: boolean;
|
||||
}
|
||||
|
||||
interface DynamicFormProps extends DynamicFormOptions {
|
||||
viewName: string;
|
||||
objectId: string | null;
|
||||
afterSections?: ComponentType<AfterSectionsProps>;
|
||||
}
|
||||
|
||||
function capitalize(text: string): string {
|
||||
@@ -44,6 +56,80 @@ function useFormTitle(model: DynamicFormModel): string {
|
||||
: t('form.editTitle', 'Edit {{name}}', { name });
|
||||
}
|
||||
|
||||
const WIDE_QUERY = '(min-width: 80rem)';
|
||||
|
||||
function subscribeWide(onChange: () => void): () => void {
|
||||
const query = window.matchMedia(WIDE_QUERY);
|
||||
query.addEventListener('change', onChange);
|
||||
return () => query.removeEventListener('change', onChange);
|
||||
}
|
||||
|
||||
function isWide(): boolean {
|
||||
return window.matchMedia(WIDE_QUERY).matches;
|
||||
}
|
||||
|
||||
function useActiveSection(ids: readonly string[]): string | undefined {
|
||||
const [active, setActive] = useState<string | undefined>(ids[0]);
|
||||
const key = ids.join('|');
|
||||
useEffect(() => {
|
||||
if (!key) return;
|
||||
const list = key.split('|');
|
||||
const visible = new Set<string>();
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
for (const entry of entries) {
|
||||
if (entry.isIntersecting) visible.add(entry.target.id);
|
||||
else visible.delete(entry.target.id);
|
||||
}
|
||||
const first = list.find((id) => visible.has(id));
|
||||
if (first) setActive(first);
|
||||
},
|
||||
{ rootMargin: '-80px 0px -55% 0px' },
|
||||
);
|
||||
for (const id of list) {
|
||||
const el = document.getElementById(id);
|
||||
if (el) observer.observe(el);
|
||||
}
|
||||
return () => observer.disconnect();
|
||||
}, [key]);
|
||||
return active;
|
||||
}
|
||||
|
||||
function SectionIndex({ sections, sectionId }: { sections: RenderableSection[]; sectionId: (key: string) => string }) {
|
||||
const { t } = useTranslation();
|
||||
const titled = sections.filter((s) => s.title);
|
||||
const active = useActiveSection(titled.map((s) => sectionId(s.key)));
|
||||
return (
|
||||
<nav
|
||||
aria-label={t('form.sectionIndex', 'Form sections')}
|
||||
className="sticky top-20 flex max-h-[calc(100vh-6rem)] flex-col gap-0.5 overflow-y-auto pt-1"
|
||||
>
|
||||
{titled.map((section) => {
|
||||
const id = sectionId(section.key);
|
||||
return (
|
||||
<button
|
||||
key={section.key}
|
||||
type="button"
|
||||
aria-current={active === id ? 'location' : undefined}
|
||||
onClick={() => {
|
||||
const section = document.getElementById(id);
|
||||
section?.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
section?.focus({ preventScroll: true });
|
||||
}}
|
||||
className={cn(
|
||||
'rounded-[10px] px-3 py-1.5 text-left text-[13px] font-medium text-muted-foreground transition-colors hover:bg-card hover:text-foreground',
|
||||
active === id &&
|
||||
'bg-highlight font-semibold text-highlight-foreground hover:bg-highlight hover:text-highlight-foreground',
|
||||
)}
|
||||
>
|
||||
{section.title}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
|
||||
function Loading({ label }: { label: string }) {
|
||||
return (
|
||||
<div className="flex items-center justify-center p-12 text-muted-foreground" role="status">
|
||||
@@ -53,15 +139,26 @@ function Loading({ label }: { label: string }) {
|
||||
);
|
||||
}
|
||||
|
||||
export function DynamicForm({ viewName, objectId }: DynamicFormProps) {
|
||||
export function DynamicForm({
|
||||
viewName,
|
||||
objectId,
|
||||
accountId,
|
||||
fieldOverrides,
|
||||
createValues,
|
||||
showCreatedValues,
|
||||
afterSections: AfterSections,
|
||||
}: DynamicFormProps) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const canUpdate = useCanAccess(viewName, 'Update');
|
||||
const canDestroy = useCanAccess(viewName, 'Destroy');
|
||||
const model = useDynamicForm(viewName, objectId);
|
||||
const model = useDynamicForm(viewName, objectId, { accountId, fieldOverrides, createValues, showCreatedValues });
|
||||
const { schema, resolved, mode, isSingleton, state, isDirty, saving, loading, loadError } = model;
|
||||
const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
|
||||
const [pendingInput, setPendingInput] = useState(false);
|
||||
const title = useFormTitle(model);
|
||||
const sectionPrefix = useId();
|
||||
const wide = useSyncExternalStore(subscribeWide, isWide, () => false);
|
||||
|
||||
if (!schema || !resolved) return <Loading label={t('form.loadingSchema', 'Loading schema...')} />;
|
||||
if (loading) return <Loading label={t('form.loadingData', 'Loading data...')} />;
|
||||
@@ -69,21 +166,23 @@ export function DynamicForm({ viewName, objectId }: DynamicFormProps) {
|
||||
const isCreate = mode === 'create';
|
||||
const readOnly = !isCreate && !canUpdate;
|
||||
const canDelete = !isCreate && !isSingleton && canDestroy;
|
||||
const hasChanges = isDirty || pendingInput;
|
||||
const subtitle = (model.parentForm ?? model.variantForm)?.subtitle;
|
||||
const errorText = state.generalError ?? loadError;
|
||||
const header = (
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex items-start gap-3.5 px-1 pb-1 pt-3">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
variant="outline"
|
||||
size="icon-lg"
|
||||
className="shrink-0"
|
||||
onClick={() => navigate(-1)}
|
||||
aria-label={t('common.back', 'Back')}
|
||||
>
|
||||
<ArrowLeft className="h-5 w-5" aria-hidden="true" />
|
||||
</Button>
|
||||
<div className="flex-1">
|
||||
<h1 className="text-2xl font-semibold tracking-tight">{title}</h1>
|
||||
<div className="min-w-0 flex-1 pt-1">
|
||||
<h1 className="page-title break-words">{title}</h1>
|
||||
{subtitle && <p className="mt-1 text-sm text-muted-foreground">{subtitle}</p>}
|
||||
</div>
|
||||
</div>
|
||||
@@ -91,9 +190,9 @@ export function DynamicForm({ viewName, objectId }: DynamicFormProps) {
|
||||
|
||||
if (model.loadFailed) {
|
||||
return (
|
||||
<div className="mx-auto max-w-4xl space-y-6">
|
||||
<div className="mx-auto max-w-5xl space-y-5">
|
||||
{header}
|
||||
<div className="rounded-md border border-destructive/20 bg-destructive/10 p-4" role="alert">
|
||||
<div className="rounded-xl bg-destructive-soft p-4" role="alert">
|
||||
<p className="whitespace-pre-line text-sm text-destructive">{loadError}</p>
|
||||
</div>
|
||||
<Button type="button" variant="outline" onClick={model.retryLoad}>
|
||||
@@ -110,68 +209,105 @@ export function DynamicForm({ viewName, objectId }: DynamicFormProps) {
|
||||
).toLowerCase();
|
||||
const sch = resolved.resolvedSchema;
|
||||
const tenantValue = state.data[TENANT_PROPERTY];
|
||||
const sectionId = (key: string) => `${sectionPrefix}-section-${key.replace(/[^A-Za-z0-9_-]/g, '_')}`;
|
||||
const showIndex = model.sections.filter((s) => s.title).length >= SECTION_INDEX_MIN;
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-4xl space-y-6">
|
||||
<div className={cn('mx-auto space-y-5', showIndex ? 'max-w-6xl' : 'max-w-5xl')}>
|
||||
{header}
|
||||
|
||||
{errorText && (
|
||||
<div className="rounded-md border border-destructive/20 bg-destructive/10 p-4" role="alert">
|
||||
<div className="rounded-xl bg-destructive-soft p-4" role="alert">
|
||||
<p className="whitespace-pre-line text-sm text-destructive">{errorText}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<FormProvider
|
||||
schema={schema}
|
||||
mode={mode}
|
||||
readOnly={readOnly}
|
||||
recordLabel={model.recordLabel}
|
||||
baseline={state.original}
|
||||
tenantId={typeof tenantValue === 'string' ? tenantValue : null}
|
||||
>
|
||||
<FormSections
|
||||
sections={model.sections}
|
||||
data={state.data}
|
||||
errors={state.fieldErrors}
|
||||
readOnly={readOnly}
|
||||
onFieldChange={model.setField}
|
||||
variant={
|
||||
sch.type === 'multiple'
|
||||
? { variants: sch.variants, value: state.variant, onChange: model.setVariant }
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
</FormProvider>
|
||||
|
||||
<div className="flex items-center justify-between pb-8 pt-2">
|
||||
<div>
|
||||
{canDelete && (
|
||||
<Button type="button" variant="destructive" disabled={saving} onClick={() => setDeleteConfirmOpen(true)}>
|
||||
<Trash2 className="mr-2 h-4 w-4" aria-hidden="true" />
|
||||
{t('common.delete', 'Delete')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
{isDirty && (
|
||||
<span className="text-xs text-muted-foreground">{t('form.unsavedChangesLabel', 'Unsaved changes')}</span>
|
||||
)}
|
||||
<Button type="button" variant="outline" onClick={() => navigate(-1)} disabled={saving}>
|
||||
{t('common.cancel', 'Cancel')}
|
||||
</Button>
|
||||
{!readOnly && (
|
||||
<Button type="button" onClick={() => void model.save()} disabled={saving || (!isCreate && !isDirty)}>
|
||||
{saving ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden="true" />
|
||||
) : (
|
||||
<Save className="mr-2 h-4 w-4" aria-hidden="true" />
|
||||
)}
|
||||
{isCreate ? t('common.create', 'Create') : t('common.save', 'Save')}
|
||||
</Button>
|
||||
)}
|
||||
<div className={cn(showIndex && 'xl:grid xl:grid-cols-[11rem_minmax(0,1fr)] xl:items-start xl:gap-6')}>
|
||||
{showIndex && wide && <SectionIndex sections={model.sections} sectionId={sectionId} />}
|
||||
<div
|
||||
className="space-y-3.5"
|
||||
onInput={(e) => {
|
||||
if (!pendingInput && e.target instanceof Node && e.currentTarget.contains(e.target)) setPendingInput(true);
|
||||
}}
|
||||
onBlur={() => {
|
||||
if (pendingInput) setPendingInput(false);
|
||||
}}
|
||||
>
|
||||
<FormProvider
|
||||
schema={schema}
|
||||
mode={mode}
|
||||
readOnly={readOnly}
|
||||
recordLabel={model.recordLabel}
|
||||
baseline={state.original}
|
||||
tenantId={typeof tenantValue === 'string' ? tenantValue : null}
|
||||
>
|
||||
<FormSections
|
||||
sections={model.sections}
|
||||
sectionId={sectionId}
|
||||
data={state.data}
|
||||
errors={state.fieldErrors}
|
||||
readOnly={readOnly}
|
||||
onFieldChange={model.setField}
|
||||
renderers={fieldOverrides?.render}
|
||||
variant={
|
||||
sch.type === 'multiple'
|
||||
? { variants: sch.variants, value: state.variant, onChange: model.setVariant }
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
{AfterSections && <AfterSections data={state.data} readOnly={readOnly} />}
|
||||
</FormProvider>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<FloatingActionBar label={t('form.actions', 'Form actions')}>
|
||||
{canDelete && (
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ink-danger"
|
||||
size="sm"
|
||||
disabled={saving}
|
||||
onClick={() => setDeleteConfirmOpen(true)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" aria-hidden="true" />
|
||||
<span className="max-sm:sr-only">{t('common.delete', 'Delete')}</span>
|
||||
</Button>
|
||||
<FloatingActionDivider />
|
||||
</>
|
||||
)}
|
||||
{!readOnly && (
|
||||
<span
|
||||
className={cn(
|
||||
'flex items-center gap-2 px-2 text-[13px] text-ink-muted max-sm:hidden',
|
||||
!hasChanges && 'invisible',
|
||||
)}
|
||||
>
|
||||
<FloatingActionDot />
|
||||
{t('form.unsavedChangesLabel', 'Unsaved changes')}
|
||||
</span>
|
||||
)}
|
||||
<Button type="button" variant="ink" size="sm" onClick={() => navigate(-1)} disabled={saving}>
|
||||
{t('common.cancel', 'Cancel')}
|
||||
</Button>
|
||||
{!readOnly && (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
className="shadow-none"
|
||||
onClick={() => void model.save()}
|
||||
disabled={saving || (!isCreate && !hasChanges)}
|
||||
>
|
||||
{saving ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />
|
||||
) : (
|
||||
<Check className="h-4 w-4" aria-hidden="true" />
|
||||
)}
|
||||
{isCreate ? t('common.create', 'Create') : t('common.save', 'Save')}
|
||||
</Button>
|
||||
)}
|
||||
</FloatingActionBar>
|
||||
|
||||
<UnsavedChangesDialog blocker={model.guard.blocker} />
|
||||
|
||||
<ConfirmDialog
|
||||
@@ -179,10 +315,11 @@ export function DynamicForm({ viewName, objectId }: DynamicFormProps) {
|
||||
onOpenChange={setDeleteConfirmOpen}
|
||||
variant="destructive"
|
||||
title={t('form.deleteTitle', 'Delete {{name}}?', { name: capitalize(deleteLabel) })}
|
||||
description={t(
|
||||
'form.deleteDescription',
|
||||
'This action cannot be undone. This will permanently delete this {{name}}.',
|
||||
{ name: deleteLabel },
|
||||
description={withDestroyContentsNotice(
|
||||
t('form.deleteDescription', 'This action cannot be undone. This will permanently delete this {{name}}.', {
|
||||
name: deleteLabel,
|
||||
}),
|
||||
resolved.object.objectName,
|
||||
)}
|
||||
confirmLabel={t('common.delete', 'Delete')}
|
||||
onConfirm={model.remove}
|
||||
|
||||
@@ -11,10 +11,9 @@ import { Label } from '@/components/ui/label';
|
||||
import { Markdown } from '@/components/common/Markdown';
|
||||
import { HelpTooltip } from '@/components/common/HelpTooltip';
|
||||
import { FieldValue } from '@/components/values/FieldValue';
|
||||
import { SievepadButton } from '@/components/forms/SievepadButton';
|
||||
import { FieldScopeProvider } from '@/components/forms/FormProvider';
|
||||
import { FieldControl } from '@/components/forms/widgets/FieldControl';
|
||||
import { widgetTraits } from '@/components/forms/widgets/registry';
|
||||
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';
|
||||
@@ -44,16 +43,16 @@ interface FieldLabelProps {
|
||||
export function FieldLabel({ id, htmlFor, label, marker, locked }: FieldLabelProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<Label id={id} htmlFor={htmlFor} className="text-sm font-medium">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Label id={id} htmlFor={htmlFor} className="text-[13.5px] font-semibold leading-snug">
|
||||
{label}
|
||||
{marker === 'required' && (
|
||||
<span className="ml-0.5 text-destructive" aria-hidden="true">
|
||||
<span className="ml-1 text-brand-text" aria-hidden="true">
|
||||
*
|
||||
</span>
|
||||
)}
|
||||
{marker === 'optional' && (
|
||||
<span className="ml-1.5 text-xs font-normal text-muted-foreground">{t('field.optional', '(optional)')}</span>
|
||||
<span className="ml-1.5 text-xs font-normal text-dim">{t('field.optional', '(optional)')}</span>
|
||||
)}
|
||||
</Label>
|
||||
{locked && (
|
||||
@@ -70,7 +69,7 @@ export function FieldLabel({ id, htmlFor, label, marker, locked }: FieldLabelPro
|
||||
export function FieldError({ id, error }: { id: string; error?: string }) {
|
||||
if (!error) return null;
|
||||
return (
|
||||
<p id={id} className="text-xs text-destructive">
|
||||
<p id={id} className="text-xs font-medium text-destructive">
|
||||
{error}
|
||||
</p>
|
||||
);
|
||||
@@ -94,7 +93,7 @@ export function FieldRow({ field, formField, value, onChange, error, readOnly: f
|
||||
referencesLocked ||
|
||||
field.update === 'serverSet' ||
|
||||
(topLevel && ctx.mode === 'edit' && field.update === 'immutable');
|
||||
const traits = widgetTraits(ft);
|
||||
const { traits, RowAddon } = resolveWidget(ft);
|
||||
const asValue = readOnly && traits.readOnlyAsValue;
|
||||
const marker = requiredMarker(field, readOnly);
|
||||
const describedBy =
|
||||
@@ -107,19 +106,12 @@ export function FieldRow({ field, formField, value, onChange, error, readOnly: f
|
||||
'aria-required': marker === 'required' && ARIA_REQUIRED_TYPES.has(ft.type) ? true : undefined,
|
||||
};
|
||||
|
||||
const widgetProps = { type: ft, field, formField, value, onChange, readOnly, control, error };
|
||||
let body: ReactNode = asValue ? (
|
||||
<FieldValue schema={ctx.schema} type={ft} value={value} />
|
||||
) : (
|
||||
<FieldScopeProvider name={formField.name} readOnly={readOnly}>
|
||||
<FieldControl
|
||||
type={ft}
|
||||
field={field}
|
||||
formField={formField}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
readOnly={readOnly}
|
||||
control={control}
|
||||
/>
|
||||
<FieldControl {...widgetProps} />
|
||||
</FieldScopeProvider>
|
||||
);
|
||||
if (!asValue && traits.labelMode === 'group') {
|
||||
@@ -132,32 +124,48 @@ export function FieldRow({ field, formField, value, onChange, error, readOnly: f
|
||||
|
||||
if (traits.labelMode === 'none') {
|
||||
return (
|
||||
<div className="space-y-1.5">
|
||||
<div data-slot="field-row" className="space-y-1.5 py-4">
|
||||
{body}
|
||||
{RowAddon && <RowAddon {...widgetProps} />}
|
||||
<FieldError id={ids.errorId} error={error} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const layout = asValue && traits.layout === 'inline' ? 'side' : traits.layout;
|
||||
return (
|
||||
<div className="space-y-1.5">
|
||||
<FieldLabel
|
||||
id={ids.labelId}
|
||||
htmlFor={traits.labelMode === 'control' && !asValue ? ids.inputId : undefined}
|
||||
label={formField.label}
|
||||
marker={marker}
|
||||
locked={locked}
|
||||
/>
|
||||
{field.description && (
|
||||
<div id={ids.descriptionId}>
|
||||
<Markdown source={field.description} className="text-xs text-muted-foreground" />
|
||||
<div
|
||||
data-slot="field-row"
|
||||
className={cn(
|
||||
'py-4',
|
||||
layout === 'side' ? 'field-grid' : 'grid gap-x-8 gap-y-2',
|
||||
layout === 'inline' && 'grid-cols-[minmax(0,1fr)_auto]',
|
||||
)}
|
||||
>
|
||||
<div className={cn('min-w-0 space-y-1', layout === 'side' && '@xl:pt-2')}>
|
||||
<FieldLabel
|
||||
id={ids.labelId}
|
||||
htmlFor={traits.labelMode === 'control' && !asValue ? ids.inputId : undefined}
|
||||
label={formField.label}
|
||||
marker={marker}
|
||||
locked={locked}
|
||||
/>
|
||||
{field.description && (
|
||||
<div id={ids.descriptionId}>
|
||||
<Markdown source={field.description} className="text-[12.5px] leading-relaxed text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className={cn('min-w-0 space-y-1.5', layout === 'inline' && 'pt-0.5', asValue && '@xl:pt-2')}>
|
||||
<div className={cn(locked && 'opacity-60')}>{body}</div>
|
||||
{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 className={cn(locked && 'opacity-60')}>{body}</div>
|
||||
{ft.type === 'string' && ft.format === 'sieve' && (
|
||||
<SievepadButton scriptName={ctx.recordLabel} source={typeof value === 'string' ? value : ''} />
|
||||
)}
|
||||
<FieldError id={ids.errorId} error={error} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -5,11 +5,12 @@
|
||||
*/
|
||||
|
||||
import type { ReactNode } from 'react';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { FieldRow } from '@/components/forms/FieldRow';
|
||||
import { VariantSelect } from '@/components/forms/VariantSelect';
|
||||
import type { EmbeddedVariant } from '@/lib/embeddedSchema';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { FieldErrors, FieldValues, RenderableSection } from '@/components/forms/formLogic';
|
||||
import type { FieldOverrides } from '@/components/forms/useDynamicForm';
|
||||
|
||||
interface VariantControl {
|
||||
variants: readonly EmbeddedVariant[];
|
||||
@@ -19,18 +20,29 @@ interface VariantControl {
|
||||
|
||||
interface FormSectionsProps {
|
||||
sections: RenderableSection[];
|
||||
sectionId?: (key: string) => string;
|
||||
data: FieldValues;
|
||||
errors: FieldErrors;
|
||||
readOnly: boolean;
|
||||
onFieldChange: (name: string, value: unknown) => void;
|
||||
variant?: VariantControl;
|
||||
renderers?: FieldOverrides['render'];
|
||||
}
|
||||
|
||||
export function FormSections({ sections, data, errors, readOnly, onFieldChange, variant }: FormSectionsProps) {
|
||||
export function FormSections({
|
||||
sections,
|
||||
sectionId,
|
||||
data,
|
||||
errors,
|
||||
readOnly,
|
||||
onFieldChange,
|
||||
variant,
|
||||
renderers,
|
||||
}: FormSectionsProps) {
|
||||
return (
|
||||
<>
|
||||
{sections.map((section) => (
|
||||
<FormSectionCard key={section.key} title={section.title}>
|
||||
<FormSectionCard key={section.key} id={sectionId?.(section.key)} title={section.title}>
|
||||
{section.fields.map(({ formField, field }) => {
|
||||
if (!field) {
|
||||
if (!variant) return null;
|
||||
@@ -45,6 +57,20 @@ export function FormSections({ sections, data, errors, readOnly, onFieldChange,
|
||||
/>
|
||||
);
|
||||
}
|
||||
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}
|
||||
@@ -62,17 +88,15 @@ export function FormSections({ sections, data, errors, readOnly, onFieldChange,
|
||||
);
|
||||
}
|
||||
|
||||
export function FormSectionCard({ title, children }: { title?: string; children: ReactNode }) {
|
||||
export function FormSectionCard({ id, title, children }: { id?: string; title?: string; children: ReactNode }) {
|
||||
return (
|
||||
<Card>
|
||||
{title && (
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">{title}</CardTitle>
|
||||
</CardHeader>
|
||||
)}
|
||||
<CardContent className={title ? '' : 'pt-6'}>
|
||||
<div className="space-y-6">{children}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<section
|
||||
id={id}
|
||||
tabIndex={id ? -1 : undefined}
|
||||
className="tile @container scroll-mt-20 px-5 pb-1.5 outline-none sm:px-6"
|
||||
>
|
||||
{title && <h2 className="section-title pb-1 pt-5">{title}</h2>}
|
||||
<div className={cn('divide-y divide-border', !title && 'pt-1')}>{children}</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -14,6 +14,8 @@ 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;
|
||||
@@ -48,8 +50,8 @@ export function SievepadButton({ scriptName, source }: SievepadButtonProps) {
|
||||
return (
|
||||
<>
|
||||
<div className="flex justify-end">
|
||||
<Button type="button" variant="outline" size="sm" onClick={handleClick} disabled={!source.trim()}>
|
||||
<Bug className="h-4 w-4" />
|
||||
<Button type="button" variant="secondary" size="sm" onClick={handleClick} disabled={!source.trim()}>
|
||||
<Bug aria-hidden="true" />
|
||||
{t('sievepad.debug', 'Debug')}
|
||||
</Button>
|
||||
</div>
|
||||
@@ -64,7 +66,7 @@ export function SievepadButton({ scriptName, source }: SievepadButtonProps) {
|
||||
confirmLabel={t('common.continue')}
|
||||
onConfirm={handleContinue}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex items-center gap-2.5 rounded-xl bg-muted px-3.5 py-3">
|
||||
<Checkbox
|
||||
id="sievepad-dont-show-again"
|
||||
checked={dontShowAgain}
|
||||
@@ -78,3 +80,8 @@ export function SievepadButton({ scriptName, source }: SievepadButtonProps) {
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function SievepadRowAddon({ value }: WidgetProps) {
|
||||
const { recordLabel } = useFormContext();
|
||||
return <SievepadButton scriptName={recordLabel} source={typeof value === 'string' ? value : ''} />;
|
||||
}
|
||||
@@ -4,12 +4,17 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import type { KeyboardEvent } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { FieldLabel } from '@/components/forms/FieldRow';
|
||||
import { fieldIds, useFieldScope, useFormContext } from '@/components/forms/formContext';
|
||||
import { fieldIds, useFieldScope, useFormContext, useInPanel } from '@/components/forms/formContext';
|
||||
import { VARIANT_FIELD } from '@/components/forms/formLogic';
|
||||
import type { EmbeddedVariant } from '@/lib/embeddedSchema';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const SEGMENTED_MAX_VARIANTS = 4;
|
||||
const SEGMENTED_MAX_LABEL_CHARS = 44;
|
||||
|
||||
interface VariantSelectProps {
|
||||
label?: string;
|
||||
@@ -21,6 +26,102 @@ interface VariantSelectProps {
|
||||
readOnly: boolean;
|
||||
}
|
||||
|
||||
function isSegmented(variants: readonly EmbeddedVariant[]): boolean {
|
||||
return (
|
||||
variants.length > 1 &&
|
||||
variants.length <= SEGMENTED_MAX_VARIANTS &&
|
||||
variants.reduce((sum, v) => sum + v.label.length, 0) <= SEGMENTED_MAX_LABEL_CHARS
|
||||
);
|
||||
}
|
||||
|
||||
interface VariantControlProps {
|
||||
id: string;
|
||||
labelledBy?: string;
|
||||
ariaLabel?: string;
|
||||
variants: readonly EmbeddedVariant[];
|
||||
value: string;
|
||||
onChange: (variant: string) => void;
|
||||
readOnly: boolean;
|
||||
}
|
||||
|
||||
const ROVING_KEYS: Record<string, number> = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 };
|
||||
|
||||
function moveRadioFocus(e: KeyboardEvent<HTMLDivElement>) {
|
||||
const step = Object.hasOwn(ROVING_KEYS, e.key) ? ROVING_KEYS[e.key] : 0;
|
||||
if (!step && e.key !== 'Home' && e.key !== 'End') return;
|
||||
const radios = Array.from(e.currentTarget.querySelectorAll<HTMLButtonElement>('[role="radio"]'));
|
||||
if (radios.length === 0) return;
|
||||
e.preventDefault();
|
||||
const current = radios.indexOf(document.activeElement as HTMLButtonElement);
|
||||
const next =
|
||||
e.key === 'Home'
|
||||
? 0
|
||||
: e.key === 'End'
|
||||
? radios.length - 1
|
||||
: (Math.max(current, 0) + step + radios.length) % radios.length;
|
||||
radios[next].focus();
|
||||
}
|
||||
|
||||
function SegmentedVariants({ id, labelledBy, ariaLabel, variants, value, onChange, readOnly }: VariantControlProps) {
|
||||
const inPanel = useInPanel();
|
||||
const hasChecked = variants.some((v) => v.name === value);
|
||||
return (
|
||||
<div
|
||||
role="radiogroup"
|
||||
id={id}
|
||||
aria-labelledby={labelledBy}
|
||||
aria-label={ariaLabel}
|
||||
aria-disabled={readOnly || undefined}
|
||||
onKeyDown={moveRadioFocus}
|
||||
className={cn(
|
||||
'inline-flex max-w-full flex-wrap gap-0.5 rounded-full p-1',
|
||||
inPanel ? 'bg-muted-strong' : 'bg-muted',
|
||||
)}
|
||||
>
|
||||
{variants.map((v, i) => {
|
||||
const checked = v.name === value;
|
||||
return (
|
||||
<button
|
||||
key={v.name}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={checked}
|
||||
tabIndex={checked || (!hasChecked && i === 0) ? 0 : -1}
|
||||
disabled={readOnly}
|
||||
onClick={() => {
|
||||
if (!checked) onChange(v.name);
|
||||
}}
|
||||
className={cn(
|
||||
'inline-flex h-7 items-center rounded-full px-3 text-[13px] font-semibold text-muted-foreground outline-none transition-[color,background-color,box-shadow] duration-200 focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-60',
|
||||
checked ? 'bg-card text-foreground shadow-tile' : 'hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
{v.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownVariants({ id, labelledBy, ariaLabel, variants, value, onChange, readOnly }: VariantControlProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Select value={value} onValueChange={onChange} disabled={readOnly}>
|
||||
<SelectTrigger id={id} className="w-full" aria-labelledby={labelledBy} aria-label={ariaLabel}>
|
||||
<SelectValue placeholder={t('form.selectType', 'Select type...')} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{variants.map((v) => (
|
||||
<SelectItem key={v.name} value={v.name}>
|
||||
{v.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
);
|
||||
}
|
||||
|
||||
export function VariantSelect({
|
||||
label,
|
||||
labelledBy,
|
||||
@@ -35,29 +136,43 @@ export function VariantSelect({
|
||||
const scope = useFieldScope();
|
||||
const ids = fieldIds(ctx.idPrefix, [...scope.path, VARIANT_FIELD]);
|
||||
const external = !!labelledBy || !!ariaLabel;
|
||||
const segmented = isSegmented(variants);
|
||||
const Control = segmented ? SegmentedVariants : DropdownVariants;
|
||||
const controlProps = {
|
||||
id: ids.inputId,
|
||||
variants,
|
||||
value,
|
||||
onChange,
|
||||
readOnly,
|
||||
};
|
||||
|
||||
if (external) {
|
||||
return (
|
||||
<div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2">
|
||||
<span className="text-xs font-semibold uppercase tracking-wider text-dim" aria-hidden="true">
|
||||
{t('field.type', 'Type')}
|
||||
</span>
|
||||
<div className={cn('min-w-0', !segmented && 'w-full max-w-sm')}>
|
||||
<Control {...controlProps} labelledBy={labelledBy} ariaLabel={ariaLabel} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-1.5">
|
||||
{!external && (
|
||||
<div data-slot="field-row" className="field-grid py-4">
|
||||
<div className="@xl:pt-2">
|
||||
<FieldLabel
|
||||
id={ids.labelId}
|
||||
htmlFor={ids.inputId}
|
||||
htmlFor={segmented ? undefined : ids.inputId}
|
||||
label={label || t('field.type', 'Type')}
|
||||
marker={null}
|
||||
locked={false}
|
||||
/>
|
||||
)}
|
||||
<Select value={value} onValueChange={onChange} disabled={readOnly}>
|
||||
<SelectTrigger id={ids.inputId} className="w-full" aria-labelledby={labelledBy} aria-label={ariaLabel}>
|
||||
<SelectValue placeholder={t('form.selectType', 'Select type...')} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{variants.map((v) => (
|
||||
<SelectItem key={v.name} value={v.name}>
|
||||
{v.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<Control {...controlProps} labelledBy={segmented ? ids.labelId : undefined} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -30,6 +30,10 @@ 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');
|
||||
@@ -40,6 +44,14 @@ 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;
|
||||
}
|
||||
|
||||
@@ -9,9 +9,22 @@ import { deepMerge, resolveForm, resolveObject, type ResolvedView } from '@/lib/
|
||||
import { SECRET_MASK } from '@/lib/jmapUtils';
|
||||
import { embeddedEntries, isRecord, resolveEmbedded } from '@/lib/embeddedSchema';
|
||||
import { isMissingValue, isRequiredField, isUnchangedSecret } from '@/lib/fieldRules';
|
||||
import { parseLocalDate, parseLocalTime } from '@/lib/localDateTime';
|
||||
import { WORKING_HOURS_SLOT, isScheduleInvalid, scheduleRules } from '@/lib/weeklySchedule';
|
||||
import { widgetTraits } from '@/extensions/widgets';
|
||||
import type { BlobUpload } from '@/services/jmap/client';
|
||||
import type { JmapSetError, ValidationError } from '@/types/jmap';
|
||||
import type { Field, FieldType, Fields, Form, FormField, Schema } from '@/types/schema';
|
||||
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>;
|
||||
@@ -67,40 +80,180 @@ export function requiredMarker(field: Field, readOnly: boolean): 'required' | 'o
|
||||
return isNullable(field.type) ? 'optional' : 'required';
|
||||
}
|
||||
|
||||
function itemCount(value: unknown): number {
|
||||
return isRecord(value) ? Object.keys(value).length : 0;
|
||||
}
|
||||
|
||||
function isMissingNestedValue(schema: Schema, field: Field, value: unknown): boolean {
|
||||
if (field.update === 'serverSet') return false;
|
||||
if (isRequiredField(field) && isMissingValue(value)) return true;
|
||||
const { type } = field;
|
||||
switch (type.type) {
|
||||
case 'object':
|
||||
return hasMissingNested(schema, type.objectName, value);
|
||||
case 'objectList':
|
||||
return (
|
||||
(type.minItems != null && itemCount(value) < type.minItems) ||
|
||||
(isRecord(value) && Object.values(value).some((item) => hasMissingNested(schema, type.objectName, item)))
|
||||
);
|
||||
case 'set':
|
||||
return type.minItems != null && itemCount(value) < type.minItems;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function missingNestedFields(schema: Schema, objectName: string, value: unknown): string[] {
|
||||
if (!isRecord(value)) return [];
|
||||
const resolved = resolveEmbedded(schema, objectName, value);
|
||||
if (!resolved) return [];
|
||||
return embeddedEntries(resolved)
|
||||
.filter(({ formField, field }) => isMissingNestedValue(schema, field, value[formField.name]))
|
||||
.map(({ formField }) => formField.name);
|
||||
}
|
||||
|
||||
function hasMissingNested(schema: Schema, objectName: string, value: unknown): boolean {
|
||||
if (!isRecord(value)) return false;
|
||||
const resolved = resolveEmbedded(schema, objectName, value);
|
||||
if (!resolved) return false;
|
||||
for (const { formField, field } of embeddedEntries(resolved)) {
|
||||
if (field.update === 'serverSet') continue;
|
||||
const nested = value[formField.name];
|
||||
if (isRequiredField(field) && isMissingValue(nested)) return true;
|
||||
if (field.type.type === 'object' && hasMissingNested(schema, field.type.objectName, nested)) return true;
|
||||
}
|
||||
return false;
|
||||
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,
|
||||
message: string,
|
||||
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 (isRequiredField(field, mode) && isMissingValue(data[name])) errors[name] = message;
|
||||
else if (
|
||||
schema &&
|
||||
field.type.type === 'object' &&
|
||||
field.update !== 'serverSet' &&
|
||||
!(mode === 'edit' && field.update === 'immutable') &&
|
||||
hasMissingNested(schema, field.type.objectName, data[name])
|
||||
) {
|
||||
errors[name] = message;
|
||||
}
|
||||
if (field.update === 'serverSet') continue;
|
||||
const invalid = invalidValue(schema, field.type, data[name], null);
|
||||
if (invalid) errors[name] = messages[invalid];
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
@@ -152,7 +305,6 @@ export function buildUpdatePatch(original: FieldValues, data: FieldValues, field
|
||||
if (key === 'id') continue;
|
||||
const field = fields?.properties[key];
|
||||
if (field?.update === 'serverSet') continue;
|
||||
if (field?.update === 'immutable' && valuesEqual(original[key], value)) continue;
|
||||
if (field && isUnchangedSecret(field, value)) continue;
|
||||
patch[key] = value === undefined ? null : withoutMaskedSecrets(value);
|
||||
}
|
||||
@@ -201,9 +353,11 @@ export function mapSetError(
|
||||
): { general: string; fieldErrors: FieldErrors } {
|
||||
const fieldErrors: FieldErrors = {};
|
||||
const extra: string[] = [];
|
||||
const validated = new Set(error.validationErrors?.map((ve) => ve.property));
|
||||
for (const prop of error.properties ?? []) {
|
||||
const top = prop.split('/')[0];
|
||||
if (top && knownFields.has(top)) fieldErrors[top] = error.description ?? messages.invalidValue;
|
||||
else if (!validated.has(prop)) extra.push(`${prop}: ${messages.invalidValue}`);
|
||||
}
|
||||
for (const ve of error.validationErrors ?? []) {
|
||||
if (!ve.property) continue;
|
||||
@@ -227,6 +381,17 @@ export function combineForms(parent: Form | null, variant: Form | null): Form |
|
||||
};
|
||||
}
|
||||
|
||||
export function validatedFieldNames(
|
||||
formNames: ReadonlySet<string>,
|
||||
fields: Fields,
|
||||
hidden: ReadonlySet<string>,
|
||||
): ReadonlySet<string> | undefined {
|
||||
if (hidden.size === 0) return formNames.size > 0 ? formNames : undefined;
|
||||
const names = new Set(formNames.size > 0 ? formNames : Object.keys(fields.properties));
|
||||
for (const name of hidden) names.delete(name);
|
||||
return names;
|
||||
}
|
||||
|
||||
export function formFieldNames(...forms: (Form | null | undefined)[]): Set<string> {
|
||||
const names = new Set<string>();
|
||||
for (const form of forms) {
|
||||
@@ -296,12 +461,20 @@ export interface RenderableSection {
|
||||
fields: RenderableField[];
|
||||
}
|
||||
|
||||
export function buildSections(form: Form | null, fields: Fields | null, mode: FormMode): RenderableSection[] {
|
||||
const visible = (field: Field) => !(mode === 'create' && field.update === 'serverSet');
|
||||
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(([, field]) => visible(field))
|
||||
.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 }] : [];
|
||||
}
|
||||
@@ -313,6 +486,7 @@ export function buildSections(form: Form | null, fields: Fields | null, mode: Fo
|
||||
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 });
|
||||
}
|
||||
@@ -321,6 +495,18 @@ export function buildSections(form: Form | null, fields: Fields | null, mode: Fo
|
||||
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']);
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useEffect, useReducer } from 'react';
|
||||
import { useEffect, useReducer, type ComponentType } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useSchemaStore } from '@/stores/schemaStore';
|
||||
@@ -14,6 +14,7 @@ import { toast } from '@/hooks/use-toast';
|
||||
import {
|
||||
buildCreateDefaults,
|
||||
buildEmbeddedDefaults,
|
||||
deepMerge,
|
||||
getDisplayProperty,
|
||||
resolveForm,
|
||||
resolveVariantForm,
|
||||
@@ -37,21 +38,32 @@ import {
|
||||
formFieldNames,
|
||||
isOtpAuthValid,
|
||||
mapSetError,
|
||||
mergeFieldErrors,
|
||||
validateFormat,
|
||||
validateRequired,
|
||||
validatedFieldNames,
|
||||
VARIANT_FIELD,
|
||||
withoutSectionTitles,
|
||||
type FieldErrors,
|
||||
type FieldValues,
|
||||
} from '@/components/forms/formLogic';
|
||||
import { formReducer, initialFormState, isFormDirty, type FormState } from '@/components/forms/formReducer';
|
||||
import { useUnsavedChangesGuard } from '@/components/forms/useUnsavedChangesGuard';
|
||||
import type { FormMode } from '@/components/forms/formContext';
|
||||
import type { JmapSetError } from '@/types/jmap';
|
||||
import type { Fields, Form, Schema } from '@/types/schema';
|
||||
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): FieldValues {
|
||||
const data = buildCreateDefaults(schema, view.object, view.resolvedSchema, variant, view.list?.filtersStatic);
|
||||
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;
|
||||
}
|
||||
@@ -63,10 +75,15 @@ function initialCreateVariant(view: ResolvedView): string | undefined {
|
||||
return typeof fromFilter === 'string' ? fromFilter : (resolvedSchema.variants[0]?.name ?? '');
|
||||
}
|
||||
|
||||
function initialState(schema: Schema | null, view: ResolvedView | null, mode: FormMode): FormState {
|
||||
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), variant ?? '', view);
|
||||
return initialFormState(createDefaults(schema, view, variant, createValues), variant ?? '', view);
|
||||
}
|
||||
|
||||
function loadedVariant(view: ResolvedView, data: FieldValues): string {
|
||||
@@ -75,7 +92,34 @@ function loadedVariant(view: ResolvedView, data: FieldValues): string {
|
||||
return typeof type === 'string' ? type : (view.resolvedSchema.variants[0]?.name ?? '');
|
||||
}
|
||||
|
||||
export function useDynamicForm(viewName: string, objectId: string | null) {
|
||||
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);
|
||||
@@ -86,14 +130,14 @@ export function useDynamicForm(viewName: string, objectId: string | null) {
|
||||
const isSingleton = resolved?.object.objectType.type === 'singleton';
|
||||
const objectName = resolved?.object.objectName;
|
||||
|
||||
const [state, dispatch] = useReducer(formReducer, null, () => initialState(schema, resolved, mode));
|
||||
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),
|
||||
data: createDefaults(schema, resolved, variant, createValues),
|
||||
variant: variant ?? '',
|
||||
source: resolved,
|
||||
});
|
||||
@@ -103,7 +147,7 @@ export function useDynamicForm(viewName: string, objectId: string | null) {
|
||||
objectName,
|
||||
mode === 'create' ? null : isSingleton ? 'singleton' : objectId,
|
||||
schema && resolved ? collectFetchProperties(schema, resolved, viewName) : ['id'],
|
||||
{ staleTime: 0, refetchOnMount: 'always' },
|
||||
{ staleTime: 0, refetchOnMount: 'always', accountId },
|
||||
);
|
||||
if (objectQuery.data && objectQuery.data !== state.source && !isDirty && resolved) {
|
||||
dispatch({
|
||||
@@ -140,7 +184,8 @@ export function useDynamicForm(viewName: string, objectId: string | null) {
|
||||
}
|
||||
}
|
||||
const form = sch?.type === 'multiple' ? combineForms(parentForm, variantForm) : variantForm;
|
||||
const sections = buildSections(form, fields, mode);
|
||||
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 =
|
||||
@@ -165,7 +210,9 @@ export function useDynamicForm(viewName: string, objectId: string | null) {
|
||||
};
|
||||
|
||||
const applySetError = (error: JmapSetError) => {
|
||||
const { general, fieldErrors } = mapSetError(error, new Set(Object.keys(fields?.properties ?? {})), {
|
||||
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,
|
||||
@@ -183,7 +230,7 @@ export function useDynamicForm(viewName: string, objectId: string | null) {
|
||||
const { variants } = resolved.resolvedSchema;
|
||||
const defaults =
|
||||
mode === 'create'
|
||||
? createDefaults(schema, resolved, next)
|
||||
? createDefaults(schema, resolved, next, createValues)
|
||||
: buildEmbeddedDefaults(schema, resolved.object.objectName, {}, next);
|
||||
const data = switchVariantValues(
|
||||
variants.find((v) => v.name === state.variant)?.fields,
|
||||
@@ -198,14 +245,33 @@ export function useDynamicForm(viewName: string, objectId: string | null) {
|
||||
const save = async () => {
|
||||
if (!resolved || saving) return;
|
||||
if (fields) {
|
||||
const visible = formFieldNames(parentForm, variantForm);
|
||||
const errors = validateRequired(
|
||||
state.data,
|
||||
fields,
|
||||
mode,
|
||||
t('form.required', 'This field is required.'),
|
||||
visible.size > 0 ? visible : undefined,
|
||||
schema ?? undefined,
|
||||
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({
|
||||
@@ -234,14 +300,14 @@ export function useDynamicForm(viewName: string, objectId: string | null) {
|
||||
}),
|
||||
fields,
|
||||
);
|
||||
const result = await setMutation.mutateAsync({ create: { [CREATE_ID]: payload }, blobs });
|
||||
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 (Object.keys(extras).length > 0) {
|
||||
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' });
|
||||
@@ -263,7 +329,7 @@ export function useDynamicForm(viewName: string, objectId: string | null) {
|
||||
}
|
||||
const { blobs, payload } = collectBlobUploads(patch, fields, state.original);
|
||||
const updateId = isSingleton ? 'singleton' : objectId!;
|
||||
const result = await setMutation.mutateAsync({ update: { [updateId]: payload }, blobs });
|
||||
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' });
|
||||
@@ -282,7 +348,7 @@ export function useDynamicForm(viewName: string, objectId: string | null) {
|
||||
if (!resolved || !objectId) return;
|
||||
dispatch({ type: 'setErrors', generalError: null });
|
||||
try {
|
||||
const result = await setMutation.mutateAsync({ destroy: [objectId] });
|
||||
const result = await setMutation.mutateAsync({ destroy: [objectId], accountId });
|
||||
if (result.destroyed?.includes(objectId)) {
|
||||
const label = resolved.list?.singularName ?? resolved.object.objectType.description;
|
||||
toast({
|
||||
|
||||
@@ -11,11 +11,14 @@ 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({ value, onChange, readOnly, control }: WidgetProps<FieldTypeBlobId>) {
|
||||
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);
|
||||
@@ -27,7 +30,7 @@ export function BlobWidget({ value, onChange, readOnly, control }: WidgetProps<F
|
||||
if (blobId && blob.isPending) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 py-2 text-sm text-muted-foreground" role="status">
|
||||
<Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />
|
||||
<Loader2 className="h-4 w-4 animate-spin text-brand-text" aria-hidden="true" />
|
||||
{t('field.loadingContent', 'Loading content...')}
|
||||
</div>
|
||||
);
|
||||
@@ -35,7 +38,7 @@ export function BlobWidget({ value, onChange, readOnly, control }: WidgetProps<F
|
||||
|
||||
if (blobId && (blob.isError || blob.data === null)) {
|
||||
return (
|
||||
<div className="flex items-center justify-between gap-2 rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2">
|
||||
<div className="flex items-center justify-between gap-3 rounded-xl bg-destructive-soft py-2.5 pl-4 pr-2.5">
|
||||
<p className="text-sm text-destructive" role="alert">
|
||||
{blob.isError
|
||||
? errorMessage(blob.error, t('field.blobLoadFailed', 'Failed to load content.'))
|
||||
@@ -45,6 +48,7 @@ export function BlobWidget({ value, onChange, readOnly, control }: WidgetProps<F
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="shrink-0"
|
||||
onClick={() => void blob.refetch()}
|
||||
disabled={blob.isFetching}
|
||||
>
|
||||
@@ -54,11 +58,13 @@ export function BlobWidget({ value, onChange, readOnly, control }: WidgetProps<F
|
||||
);
|
||||
}
|
||||
|
||||
const text = edited ?? blob.data ?? '';
|
||||
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
<BufferedTextarea
|
||||
{...control}
|
||||
value={edited ?? blob.data ?? ''}
|
||||
value={text}
|
||||
onCommit={(text) => {
|
||||
setEdited(text);
|
||||
onChange(text);
|
||||
@@ -68,10 +74,11 @@ export function BlobWidget({ value, onChange, readOnly, control }: WidgetProps<F
|
||||
className="font-mono text-xs"
|
||||
/>
|
||||
{isOwnEdit && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
<p className="text-xs font-medium text-warning">
|
||||
{t('field.contentModified', 'Content modified (will be saved as a new blob)')}
|
||||
</p>
|
||||
)}
|
||||
{type.format === 'sieve' && <SievepadButton scriptName={recordLabel} source={text} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -40,6 +40,7 @@ export function BufferedInput({ value, onCommit, onBlur, onKeyDown, ...rest }: B
|
||||
}
|
||||
|
||||
interface BufferedTextareaProps extends Omit<TextareaHTMLAttributes<HTMLTextAreaElement>, 'onChange' | 'value'> {
|
||||
variant?: 'field' | 'bare';
|
||||
value: string;
|
||||
onCommit: (v: string) => void;
|
||||
}
|
||||
|
||||
@@ -15,12 +15,12 @@ import { cn } from '@/lib/utils';
|
||||
import type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
import type { FieldTypeUtcDateTime } from '@/types/schema';
|
||||
|
||||
const Calendar = lazy(() => import('@/components/ui/calendar').then((m) => ({ default: m.Calendar })));
|
||||
export const Calendar = lazy(() => import('@/components/ui/calendar').then((m) => ({ default: m.Calendar })));
|
||||
|
||||
function CalendarFallback() {
|
||||
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-muted-foreground" aria-hidden="true" />
|
||||
<Loader2 className="h-5 w-5 animate-spin text-brand-text" aria-hidden="true" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -50,15 +50,15 @@ export function DateTimeWidget({ type, value, onChange, readOnly, control }: Wid
|
||||
<Button
|
||||
{...control}
|
||||
type="button"
|
||||
variant="outline"
|
||||
variant="field"
|
||||
disabled={readOnly}
|
||||
className={cn('flex-1 justify-start text-left font-normal', !selected && 'text-muted-foreground')}
|
||||
className={cn('flex-1 justify-start px-3 text-left', !selected && 'text-dim')}
|
||||
>
|
||||
<CalendarIcon className="mr-2 h-4 w-4" aria-hidden="true" />
|
||||
<CalendarIcon className="text-dim" aria-hidden="true" />
|
||||
{selected ? formatDateTime(selected) : t('field.pickDate', 'Pick a date')}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-0" align="start">
|
||||
<PopoverContent className="w-auto overflow-hidden p-0" align="start">
|
||||
<Suspense fallback={<CalendarFallback />}>
|
||||
<Calendar
|
||||
mode="single"
|
||||
@@ -70,7 +70,7 @@ export function DateTimeWidget({ type, value, onChange, readOnly, control }: Wid
|
||||
}}
|
||||
/>
|
||||
</Suspense>
|
||||
<div className="border-t p-3">
|
||||
<div className="border-t border-border bg-muted/60 p-3">
|
||||
<Input
|
||||
type="time"
|
||||
value={localTime}
|
||||
@@ -92,7 +92,7 @@ export function DateTimeWidget({ type, value, onChange, readOnly, control }: Wid
|
||||
onClick={() => onChange(null)}
|
||||
aria-label={t('common.clear', 'Clear')}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
<X aria-hidden="true" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -8,10 +8,11 @@ import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { FieldRow } from '@/components/forms/FieldRow';
|
||||
import { VariantSelect } from '@/components/forms/VariantSelect';
|
||||
import { useFormContext } from '@/components/forms/formContext';
|
||||
import { 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 {
|
||||
@@ -20,11 +21,20 @@ interface EmbeddedObjectEditorProps {
|
||||
value: unknown;
|
||||
onChange: (value: unknown) => void;
|
||||
readOnly: boolean;
|
||||
bare?: boolean;
|
||||
}
|
||||
|
||||
function EmbeddedObjectEditor({ objectName, control, value, onChange, readOnly }: EmbeddedObjectEditorProps) {
|
||||
export function EmbeddedObjectEditor({
|
||||
objectName,
|
||||
control,
|
||||
value,
|
||||
onChange,
|
||||
readOnly,
|
||||
bare = false,
|
||||
}: EmbeddedObjectEditorProps) {
|
||||
const { t } = useTranslation();
|
||||
const { schema, mode, baseline } = useFormContext();
|
||||
const inPanel = useInPanel();
|
||||
const [initial, setInitial] = useState({ baseline, value });
|
||||
if (initial.baseline !== baseline) setInitial({ baseline, value });
|
||||
const resolved = resolveEmbedded(schema, objectName, value);
|
||||
@@ -46,28 +56,48 @@ function EmbeddedObjectEditor({ objectName, control, value, onChange, readOnly }
|
||||
};
|
||||
const entries = embeddedEntries(resolved).filter(({ field }) => field.update !== 'serverSet');
|
||||
|
||||
if (!resolved.variants && entries.length === 0) return null;
|
||||
|
||||
const frame = bare ? 'bare' : inPanel ? 'rule' : 'panel';
|
||||
return (
|
||||
<div className="space-y-4 rounded-md border p-4">
|
||||
{resolved.variants && (
|
||||
<VariantSelect
|
||||
labelledBy={control?.['aria-labelledby']}
|
||||
ariaLabel={control?.['aria-label']}
|
||||
variants={resolved.variants}
|
||||
value={resolved.variant?.name ?? ''}
|
||||
onChange={changeVariant}
|
||||
readOnly={readOnly}
|
||||
/>
|
||||
)}
|
||||
{entries.map(({ formField, field }) => (
|
||||
<FieldRow
|
||||
key={formField.name}
|
||||
field={field}
|
||||
formField={formField}
|
||||
value={obj[formField.name]}
|
||||
onChange={(v) => onChange({ ...obj, [formField.name]: v })}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<PanelContext value={true}>
|
||||
<div
|
||||
data-slot="embedded-object"
|
||||
className={cn(
|
||||
'@container',
|
||||
frame === 'panel' && 'rounded-xl bg-muted px-4',
|
||||
frame === 'rule' && 'border-l-2 border-input pl-4',
|
||||
)}
|
||||
>
|
||||
{resolved.variants && (
|
||||
<div className={cn(frame === 'panel' ? 'py-3' : 'py-2', entries.length > 0 && 'border-b border-border')}>
|
||||
<VariantSelect
|
||||
labelledBy={control?.['aria-labelledby']}
|
||||
ariaLabel={control?.['aria-label']}
|
||||
variants={resolved.variants}
|
||||
value={resolved.variant?.name ?? ''}
|
||||
onChange={changeVariant}
|
||||
readOnly={readOnly}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{entries.length > 0 && (
|
||||
<div className={cn('divide-y divide-border', frame === 'rule' && '[&>[data-slot=field-row]]:py-3')}>
|
||||
<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>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -98,7 +98,7 @@ export function EnumMultiSelect({ enumName, items, onChange, readOnly, minItems,
|
||||
const checkboxItem = (v: EnumVariant, idPrefix: string) => {
|
||||
const id = `${idPrefix}-${v.name.replace(/[^A-Za-z0-9_-]/g, '_')}`;
|
||||
return (
|
||||
<div key={v.name} className="flex items-center gap-2 py-0.5">
|
||||
<div key={v.name} className="flex items-center gap-2.5 rounded-lg px-2 py-1.5 transition-colors hover:bg-muted">
|
||||
<Checkbox
|
||||
id={id}
|
||||
checked={items.includes(v.name)}
|
||||
@@ -116,7 +116,11 @@ export function EnumMultiSelect({ enumName, items, onChange, readOnly, minItems,
|
||||
|
||||
if (variants.length <= SEARCHABLE_THRESHOLD) {
|
||||
return (
|
||||
<div className={variants.length > GRID_THRESHOLD ? 'grid grid-cols-2 gap-2' : 'space-y-2'}>
|
||||
<div
|
||||
className={
|
||||
variants.length > GRID_THRESHOLD ? '-mx-2 grid gap-x-2 gap-y-0.5 sm:grid-cols-2' : '-mx-2 space-y-0.5'
|
||||
}
|
||||
>
|
||||
{variants.map((v) => checkboxItem(v, baseId))}
|
||||
</div>
|
||||
);
|
||||
@@ -150,22 +154,23 @@ export function EnumMultiSelect({ enumName, items, onChange, readOnly, minItems,
|
||||
)}
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button {...control} type="button" variant="outline" size="sm" className="gap-1" disabled={readOnly}>
|
||||
<Search className="h-4 w-4" aria-hidden="true" />
|
||||
<Button {...control} type="button" variant="secondary" size="sm" disabled={readOnly}>
|
||||
<Search aria-hidden="true" />
|
||||
{t('field.selectOptions', 'Select options...')}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-72 p-0" align="start">
|
||||
<div className="border-b p-2">
|
||||
<PopoverContent className="w-72 overflow-hidden p-0" align="start">
|
||||
<div className="p-2 pb-1">
|
||||
<Input
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
placeholder={t('common.searchPlaceholder', 'Search...')}
|
||||
aria-label={t('common.search', 'Search')}
|
||||
className="h-8"
|
||||
variant="pill"
|
||||
className="h-8 px-3.5"
|
||||
/>
|
||||
</div>
|
||||
<div className="max-h-60 space-y-1 overflow-y-auto p-2">
|
||||
<div className="max-h-60 space-y-0.5 overflow-y-auto p-1.5">
|
||||
{filtered.length === 0 && (
|
||||
<p className="py-2 text-center text-sm text-muted-foreground">{t('field.noMatches', 'No matches')}</p>
|
||||
)}
|
||||
|
||||
@@ -4,92 +4,10 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { lazy, Suspense } from 'react';
|
||||
import { ColorWidget, MultilineWidget, SecretWidget, TextWidget } from '@/components/forms/widgets/StringWidgets';
|
||||
import { DurationWidget, NumberWidget, SizeWidget } from '@/components/forms/widgets/NumberWidgets';
|
||||
import { DateTimeWidget } from '@/components/forms/widgets/DateTimeWidget';
|
||||
import { BooleanWidget } from '@/components/forms/widgets/BooleanWidget';
|
||||
import { EnumWidget } from '@/components/forms/widgets/EnumWidgets';
|
||||
import { BlobWidget } from '@/components/forms/widgets/BlobWidget';
|
||||
import { ObjectIdWidget } from '@/components/forms/widgets/ObjectIdWidgets';
|
||||
import { SetWidget } from '@/components/forms/widgets/SetWidget';
|
||||
import { EmbeddedObjectWidget } from '@/components/forms/widgets/EmbeddedObjectWidget';
|
||||
import { ObjectListWidget } from '@/components/forms/widgets/ObjectListWidget';
|
||||
import { MapWidget } from '@/components/forms/widgets/MapWidget';
|
||||
import { RateWidget } from '@/components/forms/widgets/RateWidget';
|
||||
import { ExpressionWidget } from '@/components/forms/widgets/ExpressionWidget';
|
||||
import { UnsupportedWidget } from '@/components/forms/widgets/UnsupportedWidget';
|
||||
import { widgetKey } from '@/components/forms/widgets/registry';
|
||||
import { resolveWidget } from '@/extensions/widgets';
|
||||
import type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
import type {
|
||||
FieldType,
|
||||
FieldTypeBlobId,
|
||||
FieldTypeBoolean,
|
||||
FieldTypeEnum,
|
||||
FieldTypeMap,
|
||||
FieldTypeNumber,
|
||||
FieldTypeObject,
|
||||
FieldTypeObjectId,
|
||||
FieldTypeObjectList,
|
||||
FieldTypeSet,
|
||||
FieldTypeString,
|
||||
FieldTypeUtcDateTime,
|
||||
} from '@/types/schema';
|
||||
|
||||
const OtpAuthField = lazy(() =>
|
||||
import('@/components/forms/widgets/OtpAuthField').then((m) => ({ default: m.OtpAuthField })),
|
||||
);
|
||||
|
||||
function narrow<T extends FieldType>(props: WidgetProps): WidgetProps<T> {
|
||||
return props as WidgetProps<T>;
|
||||
}
|
||||
|
||||
export function FieldControl(props: WidgetProps) {
|
||||
switch (widgetKey(props.type)) {
|
||||
case 'string':
|
||||
return <TextWidget {...narrow<FieldTypeString>(props)} />;
|
||||
case 'string:secret':
|
||||
return <SecretWidget {...narrow<FieldTypeString>(props)} />;
|
||||
case 'string:multiline':
|
||||
return <MultilineWidget {...narrow<FieldTypeString>(props)} />;
|
||||
case 'string:color':
|
||||
return <ColorWidget {...narrow<FieldTypeString>(props)} />;
|
||||
case 'number':
|
||||
return <NumberWidget {...narrow<FieldTypeNumber>(props)} />;
|
||||
case 'number:size':
|
||||
return <SizeWidget {...narrow<FieldTypeNumber>(props)} />;
|
||||
case 'number:duration':
|
||||
return <DurationWidget {...narrow<FieldTypeNumber>(props)} />;
|
||||
case 'utcDateTime':
|
||||
return <DateTimeWidget {...narrow<FieldTypeUtcDateTime>(props)} />;
|
||||
case 'boolean':
|
||||
return <BooleanWidget {...narrow<FieldTypeBoolean>(props)} />;
|
||||
case 'enum':
|
||||
return <EnumWidget {...narrow<FieldTypeEnum>(props)} />;
|
||||
case 'blobId':
|
||||
return <BlobWidget {...narrow<FieldTypeBlobId>(props)} />;
|
||||
case 'objectId':
|
||||
return <ObjectIdWidget {...narrow<FieldTypeObjectId>(props)} />;
|
||||
case 'object':
|
||||
return <EmbeddedObjectWidget {...narrow<FieldTypeObject>(props)} />;
|
||||
case 'object:x:Expression':
|
||||
return <ExpressionWidget {...narrow<FieldTypeObject>(props)} />;
|
||||
case 'object:x:Rate':
|
||||
return <RateWidget {...narrow<FieldTypeObject>(props)} />;
|
||||
case 'object:x:OtpAuth':
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<OtpAuthField {...narrow<FieldTypeObject>(props)} />
|
||||
</Suspense>
|
||||
);
|
||||
case 'objectList':
|
||||
return <ObjectListWidget {...narrow<FieldTypeObjectList>(props)} />;
|
||||
case 'set':
|
||||
case 'set:enum':
|
||||
return <SetWidget {...narrow<FieldTypeSet>(props)} />;
|
||||
case 'map':
|
||||
return <MapWidget {...narrow<FieldTypeMap>(props)} />;
|
||||
case 'unsupported':
|
||||
return <UnsupportedWidget {...props} />;
|
||||
}
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -4,22 +4,24 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useState, type KeyboardEvent } from 'react';
|
||||
import { useId, useState, type KeyboardEvent } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ChevronRight, Loader2, Plus, X } from 'lucide-react';
|
||||
import { ChevronRight, Loader2, Plus, Trash2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { ObjectSearchPopover } from '@/components/common/ObjectSearchPopover';
|
||||
import { FieldScopeProvider } from '@/components/forms/FormProvider';
|
||||
import { useFormContext } from '@/components/forms/formContext';
|
||||
import { PanelContext, useFormContext, useInPanel } from '@/components/forms/formContext';
|
||||
import { FieldControl } from '@/components/forms/widgets/FieldControl';
|
||||
import { EmbeddedObjectEditor } from '@/components/forms/widgets/EmbeddedObjectWidget';
|
||||
import { formatPlaceholder } from '@/components/forms/widgets/placeholders';
|
||||
import { widgetKey, widgetTraits } from '@/extensions/widgets';
|
||||
import { useNoPermissionMessage } from '@/lib/objectOptions';
|
||||
import { useDisplayName, useObjectOptions } from '@/data/objectOptions';
|
||||
import { buildNewObjectValue, getEnum, getEnumVariant } from '@/lib/schemaResolver';
|
||||
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';
|
||||
|
||||
@@ -37,6 +39,8 @@ function defaultMapValue(valueClass: MapValueType, newObject: (objectName: strin
|
||||
export function MapWidget({ type, formField, value, onChange, readOnly }: WidgetProps<FieldTypeMap>) {
|
||||
const { t } = useTranslation();
|
||||
const { schema } = useFormContext();
|
||||
const inPanel = useInPanel();
|
||||
const baseId = useId();
|
||||
const map = isRecord(value) ? value : {};
|
||||
const entries = Object.entries(map);
|
||||
const [newKey, setNewKey] = useState('');
|
||||
@@ -78,77 +82,133 @@ export function MapWidget({ type, formField, value, onChange, readOnly }: Widget
|
||||
}
|
||||
};
|
||||
|
||||
const objectValues = valueField.type.type === 'object' && 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 (
|
||||
<div className="space-y-3">
|
||||
{entries.map(([key, val]) => (
|
||||
<Collapsible key={key} open={expanded.has(key)} onOpenChange={(open) => setOpen(key, open)}>
|
||||
<div className="rounded-md border">
|
||||
<div className="flex items-center">
|
||||
<CollapsibleTrigger asChild>
|
||||
<PanelContext value={true}>
|
||||
<div
|
||||
data-slot="map-widget"
|
||||
className={cn('space-y-0.5 rounded-xl p-1.5', inPanel ? 'bg-card shadow-tile' : 'bg-muted')}
|
||||
>
|
||||
{!objectValues && entries.length > 0 && (formField.keyLabel || formField.valueLabel) && (
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="grid grid-cols-[minmax(0,1fr)_minmax(0,1.2fr)_2rem] gap-3 px-3 pb-0.5 pt-1.5 text-[11px] font-semibold uppercase tracking-wider text-dim"
|
||||
>
|
||||
<span>{formField.keyLabel}</span>
|
||||
<span>{formField.valueLabel}</span>
|
||||
</div>
|
||||
)}
|
||||
{entries.map(([key, val]) =>
|
||||
objectValues ? (
|
||||
<div key={key} className={cn('rounded-lg', expanded.has(key) && (inPanel ? 'bg-muted' : 'bg-card'))}>
|
||||
<div className="flex items-center gap-1 pr-1">
|
||||
<button
|
||||
type="button"
|
||||
className="flex flex-1 items-center gap-2 rounded-t-md p-3 text-sm font-medium transition-colors hover:bg-accent/50 [&[data-state=open]>svg]:rotate-90"
|
||||
onClick={() => setOpen(key, !expanded.has(key))}
|
||||
aria-expanded={expanded.has(key)}
|
||||
aria-controls={`${baseId}-${key}`}
|
||||
className="flex min-w-0 flex-1 items-center gap-2.5 rounded-lg px-2.5 py-2 text-left text-[13.5px] font-semibold outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
<ChevronRight className="h-4 w-4 shrink-0 transition-transform duration-200" aria-hidden="true" />
|
||||
<MapKeyLabel keyClass={type.keyClass} keyValue={key} />
|
||||
<ChevronRight
|
||||
className={cn(
|
||||
'h-4 w-4 shrink-0 text-dim transition-transform duration-200',
|
||||
expanded.has(key) && 'rotate-90',
|
||||
)}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span className="truncate">
|
||||
<MapKeyLabel keyClass={type.keyClass} keyValue={key} />
|
||||
</span>
|
||||
</button>
|
||||
</CollapsibleTrigger>
|
||||
{!readOnly && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="mr-2 h-7 w-7 shrink-0"
|
||||
onClick={() => removeEntry(key)}
|
||||
disabled={!canRemove}
|
||||
aria-label={t('field.removeEntry', 'Remove entry {{name}}', { name: key })}
|
||||
>
|
||||
<X className="h-4 w-4" aria-hidden="true" />
|
||||
</Button>
|
||||
{removeButton(key)}
|
||||
</div>
|
||||
{expanded.has(key) && (
|
||||
<div id={`${baseId}-${key}`} className="border-t border-border px-4">
|
||||
{valueControl(key, val)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<CollapsibleContent>
|
||||
<div className="px-4 pb-4 pt-1">
|
||||
<FieldScopeProvider name={key} readOnly={readOnly}>
|
||||
<FieldControl
|
||||
type={valueField.type}
|
||||
field={valueField}
|
||||
formField={{ name: key, label: formField.valueLabel ?? '' }}
|
||||
value={val}
|
||||
onChange={(v) => onChange({ ...map, [key]: v })}
|
||||
readOnly={readOnly}
|
||||
control={{ 'aria-label': formField.valueLabel ?? key }}
|
||||
/>
|
||||
</FieldScopeProvider>
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
) : (
|
||||
<div
|
||||
key={key}
|
||||
className="grid grid-cols-[minmax(0,1fr)_minmax(0,1.2fr)_2rem] items-center gap-3 rounded-lg py-1 pl-3 transition-colors hover:bg-muted-strong/60"
|
||||
>
|
||||
<span className="truncate text-sm font-medium">
|
||||
<MapKeyLabel keyClass={type.keyClass} keyValue={key} />
|
||||
</span>
|
||||
<div className="min-w-0">{valueControl(key, val)}</div>
|
||||
{removeButton(key)}
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
{!readOnly && canAdd && (
|
||||
<div className="flex items-center gap-2 p-1">
|
||||
<MapKeyInput
|
||||
keyClass={type.keyClass}
|
||||
label={formField.keyLabel ?? t('field.newKey', 'New key')}
|
||||
value={newKey}
|
||||
onChange={setNewKey}
|
||||
onKeyDown={handleKeyDown}
|
||||
existingKeys={map}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={addEntry}
|
||||
disabled={!trimmedKey || Object.hasOwn(map, trimmedKey)}
|
||||
className="shrink-0"
|
||||
>
|
||||
<Plus className="h-4 w-4" aria-hidden="true" />
|
||||
{t('field.add', 'Add')}
|
||||
</Button>
|
||||
</div>
|
||||
</Collapsible>
|
||||
))}
|
||||
{!readOnly && canAdd && (
|
||||
<div className="flex items-center gap-2">
|
||||
<MapKeyInput
|
||||
keyClass={type.keyClass}
|
||||
label={formField.keyLabel ?? t('field.newKey', 'New key')}
|
||||
value={newKey}
|
||||
onChange={setNewKey}
|
||||
onKeyDown={handleKeyDown}
|
||||
existingKeys={map}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={addEntry}
|
||||
disabled={!trimmedKey || Object.hasOwn(map, trimmedKey)}
|
||||
className="shrink-0 gap-1"
|
||||
>
|
||||
<Plus className="h-4 w-4" aria-hidden="true" />
|
||||
{t('field.add', 'Add')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{readOnly && entries.length === 0 && (
|
||||
<p className="px-2.5 py-2 text-sm text-muted-foreground">{t('field.none', 'None')}</p>
|
||||
)}
|
||||
</div>
|
||||
</PanelContext>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -143,7 +143,7 @@ function UnitNumberWidget({
|
||||
onClick={() => onChange(null)}
|
||||
aria-label={t('common.clear', 'Clear')}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
<X aria-hidden="true" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { ObjectSearchPopover } from '@/components/common/ObjectSearchPopover';
|
||||
import { ObjectFieldFrame, ObjectSearchPopover } from '@/components/common/ObjectSearchPopover';
|
||||
import { useNoPermissionMessage } from '@/lib/objectOptions';
|
||||
import { useObjectOptions, useDisplayName, type ObjectOption } from '@/data/objectOptions';
|
||||
import { useFormContext } from '@/components/forms/formContext';
|
||||
@@ -52,30 +52,38 @@ export function ObjectIdWidget({
|
||||
const list = useObjectOptions(type.objectName, schema, tenantId);
|
||||
const noPermissionMessage = useNoPermissionMessage(schema, type.objectName);
|
||||
|
||||
const pill = id ? (
|
||||
<ObjectIdPill
|
||||
objectName={type.objectName}
|
||||
id={id}
|
||||
options={list.options}
|
||||
onRemove={!readOnly && type.nullable ? () => onChange(null) : undefined}
|
||||
/>
|
||||
) : null;
|
||||
|
||||
if (readOnly) {
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{pill ?? <span className="text-sm text-dim">{t('field.none', 'None')}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{id && (
|
||||
<ObjectIdPill
|
||||
objectName={type.objectName}
|
||||
id={id}
|
||||
options={list.options}
|
||||
onRemove={!readOnly && type.nullable ? () => onChange(null) : undefined}
|
||||
/>
|
||||
)}
|
||||
{!id && readOnly && <span className="text-sm text-muted-foreground">{t('field.none', 'None')}</span>}
|
||||
{!readOnly && (
|
||||
<ObjectSearchPopover
|
||||
control={control}
|
||||
label={t('field.chooseValue', 'Choose {{name}}', { name: formField.label })}
|
||||
options={list.options}
|
||||
loading={list.loading}
|
||||
error={list.error}
|
||||
ensureLoaded={list.ensureLoaded}
|
||||
onSelect={(next) => onChange(next)}
|
||||
disabledMessage={noPermissionMessage}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<ObjectFieldFrame disabled={!!noPermissionMessage} 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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -105,33 +113,40 @@ export function ObjectIdMultiSelect({
|
||||
const available = list.options.filter((o) => !items.includes(o.id));
|
||||
const atMinimum = minItems != null && items.length <= minItems;
|
||||
|
||||
const pills = items.map((id) => (
|
||||
<ObjectIdPill
|
||||
key={id}
|
||||
objectName={objectName}
|
||||
id={id}
|
||||
options={list.options}
|
||||
removeDisabled={atMinimum}
|
||||
onRemove={readOnly ? undefined : () => onChange(items.filter((i) => i !== id))}
|
||||
/>
|
||||
));
|
||||
|
||||
if (readOnly) {
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{pills}
|
||||
{items.length === 0 && <span className="text-sm text-dim">{t('field.none', 'None')}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{items.map((id) => (
|
||||
<ObjectIdPill
|
||||
key={id}
|
||||
objectName={objectName}
|
||||
id={id}
|
||||
options={list.options}
|
||||
removeDisabled={atMinimum}
|
||||
onRemove={readOnly ? undefined : () => onChange(items.filter((i) => i !== id))}
|
||||
/>
|
||||
))}
|
||||
{!readOnly && (
|
||||
<ObjectSearchPopover
|
||||
control={control}
|
||||
label={t('field.addValue', 'Add {{name}}', { name: label })}
|
||||
options={available}
|
||||
loading={list.loading}
|
||||
error={list.error}
|
||||
ensureLoaded={list.ensureLoaded}
|
||||
onSelect={(id) => onChange([...items, id])}
|
||||
disabledMessage={noPermissionMessage}
|
||||
/>
|
||||
)}
|
||||
{items.length === 0 && readOnly && (
|
||||
<span className="text-sm text-muted-foreground">{t('field.none', 'None')}</span>
|
||||
)}
|
||||
</div>
|
||||
<ObjectFieldFrame disabled={!!noPermissionMessage}>
|
||||
{pills}
|
||||
<ObjectSearchPopover
|
||||
control={control}
|
||||
label={t('field.addValue', 'Add {{name}}', { name: label })}
|
||||
placeholder={items.length === 0 ? t('field.selectEllipsis', 'Select...') : ''}
|
||||
options={available}
|
||||
loading={list.loading}
|
||||
error={list.error}
|
||||
ensureLoaded={list.ensureLoaded}
|
||||
onSelect={(id) => onChange([...items, id])}
|
||||
disabledMessage={noPermissionMessage}
|
||||
/>
|
||||
</ObjectFieldFrame>
|
||||
);
|
||||
}
|
||||
@@ -4,14 +4,19 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useId, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Plus, X } from 'lucide-react';
|
||||
import { ChevronRight, Plus, Trash2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { FieldScopeProvider } from '@/components/forms/FormProvider';
|
||||
import { useFormContext } from '@/components/forms/formContext';
|
||||
import { PanelContext, useFormContext, useInPanel } from '@/components/forms/formContext';
|
||||
import { FieldControl } from '@/components/forms/widgets/FieldControl';
|
||||
import { EmbeddedObjectEditor } from '@/components/forms/widgets/EmbeddedObjectWidget';
|
||||
import { widgetKey } from '@/extensions/widgets';
|
||||
import { FieldValue } from '@/components/values/FieldValue';
|
||||
import { buildNewObjectValue } from '@/lib/schemaResolver';
|
||||
import { isRecord } from '@/lib/embeddedSchema';
|
||||
import { embeddedSummary, isRecord } from '@/lib/embeddedSchema';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
import type { Field, FieldTypeObject, FieldTypeObjectList } from '@/types/schema';
|
||||
|
||||
@@ -22,16 +27,28 @@ export function ObjectListWidget({
|
||||
value,
|
||||
onChange,
|
||||
readOnly,
|
||||
control,
|
||||
}: WidgetProps<FieldTypeObjectList>) {
|
||||
const { t } = useTranslation();
|
||||
const { schema } = useFormContext();
|
||||
const inPanel = useInPanel();
|
||||
const baseId = useId();
|
||||
const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(() => new Set());
|
||||
const itemType: FieldTypeObject = { type: 'object', objectName: type.objectName };
|
||||
const itemField: Field = { description: '', type: itemType, update: field.update, enterprise: field.enterprise };
|
||||
const embedded = widgetKey(itemType) === 'object';
|
||||
const items = isRecord(value) ? value : {};
|
||||
const entries = Object.entries(items).sort(([a], [b]) => Number(a) - Number(b));
|
||||
const canRemove = type.minItems == null || entries.length > type.minItems;
|
||||
const canAdd = type.maxItems == null || entries.length < type.maxItems;
|
||||
|
||||
const toggle = (key: string) =>
|
||||
setCollapsed((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (!next.delete(key)) next.add(key);
|
||||
return next;
|
||||
});
|
||||
|
||||
const addItem = () => {
|
||||
const next = entries.length > 0 ? Math.max(...entries.map(([k]) => Number(k) || 0)) + 1 : 0;
|
||||
onChange({ ...items, [String(next)]: buildNewObjectValue(schema, type.objectName) });
|
||||
@@ -41,45 +58,99 @@ export function ObjectListWidget({
|
||||
const copy = { ...items };
|
||||
delete copy[key];
|
||||
onChange(copy);
|
||||
if (collapsed.has(key)) toggle(key);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-2">
|
||||
{entries.map(([key, item], position) => {
|
||||
const itemLabel = t('field.itemN', '{{label}} {{n}}', { label: formField.label, n: position + 1 });
|
||||
const summary = embeddedSummary(schema, type.objectName, item);
|
||||
const open = !!control['aria-invalid'] || !collapsed.has(key);
|
||||
const bodyId = `${baseId}-${key}`;
|
||||
return (
|
||||
<div key={key} className="space-y-3 rounded-md border p-4">
|
||||
{!readOnly && (
|
||||
<div className="flex justify-end">
|
||||
<div
|
||||
key={key}
|
||||
data-slot="object-list-item"
|
||||
className={cn('overflow-hidden rounded-xl', inPanel ? 'bg-card shadow-tile' : 'bg-muted')}
|
||||
>
|
||||
<div className="flex items-center gap-1 py-1.5 pl-1.5 pr-1.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggle(key)}
|
||||
aria-expanded={open}
|
||||
aria-controls={bodyId}
|
||||
className="flex min-w-0 flex-1 items-center gap-2.5 rounded-lg px-1.5 py-1 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
<ChevronRight
|
||||
className={cn('h-4 w-4 shrink-0 text-dim transition-transform duration-200', open && 'rotate-90')}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span className="flex min-w-0 flex-col">
|
||||
<span className="truncate text-[13.5px] font-semibold">{summary.variantLabel ?? itemLabel}</span>
|
||||
{summary.summary && (
|
||||
<span className="truncate text-[12.5px] text-muted-foreground">
|
||||
{summary.summary.type ? (
|
||||
<FieldValue
|
||||
schema={schema}
|
||||
type={summary.summary.type}
|
||||
value={summary.summary.value}
|
||||
variant="compact"
|
||||
/>
|
||||
) : (
|
||||
String(summary.summary.value)
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
{!readOnly && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7"
|
||||
variant="ghost-danger"
|
||||
size="icon-sm"
|
||||
className="shrink-0"
|
||||
onClick={() => removeItem(key)}
|
||||
disabled={!canRemove}
|
||||
aria-label={t('field.removeItemN', 'Remove item {{n}}', { n: position + 1 })}
|
||||
>
|
||||
<X className="h-4 w-4" aria-hidden="true" />
|
||||
<Trash2 className="h-4 w-4" aria-hidden="true" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<FieldScopeProvider name={key} readOnly={readOnly}>
|
||||
<FieldControl
|
||||
type={itemType}
|
||||
field={itemField}
|
||||
formField={{ name: key, label: itemLabel }}
|
||||
value={item}
|
||||
onChange={(v) => onChange({ ...items, [key]: v })}
|
||||
readOnly={readOnly}
|
||||
control={{ 'aria-label': itemLabel }}
|
||||
/>
|
||||
</FieldScopeProvider>
|
||||
)}
|
||||
</div>
|
||||
<div id={bodyId} hidden={!open} className="border-t border-border px-4">
|
||||
<PanelContext value={true}>
|
||||
<FieldScopeProvider name={key} readOnly={readOnly}>
|
||||
{embedded ? (
|
||||
<EmbeddedObjectEditor
|
||||
bare
|
||||
objectName={type.objectName}
|
||||
control={{ 'aria-label': itemLabel }}
|
||||
value={item}
|
||||
onChange={(v) => onChange({ ...items, [key]: v })}
|
||||
readOnly={readOnly}
|
||||
/>
|
||||
) : (
|
||||
<div className="py-3">
|
||||
<FieldControl
|
||||
type={itemType}
|
||||
field={itemField}
|
||||
formField={{ name: key, label: itemLabel }}
|
||||
value={item}
|
||||
onChange={(v) => onChange({ ...items, [key]: v })}
|
||||
readOnly={readOnly}
|
||||
control={{ 'aria-label': itemLabel }}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</FieldScopeProvider>
|
||||
</PanelContext>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{!readOnly && canAdd && (
|
||||
<Button type="button" variant="outline" size="sm" onClick={addItem} className="gap-1">
|
||||
<Button type="button" variant="secondary" size="sm" onClick={addItem}>
|
||||
<Plus className="h-4 w-4" aria-hidden="true" />
|
||||
{t('field.addItem', 'Add item')}
|
||||
</Button>
|
||||
|
||||
@@ -133,7 +133,7 @@ export function OtpAuthField({ value, onChange, readOnly }: WidgetProps<FieldTyp
|
||||
|
||||
if (!isConfigured && setupUrl) {
|
||||
return (
|
||||
<div className="rounded-md border bg-muted/30 p-4 space-y-4">
|
||||
<div className="space-y-4 rounded-xl bg-muted p-4">
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm font-medium">{t('otp.scanPrompt', 'Scan with your authenticator app')}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
@@ -150,11 +150,11 @@ export function OtpAuthField({ value, onChange, readOnly }: WidgetProps<FieldTyp
|
||||
alt={t('otp.qrCodeAlt', 'TOTP QR code')}
|
||||
width={220}
|
||||
height={220}
|
||||
className="rounded-md border bg-white p-2"
|
||||
className="rounded-xl bg-white p-2 shadow-tile"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-[220px] w-[220px] items-center justify-center text-muted-foreground">
|
||||
<Loader2 className="h-6 w-6 animate-spin" />
|
||||
<Loader2 className="h-6 w-6 animate-spin text-brand-text" aria-hidden="true" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -168,7 +168,9 @@ export function OtpAuthField({ value, onChange, readOnly }: WidgetProps<FieldTyp
|
||||
)}
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<code className="flex-1 rounded bg-muted p-2 text-sm font-mono break-all select-all">{setupSecret}</code>
|
||||
<code className="flex-1 select-all break-all rounded-lg bg-card px-3 py-2 font-mono text-sm">
|
||||
{setupSecret}
|
||||
</code>
|
||||
{setupTotp && <CopyButton value={setupTotp.secret.base32} label={t('otp.secret', 'secret')} />}
|
||||
</div>
|
||||
</div>
|
||||
@@ -197,11 +199,11 @@ export function OtpAuthField({ value, onChange, readOnly }: WidgetProps<FieldTyp
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<Button type="button" variant="outline" size="sm" onClick={cancelSetup}>
|
||||
<Button type="button" variant="ghost" size="sm" onClick={cancelSetup}>
|
||||
{t('common.cancel', 'Cancel')}
|
||||
</Button>
|
||||
<Button type="button" size="sm" onClick={confirmSetup}>
|
||||
<ShieldCheck className="mr-2 h-4 w-4" />
|
||||
<ShieldCheck aria-hidden="true" />
|
||||
{t('common.confirm', 'Confirm')}
|
||||
</Button>
|
||||
</div>
|
||||
@@ -215,8 +217,8 @@ export function OtpAuthField({ value, onChange, readOnly }: WidgetProps<FieldTyp
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t('otp.statusDisabled', 'Two-factor authentication is not enabled.')}
|
||||
</span>
|
||||
<Button type="button" variant="outline" size="sm" onClick={startSetup}>
|
||||
<ShieldCheck className="mr-2 h-4 w-4" />
|
||||
<Button type="button" variant="secondary" size="sm" onClick={startSetup}>
|
||||
<ShieldCheck aria-hidden="true" />
|
||||
{t('otp.setUp', 'Set up TOTP')}
|
||||
</Button>
|
||||
</div>
|
||||
@@ -224,9 +226,11 @@ export function OtpAuthField({ value, onChange, readOnly }: WidgetProps<FieldTyp
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-md border bg-muted/30 p-4 space-y-3">
|
||||
<div className="space-y-3 rounded-xl bg-muted p-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<ShieldCheck className="h-4 w-4 text-green-600" />
|
||||
<span className="grid size-7 place-items-center rounded-[9px] bg-success-soft text-success">
|
||||
<ShieldCheck className="h-4 w-4" aria-hidden="true" />
|
||||
</span>
|
||||
<span className="text-sm font-medium">{t('otp.statusEnabled', 'Two-factor authentication is enabled.')}</span>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
@@ -253,7 +257,7 @@ export function OtpAuthField({ value, onChange, readOnly }: WidgetProps<FieldTyp
|
||||
</div>
|
||||
<div className="flex items-center justify-end">
|
||||
<Button type="button" variant="destructive" size="sm" onClick={handleDisable} disabled={!otpCodeValue.trim()}>
|
||||
<ShieldOff className="mr-2 h-4 w-4" />
|
||||
<ShieldOff aria-hidden="true" />
|
||||
{t('otp.disable', 'Disable')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -48,7 +48,7 @@ export function RateWidget({ type, value, onChange, readOnly, control }: WidgetP
|
||||
};
|
||||
|
||||
if (readOnly) {
|
||||
if (isNull) return <span className="text-sm italic text-muted-foreground">{t('field.notSet', 'Not set')}</span>;
|
||||
if (isNull) return <span className="text-sm italic text-dim">{t('field.notSet', 'Not set')}</span>;
|
||||
return (
|
||||
<span className="text-sm">
|
||||
{t('rate.summary', '{{amount}} per {{period}}', {
|
||||
@@ -62,15 +62,15 @@ export function RateWidget({ type, value, onChange, readOnly, control }: WidgetP
|
||||
if (isNull) {
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm italic text-muted-foreground">{t('field.notSet', 'Not set')}</span>
|
||||
<span className="text-sm italic text-dim">{t('field.notSet', 'Not set')}</span>
|
||||
<Button
|
||||
{...control}
|
||||
type="button"
|
||||
variant="outline"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => onChange({ count: 1, period: 1000 })}
|
||||
>
|
||||
<Plus className="mr-1 h-4 w-4" aria-hidden="true" />
|
||||
<Plus aria-hidden="true" />
|
||||
{t('field.enable', 'Enable')}
|
||||
</Button>
|
||||
</div>
|
||||
@@ -128,7 +128,7 @@ export function RateWidget({ type, value, onChange, readOnly, control }: WidgetP
|
||||
onClick={() => onChange(null)}
|
||||
aria-label={t('common.clear', 'Clear')}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
<X aria-hidden="true" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { ReactNode } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { X } from 'lucide-react';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface RemovablePillProps {
|
||||
label: string;
|
||||
@@ -19,15 +20,20 @@ interface RemovablePillProps {
|
||||
export function RemovablePill({ label, onRemove, removeDisabled, children }: RemovablePillProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Badge variant="secondary" className="gap-1 pr-1 text-sm">
|
||||
{children ?? label}
|
||||
<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="ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
className="grid size-5 shrink-0 place-items-center rounded-full bg-card text-muted-foreground transition-colors hover:bg-highlight hover:text-highlight-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
<X className="h-3 w-3" aria-hidden="true" />
|
||||
</button>
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useId, useState, type ClipboardEvent } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Plus } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -14,8 +14,9 @@ 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 } from '@/types/schema';
|
||||
import type { FieldTypeSet, ScalarTypeString } from '@/types/schema';
|
||||
|
||||
function toSetObject(items: string[]): Record<string, true> {
|
||||
const obj: Record<string, true> = {};
|
||||
@@ -32,6 +33,7 @@ export function SetWidget({ type, formField, value, onChange, readOnly, control
|
||||
case 'string':
|
||||
return (
|
||||
<TagInput
|
||||
type={scalar}
|
||||
label={formField.label}
|
||||
items={items}
|
||||
onChange={commit}
|
||||
@@ -74,6 +76,7 @@ export function SetWidget({ type, formField, value, onChange, readOnly, control
|
||||
}
|
||||
|
||||
interface TagInputProps {
|
||||
type: ScalarTypeString;
|
||||
label: string;
|
||||
items: string[];
|
||||
onChange: (items: string[]) => void;
|
||||
@@ -84,60 +87,142 @@ interface TagInputProps {
|
||||
control: ControlProps;
|
||||
}
|
||||
|
||||
function TagInput({ label, items, onChange, readOnly, minItems, maxItems, placeholder, control }: TagInputProps) {
|
||||
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 addTag = () => {
|
||||
const trimmed = inputValue.trim();
|
||||
if (!trimmed || items.includes(trimmed) || full) return;
|
||||
onChange([...items, trimmed]);
|
||||
setInputValue('');
|
||||
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 className="space-y-2">
|
||||
{items.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{items.map((item) => (
|
||||
<RemovablePill
|
||||
key={item}
|
||||
label={item}
|
||||
onRemove={readOnly ? undefined : () => onChange(items.filter((i) => i !== item))}
|
||||
removeDisabled={minItems != null && items.length <= minItems}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{!readOnly && (
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
{...control}
|
||||
value={inputValue}
|
||||
onChange={(e) => setInputValue(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
addTag();
|
||||
<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
|
||||
}
|
||||
}}
|
||||
disabled={full}
|
||||
placeholder={placeholder ?? t('field.typeAndPressEnter', 'Type and press Enter...')}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={addTag}
|
||||
disabled={!inputValue.trim() || full}
|
||||
aria-label={t('field.addValue', 'Add {{name}}', { name: label })}
|
||||
>
|
||||
<Plus className="h-4 w-4" aria-hidden="true" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -58,25 +58,41 @@ export function MultilineWidget(props: WidgetProps<FieldTypeString>) {
|
||||
|
||||
if (type.format === 'html') {
|
||||
return (
|
||||
<div className="rounded-md border bg-muted/30">
|
||||
<div className="flex items-center gap-2 border-b px-3 py-1.5 text-xs text-muted-foreground">
|
||||
<div className="field-surface overflow-hidden rounded-xl">
|
||||
<div className="flex items-center gap-2 bg-muted px-3.5 py-1.5 text-[11px] font-semibold uppercase tracking-wider text-dim">
|
||||
<span className="font-mono">HTML</span>
|
||||
</div>
|
||||
<BufferedTextarea
|
||||
{...common}
|
||||
rows={10}
|
||||
spellCheck={false}
|
||||
className="resize-y rounded-none rounded-b-md border-0 bg-transparent font-mono text-xs focus-visible:ring-0"
|
||||
variant="bare"
|
||||
className="resize-y font-mono text-xs"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (type.format === 'sieve') {
|
||||
return <BufferedTextarea {...common} rows={16} spellCheck={false} className="font-mono text-xs" />;
|
||||
}
|
||||
return <BufferedTextarea {...common} rows={4} />;
|
||||
}
|
||||
|
||||
export function SieveWidget(props: WidgetProps<FieldTypeString>) {
|
||||
const { type, formField, value, readOnly, control } = props;
|
||||
return (
|
||||
<BufferedTextarea
|
||||
{...control}
|
||||
value={stringValue(value)}
|
||||
onCommit={stringCommitter(props)}
|
||||
disabled={readOnly}
|
||||
placeholder={formField.placeholder}
|
||||
minLength={type.minLength}
|
||||
maxLength={type.maxLength}
|
||||
rows={16}
|
||||
spellCheck={false}
|
||||
className="font-mono text-xs"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ColorWidget(props: WidgetProps<FieldTypeString>) {
|
||||
const { t } = useTranslation();
|
||||
const { value, readOnly, control } = props;
|
||||
@@ -90,7 +106,7 @@ export function ColorWidget(props: WidgetProps<FieldTypeString>) {
|
||||
onChange={(e) => commit(e.target.value)}
|
||||
disabled={readOnly}
|
||||
aria-label={t('field.colorPicker', 'Color picker')}
|
||||
className="h-9 w-14 cursor-pointer rounded-md border border-input bg-transparent p-1"
|
||||
className="h-9 w-14 cursor-pointer field-surface rounded-full p-1 [&::-moz-color-swatch]:rounded-full [&::-moz-color-swatch]:border-0 [&::-webkit-color-swatch]:rounded-full [&::-webkit-color-swatch]:border-0 [&::-webkit-color-swatch-wrapper]:p-0"
|
||||
/>
|
||||
<BufferedInput
|
||||
{...control}
|
||||
@@ -138,14 +154,14 @@ export function SecretWidget(props: WidgetProps<FieldTypeString>) {
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 shrink-0"
|
||||
size="icon-sm"
|
||||
className="shrink-0"
|
||||
onClick={() => setVisible((p) => !p)}
|
||||
aria-label={visible ? t('field.hideValue', 'Hide value') : t('field.showValue', 'Show value')}
|
||||
aria-pressed={visible}
|
||||
tabIndex={-1}
|
||||
>
|
||||
{visible ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||
{visible ? <EyeOff aria-hidden="true" /> : <Eye aria-hidden="true" />}
|
||||
</Button>
|
||||
);
|
||||
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
export function UnsupportedWidget({ type }: WidgetProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
<p className="rounded-xl bg-muted px-4 py-3 text-sm text-muted-foreground">
|
||||
{t('field.unsupportedType', 'Unsupported field type: {{type}}', { type: (type as { type?: string }).type ?? '' })}
|
||||
</p>
|
||||
);
|
||||
|
||||
@@ -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}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -18,6 +18,10 @@ export function formatPlaceholder(format: StringFormat): string | undefined {
|
||||
return 'user@example.com';
|
||||
case 'uri':
|
||||
return 'https://example.com';
|
||||
case 'localTime':
|
||||
return 'HH:MM';
|
||||
case 'localDate':
|
||||
return 'YYYY-MM-DD';
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -1,109 +0,0 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import type { FieldType } from '@/types/schema';
|
||||
|
||||
export type LabelMode = 'control' | 'group' | 'none';
|
||||
|
||||
export interface WidgetTraits {
|
||||
labelMode: LabelMode;
|
||||
readOnlyAsValue: boolean;
|
||||
}
|
||||
|
||||
export type WidgetKey =
|
||||
| 'string'
|
||||
| 'string:secret'
|
||||
| 'string:multiline'
|
||||
| 'string:color'
|
||||
| 'number'
|
||||
| 'number:size'
|
||||
| 'number:duration'
|
||||
| 'utcDateTime'
|
||||
| 'boolean'
|
||||
| 'enum'
|
||||
| 'blobId'
|
||||
| 'objectId'
|
||||
| 'object'
|
||||
| 'object:x:Expression'
|
||||
| 'object:x:Rate'
|
||||
| 'object:x:OtpAuth'
|
||||
| 'objectList'
|
||||
| 'set'
|
||||
| 'set:enum'
|
||||
| 'map'
|
||||
| 'unsupported';
|
||||
|
||||
export function widgetKey(type: FieldType): WidgetKey {
|
||||
switch (type.type) {
|
||||
case 'string':
|
||||
switch (type.format) {
|
||||
case 'secret':
|
||||
case 'secretText':
|
||||
return 'string:secret';
|
||||
case 'text':
|
||||
case 'html':
|
||||
case 'sieve':
|
||||
return 'string:multiline';
|
||||
case 'color':
|
||||
return 'string:color';
|
||||
default:
|
||||
return 'string';
|
||||
}
|
||||
case 'number':
|
||||
return type.format === 'size' ? 'number:size' : type.format === 'duration' ? 'number:duration' : 'number';
|
||||
case 'object':
|
||||
switch (type.objectName) {
|
||||
case 'x:Expression':
|
||||
return 'object:x:Expression';
|
||||
case 'x:Rate':
|
||||
return 'object:x:Rate';
|
||||
case 'x:OtpAuth':
|
||||
return 'object:x:OtpAuth';
|
||||
default:
|
||||
return 'object';
|
||||
}
|
||||
case 'set':
|
||||
return type.class.type === 'enum' ? 'set:enum' : 'set';
|
||||
case 'utcDateTime':
|
||||
case 'boolean':
|
||||
case 'enum':
|
||||
case 'blobId':
|
||||
case 'objectId':
|
||||
case 'objectList':
|
||||
case 'map':
|
||||
return type.type;
|
||||
default:
|
||||
return 'unsupported';
|
||||
}
|
||||
}
|
||||
|
||||
const TRAITS: Record<WidgetKey, WidgetTraits> = {
|
||||
string: { labelMode: 'control', readOnlyAsValue: true },
|
||||
'string:secret': { labelMode: 'control', readOnlyAsValue: true },
|
||||
'string:multiline': { labelMode: 'control', readOnlyAsValue: true },
|
||||
'string:color': { labelMode: 'control', readOnlyAsValue: true },
|
||||
number: { labelMode: 'control', readOnlyAsValue: true },
|
||||
'number:size': { labelMode: 'control', readOnlyAsValue: true },
|
||||
'number:duration': { labelMode: 'control', readOnlyAsValue: true },
|
||||
utcDateTime: { labelMode: 'control', readOnlyAsValue: true },
|
||||
boolean: { labelMode: 'control', readOnlyAsValue: true },
|
||||
enum: { labelMode: 'control', readOnlyAsValue: true },
|
||||
blobId: { labelMode: 'control', readOnlyAsValue: false },
|
||||
objectId: { labelMode: 'control', readOnlyAsValue: true },
|
||||
object: { labelMode: 'group', readOnlyAsValue: false },
|
||||
'object:x:Expression': { labelMode: 'group', readOnlyAsValue: false },
|
||||
'object:x:Rate': { labelMode: 'control', readOnlyAsValue: false },
|
||||
'object:x:OtpAuth': { labelMode: 'none', readOnlyAsValue: false },
|
||||
objectList: { labelMode: 'group', readOnlyAsValue: false },
|
||||
set: { labelMode: 'control', readOnlyAsValue: true },
|
||||
'set:enum': { labelMode: 'group', readOnlyAsValue: true },
|
||||
map: { labelMode: 'group', readOnlyAsValue: false },
|
||||
unsupported: { labelMode: 'none', readOnlyAsValue: false },
|
||||
};
|
||||
|
||||
export function widgetTraits(type: FieldType): WidgetTraits {
|
||||
return TRAITS[widgetKey(type)];
|
||||
}
|
||||
@@ -23,4 +23,5 @@ export interface WidgetProps<T extends FieldType = FieldType> {
|
||||
onChange: (value: unknown) => void;
|
||||
readOnly: boolean;
|
||||
control: ControlProps;
|
||||
error?: string;
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
*/
|
||||
|
||||
import { Component, type ErrorInfo, type ReactNode } from 'react';
|
||||
import { TriangleAlert } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import i18n from '@/i18n';
|
||||
|
||||
@@ -50,11 +51,12 @@ export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundarySt
|
||||
}
|
||||
|
||||
return (
|
||||
<div role="alert" className="flex flex-col items-center justify-center gap-4 p-8">
|
||||
<div className="text-destructive text-lg font-semibold">
|
||||
{i18n.t('errorBoundary.title', 'Something went wrong')}
|
||||
</div>
|
||||
<p className="text-muted-foreground text-sm max-w-md text-center">
|
||||
<div role="alert" className="mx-auto mt-6 flex max-w-lg flex-col items-center gap-4 tile p-8 text-center">
|
||||
<span className="grid size-11 place-items-center rounded-[13px] bg-destructive-soft text-destructive">
|
||||
<TriangleAlert className="h-5 w-5" aria-hidden="true" />
|
||||
</span>
|
||||
<div className="section-title text-lg">{i18n.t('errorBoundary.title', 'Something went wrong')}</div>
|
||||
<p className="max-w-md text-sm text-muted-foreground">
|
||||
{this.state.error?.message ?? i18n.t('errors.unexpectedError', 'An unexpected error occurred.')}
|
||||
</p>
|
||||
<Button variant="outline" onClick={this.handleReset}>
|
||||
|
||||
@@ -4,49 +4,17 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { lazy, Suspense, type ComponentType, type ReactNode } from 'react';
|
||||
import { Suspense, type ReactNode } from 'react';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { TFunction } from 'i18next';
|
||||
import { useSchemaStore } from '@/stores/schemaStore';
|
||||
import { usePermissionCheckers } from '@/hooks/usePermissions';
|
||||
import { resolveObject } from '@/lib/schemaResolver';
|
||||
import type { PermissionCheckers } from '@/lib/permissions';
|
||||
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 DeliveryTracePage = lazyFeature(
|
||||
() => import('@/features/troubleshoot/DeliveryTracePage'),
|
||||
(m) => m.DeliveryTracePage,
|
||||
);
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
const DashboardView = lazyFeature(
|
||||
() => import('@/features/dashboard/components/DashboardView'),
|
||||
(m) => m.DashboardView,
|
||||
);
|
||||
const LiveTracingPage = lazyFeature(
|
||||
() => import('@/features/tracing/components/LiveTracingPage'),
|
||||
(m) => m.LiveTracingPage,
|
||||
);
|
||||
const TraceDetailView = lazyFeature(
|
||||
() => import('@/features/tracing/components/TraceDetailView'),
|
||||
(m) => m.TraceDetailView,
|
||||
);
|
||||
// SPDX-SnippetEnd
|
||||
const ActionPage = lazyFeature(
|
||||
() => import('@/features/actions/ActionPage'),
|
||||
(m) => m.ActionPage,
|
||||
);
|
||||
|
||||
interface MainContentProps {
|
||||
viewName?: string;
|
||||
@@ -54,104 +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 permissions = usePermissionCheckers();
|
||||
const location = useLocation();
|
||||
const { t } = useTranslation();
|
||||
const page = resolvePage(schema, viewName, id, permissions);
|
||||
|
||||
let content: ReactNode;
|
||||
switch (page.kind) {
|
||||
case 'loading':
|
||||
content = <LoadingFallback />;
|
||||
break;
|
||||
case 'unknownComponent':
|
||||
content = (
|
||||
<div className="mt-3 rounded-2xl bg-muted p-10 text-center text-muted-foreground">
|
||||
{t('errors.unknownComponent', 'Unknown component: {{name}}', { name: page.name })}
|
||||
</div>
|
||||
);
|
||||
break;
|
||||
case 'unknownView':
|
||||
content = (
|
||||
<div role="alert" className="mt-3 rounded-xl bg-destructive-soft p-4 text-center text-sm text-destructive">
|
||||
{t('errors.unknownView', 'Unknown view: {{name}}', { name: viewName })}
|
||||
</div>
|
||||
);
|
||||
break;
|
||||
case 'route': {
|
||||
const Page = page.component;
|
||||
content = <Page viewName={page.viewName} objectId={id ?? null} section={section} />;
|
||||
break;
|
||||
}
|
||||
case 'object': {
|
||||
const objectId = pageObjectId(page.target);
|
||||
const key = objectId ? `${page.viewName}/${objectId}` : page.viewName;
|
||||
const Page = page.component;
|
||||
content = Page ? (
|
||||
<Page key={key} viewName={page.viewName} objectId={objectId} section={section} />
|
||||
) : (
|
||||
genericView(page.viewName, page.target, key)
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<ErrorBoundary resetKey={location.pathname}>
|
||||
<Suspense fallback={<LoadingFallback />}>{renderView(t, schema, permissions, viewName, id, section)}</Suspense>
|
||||
<Suspense fallback={<LoadingFallback />}>{content}</Suspense>
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
|
||||
function renderView(
|
||||
t: TFunction,
|
||||
schema: Schema | null,
|
||||
permissions: PermissionCheckers,
|
||||
viewName?: string,
|
||||
id?: string,
|
||||
section?: string,
|
||||
): ReactNode {
|
||||
if (!viewName) {
|
||||
return <LoadingFallback />;
|
||||
}
|
||||
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
if (viewName.startsWith('Dashboard/')) {
|
||||
const dashboardId = viewName.slice('Dashboard/'.length);
|
||||
return <DashboardView dashboardId={dashboardId} section={section ?? ''} />;
|
||||
}
|
||||
// SPDX-SnippetEnd
|
||||
|
||||
if (viewName.startsWith('CustomComponent/')) {
|
||||
const componentName = viewName.slice('CustomComponent/'.length);
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
if (componentName === 'Dashboard') {
|
||||
const firstId = schema?.dashboards?.[0]?.id ?? 'overview';
|
||||
return <DashboardView dashboardId={firstId} section={section ?? ''} />;
|
||||
}
|
||||
// SPDX-SnippetEnd
|
||||
if (componentName === 'LiveDelivery') {
|
||||
return <DeliveryTracePage />;
|
||||
}
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
if (componentName === 'LiveTracing') {
|
||||
return <LiveTracingPage />;
|
||||
}
|
||||
// SPDX-SnippetEnd
|
||||
return (
|
||||
<div className="rounded-lg border border-dashed p-12 text-center text-muted-foreground">
|
||||
{t('errors.unknownComponent', 'Unknown component: {{name}}', { name: componentName })}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!schema) {
|
||||
return <LoadingFallback />;
|
||||
}
|
||||
|
||||
const resolved = resolveObject(schema, viewName);
|
||||
if (!resolved) {
|
||||
return (
|
||||
<div role="alert" className="flex items-center justify-center p-8 text-destructive">
|
||||
{t('errors.unknownView', 'Unknown view: {{name}}', { name: viewName })}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (resolved.objectName === 'x:Action') {
|
||||
return <ActionPage key={viewName} viewName={viewName} />;
|
||||
}
|
||||
|
||||
if (resolved.objectType.type === 'singleton') {
|
||||
return <DynamicForm key={`${viewName}/singleton`} viewName={viewName} objectId="singleton" />;
|
||||
}
|
||||
|
||||
if (id === 'new') {
|
||||
return <DynamicForm key={`${viewName}/new`} viewName={viewName} objectId={null} />;
|
||||
}
|
||||
|
||||
if (id) {
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
if (resolved.objectName === 'x:Trace') {
|
||||
return <TraceDetailView key={`${viewName}/${id}`} viewName={viewName} objectId={id} />;
|
||||
}
|
||||
// SPDX-SnippetEnd
|
||||
if (!permissions.hasObjectPermission(resolved.permissionPrefix, 'Update')) {
|
||||
return <DynamicViewPage key={`${viewName}/${id}`} viewName={viewName} objectId={id} />;
|
||||
}
|
||||
return <DynamicForm key={`${viewName}/${id}`} viewName={viewName} objectId={id} />;
|
||||
}
|
||||
|
||||
return <DynamicList key={viewName} viewName={viewName} />;
|
||||
}
|
||||
@@ -4,33 +4,34 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useEffect, useId, useRef, useState, type CSSProperties } from 'react';
|
||||
import { useEffect, useId, useRef, useState } from 'react';
|
||||
import { Link, useLocation, useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ChevronDown, Lock } from 'lucide-react';
|
||||
import { ChevronRight, Lock } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { Button, buttonVariants } from '@/components/ui/button';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { DynamicIcon } from '@/components/common/DynamicIcon';
|
||||
import { EnterpriseUpsell } from '@/components/common/EnterpriseUpsell';
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import { useUIStore } from '@/stores/uiStore';
|
||||
import type { Layout } from '@/types/schema';
|
||||
import { layoutNavNodes, navNodeKey, pathMatchesView, someLink, viewPath, type NavNode } from './navTree';
|
||||
import { activeViewName, layoutNavNodes, navNodeKey, someLink, viewPath, type NavNode } from './navTree';
|
||||
import { SIDEBAR_ID, SidebarNavContext, useSidebarNav } from './sidebarContext';
|
||||
import { useLayoutNavigation } from './useLayoutNavigation';
|
||||
|
||||
function indent(depth: number): CSSProperties | undefined {
|
||||
return depth > 0 ? { paddingInlineStart: `${(depth + 1) * 12 + 8}px` } : undefined;
|
||||
}
|
||||
const itemClass =
|
||||
'flex w-full items-center gap-2.5 rounded-[10px] px-2.5 text-left font-medium text-muted-foreground outline-none transition-colors duration-200 hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring';
|
||||
|
||||
const itemClass = 'w-full justify-start gap-2 font-normal';
|
||||
function itemSize(depth: number) {
|
||||
return depth > 0 ? 'h-8 text-[13px]' : 'h-9 text-sm';
|
||||
}
|
||||
|
||||
function NavLink({ node, depth }: { node: Extract<NavNode, { kind: 'link' }>; depth: number }) {
|
||||
const { t } = useTranslation();
|
||||
const nav = useSidebarNav();
|
||||
const ref = useRef<HTMLAnchorElement>(null);
|
||||
const isActive = pathMatchesView(nav.pathname, nav.sectionName, node.viewName);
|
||||
const isActive = node.viewName === nav.activeViewName;
|
||||
|
||||
useEffect(() => {
|
||||
if (isActive) ref.current?.scrollIntoView?.({ block: 'nearest' });
|
||||
@@ -45,17 +46,11 @@ function NavLink({ node, depth }: { node: Extract<NavNode, { kind: 'link' }>; de
|
||||
<span className="truncate">{label}</span>
|
||||
</>
|
||||
);
|
||||
const className = cn(buttonVariants({ variant: 'ghost' }), itemClass, depth > 0 && 'text-sm');
|
||||
const className = cn(itemClass, itemSize(depth));
|
||||
|
||||
if (nav.isLocked(node.viewName)) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={className}
|
||||
style={indent(depth)}
|
||||
onClick={nav.openUpsell}
|
||||
aria-describedby={nav.lockedHintId}
|
||||
>
|
||||
<button type="button" className={className} onClick={nav.openUpsell} aria-describedby={nav.lockedHintId}>
|
||||
{content}
|
||||
<Lock aria-hidden="true" className="ml-auto h-3 w-3 text-muted-foreground" />
|
||||
</button>
|
||||
@@ -67,8 +62,11 @@ function NavLink({ node, depth }: { node: Extract<NavNode, { kind: 'link' }>; de
|
||||
ref={ref}
|
||||
to={viewPath(nav.sectionName, node.viewName)}
|
||||
aria-current={isActive ? 'page' : undefined}
|
||||
className={cn(className, isActive && 'bg-accent text-accent-foreground')}
|
||||
style={indent(depth)}
|
||||
className={cn(
|
||||
className,
|
||||
isActive &&
|
||||
'bg-highlight font-semibold text-highlight-foreground hover:bg-highlight hover:text-highlight-foreground',
|
||||
)}
|
||||
>
|
||||
{content}
|
||||
</Link>
|
||||
@@ -77,9 +75,7 @@ function NavLink({ node, depth }: { node: Extract<NavNode, { kind: 'link' }>; de
|
||||
|
||||
function NavContainer({ node, depth }: { node: Extract<NavNode, { kind: 'container' }>; depth: number }) {
|
||||
const nav = useSidebarNav();
|
||||
const containsActive = someLink(node.children, (viewName) =>
|
||||
pathMatchesView(nav.pathname, nav.sectionName, viewName),
|
||||
);
|
||||
const containsActive = someLink(node.children, (viewName) => viewName === nav.activeViewName);
|
||||
const [open, setOpen] = useState(containsActive);
|
||||
const [prevContainsActive, setPrevContainsActive] = useState(containsActive);
|
||||
if (containsActive !== prevContainsActive) {
|
||||
@@ -92,25 +88,19 @@ function NavContainer({ node, depth }: { node: Extract<NavNode, { kind: 'contain
|
||||
return (
|
||||
<Collapsible open={open} onOpenChange={setOpen}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<Button variant="ghost" className={cn(itemClass, depth > 0 && 'text-sm')} style={indent(depth)}>
|
||||
{depth > 0 && (
|
||||
<ChevronDown
|
||||
aria-hidden="true"
|
||||
className="h-3 w-3 shrink-0 transition-transform duration-200 [[data-state=closed]>&]:rotate-[-90deg]"
|
||||
/>
|
||||
)}
|
||||
<button type="button" className={cn(itemClass, itemSize(depth))}>
|
||||
{node.icon && <DynamicIcon name={node.icon} className="h-4 w-4 shrink-0" />}
|
||||
<span className="truncate">{node.name}</span>
|
||||
{depth === 0 && (
|
||||
<ChevronDown
|
||||
aria-hidden="true"
|
||||
className="ml-auto h-3 w-3 shrink-0 transition-transform duration-200 [[data-state=closed]>&]:rotate-[-90deg]"
|
||||
/>
|
||||
)}
|
||||
</Button>
|
||||
<ChevronRight
|
||||
aria-hidden="true"
|
||||
className="ml-auto h-3.5 w-3.5 shrink-0 opacity-60 transition-transform duration-200 [[data-state=open]>&]:rotate-90"
|
||||
/>
|
||||
</button>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<NavNodes nodes={node.children} depth={depth + 1} />
|
||||
<div className="my-0.5 ml-[18px] flex flex-col gap-0.5 border-l border-input pl-2">
|
||||
<NavNodes nodes={node.children} depth={depth + 1} />
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
);
|
||||
@@ -136,7 +126,7 @@ function SectionSwitcher({ layouts, activeSection }: { layouts: Layout[]; active
|
||||
<div
|
||||
role="group"
|
||||
aria-label={t('sections', 'Sections')}
|
||||
className="flex items-center justify-around border-t bg-background px-2 py-2"
|
||||
className="m-2.5 mt-0 flex items-center gap-0.5 rounded-full bg-muted p-1"
|
||||
>
|
||||
{layouts.map((target) => {
|
||||
const isActive = target.name === activeSection;
|
||||
@@ -154,7 +144,10 @@ function SectionSwitcher({ layouts, activeSection }: { layouts: Layout[]; active
|
||||
const path = landingPath(target);
|
||||
if (path) navigate(path);
|
||||
}}
|
||||
className={cn('h-9 w-9', isActive && 'bg-accent text-accent-foreground')}
|
||||
className={cn(
|
||||
'h-8 flex-1 rounded-full',
|
||||
isActive && 'bg-card text-foreground shadow-tile hover:bg-card hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
<DynamicIcon name={target.icon} className="h-4 w-4" />
|
||||
</Button>
|
||||
@@ -185,9 +178,11 @@ export function Sidebar() {
|
||||
const layout = layouts.find((l) => l.name === activeSection);
|
||||
if (!layout) return null;
|
||||
|
||||
const nodes = layoutNavNodes(layout);
|
||||
const nav = {
|
||||
sectionName: layout.name,
|
||||
pathname,
|
||||
activeViewName: activeViewName(nodes, pathname, layout.name),
|
||||
isVisible,
|
||||
isLocked,
|
||||
openUpsell: () => setUpsellOpen(true),
|
||||
@@ -198,21 +193,21 @@ export function Sidebar() {
|
||||
<>
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="fixed inset-0 top-14 z-20 bg-black/40 md:hidden"
|
||||
className="fixed inset-0 top-16 z-20 bg-overlay md:hidden"
|
||||
onClick={() => setSidebarOpen(false)}
|
||||
/>
|
||||
<aside
|
||||
id={SIDEBAR_ID}
|
||||
aria-label={t('sidebar.label', 'Sidebar')}
|
||||
className="fixed bottom-0 left-0 top-14 z-30 flex w-64 flex-col border-r bg-background"
|
||||
className="fixed bottom-3 left-3 top-16 z-30 flex w-60 flex-col tile overflow-hidden"
|
||||
>
|
||||
<span id={lockedHintId} className="sr-only">
|
||||
{t('enterprise.featureHint', 'Enterprise feature')}
|
||||
</span>
|
||||
<div className="flex-1 overflow-y-auto py-2 [scrollbar-width:thin]">
|
||||
<nav aria-label={layout.name} className="flex flex-col gap-0.5 px-2">
|
||||
<div className="flex-1 overflow-y-auto py-2.5 [scrollbar-width:thin]">
|
||||
<nav aria-label={layout.name} className="flex flex-col gap-0.5 px-2.5">
|
||||
<SidebarNavContext value={nav}>
|
||||
<NavNodes nodes={layoutNavNodes(layout)} depth={0} />
|
||||
<NavNodes nodes={nodes} depth={0} />
|
||||
</SidebarNavContext>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
@@ -26,7 +26,7 @@ import { EnterpriseUpsell } from '@/components/common/EnterpriseUpsell';
|
||||
import { DynamicIcon } from '@/components/common/DynamicIcon';
|
||||
import { useUIStore } from '@/stores/uiStore';
|
||||
import { useAuthStore } from '@/stores/authStore';
|
||||
import { buildEndSessionUrl, getPostLogoutRedirectUri, revokeSessionTokens } from '@/services/auth/oauth';
|
||||
import { buildEndSessionUrl, getPostLogoutRedirectUri } from '@/services/auth/oauth';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useIsCommunity } from '@/hooks/usePermissions';
|
||||
import { SIDEBAR_ID } from './sidebarContext';
|
||||
@@ -63,7 +63,7 @@ export function TopBar() {
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<header className="sticky top-0 z-40 flex h-14 items-center gap-4 border-b bg-background px-4">
|
||||
<header className="sticky top-0 z-40 flex h-16 items-center gap-4 bg-background/80 px-4 backdrop-blur-xl backdrop-saturate-150 sm:px-5">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
@@ -78,7 +78,7 @@ export function TopBar() {
|
||||
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Link to="/" className="flex shrink-0 items-center">
|
||||
<Link to="/" className="flex shrink-0 items-center md:w-[228px]">
|
||||
<Logo />
|
||||
</Link>
|
||||
</TooltipTrigger>
|
||||
@@ -87,24 +87,24 @@ export function TopBar() {
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
|
||||
<div className="hidden min-w-0 flex-1 items-center justify-center px-4 md:flex">
|
||||
<div className="hidden min-w-0 flex-1 items-center md:flex">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPaletteOpen(true)}
|
||||
className="flex h-9 w-full max-w-md items-center gap-2 rounded-md border border-input bg-transparent px-3 text-sm text-muted-foreground shadow-sm transition-colors hover:bg-accent"
|
||||
className="flex h-10 w-full max-w-md items-center gap-2.5 rounded-full bg-card pl-4 pr-2 text-sm text-dim shadow-tile transition-shadow duration-200 hover:shadow-lift"
|
||||
>
|
||||
<Search aria-hidden="true" className="h-4 w-4" />
|
||||
<span className="flex-1 text-left">{t('globalSearch.placeholder', 'Search pages, fields, settings...')}</span>
|
||||
<kbd
|
||||
aria-hidden="true"
|
||||
className="pointer-events-none flex h-5 select-none items-center rounded border bg-muted px-1.5 font-mono text-[10px] font-medium"
|
||||
className="pointer-events-none flex h-6 select-none items-center rounded-full bg-muted px-2.5 font-mono text-[11px] font-medium text-muted-foreground"
|
||||
>
|
||||
{IS_MAC ? '⌘K' : 'Ctrl K'}
|
||||
</kbd>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="ml-auto flex items-center gap-2 md:ml-0">
|
||||
<div className="ml-auto flex items-center gap-1.5">
|
||||
{isCommunity && <EnterpriseUpsell open={upsellOpen} onClose={() => setUpsellOpen(false)} />}
|
||||
|
||||
<Button
|
||||
@@ -129,7 +129,7 @@ export function TopBar() {
|
||||
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" aria-label={t('userMenu', 'User menu')}>
|
||||
<Button variant="outline" size="icon-lg" aria-label={t('userMenu', 'User menu')}>
|
||||
<User aria-hidden="true" className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
@@ -186,7 +186,6 @@ export function TopBar() {
|
||||
const endSessionUrl = endSessionEndpoint
|
||||
? buildEndSessionUrl(endSessionEndpoint, getPostLogoutRedirectUri())
|
||||
: null;
|
||||
if (endSessionUrl) revokeSessionTokens();
|
||||
logout();
|
||||
if (endSessionUrl) {
|
||||
window.location.href = endSessionUrl;
|
||||
|
||||
@@ -55,3 +55,14 @@ export function pathMatchesView(pathname: string, sectionName: string, viewName:
|
||||
export function someLink(nodes: NavNode[], predicate: (viewName: string) => boolean): boolean {
|
||||
return nodes.some((node) => (node.kind === 'link' ? predicate(node.viewName) : someLink(node.children, predicate)));
|
||||
}
|
||||
|
||||
export function activeViewName(nodes: NavNode[], pathname: string, sectionName: string): string | undefined {
|
||||
let active: string | undefined;
|
||||
for (const node of nodes) {
|
||||
let candidate: string | undefined;
|
||||
if (node.kind === 'container') candidate = activeViewName(node.children, pathname, sectionName);
|
||||
else if (pathMatchesView(pathname, sectionName, node.viewName)) candidate = node.viewName;
|
||||
if (candidate !== undefined && (active === undefined || candidate.length > active.length)) active = candidate;
|
||||
}
|
||||
return active;
|
||||
}
|
||||
@@ -11,6 +11,7 @@ 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;
|
||||
|
||||
@@ -10,6 +10,9 @@ import { ArrowUpDown, ChevronDown, ChevronUp } from 'lucide-react';
|
||||
import type { Column } from '@/types/schema';
|
||||
import type { ListSort } from './listUrlState';
|
||||
|
||||
export const HEADER_CELL =
|
||||
'px-3.5 py-2.5 first:pl-5 last:pr-5 text-left text-[11px] font-semibold uppercase tracking-wider text-dim';
|
||||
|
||||
interface ColumnHeaderProps {
|
||||
column: Column;
|
||||
sortable: boolean;
|
||||
@@ -20,7 +23,7 @@ interface ColumnHeaderProps {
|
||||
export function ColumnHeader({ column, sortable, sort, onSort }: ColumnHeaderProps) {
|
||||
const { t } = useTranslation();
|
||||
const direction = sort?.field === column.name ? (sort.ascending ? 'ascending' : 'descending') : 'none';
|
||||
const className = 'px-3 py-3 text-left font-medium text-muted-foreground';
|
||||
const className = HEADER_CELL;
|
||||
|
||||
if (!sortable) {
|
||||
return (
|
||||
@@ -43,13 +46,13 @@ export function ColumnHeader({ column, sortable, sort, onSort }: ColumnHeaderPro
|
||||
type="button"
|
||||
onClick={() => onSort(column.name)}
|
||||
title={hint}
|
||||
className="-mx-1 inline-flex items-center gap-1 rounded px-1 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
className="-mx-1 inline-flex items-center gap-1 rounded-md px-1 uppercase tracking-wider hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
{column.label}
|
||||
{direction === 'ascending' ? (
|
||||
<ChevronUp className="h-4 w-4" aria-hidden />
|
||||
<ChevronUp className="h-3.5 w-3.5" aria-hidden />
|
||||
) : direction === 'descending' ? (
|
||||
<ChevronDown className="h-4 w-4" aria-hidden />
|
||||
<ChevronDown className="h-3.5 w-3.5" aria-hidden />
|
||||
) : (
|
||||
<ArrowUpDown className="h-3 w-3" aria-hidden />
|
||||
)}
|
||||
|
||||
@@ -14,6 +14,7 @@ import { ConfirmDialog } from '@/components/common/ConfirmDialog';
|
||||
import { EnterpriseUpsell } from '@/components/common/EnterpriseUpsell';
|
||||
import { useIsCommunity, usePermissionCheckers } from '@/hooks/usePermissions';
|
||||
import { useResolvedView } from '@/hooks/useResolvedView';
|
||||
import { withDestroyContentsNotice } from '@/lib/destroyContents';
|
||||
import { layoutViewFor } from '@/lib/layout';
|
||||
import { canAccessView } from '@/lib/permissions';
|
||||
import { getDisplayProperty } from '@/lib/schemaResolver';
|
||||
@@ -128,20 +129,23 @@ function DynamicListView({ viewName, schema, resolved, list }: DynamicListViewPr
|
||||
title: allMatching
|
||||
? t('list.deleteAllMatchingTitle', 'Delete all matching {{name}}', { name: list.pluralName })
|
||||
: t('list.deleteManyTitle', 'Delete {{count}} {{name}}', { count, name }),
|
||||
description: allMatching
|
||||
? t(
|
||||
'list.deleteAllMatchingDescription',
|
||||
'Are you sure you want to delete ALL {{name}} matching the current filters? This action cannot be undone.',
|
||||
{ name: list.pluralName },
|
||||
)
|
||||
: t(
|
||||
'list.deleteManyDescription',
|
||||
'Are you sure you want to delete {{count}} {{name}}? This action cannot be undone.',
|
||||
{
|
||||
count,
|
||||
name,
|
||||
},
|
||||
),
|
||||
description: withDestroyContentsNotice(
|
||||
allMatching
|
||||
? t(
|
||||
'list.deleteAllMatchingDescription',
|
||||
'Are you sure you want to delete ALL {{name}} matching the current filters? This action cannot be undone.',
|
||||
{ name: list.pluralName },
|
||||
)
|
||||
: t(
|
||||
'list.deleteManyDescription',
|
||||
'Are you sure you want to delete {{count}} {{name}}? This action cannot be undone.',
|
||||
{
|
||||
count,
|
||||
name,
|
||||
},
|
||||
),
|
||||
objectName,
|
||||
),
|
||||
confirmLabel: t('list.deleteAll', 'Delete all'),
|
||||
destructive: true,
|
||||
onConfirm: run,
|
||||
@@ -170,10 +174,11 @@ function DynamicListView({ viewName, schema, resolved, list }: DynamicListViewPr
|
||||
if (action.type === 'delete') {
|
||||
setConfirm({
|
||||
title: t('list.deleteItemTitle', 'Delete {{name}}?', { name: list.singularName }),
|
||||
description: t(
|
||||
'list.deleteItemDescription',
|
||||
'Are you sure you want to delete {{label}}? This action cannot be undone.',
|
||||
{ label },
|
||||
description: withDestroyContentsNotice(
|
||||
t('list.deleteItemDescription', 'Are you sure you want to delete {{label}}? This action cannot be undone.', {
|
||||
label,
|
||||
}),
|
||||
objectName,
|
||||
),
|
||||
confirmLabel: t('list.delete', 'Delete'),
|
||||
destructive: true,
|
||||
@@ -197,105 +202,107 @@ function DynamicListView({ viewName, schema, resolved, list }: DynamicListViewPr
|
||||
const viewFor = (name: string) => layoutViewFor(schema, viewToSection, name, viewName);
|
||||
|
||||
return (
|
||||
<div className="relative space-y-4">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold tracking-tight">{list.title}</h1>
|
||||
<div className="space-y-3.5">
|
||||
<div className="flex flex-wrap items-end justify-between gap-4 px-1 pb-1 pt-3">
|
||||
<div className="min-w-0">
|
||||
<h1 className="page-title">{list.title}</h1>
|
||||
{list.subtitle && <p className="mt-1 text-sm text-muted-foreground">{list.subtitle}</p>}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{massActions.length > 0 && selectedCount > 0 && (
|
||||
<MassActionBar
|
||||
actions={massActions}
|
||||
count={selectedCount}
|
||||
disabled={actions.pending}
|
||||
onSelect={confirmMassAction}
|
||||
/>
|
||||
)}
|
||||
{canCreate && section && (
|
||||
<Button onClick={() => navigate(`/${section}/${viewName}/new`)}>
|
||||
<Plus className="mr-2 h-4 w-4" aria-hidden />
|
||||
{t('list.create', 'Create {{name}}', { name: list.singularName })}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{canCreate && section && (
|
||||
<Button onClick={() => navigate(`/${section}/${viewName}/new`)}>
|
||||
<Plus aria-hidden />
|
||||
{t('list.create', 'Create {{name}}', { name: list.singularName })}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{visibleFilters.length > 0 && (
|
||||
<FilterBar
|
||||
schema={schema}
|
||||
filters={visibleFilters}
|
||||
applied={state.filters}
|
||||
isXPrefixed={objectName.startsWith('x:')}
|
||||
disabled={listState.isFetching}
|
||||
onApply={listState.applyFilters}
|
||||
onReset={listState.resetFilters}
|
||||
/>
|
||||
)}
|
||||
|
||||
{listState.error && <ListError message={listState.error} onRetry={listState.refetch} />}
|
||||
{actions.error && <ListError message={actions.error} onDismiss={actions.clearError} />}
|
||||
|
||||
{massActions.length > 0 && selection.pageState === 'all' && (
|
||||
<SelectionBanner
|
||||
allMatching={selection.allMatching}
|
||||
pageCount={selection.selectedIds.length}
|
||||
total={total}
|
||||
pluralName={list.pluralName}
|
||||
onSelectAllMatching={selection.selectAllMatching}
|
||||
<section className="tile relative overflow-hidden">
|
||||
{visibleFilters.length > 0 && (
|
||||
<FilterBar
|
||||
schema={schema}
|
||||
filters={visibleFilters}
|
||||
applied={state.filters}
|
||||
isXPrefixed={objectName.startsWith('x:')}
|
||||
disabled={listState.isFetching}
|
||||
onApply={listState.applyFilters}
|
||||
onReset={listState.resetFilters}
|
||||
/>
|
||||
)}
|
||||
|
||||
{massActions.length > 0 && selection.pageState === 'all' && (
|
||||
<SelectionBanner
|
||||
allMatching={selection.allMatching}
|
||||
pageCount={selection.selectedIds.length}
|
||||
total={total}
|
||||
pluralName={list.pluralName}
|
||||
onSelectAllMatching={selection.selectAllMatching}
|
||||
onClear={selection.clear}
|
||||
/>
|
||||
)}
|
||||
|
||||
<ListTable
|
||||
caption={list.title}
|
||||
columns={list.columns}
|
||||
fields={fields}
|
||||
items={items}
|
||||
schema={schema}
|
||||
objectName={objectName}
|
||||
sort={state.sort}
|
||||
sortable={new Set(list.sort ?? [])}
|
||||
onSort={listState.toggleSort}
|
||||
selection={massActions.length > 0 ? selection : null}
|
||||
rowHref={(id) => (section ? `/${section}/${viewName}/${id}` : null)}
|
||||
rowLabel={(item) => itemLabel(item, labelProperty)}
|
||||
renderRowActions={
|
||||
itemActions.length > 0
|
||||
? (_item, id, label) => (
|
||||
<RowActions
|
||||
actions={itemActions}
|
||||
label={label}
|
||||
hrefFor={(action) => itemActionHref(action, id, sectionFor, section, viewFor)}
|
||||
onMutation={(entry) => confirmItemAction(entry, id, label)}
|
||||
onLocked={() => setUpsellOpen(true)}
|
||||
disabled={actions.pending}
|
||||
/>
|
||||
)
|
||||
: null
|
||||
}
|
||||
loading={listState.isLoading}
|
||||
busy={busy}
|
||||
/>
|
||||
|
||||
{(items.length > 0 || state.anchors.length > 0) && (
|
||||
<Pagination
|
||||
range={listState.range}
|
||||
total={total}
|
||||
count={items.length}
|
||||
pluralName={list.pluralName}
|
||||
disabled={listState.isFetching}
|
||||
onPrev={listState.prevPage}
|
||||
onNext={listState.nextPage}
|
||||
/>
|
||||
)}
|
||||
|
||||
{busy && items.length > 0 && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-card/50" aria-hidden>
|
||||
<Loader2 className="h-6 w-6 animate-spin text-brand-text" />
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{massActions.length > 0 && selectedCount > 0 && (
|
||||
<MassActionBar
|
||||
actions={massActions}
|
||||
count={selectedCount}
|
||||
disabled={actions.pending}
|
||||
onSelect={confirmMassAction}
|
||||
onClear={selection.clear}
|
||||
/>
|
||||
)}
|
||||
|
||||
<ListTable
|
||||
caption={list.title}
|
||||
columns={list.columns}
|
||||
fields={fields}
|
||||
items={items}
|
||||
schema={schema}
|
||||
objectName={objectName}
|
||||
sort={state.sort}
|
||||
sortable={new Set(list.sort ?? [])}
|
||||
onSort={listState.toggleSort}
|
||||
selection={massActions.length > 0 ? selection : null}
|
||||
rowHref={(id) => (section ? `/${section}/${viewName}/${id}` : null)}
|
||||
rowLabel={(item) => itemLabel(item, labelProperty)}
|
||||
renderRowActions={
|
||||
itemActions.length > 0
|
||||
? (_item, id, label) => (
|
||||
<RowActions
|
||||
actions={itemActions}
|
||||
label={label}
|
||||
hrefFor={(action) => itemActionHref(action, id, sectionFor, section, viewFor)}
|
||||
onMutation={(entry) => confirmItemAction(entry, id, label)}
|
||||
onLocked={() => setUpsellOpen(true)}
|
||||
disabled={actions.pending}
|
||||
/>
|
||||
)
|
||||
: null
|
||||
}
|
||||
loading={listState.isLoading}
|
||||
busy={busy}
|
||||
/>
|
||||
|
||||
{(items.length > 0 || state.anchors.length > 0) && (
|
||||
<Pagination
|
||||
range={listState.range}
|
||||
total={total}
|
||||
count={items.length}
|
||||
pluralName={list.pluralName}
|
||||
disabled={listState.isFetching}
|
||||
onPrev={listState.prevPage}
|
||||
onNext={listState.nextPage}
|
||||
/>
|
||||
)}
|
||||
|
||||
{busy && items.length > 0 && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-background/50" aria-hidden>
|
||||
<Loader2 className="h-6 w-6 animate-spin" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ConfirmDialog
|
||||
open={confirm !== null}
|
||||
onOpenChange={(open) => {
|
||||
|
||||
@@ -9,6 +9,7 @@ import { useTranslation } from 'react-i18next';
|
||||
import { ChevronDown, ChevronUp, Filter as FilterIcon, RotateCcw, Search } from 'lucide-react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
|
||||
import type { Filter, Schema } from '@/types/schema';
|
||||
import { filtersKey } from './listUrlState';
|
||||
@@ -50,23 +51,48 @@ export function FilterBar({ schema, filters, applied, isXPrefixed, disabled, onA
|
||||
onReset();
|
||||
};
|
||||
|
||||
const activeCount = filters.filter((f) => Object.hasOwn(applied, f.field) && applied[f.field] !== '').length;
|
||||
|
||||
return (
|
||||
<Collapsible open={open} onOpenChange={setOpen}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="gap-2" aria-controls={panelId}>
|
||||
<FilterIcon className="h-4 w-4" aria-hidden />
|
||||
{t('list.filters', 'Filters')}
|
||||
{open ? <ChevronUp className="h-4 w-4" aria-hidden /> : <ChevronDown className="h-4 w-4" aria-hidden />}
|
||||
</Button>
|
||||
</CollapsibleTrigger>
|
||||
<div className="flex flex-wrap items-center gap-2 p-2.5">
|
||||
<CollapsibleTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
aria-controls={panelId}
|
||||
className={cn(
|
||||
'inline-flex h-8 items-center gap-1.5 rounded-full px-3.5 text-[13px] font-medium transition-colors duration-200 ease-bento focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
|
||||
activeCount > 0 || open
|
||||
? 'bg-highlight text-highlight-foreground hover:bg-highlight-strong'
|
||||
: 'bg-muted text-muted-foreground hover:bg-muted-strong hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
<FilterIcon className="h-3.5 w-3.5" aria-hidden />
|
||||
{t('list.filters', 'Filters')}
|
||||
{activeCount > 0 && (
|
||||
<span
|
||||
className="grid h-[18px] min-w-[18px] place-items-center rounded-full bg-primary px-1 text-[11px] font-semibold text-primary-foreground"
|
||||
aria-hidden
|
||||
>
|
||||
{activeCount}
|
||||
</span>
|
||||
)}
|
||||
{open ? (
|
||||
<ChevronUp className="h-3.5 w-3.5" aria-hidden />
|
||||
) : (
|
||||
<ChevronDown className="h-3.5 w-3.5" aria-hidden />
|
||||
)}
|
||||
</button>
|
||||
</CollapsibleTrigger>
|
||||
</div>
|
||||
<CollapsibleContent id={panelId}>
|
||||
<form
|
||||
role="search"
|
||||
aria-label={t('list.filters', 'Filters')}
|
||||
onSubmit={handleSubmit}
|
||||
className="mt-2 rounded-lg border bg-background shadow-sm"
|
||||
className="mx-2.5 mb-2.5 rounded-xl bg-muted p-4"
|
||||
>
|
||||
<div className="grid gap-4 p-5 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{filters.map((filter) => (
|
||||
<FilterField
|
||||
key={filter.field}
|
||||
@@ -79,13 +105,13 @@ export function FilterBar({ schema, filters, applied, isXPrefixed, disabled, onA
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex items-center justify-end gap-2 border-t px-5 py-3">
|
||||
<div className="mt-4 flex items-center justify-end gap-2">
|
||||
<Button type="button" variant="ghost" size="sm" onClick={handleReset} disabled={disabled}>
|
||||
<RotateCcw className="mr-2 h-4 w-4" aria-hidden />
|
||||
<RotateCcw aria-hidden />
|
||||
{t('list.resetFilters', 'Reset')}
|
||||
</Button>
|
||||
<Button type="submit" size="sm" disabled={disabled}>
|
||||
<Search className="mr-2 h-4 w-4" aria-hidden />
|
||||
<Search aria-hidden />
|
||||
{t('list.searchFilters', 'Search')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -11,6 +11,7 @@ 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';
|
||||
|
||||
@@ -33,8 +34,8 @@ function opField(filter: Filter): string {
|
||||
|
||||
function LabelledField({ id, label, children }: { id: string; label: string; children: ReactNode }) {
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<label htmlFor={id} className="text-xs font-medium text-muted-foreground">
|
||||
<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}
|
||||
@@ -45,8 +46,8 @@ function LabelledField({ id, label, children }: { id: string; label: string; chi
|
||||
function GroupField({ label, children }: { label: string; children: ReactNode }) {
|
||||
const labelId = useId();
|
||||
return (
|
||||
<div role="group" aria-labelledby={labelId} className="flex flex-col gap-1.5">
|
||||
<span id={labelId} className="text-xs font-medium text-muted-foreground">
|
||||
<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}
|
||||
@@ -59,12 +60,11 @@ function TextFilter({ filter, values, onChange }: FilterFieldProps<FilterText>)
|
||||
const id = useId();
|
||||
return (
|
||||
<LabelledField id={id} label={filter.label}>
|
||||
<Input
|
||||
<SearchInput
|
||||
id={id}
|
||||
type="search"
|
||||
placeholder={t('list.filterPlaceholder', 'Search {{label}}...', { label: filter.label.toLowerCase() })}
|
||||
value={values[filter.field] ?? ''}
|
||||
onChange={(e) => onChange(filter.field, e.target.value)}
|
||||
onValueChange={(next) => onChange(filter.field, next)}
|
||||
/>
|
||||
</LabelledField>
|
||||
);
|
||||
|
||||
@@ -14,20 +14,20 @@ export function ListSpinner({ className }: { className?: string }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div role="status" className={className ?? 'flex items-center justify-center p-8'}>
|
||||
<Loader2 className="h-6 w-6 animate-spin" aria-hidden />
|
||||
<Loader2 className="h-6 w-6 animate-spin text-brand-text" aria-hidden />
|
||||
<span className="sr-only">{t('common.loading', 'Loading...')}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ListMessage({ children }: { children: ReactNode }) {
|
||||
return <div className="p-8 text-center text-muted-foreground">{children}</div>;
|
||||
return <div className="rounded-2xl bg-muted p-10 text-center text-muted-foreground">{children}</div>;
|
||||
}
|
||||
|
||||
export function ListTableMessage({ colSpan, children }: { colSpan: number; children: ReactNode }) {
|
||||
return (
|
||||
<tr>
|
||||
<td colSpan={colSpan} className="px-3 py-12 text-center text-muted-foreground">
|
||||
<td colSpan={colSpan} className="border-t border-border px-3 py-12 text-center text-muted-foreground">
|
||||
{children}
|
||||
</td>
|
||||
</tr>
|
||||
@@ -47,12 +47,17 @@ export function ListError({
|
||||
return (
|
||||
<div
|
||||
role="alert"
|
||||
className="flex items-start justify-between gap-3 rounded-md border border-destructive/50 bg-destructive/10 p-3 text-sm text-destructive"
|
||||
className="flex items-start justify-between gap-3 rounded-xl bg-destructive-soft p-4 text-sm text-destructive"
|
||||
>
|
||||
<span className="whitespace-pre-line">{message}</span>
|
||||
<div className="flex shrink-0 items-center gap-1">
|
||||
{onRetry && (
|
||||
<Button variant="ghost" size="sm" className="h-7" onClick={onRetry}>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 text-destructive hover:bg-destructive/10 hover:text-destructive"
|
||||
onClick={onRetry}
|
||||
>
|
||||
{t('common.retry', 'Retry')}
|
||||
</Button>
|
||||
)}
|
||||
@@ -60,7 +65,7 @@ export function ListError({
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7"
|
||||
className="h-7 w-7 text-destructive hover:bg-destructive/10 hover:text-destructive"
|
||||
onClick={onDismiss}
|
||||
aria-label={t('common.close', 'Close')}
|
||||
>
|
||||
|
||||
+131
-105
@@ -4,15 +4,16 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import type { ReactNode } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
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 } from './ColumnHeader';
|
||||
import { ColumnHeader, HEADER_CELL } from './ColumnHeader';
|
||||
import { ListSpinner, ListTableMessage } from './ListStates';
|
||||
import { itemId, type ListItem } from './listQuery';
|
||||
import type { ListSort } from './listUrlState';
|
||||
@@ -36,8 +37,28 @@ interface ListTableProps {
|
||||
busy: boolean;
|
||||
}
|
||||
|
||||
const STRETCHED_LINK =
|
||||
"font-medium text-foreground hover:underline focus-visible:outline-none after:absolute after:inset-0 after:content-[''] focus-visible:after:ring-2 focus-visible:after:ring-inset focus-visible:after:ring-ring";
|
||||
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,
|
||||
@@ -57,6 +78,7 @@ export function ListTable({
|
||||
busy,
|
||||
}: ListTableProps) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const colSpan = columns.length + (selection ? 1 : 0) + (renderRowActions ? 1 : 0);
|
||||
const rows = items.flatMap((item) => {
|
||||
const id = itemId(item);
|
||||
@@ -64,108 +86,112 @@ export function ListTable({
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border bg-background shadow-sm">
|
||||
<div className="overflow-x-auto rounded-[calc(var(--radius-lg)-1px)]">
|
||||
<table className="w-full text-sm" aria-busy={busy || undefined}>
|
||||
<caption className="sr-only">{caption}</caption>
|
||||
<thead>
|
||||
<tr className="border-b bg-muted">
|
||||
{selection && (
|
||||
<th scope="col" className="w-10 px-3 py-3">
|
||||
<Checkbox
|
||||
checked={
|
||||
selection.pageState === 'all' ? true : selection.pageState === 'some' ? 'indeterminate' : false
|
||||
}
|
||||
disabled={rows.length === 0}
|
||||
onCheckedChange={selection.togglePage}
|
||||
aria-label={t('list.selectAllOnPage', 'Select all on this page')}
|
||||
/>
|
||||
</th>
|
||||
)}
|
||||
{columns.map((col) => (
|
||||
<ColumnHeader
|
||||
key={col.name}
|
||||
column={col}
|
||||
sortable={sortable.has(col.name)}
|
||||
sort={sort}
|
||||
onSort={onSort}
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm" aria-busy={busy || undefined}>
|
||||
<caption className="sr-only">{caption}</caption>
|
||||
<thead>
|
||||
<tr>
|
||||
{selection && (
|
||||
<th scope="col" className="w-10 py-2.5 pl-5 pr-2 text-left align-middle">
|
||||
<Checkbox
|
||||
checked={
|
||||
selection.pageState === 'all' ? true : selection.pageState === 'some' ? 'indeterminate' : false
|
||||
}
|
||||
disabled={rows.length === 0}
|
||||
onCheckedChange={selection.togglePage}
|
||||
aria-label={t('list.selectAllOnPage', 'Select all on this page')}
|
||||
/>
|
||||
))}
|
||||
{renderRowActions && (
|
||||
<th scope="col" className="w-12 px-3 py-3 text-right font-medium text-muted-foreground">
|
||||
{t('list.actions', 'Actions')}
|
||||
</th>
|
||||
)}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{loading && rows.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={colSpan} className="px-3 py-12">
|
||||
<ListSpinner className="flex items-center justify-center" />
|
||||
</td>
|
||||
</tr>
|
||||
) : rows.length === 0 ? (
|
||||
<ListTableMessage colSpan={colSpan}>{t('list.noResults', 'No results found')}</ListTableMessage>
|
||||
) : (
|
||||
rows.map(({ item, id }) => {
|
||||
const label = rowLabel(item);
|
||||
const href = rowHref(id);
|
||||
return (
|
||||
<tr key={id} className="relative border-b transition-colors hover:bg-muted/50">
|
||||
{selection && (
|
||||
<td className="relative z-10 px-3 py-2">
|
||||
<Checkbox
|
||||
checked={selection.isSelected(id)}
|
||||
onCheckedChange={() => selection.toggle(id)}
|
||||
aria-label={t('list.selectNamed', 'Select {{label}}', { label })}
|
||||
/>
|
||||
</td>
|
||||
)}
|
||||
{columns.map((col, index) => {
|
||||
const value = item[col.name];
|
||||
const content = (
|
||||
<ListCell
|
||||
schema={schema}
|
||||
objectName={objectName}
|
||||
column={col.name}
|
||||
field={fields[col.name]}
|
||||
value={value}
|
||||
/>
|
||||
);
|
||||
if (index === 0) {
|
||||
return (
|
||||
<th key={col.name} scope="row" className="px-3 py-2 text-left font-normal">
|
||||
{href ? (
|
||||
<Link
|
||||
to={href}
|
||||
className={STRETCHED_LINK}
|
||||
aria-label={isEmptyValue(value) ? label : undefined}
|
||||
>
|
||||
{content}
|
||||
</Link>
|
||||
) : (
|
||||
content
|
||||
)}
|
||||
</th>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<td key={col.name} className="px-3 py-2">
|
||||
{content}
|
||||
</td>
|
||||
);
|
||||
})}
|
||||
{renderRowActions && (
|
||||
<td className="relative z-10 px-3 py-2 text-right">{renderRowActions(item, id, label)}</td>
|
||||
)}
|
||||
</tr>
|
||||
);
|
||||
})
|
||||
</th>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{columns.map((col) => (
|
||||
<ColumnHeader key={col.name} column={col} sortable={sortable.has(col.name)} sort={sort} onSort={onSort} />
|
||||
))}
|
||||
{renderRowActions && (
|
||||
<th scope="col" className={cn(HEADER_CELL, 'w-12 text-right last:pr-3')}>
|
||||
<span className="sr-only">{t('list.actions', 'Actions')}</span>
|
||||
</th>
|
||||
)}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{loading && rows.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={colSpan} className="border-t border-border px-3 py-12">
|
||||
<ListSpinner className="flex items-center justify-center" />
|
||||
</td>
|
||||
</tr>
|
||||
) : rows.length === 0 ? (
|
||||
<ListTableMessage colSpan={colSpan}>{t('list.noResults', 'No results found')}</ListTableMessage>
|
||||
) : (
|
||||
rows.map(({ item, id }) => {
|
||||
const label = rowLabel(item);
|
||||
const href = rowHref(id);
|
||||
return (
|
||||
<tr
|
||||
key={id}
|
||||
className={cn(
|
||||
'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>
|
||||
);
|
||||
}
|
||||
@@ -5,9 +5,10 @@
|
||||
*/
|
||||
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ChevronDown } from 'lucide-react';
|
||||
import { ChevronUp, X } from 'lucide-react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { FloatingActionBar, FloatingActionDivider, FloatingActionDot } from '@/components/common/FloatingActionBar';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
@@ -24,33 +25,47 @@ interface MassActionBarProps {
|
||||
count: number;
|
||||
disabled: boolean;
|
||||
onSelect: (action: RunnableMassAction) => void;
|
||||
onClear: () => void;
|
||||
}
|
||||
|
||||
export function MassActionBar({ actions, count, disabled, onSelect }: MassActionBarProps) {
|
||||
export function MassActionBar({ actions, count, disabled, onSelect, onClear }: MassActionBarProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="sm" disabled={disabled}>
|
||||
{t('list.massActionCount', 'Actions ({{count}})', { count })}
|
||||
<ChevronDown className="ml-1 h-4 w-4" aria-hidden />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{actions.map(({ key, action }) =>
|
||||
action.type === 'separator' ? (
|
||||
<DropdownMenuSeparator key={key} />
|
||||
) : (
|
||||
<DropdownMenuItem
|
||||
key={key}
|
||||
className={action.type === 'delete' ? 'text-destructive' : undefined}
|
||||
onSelect={() => onSelect(action)}
|
||||
>
|
||||
{action.label}
|
||||
</DropdownMenuItem>
|
||||
),
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<FloatingActionBar>
|
||||
<span className="pl-2">
|
||||
<FloatingActionDot />
|
||||
</span>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ink" size="sm" className="text-ink-foreground" disabled={disabled}>
|
||||
{t('list.massActionCount', 'Actions ({{count}})', { count })}
|
||||
<ChevronUp aria-hidden />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="center" side="top" sideOffset={10}>
|
||||
{actions.map(({ key, action }) =>
|
||||
action.type === 'separator' ? (
|
||||
<DropdownMenuSeparator key={key} />
|
||||
) : (
|
||||
<DropdownMenuItem
|
||||
key={key}
|
||||
className={
|
||||
action.type === 'delete'
|
||||
? 'text-destructive focus:bg-destructive-soft focus:text-destructive'
|
||||
: undefined
|
||||
}
|
||||
onSelect={() => onSelect(action)}
|
||||
>
|
||||
{action.label}
|
||||
</DropdownMenuItem>
|
||||
),
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<FloatingActionDivider />
|
||||
<Button variant="ink" size="icon-sm" onClick={onClear} aria-label={t('list.clearSelection', 'Clear selection')}>
|
||||
<X aria-hidden />
|
||||
</Button>
|
||||
</FloatingActionBar>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
*/
|
||||
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ChevronLeft, ChevronRight } from 'lucide-react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import type { PageRange } from './listQuery';
|
||||
@@ -24,7 +25,7 @@ export function Pagination({ range, total, count, pluralName, disabled, onPrev,
|
||||
return (
|
||||
<nav
|
||||
aria-label={t('list.pagination', 'Pagination')}
|
||||
className="flex items-center justify-between text-sm text-muted-foreground"
|
||||
className="flex flex-wrap items-center justify-between gap-2 border-t border-border py-2.5 pl-5 pr-2.5 text-[13px] text-muted-foreground"
|
||||
>
|
||||
<p aria-live="polite">
|
||||
{total !== null
|
||||
@@ -36,12 +37,14 @@ export function Pagination({ range, total, count, pluralName, disabled, onPrev,
|
||||
})
|
||||
: t('list.showingItems', 'Showing {{count}} items', { count })}
|
||||
</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="outline" size="sm" disabled={!range.hasPrev || disabled} onClick={onPrev}>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Button variant="secondary" size="sm" disabled={!range.hasPrev || disabled} onClick={onPrev}>
|
||||
<ChevronLeft aria-hidden />
|
||||
{t('list.previous', 'Previous')}
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" disabled={!range.hasNext || disabled} onClick={onNext}>
|
||||
<Button variant="secondary" size="sm" disabled={!range.hasNext || disabled} onClick={onNext}>
|
||||
{t('list.next', 'Next')}
|
||||
<ChevronRight aria-hidden />
|
||||
</Button>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
@@ -37,8 +37,7 @@ export function RowActions({ actions, label, hrefFor, onMutation, onLocked, disa
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0"
|
||||
size="icon-sm"
|
||||
disabled={disabled}
|
||||
aria-label={t('list.actionsFor', 'Actions for {{label}}', { label })}
|
||||
>
|
||||
@@ -52,7 +51,11 @@ export function RowActions({ actions, label, hrefFor, onMutation, onLocked, disa
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={entry.key}
|
||||
className={entry.action.type === 'delete' ? 'text-destructive' : undefined}
|
||||
className={
|
||||
entry.action.type === 'delete'
|
||||
? 'text-destructive focus:bg-destructive-soft focus:text-destructive'
|
||||
: undefined
|
||||
}
|
||||
onSelect={() => onMutation(entry)}
|
||||
>
|
||||
{entry.action.label}
|
||||
@@ -63,7 +66,7 @@ export function RowActions({ actions, label, hrefFor, onMutation, onLocked, disa
|
||||
return (
|
||||
<DropdownMenuItem key={entry.key} onSelect={onLocked}>
|
||||
{entry.label}
|
||||
<Lock className="ml-auto h-3 w-3 text-muted-foreground" aria-hidden />
|
||||
<Lock className="ml-auto h-3 w-3 text-dim" aria-hidden />
|
||||
<span className="sr-only">
|
||||
{t('enterprise.featureDisabled', 'This feature requires an Enterprise license.')}
|
||||
</span>
|
||||
|
||||
@@ -24,11 +24,15 @@ export function SelectionBanner({
|
||||
onClear,
|
||||
}: SelectionBannerProps) {
|
||||
const { t } = useTranslation();
|
||||
const linkClass = 'text-primary underline hover:text-primary/80';
|
||||
const linkClass =
|
||||
'font-semibold text-brand-text underline-offset-4 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring rounded-sm';
|
||||
|
||||
if (allMatching) {
|
||||
return (
|
||||
<div role="status" className="rounded-md border border-primary/50 bg-primary/10 px-4 py-2 text-center text-sm">
|
||||
<div
|
||||
role="status"
|
||||
className="border-t border-border first:border-t-0 bg-highlight/70 px-5 py-2.5 text-center text-[13px]"
|
||||
>
|
||||
{t('list.allMatchingSelected', 'All {{total}} {{name}} matching the current filters are selected.', {
|
||||
total: total ?? 0,
|
||||
name: pluralName,
|
||||
@@ -43,7 +47,10 @@ export function SelectionBanner({
|
||||
if (total === null || total <= pageCount) return null;
|
||||
|
||||
return (
|
||||
<div role="status" className="rounded-md border bg-muted/50 px-4 py-2 text-center text-sm">
|
||||
<div
|
||||
role="status"
|
||||
className="border-t border-border first:border-t-0 bg-muted/60 px-5 py-2.5 text-center text-[13px]"
|
||||
>
|
||||
{t('list.allPageSelected', 'All {{count}} items on this page are selected.', { count: pageCount })}{' '}
|
||||
<button type="button" className={linkClass} onClick={onSelectAllMatching}>
|
||||
{t('list.selectAllMatchingNamed', 'Select all {{total}} {{name}} matching the current filters', {
|
||||
|
||||
@@ -27,7 +27,7 @@ function AlertDialogOverlay({ className, ...props }: React.ComponentProps<typeof
|
||||
<AlertDialogPrimitive.Overlay
|
||||
data-slot="alert-dialog-overlay"
|
||||
className={cn(
|
||||
'fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
|
||||
'fixed inset-0 z-50 bg-overlay data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
@@ -42,7 +42,7 @@ function AlertDialogContent({ className, ...props }: React.ComponentProps<typeof
|
||||
<AlertDialogPrimitive.Content
|
||||
data-slot="alert-dialog-content"
|
||||
className={cn(
|
||||
'fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 sm:rounded-lg',
|
||||
'fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 rounded-3xl bg-card p-6 shadow-pop duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
@@ -76,7 +76,7 @@ function AlertDialogTitle({ className, ...props }: React.ComponentProps<typeof A
|
||||
return (
|
||||
<AlertDialogPrimitive.Title
|
||||
data-slot="alert-dialog-title"
|
||||
className={cn('text-lg font-semibold', className)}
|
||||
className={cn('font-display text-lg font-bold tracking-[-0.015em]', className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -11,22 +11,28 @@ import { cva, type VariantProps } from 'class-variance-authority';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const buttonVariants = cva(
|
||||
'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0',
|
||||
'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-full text-sm font-semibold transition-[color,background-color,box-shadow] duration-200 ease-bento focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'bg-primary text-primary-foreground shadow hover:bg-primary/90',
|
||||
destructive: 'bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90',
|
||||
outline: 'border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground',
|
||||
secondary: 'bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80',
|
||||
ghost: 'hover:bg-accent hover:text-accent-foreground',
|
||||
link: 'text-primary underline-offset-4 hover:underline',
|
||||
default: 'bg-primary text-primary-foreground shadow-primary hover:bg-primary-hover',
|
||||
destructive: 'bg-destructive text-destructive-foreground hover:bg-destructive-hover',
|
||||
outline: 'bg-card text-foreground shadow-tile hover:shadow-lift',
|
||||
secondary: 'bg-secondary text-secondary-foreground hover:bg-highlight hover:text-highlight-foreground',
|
||||
ghost: 'text-muted-foreground hover:bg-accent hover:text-accent-foreground',
|
||||
link: 'text-brand-text underline-offset-4 hover:underline',
|
||||
ink: 'text-ink-muted hover:bg-ink-2 hover:text-ink-foreground',
|
||||
'ink-danger': 'text-ink-danger hover:bg-ink-danger/12',
|
||||
'ghost-danger': 'text-muted-foreground hover:bg-destructive-soft hover:text-destructive',
|
||||
field: 'field-surface rounded-lg font-normal text-foreground focus-visible:ring-0 focus-visible:ring-offset-0',
|
||||
},
|
||||
size: {
|
||||
default: 'h-9 px-4 py-2',
|
||||
sm: 'h-8 rounded-md px-3 text-xs',
|
||||
lg: 'h-10 rounded-md px-8',
|
||||
sm: 'h-8 px-3.5 text-[13px]',
|
||||
lg: 'h-11 px-7',
|
||||
icon: 'h-9 w-9',
|
||||
'icon-sm': 'h-8 w-8',
|
||||
'icon-lg': 'h-10 w-10',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
|
||||
@@ -62,10 +62,7 @@ function Calendar({
|
||||
'flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium',
|
||||
defaultClassNames.dropdowns,
|
||||
),
|
||||
dropdown_root: cn(
|
||||
'relative rounded-md border border-input shadow-xs has-focus:border-ring has-focus:ring-[3px] has-focus:ring-ring/50',
|
||||
defaultClassNames.dropdown_root,
|
||||
),
|
||||
dropdown_root: cn('field-surface relative rounded-lg', defaultClassNames.dropdown_root),
|
||||
dropdown: cn('absolute inset-0 bg-popover opacity-0', defaultClassNames.dropdown),
|
||||
caption_label: cn(
|
||||
'font-medium select-none',
|
||||
|
||||
@@ -12,19 +12,23 @@ function Card({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card"
|
||||
className={cn('rounded-xl border bg-card text-card-foreground shadow', className)}
|
||||
className={cn('rounded-2xl bg-card text-card-foreground shadow-tile', className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CardHeader({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
return <div data-slot="card-header" className={cn('flex flex-col space-y-1.5 p-6', className)} {...props} />;
|
||||
return <div data-slot="card-header" className={cn('flex flex-col space-y-1.5 p-5', className)} {...props} />;
|
||||
}
|
||||
|
||||
function CardTitle({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
return (
|
||||
<div data-slot="card-title" className={cn('font-semibold leading-none tracking-tight', className)} {...props} />
|
||||
<div
|
||||
data-slot="card-title"
|
||||
className={cn('font-display font-bold leading-tight tracking-[-0.012em]', className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -33,11 +37,11 @@ function CardDescription({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
}
|
||||
|
||||
function CardContent({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
return <div data-slot="card-content" className={cn('p-6 pt-0', className)} {...props} />;
|
||||
return <div data-slot="card-content" className={cn('p-5 pt-0', className)} {...props} />;
|
||||
}
|
||||
|
||||
function CardFooter({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
return <div data-slot="card-footer" className={cn('flex items-center p-6 pt-0', className)} {...props} />;
|
||||
return <div data-slot="card-footer" className={cn('flex items-center p-5 pt-0', className)} {...props} />;
|
||||
}
|
||||
|
||||
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent };
|
||||
@@ -10,11 +10,11 @@ import type { TooltipPayload } from 'recharts/types/state/tooltipSlice';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export const CHART_COLORS = [
|
||||
'hsl(var(--chart-1))',
|
||||
'hsl(var(--chart-2))',
|
||||
'hsl(var(--chart-3))',
|
||||
'hsl(var(--chart-4))',
|
||||
'hsl(var(--chart-5))',
|
||||
'var(--chart-1)',
|
||||
'var(--chart-2)',
|
||||
'var(--chart-3)',
|
||||
'var(--chart-4)',
|
||||
'var(--chart-5)',
|
||||
] as const;
|
||||
|
||||
export function getChartColor(index: number): string {
|
||||
@@ -39,7 +39,7 @@ export function ChartTooltipContent({
|
||||
if (!active || !payload?.length) return null;
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border bg-background p-2 shadow-md">
|
||||
<div className="popover-surface p-2.5">
|
||||
{label && <p className="mb-1 text-xs text-muted-foreground">{label}</p>}
|
||||
{payload.map((entry, i) => (
|
||||
<div key={i} className="flex items-center gap-2 text-sm">
|
||||
|
||||
@@ -15,13 +15,13 @@ function Checkbox({ className, ...props }: React.ComponentProps<typeof CheckboxP
|
||||
<CheckboxPrimitive.Root
|
||||
data-slot="checkbox"
|
||||
className={cn(
|
||||
'peer h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground',
|
||||
'peer h-[18px] w-[18px] shrink-0 rounded-[6px] border-0 bg-field shadow-[inset_0_0_0_1.5px_var(--input)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background data-[state=checked]:shadow-none data-[state=indeterminate]:bg-primary data-[state=indeterminate]:text-primary-foreground data-[state=indeterminate]:shadow-none disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<CheckboxPrimitive.Indicator className="flex items-center justify-center text-current">
|
||||
<Check className="h-4 w-4" />
|
||||
<Check className="h-3 w-3" strokeWidth={3} />
|
||||
</CheckboxPrimitive.Indicator>
|
||||
</CheckboxPrimitive.Root>
|
||||
);
|
||||
|
||||
@@ -82,11 +82,11 @@ export function Combobox({
|
||||
{...ariaProps}
|
||||
ref={triggerRef}
|
||||
type="button"
|
||||
variant="outline"
|
||||
variant="field"
|
||||
role="combobox"
|
||||
aria-expanded={open}
|
||||
disabled={disabled}
|
||||
className={cn('w-full justify-between font-normal', !selected && 'text-muted-foreground', className)}
|
||||
className={cn('w-full justify-between px-3', !selected && 'text-dim', className)}
|
||||
>
|
||||
<span className="flex items-center gap-2 truncate">
|
||||
{selected?.marker}
|
||||
|
||||
@@ -17,7 +17,7 @@ function Command({ className, ...props }: React.ComponentProps<typeof CommandPri
|
||||
<CommandPrimitive
|
||||
data-slot="command"
|
||||
className={cn(
|
||||
'flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground',
|
||||
'flex h-full w-full flex-col overflow-hidden rounded-2xl bg-popover text-popover-foreground',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
@@ -100,7 +100,7 @@ function CommandItem({ className, ...props }: React.ComponentProps<typeof Comman
|
||||
<CommandPrimitive.Item
|
||||
data-slot="command-item"
|
||||
className={cn(
|
||||
'relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50',
|
||||
'relative flex cursor-default select-none items-center rounded-lg px-2.5 py-1.5 text-sm outline-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -37,7 +37,7 @@ function DialogOverlay({ className, ...props }: React.ComponentProps<typeof Dial
|
||||
<DialogPrimitive.Overlay
|
||||
data-slot="dialog-overlay"
|
||||
className={cn(
|
||||
'fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
|
||||
'fixed inset-0 z-50 bg-overlay data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
@@ -56,14 +56,14 @@ function DialogContent({
|
||||
<DialogPrimitive.Content
|
||||
data-slot="dialog-content"
|
||||
className={cn(
|
||||
'fixed left-[50%] top-[50%] z-50 grid max-h-[calc(100dvh-2rem)] w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 overflow-y-auto border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 sm:rounded-lg',
|
||||
'fixed left-[50%] top-[50%] z-50 grid max-h-[calc(100dvh-2rem)] w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 overflow-y-auto rounded-3xl bg-card p-6 shadow-pop duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
|
||||
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-full p-1.5 opacity-70 hover:bg-muted ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
|
||||
<X className="h-4 w-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
@@ -97,7 +97,7 @@ function DialogTitle({ className, ...props }: React.ComponentProps<typeof Dialog
|
||||
return (
|
||||
<DialogPrimitive.Title
|
||||
data-slot="dialog-title"
|
||||
className={cn('text-lg font-semibold leading-none tracking-tight', className)}
|
||||
className={cn('font-display text-lg font-bold leading-tight tracking-[-0.015em]', className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -44,7 +44,7 @@ function DropdownMenuSubTrigger({
|
||||
<DropdownMenuPrimitive.SubTrigger
|
||||
data-slot="dropdown-menu-sub-trigger"
|
||||
className={cn(
|
||||
'flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0',
|
||||
'flex cursor-default gap-2 select-none items-center rounded-lg px-2.5 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0',
|
||||
inset && 'pl-8',
|
||||
className,
|
||||
)}
|
||||
@@ -64,7 +64,7 @@ function DropdownMenuSubContent({
|
||||
<DropdownMenuPrimitive.SubContent
|
||||
data-slot="dropdown-menu-sub-content"
|
||||
className={cn(
|
||||
'z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
|
||||
'z-50 min-w-[8rem] overflow-hidden popover-surface p-1.5 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
@@ -83,7 +83,7 @@ function DropdownMenuContent({
|
||||
data-slot="dropdown-menu-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
'z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md',
|
||||
'z-50 min-w-[8rem] overflow-hidden popover-surface p-1.5',
|
||||
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
|
||||
className,
|
||||
)}
|
||||
@@ -102,7 +102,7 @@ function DropdownMenuItem({
|
||||
<DropdownMenuPrimitive.Item
|
||||
data-slot="dropdown-menu-item"
|
||||
className={cn(
|
||||
'relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&>svg]:size-4 [&>svg]:shrink-0',
|
||||
'relative flex cursor-default select-none items-center gap-2 rounded-lg px-2.5 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&>svg]:size-4 [&>svg]:shrink-0',
|
||||
inset && 'pl-8',
|
||||
className,
|
||||
)}
|
||||
@@ -121,7 +121,7 @@ function DropdownMenuCheckboxItem({
|
||||
<DropdownMenuPrimitive.CheckboxItem
|
||||
data-slot="dropdown-menu-checkbox-item"
|
||||
className={cn(
|
||||
'relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
|
||||
'relative flex cursor-default select-none items-center rounded-lg py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
|
||||
className,
|
||||
)}
|
||||
checked={checked}
|
||||
@@ -146,7 +146,7 @@ function DropdownMenuRadioItem({
|
||||
<DropdownMenuPrimitive.RadioItem
|
||||
data-slot="dropdown-menu-radio-item"
|
||||
className={cn(
|
||||
'relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
|
||||
'relative flex cursor-default select-none items-center rounded-lg py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -8,13 +8,21 @@ import * as React from 'react';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
function Input({ className, type, ...props }: React.ComponentProps<'input'>) {
|
||||
function Input({
|
||||
className,
|
||||
type,
|
||||
variant = 'field',
|
||||
...props
|
||||
}: React.ComponentProps<'input'> & { variant?: 'field' | 'pill' }) {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
'flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
|
||||
'flex h-9 w-full px-3 py-1 text-base file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-dim focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
|
||||
variant === 'field'
|
||||
? 'field-surface rounded-lg'
|
||||
: 'rounded-full border-0 bg-muted focus-visible:ring-2 focus-visible:ring-ring',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -25,6 +25,7 @@ function PopoverContent({
|
||||
className,
|
||||
align = 'center',
|
||||
sideOffset = 4,
|
||||
collisionPadding = 8,
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
|
||||
return (
|
||||
@@ -33,8 +34,9 @@ function PopoverContent({
|
||||
data-slot="popover-content"
|
||||
align={align}
|
||||
sideOffset={sideOffset}
|
||||
collisionPadding={collisionPadding}
|
||||
className={cn(
|
||||
'z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
|
||||
'z-50 w-72 popover-surface p-4 outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -22,19 +22,27 @@ function SelectValue(props: React.ComponentProps<typeof SelectPrimitive.Value>)
|
||||
return <SelectPrimitive.Value data-slot="select-value" {...props} />;
|
||||
}
|
||||
|
||||
function SelectTrigger({ className, children, ...props }: React.ComponentProps<typeof SelectPrimitive.Trigger>) {
|
||||
function SelectTrigger({
|
||||
className,
|
||||
children,
|
||||
variant = 'field',
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & { variant?: 'field' | 'pill' }) {
|
||||
return (
|
||||
<SelectPrimitive.Trigger
|
||||
data-slot="select-trigger"
|
||||
className={cn(
|
||||
'flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1',
|
||||
'flex items-center justify-between whitespace-nowrap placeholder:text-dim focus:outline-none disabled:cursor-not-allowed disabled:opacity-50 [&>span]:min-w-0 [&>span]:truncate',
|
||||
variant === 'field'
|
||||
? 'field-surface h-9 w-full gap-2 rounded-lg px-3 py-2 text-sm'
|
||||
: 'h-8 w-auto gap-2 rounded-full bg-card px-3.5 text-[13px] font-semibold shadow-tile transition-shadow duration-200 hover:shadow-lift focus-visible:ring-2 focus-visible:ring-ring data-[state=open]:shadow-lift',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDown className="h-4 w-4 opacity-50" />
|
||||
<ChevronDown className="h-4 w-4 shrink-0 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
);
|
||||
@@ -78,9 +86,9 @@ function SelectContent({
|
||||
<SelectPrimitive.Content
|
||||
data-slot="select-content"
|
||||
className={cn(
|
||||
'relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
|
||||
'relative z-50 max-h-96 min-w-[8rem] overflow-hidden popover-surface data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
|
||||
position === 'popper' &&
|
||||
'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
|
||||
'max-w-[var(--radix-select-content-available-width)] data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
|
||||
className,
|
||||
)}
|
||||
position={position}
|
||||
@@ -117,7 +125,7 @@ function SelectItem({ className, children, ...props }: React.ComponentProps<type
|
||||
<SelectPrimitive.Item
|
||||
data-slot="select-item"
|
||||
className={cn(
|
||||
'relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
|
||||
'relative flex w-full cursor-default select-none items-center rounded-lg py-1.5 pl-2.5 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -14,12 +14,12 @@ function Switch({ className, ...props }: React.ComponentProps<typeof SwitchPrimi
|
||||
<SwitchPrimitives.Root
|
||||
data-slot="switch"
|
||||
className={cn(
|
||||
'peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input',
|
||||
'peer inline-flex h-6 w-10 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-muted-strong',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<SwitchPrimitives.Thumb className="pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0" />
|
||||
<SwitchPrimitives.Thumb className="pointer-events-none block h-5 w-5 rounded-full bg-card shadow-[0_1px_3px_rgb(0_0_0/0.25)] ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=checked]:bg-white data-[state=unchecked]:translate-x-0" />
|
||||
</SwitchPrimitives.Root>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ function TabsList({ className, ...props }: React.ComponentProps<typeof TabsPrimi
|
||||
<TabsPrimitive.List
|
||||
data-slot="tabs-list"
|
||||
className={cn(
|
||||
'inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground',
|
||||
'inline-flex h-10 items-center justify-center gap-0.5 rounded-full bg-muted p-1 text-muted-foreground',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
@@ -31,7 +31,7 @@ function TabsTrigger({ className, ...props }: React.ComponentProps<typeof TabsPr
|
||||
<TabsPrimitive.Trigger
|
||||
data-slot="tabs-trigger"
|
||||
className={cn(
|
||||
'inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow',
|
||||
'inline-flex h-8 items-center justify-center gap-1.5 whitespace-nowrap rounded-full px-3.5 py-1 text-[13px] font-semibold ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 hover:text-foreground data-[state=active]:bg-card data-[state=active]:text-foreground data-[state=active]:shadow-tile',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -8,12 +8,17 @@ import * as React from 'react';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
function Textarea({ className, ...props }: React.ComponentProps<'textarea'>) {
|
||||
function Textarea({
|
||||
className,
|
||||
variant = 'field',
|
||||
...props
|
||||
}: React.ComponentProps<'textarea'> & { variant?: 'field' | 'bare' }) {
|
||||
return (
|
||||
<textarea
|
||||
data-slot="textarea"
|
||||
className={cn(
|
||||
'flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
|
||||
'flex min-h-[60px] w-full px-3 py-2 text-base placeholder:text-dim focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
|
||||
variant === 'field' ? 'field-surface rounded-lg' : 'border-0 bg-transparent',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -24,15 +24,15 @@ function ToastViewport({ className, ...props }: React.ComponentProps<'ol'>) {
|
||||
}
|
||||
|
||||
const toastVariants = cva(
|
||||
'group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full',
|
||||
'group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-2xl p-4 pr-7 shadow-pop ring-1 transition-all data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'border bg-background text-foreground',
|
||||
destructive: 'destructive group border-destructive bg-destructive text-destructive-foreground',
|
||||
success: 'border-green-500 bg-background text-foreground',
|
||||
warning: 'border-yellow-500 bg-background text-foreground',
|
||||
info: 'border-blue-500 bg-background text-foreground',
|
||||
default: 'bg-popover text-popover-foreground ring-border',
|
||||
destructive: 'destructive group bg-destructive-soft text-foreground ring-destructive/40',
|
||||
success: 'bg-success-soft text-foreground ring-success/40',
|
||||
warning: 'bg-warning-soft text-foreground ring-warning/40',
|
||||
info: 'bg-info-soft text-foreground ring-info/40',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
@@ -71,7 +71,7 @@ function ToastClose({ className, ...props }: React.ComponentProps<'button'>) {
|
||||
data-slot="toast-close"
|
||||
aria-label="Close"
|
||||
className={cn(
|
||||
'absolute right-1 top-1 rounded-md p-1 text-foreground/60 transition-colors hover:text-foreground focus:outline-none focus:ring-1 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600',
|
||||
'absolute right-1.5 top-1.5 rounded-full p-1 text-foreground/60 transition-colors hover:bg-muted hover:text-foreground focus:outline-none focus:ring-1 focus:ring-ring',
|
||||
className,
|
||||
)}
|
||||
type="button"
|
||||
|
||||
@@ -32,7 +32,7 @@ function TooltipContent({
|
||||
data-slot="tooltip-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
'z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
|
||||
'z-50 overflow-hidden rounded-lg bg-ink px-3 py-1.5 text-xs text-ink-foreground shadow-ink animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -8,10 +8,12 @@ import { Fragment, type ReactNode } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ChevronRight } from 'lucide-react';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
|
||||
import { HelpTooltip } from '@/components/common/HelpTooltip';
|
||||
import { formatDateTime } from '@/lib/format';
|
||||
import { getEnumVariant } from '@/lib/schemaResolver';
|
||||
import { resolveWidget } from '@/extensions/widgets';
|
||||
import { getEnumVariant, mapEntryValueType } from '@/lib/schemaResolver';
|
||||
import {
|
||||
embeddedEntries,
|
||||
embeddedSummary,
|
||||
@@ -49,6 +51,8 @@ export function FieldValue({ schema, type, value, variant = 'full', className }:
|
||||
|
||||
function renderValue(schema: Schema, type: FieldType, value: unknown, variant: ValueVariant): ReactNode {
|
||||
if (isEmptyValue(value)) return <EmptyValue variant={variant} />;
|
||||
const { View } = resolveWidget(type);
|
||||
if (View) return <View schema={schema} type={type} value={value} variant={variant} />;
|
||||
switch (type.type) {
|
||||
case 'string':
|
||||
return <StringValue value={value} format={type.format} variant={variant} />;
|
||||
@@ -124,11 +128,11 @@ function SetValue({
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span className="flex flex-wrap gap-1">
|
||||
<span className="flex flex-wrap gap-1.5">
|
||||
{items.map((item) => {
|
||||
const color = itemType.type === 'enum' ? getEnumVariant(schema, itemType.enumName, item)?.color : undefined;
|
||||
return (
|
||||
<Badge key={item} variant="secondary" className="gap-1 text-xs">
|
||||
<Badge key={item} variant="secondary" className="h-6 gap-1.5 font-medium">
|
||||
{color && (
|
||||
<span className="inline-block h-2 w-2 shrink-0 rounded-full" style={{ backgroundColor: color }} />
|
||||
)}
|
||||
@@ -169,13 +173,13 @@ function MapValue({
|
||||
);
|
||||
}
|
||||
return (
|
||||
<dl className="space-y-2">
|
||||
<dl className="@container divide-y divide-border border-l-2 border-input pl-4">
|
||||
{entries.map(([key, val]) => (
|
||||
<ValueRow
|
||||
key={key}
|
||||
schema={schema}
|
||||
label={<ScalarLabel schema={schema} type={keyClass} value={key} />}
|
||||
type={valueClass as FieldType}
|
||||
type={mapEntryValueType(schema, keyClass, valueClass, key) as FieldType}
|
||||
value={val}
|
||||
/>
|
||||
))}
|
||||
@@ -205,7 +209,7 @@ function ObjectListValue({
|
||||
return <span>{t('value.itemCount', '{{count}} items', { count: entries.length })}</span>;
|
||||
}
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="space-y-1.5">
|
||||
{entries.map(([key, item]) => (
|
||||
<ObjectValue key={key} schema={schema} objectName={objectName} value={item} />
|
||||
))}
|
||||
@@ -306,7 +310,7 @@ export function ObjectValue({
|
||||
<CollapsibleTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="flex items-center gap-1.5 text-sm text-muted-foreground transition-colors hover:text-foreground [&[data-state=open]>svg]:rotate-90"
|
||||
className="-ml-1 flex items-center gap-1.5 rounded-md px-1 py-0.5 text-sm text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring [&[data-state=open]>svg]:rotate-90"
|
||||
>
|
||||
<ChevronRight className="h-3.5 w-3.5 shrink-0 transition-transform duration-200" aria-hidden="true" />
|
||||
{typeLabel || summary.summary ? (
|
||||
@@ -317,7 +321,7 @@ export function ObjectValue({
|
||||
</button>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<dl className="mt-2 ml-5 space-y-2 border-l-2 border-muted/40 pl-4">
|
||||
<dl className="@container mt-1.5 ml-1.5 divide-y divide-border border-l-2 border-input pl-4">
|
||||
{entries.map((entry) => (
|
||||
<ValueRow
|
||||
key={entry.key}
|
||||
@@ -361,8 +365,8 @@ export interface ValueRowProps {
|
||||
export function ValueRow({ schema, label, description, type, value }: ValueRowProps) {
|
||||
const block = isBlockValue(type, value);
|
||||
return (
|
||||
<div className={block ? 'space-y-1' : 'flex items-baseline gap-2'}>
|
||||
<dt className="flex min-w-[140px] shrink-0 items-center gap-1 text-sm text-muted-foreground">
|
||||
<div data-slot="value-row" className={cn('py-3', block ? 'grid gap-y-1.5' : 'field-grid')}>
|
||||
<dt className="flex min-w-0 items-center gap-1 text-[13px] font-medium text-muted-foreground">
|
||||
{label}
|
||||
{description && typeof label === 'string' && <HelpTooltip content={description} label={label} />}
|
||||
</dt>
|
||||
|
||||
@@ -19,8 +19,8 @@ export type ValueVariant = 'full' | 'compact';
|
||||
|
||||
export function EmptyValue({ variant = 'full' }: { variant?: ValueVariant }) {
|
||||
const { t } = useTranslation();
|
||||
if (variant === 'compact') return <span className="text-muted-foreground">-</span>;
|
||||
return <span className="text-sm italic text-muted-foreground">{t('field.notSet', 'Not set')}</span>;
|
||||
if (variant === 'compact') return <span className="text-dim">-</span>;
|
||||
return <span className="text-sm italic text-dim">{t('field.notSet', 'Not set')}</span>;
|
||||
}
|
||||
|
||||
export function StringValue({
|
||||
@@ -39,7 +39,10 @@ export function StringValue({
|
||||
if (format === 'color') {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-2 text-sm">
|
||||
<span className="inline-block h-3.5 w-3.5 shrink-0 rounded-sm border" style={{ backgroundColor: str }} />
|
||||
<span
|
||||
className="inline-block h-3.5 w-3.5 shrink-0 rounded-full shadow-[inset_0_0_0_1px_var(--input)]"
|
||||
style={{ backgroundColor: str }}
|
||||
/>
|
||||
<span className="font-mono">{str}</span>
|
||||
</span>
|
||||
);
|
||||
@@ -48,8 +51,8 @@ export function StringValue({
|
||||
return (
|
||||
<pre
|
||||
className={cn(
|
||||
'whitespace-pre-wrap break-words rounded bg-muted/50 font-mono text-xs',
|
||||
variant === 'compact' ? 'max-w-md px-1.5 py-1' : 'p-2',
|
||||
'whitespace-pre-wrap break-words bg-muted font-mono text-xs',
|
||||
variant === 'compact' ? 'max-w-md rounded-lg px-2 py-1' : 'rounded-xl p-3',
|
||||
format === 'text' && 'font-sans',
|
||||
)}
|
||||
>
|
||||
@@ -72,9 +75,9 @@ export function NumberValue({ value, format }: { value: unknown; format: string
|
||||
export function BooleanValue({ value }: { value: unknown }) {
|
||||
const { t } = useTranslation();
|
||||
return value === true ? (
|
||||
<Check className="h-4 w-4 text-green-600" role="img" aria-label={t('common.yes', 'Yes')} />
|
||||
<Check className="h-4 w-4 text-success" role="img" aria-label={t('common.yes', 'Yes')} />
|
||||
) : (
|
||||
<X className="h-4 w-4 text-red-500" role="img" aria-label={t('common.no', 'No')} />
|
||||
<X className="h-4 w-4 text-destructive" role="img" aria-label={t('common.no', 'No')} />
|
||||
);
|
||||
}
|
||||
|
||||
@@ -83,7 +86,11 @@ export function EnumValue({ schema, enumName, value }: { schema: Schema; enumNam
|
||||
const variant = getEnumVariant(schema, enumName, name);
|
||||
if (!variant) return <span className="text-sm">{name}</span>;
|
||||
return (
|
||||
<Badge variant="secondary" style={variant.color ? { backgroundColor: variant.color, color: '#fff' } : undefined}>
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className={cn('h-6', variant.color && 'text-primary-foreground')}
|
||||
style={variant.color ? { backgroundColor: variant.color } : undefined}
|
||||
>
|
||||
{variant.label}
|
||||
</Badge>
|
||||
);
|
||||
@@ -104,7 +111,7 @@ export function ObjectIdValue({
|
||||
const content = loading && !label ? <Loader2 className="h-3 w-3 animate-spin" /> : (label ?? id);
|
||||
if (variant === 'compact') return <span>{content}</span>;
|
||||
return (
|
||||
<Badge variant="secondary" className="text-sm">
|
||||
<Badge variant="secondary" className="h-6 font-medium">
|
||||
{content}
|
||||
</Badge>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useState } from 'react';
|
||||
import { formatUtcOffset } from '@/lib/format';
|
||||
import { getEnumVariant } from '@/lib/schemaResolver';
|
||||
import type { ValueProps } from '@/extensions/types';
|
||||
|
||||
export function TimeZoneValue({ schema, type, value, variant }: ValueProps) {
|
||||
const [now] = useState(() => new Date());
|
||||
const name = String(value);
|
||||
const label = (type.type === 'enum' ? getEnumVariant(schema, type.enumName, name)?.label : undefined) ?? name;
|
||||
const offset = variant === 'full' ? formatUtcOffset(name, now) : null;
|
||||
return (
|
||||
<span className="text-sm">
|
||||
{label}
|
||||
{offset && <span className="ms-1.5 text-muted-foreground tabular-nums">({offset})</span>}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useInPanel } from '@/components/forms/formContext';
|
||||
import { formatNumber, formatWeekday } from '@/lib/format';
|
||||
import { MINUTES_PER_DAY, MINUTES_PER_HOUR } from '@/lib/localDateTime';
|
||||
import { formatSlot, localeWeekdayOrder } from '@/lib/scheduleFormat';
|
||||
import {
|
||||
daySegments,
|
||||
parseSlot,
|
||||
slotEntries,
|
||||
weekdayIndex,
|
||||
type ScheduleRules,
|
||||
type Slot,
|
||||
type Weekday,
|
||||
} from '@/lib/weeklySchedule';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { ValueProps } from '@/extensions/types';
|
||||
|
||||
const AXIS_HOURS = [0, 6, 12, 18, 24] as const;
|
||||
|
||||
interface WeekChartProps {
|
||||
entries: readonly [string, Slot][];
|
||||
rules: ScheduleRules;
|
||||
order: readonly Weekday[];
|
||||
label: string;
|
||||
}
|
||||
|
||||
function percent(minutes: number): string {
|
||||
return `${(minutes / MINUTES_PER_DAY) * 100}%`;
|
||||
}
|
||||
|
||||
export function WeekChart({ entries, rules, order, label }: WeekChartProps) {
|
||||
const inPanel = useInPanel();
|
||||
const segments = daySegments(entries, rules);
|
||||
return (
|
||||
<div role="img" aria-label={label} data-slot="week-chart" className="space-y-1">
|
||||
{order.map((day) => (
|
||||
<div key={day} className="flex items-center gap-2">
|
||||
<span className="w-10 shrink-0 truncate text-[12px] text-muted-foreground" aria-hidden="true">
|
||||
{formatWeekday(day, 'short')}
|
||||
</span>
|
||||
<div className={cn('relative h-4 flex-1 overflow-hidden rounded-full', inPanel ? 'bg-muted' : 'bg-card')}>
|
||||
{AXIS_HOURS.slice(1, -1).map((hour) => (
|
||||
<span
|
||||
key={hour}
|
||||
className="absolute inset-y-0 w-px bg-border"
|
||||
style={{ insetInlineStart: percent(hour * MINUTES_PER_HOUR) }}
|
||||
/>
|
||||
))}
|
||||
{segments[weekdayIndex(day) ?? 0].map((segment) => (
|
||||
<span
|
||||
key={`${segment.key}-${segment.start}`}
|
||||
data-slot="week-chart-bar"
|
||||
className="absolute inset-y-0 rounded-full bg-primary"
|
||||
style={{ insetInlineStart: percent(segment.start), width: percent(segment.end - segment.start) }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
<div className="flex gap-2" aria-hidden="true">
|
||||
<span className="w-10 shrink-0" />
|
||||
<div className="relative h-4 flex-1 text-[11px] text-dim tabular-nums">
|
||||
{AXIS_HOURS.map((hour) => (
|
||||
<span
|
||||
key={hour}
|
||||
className={cn(
|
||||
'absolute',
|
||||
hour === 0 ? 'start-0' : hour === 24 ? 'end-0' : '-translate-x-1/2 rtl:translate-x-1/2',
|
||||
)}
|
||||
style={hour === 0 || hour === 24 ? undefined : { insetInlineStart: percent(hour * MINUTES_PER_HOUR) }}
|
||||
>
|
||||
{formatNumber(hour)}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const DISPLAY_RULES: ScheduleRules = 'overnight';
|
||||
|
||||
export function WeeklyScheduleValue({ value, variant }: ValueProps) {
|
||||
const { t } = useTranslation();
|
||||
const order = localeWeekdayOrder();
|
||||
const entries = slotEntries(value).map(([key, item]): [string, Slot] => [key, parseSlot(item)]);
|
||||
const lines = entries.map(([, slot]) => formatSlot(t, slot, order, DISPLAY_RULES));
|
||||
if (variant === 'compact') return <span className="text-sm">{lines.join('; ')}</span>;
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<WeekChart entries={entries} rules={DISPLAY_RULES} order={order} label={lines.join('; ')} />
|
||||
<ul className="space-y-0.5 text-sm">
|
||||
{lines.map((line, i) => (
|
||||
<li key={entries[i][0]}>{line}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -4,19 +4,30 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import type { ComponentType } from 'react';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { ValueRow } from '@/components/values/FieldValue';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { resolveForm, resolveSchema, resolveVariantForm } from '@/lib/schemaResolver';
|
||||
import { isEmptyValue, variantLabel } from '@/lib/embeddedSchema';
|
||||
import type { Field, Fields, Form, FormField, Schema } from '@/types/schema';
|
||||
|
||||
export interface ViewRenderProps {
|
||||
schema: Schema;
|
||||
field: Field;
|
||||
formField: FormField;
|
||||
data: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export type ViewRenderers = Readonly<Record<string, ComponentType<ViewRenderProps>>>;
|
||||
|
||||
export interface DynamicViewProps {
|
||||
schema: Schema;
|
||||
objectName: string;
|
||||
viewName: string;
|
||||
data: Record<string, unknown>;
|
||||
visibleFields?: Set<string>;
|
||||
renderers?: ViewRenderers;
|
||||
}
|
||||
|
||||
interface ViewSection {
|
||||
@@ -70,29 +81,24 @@ function buildViewSections(
|
||||
return items.length > 0 ? [{ key: 'section-0', items }] : [];
|
||||
}
|
||||
|
||||
export function DynamicView({ schema, objectName, viewName, data, visibleFields }: DynamicViewProps) {
|
||||
export function DynamicView({ schema, objectName, viewName, data, visibleFields, renderers }: DynamicViewProps) {
|
||||
const layout = resolveViewLayout(schema, objectName, viewName, data);
|
||||
if (!layout) return null;
|
||||
const sections = buildViewSections(layout, data, visibleFields);
|
||||
const typeLabel = variantLabel(schema, objectName, data['@type']);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{typeLabel && (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
{typeLabel}
|
||||
</Badge>
|
||||
)}
|
||||
<div className="space-y-3.5">
|
||||
{typeLabel && <Badge variant="default">{typeLabel}</Badge>}
|
||||
{sections.map((section) => (
|
||||
<Card key={section.key}>
|
||||
{section.title && (
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-base">{section.title}</CardTitle>
|
||||
</CardHeader>
|
||||
)}
|
||||
<CardContent className={section.title ? 'pt-0' : ''}>
|
||||
<dl className="space-y-2">
|
||||
{section.items.map(({ formField, field }) => (
|
||||
<section key={section.key} className="tile @container px-5 pb-1.5 sm:px-6">
|
||||
{section.title && <h2 className="section-title pb-1 pt-5">{section.title}</h2>}
|
||||
<dl className={cn('divide-y divide-border', !section.title && 'pt-1')}>
|
||||
{section.items.map(({ formField, field }) => {
|
||||
const Render = renderers && Object.hasOwn(renderers, formField.name) ? renderers[formField.name] : null;
|
||||
return Render ? (
|
||||
<Render key={formField.name} schema={schema} field={field} formField={formField} data={data} />
|
||||
) : (
|
||||
<ValueRow
|
||||
key={formField.name}
|
||||
schema={schema}
|
||||
@@ -101,10 +107,10 @@ export function DynamicView({ schema, objectName, viewName, data, visibleFields
|
||||
type={field.type}
|
||||
value={data[formField.name]}
|
||||
/>
|
||||
))}
|
||||
</dl>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</dl>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -13,19 +13,21 @@ import { resolveObject, resolveList, getDisplayProperty } from '@/lib/schemaReso
|
||||
import { coerceLabel } from '@/lib/objectOptions';
|
||||
import { errorMessage } from '@/lib/jmapErrors';
|
||||
import { useJmapObject } from '@/data/objects';
|
||||
import { DynamicView } from './DynamicView';
|
||||
import { DynamicView, type ViewRenderers } from './DynamicView';
|
||||
|
||||
interface DynamicViewPageProps {
|
||||
viewName: string;
|
||||
objectId: string;
|
||||
accountId?: string;
|
||||
renderers?: ViewRenderers;
|
||||
}
|
||||
|
||||
export function DynamicViewPage({ viewName, objectId }: DynamicViewPageProps) {
|
||||
export function DynamicViewPage({ viewName, objectId, accountId, renderers }: DynamicViewPageProps) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const schema = useSchemaStore((s) => s.schema);
|
||||
const resolvedObject = schema ? resolveObject(schema, viewName) : null;
|
||||
const query = useJmapObject(resolvedObject?.objectName, objectId);
|
||||
const query = useJmapObject(resolvedObject?.objectName, objectId, undefined, { accountId });
|
||||
const data = query.data ?? null;
|
||||
const loading = query.isPending && query.fetchStatus !== 'idle';
|
||||
const error = !schema
|
||||
@@ -41,19 +43,21 @@ export function DynamicViewPage({ viewName, objectId }: DynamicViewPageProps) {
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center p-12">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
<Loader2 className="h-6 w-6 animate-spin text-brand-text" aria-hidden="true" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error || !data || !schema) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="mx-auto max-w-5xl space-y-5 pt-3">
|
||||
<Button variant="outline" size="sm" onClick={() => navigate(-1)}>
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
<ArrowLeft aria-hidden="true" />
|
||||
{t('common.back', 'Back')}
|
||||
</Button>
|
||||
<div className="text-destructive p-4">{error ?? t('view.failedToLoad', 'Failed to load')}</div>
|
||||
<div className="rounded-xl bg-destructive-soft p-4 text-sm text-destructive" role="alert">
|
||||
{error ?? t('view.failedToLoad', 'Failed to load')}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -71,16 +75,27 @@ export function DynamicViewPage({ viewName, objectId }: DynamicViewPageProps) {
|
||||
: singularName.charAt(0).toUpperCase() + singularName.slice(1);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-3">
|
||||
<Button variant="outline" size="sm" onClick={() => navigate(-1)}>
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
{t('common.back', 'Back')}
|
||||
<div className="mx-auto max-w-5xl space-y-5">
|
||||
<div className="flex items-start gap-3.5 px-1 pb-1 pt-3">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon-lg"
|
||||
className="shrink-0"
|
||||
onClick={() => navigate(-1)}
|
||||
aria-label={t('common.back', 'Back')}
|
||||
>
|
||||
<ArrowLeft className="h-5 w-5" aria-hidden="true" />
|
||||
</Button>
|
||||
<h1 className="text-xl font-semibold">{title}</h1>
|
||||
<h1 className="page-title min-w-0 flex-1 break-words pt-1.5">{title}</h1>
|
||||
</div>
|
||||
|
||||
<DynamicView schema={schema} objectName={resolved.objectName} viewName={viewName} data={data} />
|
||||
<DynamicView
|
||||
schema={schema}
|
||||
objectName={resolved.objectName}
|
||||
viewName={viewName}
|
||||
data={data}
|
||||
renderers={renderers}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+2
-2
@@ -14,8 +14,8 @@ export const jmapKeys = {
|
||||
all: ['jmap'] as const,
|
||||
type: (objectName: string) => ['jmap', objectName] as const,
|
||||
objects: (objectName: string) => ['jmap', objectName, 'object'] as const,
|
||||
object: (objectName: string, id: string, properties?: readonly string[]) =>
|
||||
['jmap', objectName, 'object', id, properties ? [...properties].sort() : null] as const,
|
||||
object: (objectName: string, id: string, properties?: readonly string[], accountId?: string) =>
|
||||
['jmap', objectName, 'object', id, properties ? [...properties].sort() : null, accountId ?? null] as const,
|
||||
lists: (objectName: string) => ['jmap', objectName, 'list'] as const,
|
||||
list: (objectName: string, params: ListPageParams) => ['jmap', objectName, 'list', params] as const,
|
||||
allOptions: (objectName: string) => ['jmap', objectName, 'options'] as const,
|
||||
|
||||
+18
-7
@@ -21,11 +21,21 @@ import type { JmapSetResponse } from '@/types/jmap';
|
||||
|
||||
export interface SetVariables extends JmapSetOptions {
|
||||
blobs?: Record<string, BlobUpload>;
|
||||
accountId?: string;
|
||||
}
|
||||
|
||||
export type BulkTarget = { ids: string[] } | { query: JmapQueryOptions };
|
||||
|
||||
export type BulkVariables = BulkTarget & ({ action: 'destroy' } | { action: 'update'; patch: JmapObject });
|
||||
export type BulkVariables = (
|
||||
| (BulkTarget & ({ action: 'destroy' } | { action: 'update'; patch: JmapObject }))
|
||||
| { action: 'updateEach'; patches: Record<string, JmapObject> }
|
||||
) & { accountId?: string };
|
||||
|
||||
async function bulkIds(objectName: string, vars: BulkVariables, signal?: AbortSignal): Promise<string[]> {
|
||||
if (vars.action === 'updateEach') return Object.keys(vars.patches);
|
||||
if ('ids' in vars) return vars.ids;
|
||||
return jmapQueryAll(objectName, vars.query, { accountId: vars.accountId, signal });
|
||||
}
|
||||
|
||||
function isListOf(key: QueryKey, objectName: string): boolean {
|
||||
return key[1] === objectName && key[2] === 'list';
|
||||
@@ -45,9 +55,9 @@ export async function invalidateObjectType(client: QueryClient, objectName: stri
|
||||
export function useJmapSet(objectName: string | null | undefined) {
|
||||
const client = useQueryClient();
|
||||
return useMutation<JmapSetResponse, Error, SetVariables>({
|
||||
mutationFn: ({ blobs, ...set }) => {
|
||||
mutationFn: ({ blobs, accountId, ...set }) => {
|
||||
if (!objectName) throw new Error('No object type to update');
|
||||
return jmapSet(objectName, set, { blobs });
|
||||
return jmapSet(objectName, set, { blobs, accountId });
|
||||
},
|
||||
onSettled: () => {
|
||||
if (objectName) return invalidateObjectType(client, objectName);
|
||||
@@ -56,7 +66,8 @@ export function useJmapSet(objectName: string | null | undefined) {
|
||||
}
|
||||
|
||||
export async function runBulkSet(objectName: string, vars: BulkVariables, signal?: AbortSignal): Promise<SetOutcome> {
|
||||
const ids = 'ids' in vars ? vars.ids : await jmapQueryAll(objectName, vars.query, { signal });
|
||||
const ids = await bulkIds(objectName, vars, signal);
|
||||
const { accountId } = vars;
|
||||
const batchSize = Math.max(1, useAuthStore.getState().maxObjectsInSet);
|
||||
const outcome: SetOutcome = { succeeded: [], failed: {} };
|
||||
for (let offset = 0; offset < ids.length; offset += batchSize) {
|
||||
@@ -65,11 +76,11 @@ export async function runBulkSet(objectName: string, vars: BulkVariables, signal
|
||||
let partial: SetOutcome;
|
||||
try {
|
||||
if (vars.action === 'destroy') {
|
||||
partial = destroyedOutcome(await jmapSet(objectName, { destroy: batch }, { signal }));
|
||||
partial = destroyedOutcome(await jmapSet(objectName, { destroy: batch }, { accountId, signal }));
|
||||
} else {
|
||||
const update: Record<string, JmapObject> = {};
|
||||
for (const id of batch) update[id] = vars.patch;
|
||||
partial = updatedOutcome(await jmapSet(objectName, { update }, { signal }));
|
||||
for (const id of batch) update[id] = vars.action === 'updateEach' ? vars.patches[id] : vars.patch;
|
||||
partial = updatedOutcome(await jmapSet(objectName, { update }, { accountId, signal }));
|
||||
}
|
||||
} catch (err) {
|
||||
const aborted = isAbortError(err);
|
||||
|
||||
+5
-4
@@ -17,14 +17,15 @@ export interface ListPage {
|
||||
|
||||
interface QueryTuning {
|
||||
enabled?: boolean;
|
||||
accountId?: string;
|
||||
staleTime?: number;
|
||||
refetchOnMount?: boolean | 'always';
|
||||
}
|
||||
|
||||
export function jmapObjectQuery(objectName: string, id: string, properties?: string[]) {
|
||||
export function jmapObjectQuery(objectName: string, id: string, properties?: string[], accountId?: string) {
|
||||
return queryOptions({
|
||||
queryKey: jmapKeys.object(objectName, id, properties),
|
||||
queryFn: ({ signal }) => jmapGetOne(objectName, id, properties, { signal }),
|
||||
queryKey: jmapKeys.object(objectName, id, properties, accountId),
|
||||
queryFn: ({ signal }) => jmapGetOne(objectName, id, properties, { signal, accountId }),
|
||||
staleTime: 0,
|
||||
});
|
||||
}
|
||||
@@ -36,7 +37,7 @@ export function useJmapObject(
|
||||
tuning: QueryTuning = {},
|
||||
) {
|
||||
return useQuery({
|
||||
...jmapObjectQuery(objectName ?? '', id ?? '', properties),
|
||||
...jmapObjectQuery(objectName ?? '', id ?? '', properties, tuning.accountId),
|
||||
enabled: !!objectName && !!id && (tuning.enabled ?? true),
|
||||
staleTime: tuning.staleTime ?? 0,
|
||||
refetchOnMount: tuning.refetchOnMount ?? true,
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
*/
|
||||
|
||||
import { QueryClient, type QueryKey } from '@tanstack/react-query';
|
||||
import { resolveAccountId, type AccountSelection } from '@/services/jmap/client';
|
||||
import { isRetryableError } from '@/services/errors';
|
||||
import { useAuthStore } from '@/stores/authStore';
|
||||
import { jmapKeys } from '@/data/keys';
|
||||
@@ -16,8 +17,10 @@ export function shouldRetry(failureCount: number, error: unknown): boolean {
|
||||
return failureCount < MAX_QUERY_RETRIES && isRetryableError(error);
|
||||
}
|
||||
|
||||
function isManagementKey(key: QueryKey): boolean {
|
||||
return typeof key[1] === 'string' && key[1].startsWith('x:');
|
||||
function accountChanged(key: QueryKey, prev: AccountSelection, next: AccountSelection): boolean {
|
||||
const objectType = key[1];
|
||||
if (typeof objectType !== 'string') return true;
|
||||
return resolveAccountId(objectType, prev) !== resolveAccountId(objectType, next);
|
||||
}
|
||||
|
||||
export function createQueryClient(): QueryClient {
|
||||
@@ -45,7 +48,10 @@ export function bindQueryClientToAuth(client: QueryClient): () => void {
|
||||
return;
|
||||
}
|
||||
if (prev.activeAccountId !== null && state.activeAccountId !== prev.activeAccountId) {
|
||||
void client.resetQueries({ queryKey: jmapKeys.all, predicate: (query) => !isManagementKey(query.queryKey) });
|
||||
void client.resetQueries({
|
||||
queryKey: jmapKeys.all,
|
||||
predicate: (query) => accountChanged(query.queryKey, prev, state),
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
Loaded 100 of 181 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user