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 |
No files matched your search
@@ -2,6 +2,33 @@
|
||||
|
||||
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
|
||||
|
||||
+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.
|
||||
|
||||
|
||||
+2
-1
@@ -1,8 +1,9 @@
|
||||
<!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="" />
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "stalwart-webui",
|
||||
"version": "2.1.0",
|
||||
"version": "2.1.3",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "stalwart-webui",
|
||||
"version": "2.1.0",
|
||||
"version": "2.1.3",
|
||||
"dependencies": {
|
||||
"@daypicker/react": "^10.0.2",
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "stalwart-webui",
|
||||
"private": true,
|
||||
"version": "2.1.0",
|
||||
"version": "2.1.3",
|
||||
"stalwart": {
|
||||
"minServerVersion": "1.0.0"
|
||||
},
|
||||
|
||||
@@ -21,6 +21,7 @@ import { UnsavedChangesDialog } from '@/components/forms/UnsavedChangesDialog';
|
||||
import { formFieldLabels } from '@/components/forms/formLogic';
|
||||
import { useDynamicForm, type DynamicFormModel, type DynamicFormOptions } from '@/components/forms/useDynamicForm';
|
||||
import type { FieldValues, RenderableSection } from '@/components/forms/formLogic';
|
||||
import { withDestroyContentsNotice } from '@/lib/destroyContents';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const SECTION_INDEX_MIN = 3;
|
||||
@@ -144,15 +145,17 @@ export function DynamicForm({
|
||||
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, { accountId, fieldOverrides, createValues });
|
||||
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);
|
||||
@@ -163,6 +166,7 @@ export function DynamicForm({
|
||||
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 = (
|
||||
@@ -220,7 +224,15 @@ export function DynamicForm({
|
||||
|
||||
<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">
|
||||
<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}
|
||||
@@ -264,8 +276,13 @@ export function DynamicForm({
|
||||
<FloatingActionDivider />
|
||||
</>
|
||||
)}
|
||||
{isDirty && (
|
||||
<span className="flex items-center gap-2 px-2 text-[13px] text-ink-muted max-sm:hidden">
|
||||
{!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>
|
||||
@@ -279,7 +296,7 @@ export function DynamicForm({
|
||||
size="sm"
|
||||
className="shadow-none"
|
||||
onClick={() => void model.save()}
|
||||
disabled={saving || (!isCreate && !isDirty)}
|
||||
disabled={saving || (!isCreate && !hasChanges)}
|
||||
>
|
||||
{saving ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />
|
||||
@@ -298,10 +315,11 @@ export function DynamicForm({
|
||||
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}
|
||||
|
||||
@@ -495,6 +495,18 @@ export function buildSections(
|
||||
return sections;
|
||||
}
|
||||
|
||||
export function withoutSectionTitles(
|
||||
sections: RenderableSection[],
|
||||
fieldNames: readonly string[] | undefined,
|
||||
): RenderableSection[] {
|
||||
if (!fieldNames || fieldNames.length === 0) return sections;
|
||||
return sections.map((section) =>
|
||||
section.title && section.fields.some(({ formField }) => fieldNames.includes(formField.name))
|
||||
? { ...section, title: undefined }
|
||||
: section,
|
||||
);
|
||||
}
|
||||
|
||||
export function collectFetchProperties(schema: Schema, view: ResolvedView, viewName: string): string[] {
|
||||
const { object, resolvedSchema } = view;
|
||||
const names = new Set<string>(['id']);
|
||||
|
||||
@@ -43,6 +43,7 @@ import {
|
||||
validateRequired,
|
||||
validatedFieldNames,
|
||||
VARIANT_FIELD,
|
||||
withoutSectionTitles,
|
||||
type FieldErrors,
|
||||
type FieldValues,
|
||||
} from '@/components/forms/formLogic';
|
||||
@@ -102,6 +103,7 @@ export interface FieldRenderProps {
|
||||
|
||||
export interface FieldOverrides {
|
||||
hidden?: readonly string[];
|
||||
untitled?: readonly string[];
|
||||
render?: Readonly<Record<string, ComponentType<FieldRenderProps>>>;
|
||||
validate?: (data: FieldValues) => FieldErrors;
|
||||
}
|
||||
@@ -110,12 +112,13 @@ export interface DynamicFormOptions {
|
||||
accountId?: string;
|
||||
fieldOverrides?: FieldOverrides;
|
||||
createValues?: FieldValues;
|
||||
showCreatedValues?: boolean;
|
||||
}
|
||||
|
||||
export function useDynamicForm(
|
||||
viewName: string,
|
||||
objectId: string | null,
|
||||
{ accountId, fieldOverrides, createValues }: DynamicFormOptions = {},
|
||||
{ accountId, fieldOverrides, createValues, showCreatedValues = true }: DynamicFormOptions = {},
|
||||
) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
@@ -182,7 +185,7 @@ export function useDynamicForm(
|
||||
}
|
||||
const form = sch?.type === 'multiple' ? combineForms(parentForm, variantForm) : variantForm;
|
||||
const hidden = new Set(fieldOverrides?.hidden);
|
||||
const sections = buildSections(form, fields, mode, hidden);
|
||||
const sections = withoutSectionTitles(buildSections(form, fields, mode, hidden), fieldOverrides?.untitled);
|
||||
|
||||
const loading = mode === 'edit' && objectQuery.fetchStatus !== 'idle' && !objectQuery.isFetchedAfterMount;
|
||||
const loadError =
|
||||
@@ -304,7 +307,7 @@ export function useDynamicForm(
|
||||
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' });
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -13,7 +13,7 @@ import { HelpTooltip } from '@/components/common/HelpTooltip';
|
||||
import { ChartTooltipContent, getChartColor } from '@/components/ui/chart';
|
||||
import type { Chart as ChartSchema, Placement } from '../types/schema';
|
||||
import type { Metric, Period } from '../types/metrics';
|
||||
import { bucketTimestamps, bucketValues, getBucketCount, formatTimeTick, formatValue } from '../helpers';
|
||||
import { bucketTimestamps, chartBucketValues, getBucketCount, formatTimeTick, formatValue } from '../helpers';
|
||||
import { ChartSizedContainer } from './ChartSizedContainer';
|
||||
import { toneClasses } from './tone';
|
||||
import { cn } from '@/lib/utils';
|
||||
@@ -33,10 +33,12 @@ export function DashboardChart({ chart, historySamples, historyWindow, period, c
|
||||
const valueFormat = chart.valueFormat ?? 'number';
|
||||
|
||||
const data = useMemo(() => {
|
||||
const seriesValues = chart.series.map((series) => bucketValues(series, historySamples, from, to, bucketCount));
|
||||
const seriesValues = chart.series.map((series) =>
|
||||
chartBucketValues(series, historySamples, from, to, bucketCount, chart.stacked ?? false),
|
||||
);
|
||||
const timestamps = bucketTimestamps(from, to, bucketCount);
|
||||
|
||||
const points = timestamps.map((ts, i) => {
|
||||
return timestamps.map((ts, i) => {
|
||||
const point: Record<string, unknown> = {
|
||||
time: ts.getTime(),
|
||||
timeLabel: formatTimeTick(ts, period),
|
||||
@@ -46,22 +48,6 @@ export function DashboardChart({ chart, historySamples, historyWindow, period, c
|
||||
});
|
||||
return point;
|
||||
});
|
||||
|
||||
if (chart.stacked) {
|
||||
const lastSeen: Record<string, number> = {};
|
||||
for (const point of points) {
|
||||
for (const series of chart.series) {
|
||||
const v = point[series.label];
|
||||
if (typeof v === 'number') {
|
||||
lastSeen[series.label] = v;
|
||||
} else {
|
||||
point[series.label] = lastSeen[series.label] ?? 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return points;
|
||||
}, [historySamples, from, to, bucketCount, chart.series, chart.stacked, period]);
|
||||
|
||||
const tickFormatter = (value: number) => formatValue(value, valueFormat);
|
||||
|
||||
@@ -249,6 +249,29 @@ export function bucketValues(
|
||||
});
|
||||
}
|
||||
|
||||
export function chartBucketValues(
|
||||
target: MetricTarget,
|
||||
samples: Metric[],
|
||||
from: Date,
|
||||
to: Date,
|
||||
bucketCount: number,
|
||||
stacked: boolean,
|
||||
): (number | null)[] {
|
||||
const values = bucketValues(target, samples, from, to, bucketCount);
|
||||
const index = indexSamples(samples);
|
||||
const kind = target.metrics.map((id) => index.get(id)?.[0]).find((m) => m !== undefined)?.['@type'];
|
||||
if (kind === 'Gauge') {
|
||||
if (!stacked) return values;
|
||||
let lastSeen = 0;
|
||||
return values.map((v) => {
|
||||
if (v !== null) lastSeen = v;
|
||||
return lastSeen;
|
||||
});
|
||||
}
|
||||
if (kind === 'Histogram' && !stacked) return values;
|
||||
return values.map((v) => v ?? 0);
|
||||
}
|
||||
|
||||
export function cardValue(card: Card, samples: Metric[]): number {
|
||||
return reduceSamples(card, selectSamples(card, samples)) ?? 0;
|
||||
}
|
||||
|
||||
@@ -6,11 +6,78 @@
|
||||
|
||||
import { isRecord, isMultilineFormat } from '@/lib/embeddedSchema';
|
||||
import type { Field } from '@/types/schema';
|
||||
import { FLAG_ACTIONS, setValues, type FlagAction, type KeywordSet } from './model';
|
||||
|
||||
export type ListItems = Record<string, Record<string, unknown>>;
|
||||
|
||||
export const MAILBOX_FIELD = 'mailboxId';
|
||||
export const MAILBOX_SCHEMA = 'x:MailRuleMailbox';
|
||||
export const KEYWORDS_FIELD = 'keywords';
|
||||
export const KEYWORD_TEST_SCHEMA = 'x:MailRuleKeywordTest';
|
||||
|
||||
const TIME_ZONE_ENUM = 'TimeZone';
|
||||
|
||||
export function toSet(keys: readonly string[]): Record<string, true> {
|
||||
return Object.fromEntries(keys.map((key) => [key, true]));
|
||||
}
|
||||
|
||||
const IMAP_FLAG_PREFIX = '\\';
|
||||
const JMAP_KEYWORD_PREFIX = '$';
|
||||
|
||||
const SYSTEM_KEYWORD_NAMES: ReadonlySet<string> = new Set([
|
||||
'seen',
|
||||
'draft',
|
||||
'flagged',
|
||||
'answered',
|
||||
'recent',
|
||||
'important',
|
||||
'phishing',
|
||||
'junk',
|
||||
'notjunk',
|
||||
'deleted',
|
||||
'forwarded',
|
||||
'mdnsent',
|
||||
'autosent',
|
||||
'canunsubscribe',
|
||||
'followed',
|
||||
'hasattachment',
|
||||
'hasmemo',
|
||||
'hasnoattachment',
|
||||
'imported',
|
||||
'istrusted',
|
||||
'mailflagbit0',
|
||||
'mailflagbit1',
|
||||
'mailflagbit2',
|
||||
'maskedemail',
|
||||
'memo',
|
||||
'muted',
|
||||
'new',
|
||||
'notify',
|
||||
'unsubscribed',
|
||||
]);
|
||||
|
||||
export function canonicalKeyword(typed: string): string {
|
||||
const keyword = typed.toLowerCase();
|
||||
if (!keyword.startsWith(IMAP_FLAG_PREFIX)) return keyword;
|
||||
const name = keyword.slice(IMAP_FLAG_PREFIX.length);
|
||||
return SYSTEM_KEYWORD_NAMES.has(name) ? `${JMAP_KEYWORD_PREFIX}${name}` : keyword;
|
||||
}
|
||||
|
||||
export function editKeywords(value: unknown, shown: readonly string[], next: readonly string[]): Record<string, true> {
|
||||
const before = new Set(shown);
|
||||
const after = new Set(next);
|
||||
const kept = setValues(value).filter((keyword) => !before.has(keyword) || after.has(keyword));
|
||||
const added = next.filter((keyword) => !before.has(keyword)).map(canonicalKeyword);
|
||||
return toSet([...kept, ...added]);
|
||||
}
|
||||
|
||||
export function setFlag(actions: Record<string, unknown>, flag: FlagAction, on: boolean): Record<string, unknown> {
|
||||
const { set, keyword } = FLAG_ACTIONS[flag];
|
||||
const opposite: KeywordSet = set === 'addKeywords' ? 'removeKeywords' : 'addKeywords';
|
||||
const others = setValues(actions[set]).filter((key) => key !== keyword);
|
||||
const next = { ...actions, [set]: toSet(on ? [...others, keyword] : others) };
|
||||
const conflicting = setValues(actions[opposite]);
|
||||
if (!on || !conflicting.includes(keyword)) return next;
|
||||
return { ...next, [opposite]: toSet(conflicting.filter((key) => key !== keyword)) };
|
||||
}
|
||||
|
||||
export function listEntries(value: unknown): [string, Record<string, unknown>][] {
|
||||
if (!isRecord(value)) return [];
|
||||
@@ -39,6 +106,7 @@ export function isInlineField(field: Field): boolean {
|
||||
const { type } = field;
|
||||
switch (type.type) {
|
||||
case 'enum':
|
||||
return type.enumName !== TIME_ZONE_ENUM;
|
||||
case 'number':
|
||||
case 'utcDateTime':
|
||||
return true;
|
||||
|
||||
@@ -0,0 +1,535 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useId, useState, type ComponentType, type ReactNode } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { TFunction } from 'i18next';
|
||||
import { Plus, Trash2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { FieldRow, type FieldRowProps } from '@/components/forms/FieldRow';
|
||||
import { FieldScopeProvider } from '@/components/forms/FormProvider';
|
||||
import { useFormContext } from '@/components/forms/formContext';
|
||||
import { missingNestedFields } from '@/components/forms/formLogic';
|
||||
import { embeddedEntries, isRecord, resolveEmbedded } from '@/lib/embeddedSchema';
|
||||
import { buildNewObjectValue } from '@/lib/schemaResolver';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { FieldControl } from '@/components/forms/widgets/FieldControl';
|
||||
import type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
import type { FieldType } from '@/types/schema';
|
||||
import { editKeywords, setFlag, toSet } from '../builder';
|
||||
import {
|
||||
FLAG_ACTIONS,
|
||||
hasFlag,
|
||||
hasOtherAction,
|
||||
isEveryMessageReply,
|
||||
MAIL_RULE_ACTIONS_OBJECT,
|
||||
otherKeywords,
|
||||
parseActions,
|
||||
setValues,
|
||||
type FlagAction,
|
||||
type KeywordSet,
|
||||
type RuleActions,
|
||||
} from '../model';
|
||||
import { actionLabel } from '../summary';
|
||||
import { KeywordInput } from './KeywordInput';
|
||||
import { MailboxPicker } from './MailboxPicker';
|
||||
import { RuleFieldRow } from './RuleFieldRow';
|
||||
|
||||
type ObjectAction = 'redirect' | 'reply' | 'reject';
|
||||
type FilledAction = 'moveTo' | 'copyTo' | 'setImportance' | KeywordSet;
|
||||
type RuleAction = FilledAction | FlagAction | ObjectAction | 'clearKeywords' | 'discard';
|
||||
type ActionGroup = 'file' | 'mark' | 'answer' | 'remove';
|
||||
|
||||
const ACTION_GROUPS: readonly { group: ActionGroup; actions: readonly RuleAction[] }[] = [
|
||||
{ group: 'file', actions: ['moveTo', 'copyTo'] },
|
||||
{
|
||||
group: 'mark',
|
||||
actions: [
|
||||
'markRead',
|
||||
'flag',
|
||||
'clearFlag',
|
||||
'markNotJunk',
|
||||
'setImportance',
|
||||
'addKeywords',
|
||||
'removeKeywords',
|
||||
'clearKeywords',
|
||||
],
|
||||
},
|
||||
{ group: 'answer', actions: ['reply', 'redirect'] },
|
||||
{ group: 'remove', actions: ['discard', 'reject'] },
|
||||
];
|
||||
|
||||
interface Focus {
|
||||
action: RuleAction;
|
||||
target: 'card' | 'chip';
|
||||
}
|
||||
|
||||
const FILLED_ACTIONS: readonly FilledAction[] = ['moveTo', 'copyTo', 'setImportance', 'addKeywords', 'removeKeywords'];
|
||||
|
||||
const FIRST_CONTROL = 'input:not([type="hidden"]), textarea, button, [role="combobox"]';
|
||||
|
||||
function focusFirstControl(card: HTMLElement | null) {
|
||||
card?.querySelector<HTMLElement>(FIRST_CONTROL)?.focus();
|
||||
}
|
||||
|
||||
function isFilled(actions: RuleActions, action: FilledAction): boolean {
|
||||
switch (action) {
|
||||
case 'moveTo':
|
||||
case 'copyTo':
|
||||
return actions[action].length > 0;
|
||||
case 'addKeywords':
|
||||
case 'removeKeywords':
|
||||
return otherKeywords(actions, action).length > 0;
|
||||
case 'setImportance':
|
||||
return actions.setImportance !== null;
|
||||
}
|
||||
}
|
||||
|
||||
function filledActions(value: unknown): ReadonlySet<RuleAction> {
|
||||
const actions = parseActions(isRecord(value) ? value : {});
|
||||
return new Set(FILLED_ACTIONS.filter((action) => isFilled(actions, action)));
|
||||
}
|
||||
|
||||
function isFlag(action: RuleAction): action is FlagAction {
|
||||
return Object.hasOwn(FLAG_ACTIONS, action);
|
||||
}
|
||||
|
||||
function LockedSwitch({ value, control }: WidgetProps) {
|
||||
return <Switch {...control} checked={value === true} disabled />;
|
||||
}
|
||||
|
||||
interface ActionRowProps extends Pick<FieldRowProps, 'value' | 'onChange'> {
|
||||
name: string;
|
||||
label: string;
|
||||
type: FieldType | undefined;
|
||||
description?: string;
|
||||
Edit?: ComponentType<WidgetProps>;
|
||||
}
|
||||
|
||||
function ActionRow({ name, label, type, description = '', Edit, ...props }: ActionRowProps) {
|
||||
if (!type) return null;
|
||||
const row = { field: { type, description, update: 'mutable' as const }, formField: { name, label }, ...props };
|
||||
return Edit ? <RuleFieldRow {...row} Edit={Edit} /> : <FieldRow {...row} />;
|
||||
}
|
||||
|
||||
interface ActionDetailsProps {
|
||||
name: string;
|
||||
objectName: string;
|
||||
value: Record<string, unknown>;
|
||||
onChange: (value: Record<string, unknown>) => void;
|
||||
readOnly: boolean;
|
||||
invalid: boolean;
|
||||
}
|
||||
|
||||
function ActionDetails({ name, objectName, value, onChange, readOnly, invalid }: ActionDetailsProps) {
|
||||
const { t } = useTranslation();
|
||||
const { schema } = useFormContext();
|
||||
const resolved = resolveEmbedded(schema, objectName, value);
|
||||
if (!resolved) return null;
|
||||
const missing = new Set(invalid ? missingNestedFields(schema, objectName, value) : []);
|
||||
return (
|
||||
<FieldScopeProvider name={name} readOnly={readOnly}>
|
||||
<div className="divide-y divide-border">
|
||||
{embeddedEntries(resolved).map(({ formField, field }) => (
|
||||
<FieldRow
|
||||
key={formField.name}
|
||||
field={field}
|
||||
formField={formField}
|
||||
value={value[formField.name]}
|
||||
onChange={(next) => onChange({ ...value, [formField.name]: next })}
|
||||
error={missing.has(formField.name) ? t('form.required', 'This field is required.') : undefined}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</FieldScopeProvider>
|
||||
);
|
||||
}
|
||||
|
||||
interface ActionCardProps {
|
||||
label: string;
|
||||
onRemove: (() => void) | null;
|
||||
focused: boolean;
|
||||
title?: ReactNode;
|
||||
children?: ReactNode;
|
||||
}
|
||||
|
||||
function ActionCard({ label, onRemove, focused, title, children }: ActionCardProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<li
|
||||
ref={focused ? focusFirstControl : undefined}
|
||||
className="rounded-xl bg-card px-3 shadow-tile"
|
||||
data-testid="mail-rule-action"
|
||||
>
|
||||
<div className="flex items-start gap-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
{title && <div className="py-3">{title}</div>}
|
||||
{children}
|
||||
</div>
|
||||
{onRemove && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost-danger"
|
||||
size="icon-sm"
|
||||
className="mt-2.5 shrink-0"
|
||||
onClick={onRemove}
|
||||
aria-label={t('mailRules.removeItem', 'Remove {{label}}', { label })}
|
||||
>
|
||||
<Trash2 className="size-4" aria-hidden="true" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function CardTitle({ label, description }: { label: string; description?: string }) {
|
||||
return (
|
||||
<>
|
||||
<p className="text-[13.5px] font-semibold">{label}</p>
|
||||
{description && <p className="mt-1 text-[12.5px] leading-relaxed text-muted-foreground">{description}</p>}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
interface ActionFormProps {
|
||||
value: unknown;
|
||||
onChange: (value: Record<string, unknown>) => void;
|
||||
readOnly: boolean;
|
||||
invalid: boolean;
|
||||
}
|
||||
|
||||
export function ActionForm({ value, onChange, readOnly, invalid }: ActionFormProps) {
|
||||
const { t } = useTranslation();
|
||||
const { schema, mode, baseline } = useFormContext();
|
||||
const [opened, setOpened] = useState(() => filledActions(value));
|
||||
const rejectHintId = useId();
|
||||
const [focus, setFocus] = useState<Focus | null>(null);
|
||||
const raw = isRecord(value) ? value : {};
|
||||
const actions = parseActions(raw);
|
||||
const properties = resolveEmbedded(schema, MAIL_RULE_ACTIONS_OBJECT, raw)?.fields?.properties ?? {};
|
||||
const saved = mode === 'edit' && isRecord(baseline) && isRecord(baseline.actions) ? baseline.actions : {};
|
||||
const hasOther = hasOtherAction(actions);
|
||||
const rejects = actions.reject !== null;
|
||||
const rejectBlocked = hasOther && !rejects;
|
||||
const set = (name: keyof RuleActions, next: unknown) => onChange({ ...raw, [name]: next });
|
||||
const open = (action: RuleAction, on: boolean) =>
|
||||
setOpened((current) => {
|
||||
const next = new Set(current);
|
||||
if (on) next.add(action);
|
||||
else next.delete(action);
|
||||
return next;
|
||||
});
|
||||
|
||||
const isActive = (action: RuleAction): boolean => {
|
||||
if (isFlag(action)) return hasFlag(actions, action);
|
||||
switch (action) {
|
||||
case 'moveTo':
|
||||
case 'copyTo':
|
||||
case 'addKeywords':
|
||||
case 'removeKeywords':
|
||||
case 'setImportance':
|
||||
return isFilled(actions, action) || opened.has(action);
|
||||
case 'clearKeywords':
|
||||
case 'discard':
|
||||
return actions[action];
|
||||
case 'redirect':
|
||||
case 'reply':
|
||||
case 'reject':
|
||||
return actions[action] !== null;
|
||||
}
|
||||
};
|
||||
|
||||
const objectType = (name: ObjectAction) => {
|
||||
const type = properties[name]?.type;
|
||||
return type?.type === 'object' ? type : null;
|
||||
};
|
||||
|
||||
const add = (action: RuleAction) => {
|
||||
setFocus({ action, target: 'card' });
|
||||
if (isFlag(action)) return onChange(setFlag(raw, action, true));
|
||||
switch (action) {
|
||||
case 'clearKeywords':
|
||||
case 'discard':
|
||||
return set(action, true);
|
||||
case 'redirect':
|
||||
case 'reply':
|
||||
case 'reject': {
|
||||
const type = objectType(action);
|
||||
if (!type) return;
|
||||
return set(action, isRecord(saved[action]) ? saved[action] : buildNewObjectValue(schema, type.objectName));
|
||||
}
|
||||
default:
|
||||
return open(action, true);
|
||||
}
|
||||
};
|
||||
|
||||
const remove = (action: RuleAction) => {
|
||||
setFocus({ action, target: 'chip' });
|
||||
if (isFlag(action)) return onChange(setFlag(raw, action, false));
|
||||
switch (action) {
|
||||
case 'moveTo':
|
||||
case 'copyTo':
|
||||
open(action, false);
|
||||
return set(action, {});
|
||||
case 'addKeywords':
|
||||
case 'removeKeywords':
|
||||
open(action, false);
|
||||
return set(action, editKeywords(raw[action], otherKeywords(actions, action), []));
|
||||
case 'setImportance':
|
||||
open(action, false);
|
||||
return set(action, null);
|
||||
case 'clearKeywords':
|
||||
case 'discard':
|
||||
return set(action, false);
|
||||
case 'redirect':
|
||||
case 'reply':
|
||||
case 'reject':
|
||||
return set(action, null);
|
||||
}
|
||||
};
|
||||
|
||||
const keywordRow = (name: KeywordSet, label: string) => {
|
||||
const shown = otherKeywords(actions, name);
|
||||
return (
|
||||
<ActionRow
|
||||
name={name}
|
||||
label={label}
|
||||
type={properties[name]?.type}
|
||||
value={toSet(shown)}
|
||||
onChange={(next) => set(name, editKeywords(raw[name], shown, setValues(next)))}
|
||||
Edit={KeywordInput}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const objectDetails = (name: ObjectAction) => {
|
||||
const type = objectType(name);
|
||||
const current = actions[name];
|
||||
if (!type || !current) return null;
|
||||
return (
|
||||
<ActionDetails
|
||||
name={name}
|
||||
objectName={type.objectName}
|
||||
value={current}
|
||||
onChange={(next) => set(name, next)}
|
||||
readOnly={readOnly}
|
||||
invalid={invalid}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const cardContent = (action: RuleAction): { title?: ReactNode; body?: ReactNode } => {
|
||||
const label = actionLabel(t, action);
|
||||
switch (action) {
|
||||
case 'moveTo':
|
||||
return {
|
||||
body: (
|
||||
<ActionRow
|
||||
name="moveTo"
|
||||
label={label}
|
||||
description={t('mailRules.builder.moveToHint', 'Moving to Junk also marks the message as spam.')}
|
||||
type={properties.moveTo?.type}
|
||||
value={raw.moveTo}
|
||||
onChange={(next) => set('moveTo', next)}
|
||||
Edit={MailboxPicker}
|
||||
/>
|
||||
),
|
||||
};
|
||||
case 'copyTo':
|
||||
return {
|
||||
body: (
|
||||
<ActionRow
|
||||
name="copyTo"
|
||||
label={label}
|
||||
type={properties.copyTo?.type}
|
||||
value={raw.copyTo}
|
||||
onChange={(next) => set('copyTo', next)}
|
||||
Edit={MailboxPicker}
|
||||
/>
|
||||
),
|
||||
};
|
||||
case 'addKeywords':
|
||||
return { body: keywordRow('addKeywords', t('mailRules.builder.keywordsToAdd', 'Keywords to add')) };
|
||||
case 'removeKeywords':
|
||||
return { body: keywordRow('removeKeywords', t('mailRules.builder.keywordsToRemove', 'Keywords to remove')) };
|
||||
case 'setImportance':
|
||||
return {
|
||||
body: (
|
||||
<ActionRow
|
||||
name="setImportance"
|
||||
label={label}
|
||||
type={properties.setImportance?.type}
|
||||
value={actions.setImportance}
|
||||
onChange={(next) => set('setImportance', next)}
|
||||
Edit={FieldControl}
|
||||
/>
|
||||
),
|
||||
};
|
||||
case 'markNotJunk':
|
||||
return {
|
||||
title: (
|
||||
<CardTitle
|
||||
label={label}
|
||||
description={t('mailRules.builder.markNotJunkHint', 'Keeps the message out of Junk.')}
|
||||
/>
|
||||
),
|
||||
};
|
||||
case 'discard':
|
||||
return {
|
||||
title: (
|
||||
<CardTitle
|
||||
label={label}
|
||||
description={t('mailRules.builder.discardHint', 'The message does not go to Trash.')}
|
||||
/>
|
||||
),
|
||||
};
|
||||
case 'reply':
|
||||
return {
|
||||
title: <CardTitle label={label} />,
|
||||
body: (
|
||||
<>
|
||||
{objectDetails('reply')}
|
||||
{isEveryMessageReply(actions.reply) && (
|
||||
<p className="pb-3 text-[12.5px] text-muted-foreground">
|
||||
{t('mailRules.builder.replyEveryMessage', 'With 0 days between replies, every message gets a reply.')}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
),
|
||||
};
|
||||
case 'redirect':
|
||||
return { title: <CardTitle label={label} />, body: objectDetails('redirect') };
|
||||
case 'reject':
|
||||
return {
|
||||
title: (
|
||||
<CardTitle
|
||||
label={label}
|
||||
description={t(
|
||||
'mailRules.builder.rejectHint',
|
||||
'Reject must be the only action. The sender is told only when their address can be verified; otherwise the message is deleted without notice.',
|
||||
)}
|
||||
/>
|
||||
),
|
||||
body: objectDetails('reject'),
|
||||
};
|
||||
default:
|
||||
return { title: <CardTitle label={label} /> };
|
||||
}
|
||||
};
|
||||
|
||||
const ordered = ACTION_GROUPS.flatMap(({ actions: group }) => group);
|
||||
const active = ordered.filter(isActive);
|
||||
const showChips = !readOnly && !rejects;
|
||||
|
||||
return (
|
||||
<FieldScopeProvider name="actions" readOnly={readOnly}>
|
||||
<div className="@container space-y-4">
|
||||
{active.length === 0 ? (
|
||||
<p className="text-[12.5px] text-muted-foreground">
|
||||
{readOnly
|
||||
? t('mailRules.builder.noActionsReadOnly', 'No actions.')
|
||||
: t('mailRules.builder.noActions', 'No actions yet. Choose at least one below.')}
|
||||
</p>
|
||||
) : (
|
||||
<ul className="space-y-2 [&_[data-slot=field-row]]:py-3">
|
||||
{active.map((action) => {
|
||||
const { title, body } = cardContent(action);
|
||||
return (
|
||||
<ActionCard
|
||||
key={action}
|
||||
label={actionLabel(t, action)}
|
||||
onRemove={readOnly ? null : () => remove(action)}
|
||||
focused={focus?.action === action && focus.target === 'card'}
|
||||
title={title}
|
||||
>
|
||||
{body}
|
||||
</ActionCard>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{showChips && active.length < ordered.length && (
|
||||
<div className="space-y-2">
|
||||
<p className="text-[13px] font-semibold">
|
||||
{active.length === 0
|
||||
? t('mailRules.builder.addAction', 'Add an action')
|
||||
: t('mailRules.builder.addAnotherAction', 'Add another action')}
|
||||
</p>
|
||||
<dl className="space-y-2">
|
||||
{ACTION_GROUPS.map(({ group, actions: members }) => {
|
||||
const available = members.filter((action) => !isActive(action));
|
||||
if (available.length === 0) return null;
|
||||
return (
|
||||
<div key={group} className="grid gap-x-3 gap-y-1.5 sm:grid-cols-[5.5rem_minmax(0,1fr)]">
|
||||
<dt className="pt-1.5 text-[12.5px] text-muted-foreground">{groupLabel(t, group)}</dt>
|
||||
<dd className="flex flex-wrap gap-1.5">
|
||||
{available.map((action) => {
|
||||
const blocked = action === 'reject' && rejectBlocked;
|
||||
return (
|
||||
<Button
|
||||
key={action}
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
className={cn(blocked && 'cursor-not-allowed opacity-50')}
|
||||
aria-disabled={blocked || undefined}
|
||||
aria-describedby={blocked ? rejectHintId : undefined}
|
||||
autoFocus={focus?.action === action && focus.target === 'chip'}
|
||||
onClick={blocked ? undefined : () => add(action)}
|
||||
>
|
||||
<Plus className="size-4" aria-hidden="true" />
|
||||
{actionLabel(t, action)}
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
</dd>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</dl>
|
||||
{rejectBlocked && (
|
||||
<p id={rejectHintId} className="text-[12.5px] text-muted-foreground">
|
||||
{t('mailRules.builder.rejectNotAlone', 'Reject must be the only action.')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="border-t border-border [&_[data-slot=field-row]]:py-3">
|
||||
<ActionRow
|
||||
name="stopProcessing"
|
||||
label={actionLabel(t, 'stopProcessing')}
|
||||
description={
|
||||
rejects
|
||||
? t('mailRules.builder.rejectStops', 'A rule that rejects mail always stops processing more rules.')
|
||||
: t('mailRules.builder.stopHint', 'Rules below this one in the list are skipped for matching messages.')
|
||||
}
|
||||
type={properties.stopProcessing?.type}
|
||||
value={rejects || actions.stopProcessing}
|
||||
onChange={(next) => set('stopProcessing', next)}
|
||||
Edit={rejects ? LockedSwitch : undefined}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</FieldScopeProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function groupLabel(t: TFunction, group: ActionGroup): string {
|
||||
switch (group) {
|
||||
case 'file':
|
||||
return t('mailRules.builder.group.file', 'File');
|
||||
case 'mark':
|
||||
return t('mailRules.builder.group.mark', 'Mark');
|
||||
case 'answer':
|
||||
return t('mailRules.builder.group.answer', 'Answer');
|
||||
case 'remove':
|
||||
return t('mailRules.builder.group.remove', 'Delete');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* 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 { RemovablePill } from '@/components/forms/widgets/RemovablePill';
|
||||
import { SetWidget } from '@/components/forms/widgets/SetWidget';
|
||||
import type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
import { editKeywords, toSet } from '../builder';
|
||||
import { setValues } from '../model';
|
||||
import { keywordName } from '../summary';
|
||||
|
||||
export function KeywordInput(props: WidgetProps) {
|
||||
const { t } = useTranslation();
|
||||
const { type, value, onChange, readOnly } = props;
|
||||
if (type.type !== 'set') return null;
|
||||
const keywords = setValues(value);
|
||||
const named: { keyword: string; name: string }[] = [];
|
||||
const typed: string[] = [];
|
||||
for (const keyword of keywords) {
|
||||
const name = keywordName(t, keyword);
|
||||
if (name) named.push({ keyword, name });
|
||||
else typed.push(keyword);
|
||||
}
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{named.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{named.map(({ keyword, name }) => (
|
||||
<RemovablePill
|
||||
key={keyword}
|
||||
label={name}
|
||||
onRemove={readOnly ? undefined : () => onChange(toSet(keywords.filter((key) => key !== keyword)))}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<SetWidget
|
||||
{...props}
|
||||
type={{ ...type, minItems: undefined, maxItems: type.maxItems && type.maxItems - named.length }}
|
||||
value={toSet(typed)}
|
||||
onChange={(next) => onChange(editKeywords(value, typed, setValues(next)))}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -9,16 +9,18 @@ import { DynamicForm } from '@/components/forms/DynamicForm';
|
||||
import { ListError, ListSpinner } from '@/components/lists/ListStates';
|
||||
import { DynamicViewPage } from '@/components/views/DynamicViewPage';
|
||||
import { errorMessage } from '@/lib/jmapErrors';
|
||||
import type { FieldErrors } from '@/components/forms/formLogic';
|
||||
import type { FieldOverrides } from '@/components/forms/useDynamicForm';
|
||||
import type { ViewRenderers } from '@/components/views/DynamicView';
|
||||
import type { PageProps } from '@/extensions/types';
|
||||
import { useRuleAccountId } from '../account';
|
||||
import { nextRulePosition } from '../model';
|
||||
import { needsAction, newRuleValues, nextRulePosition, parseActions } from '../model';
|
||||
import { useMailRules } from '../queries';
|
||||
import { actionRequiredMessage } from '../summary';
|
||||
import { RuleBuilderRow, RuleSummaryRow } from './RuleBuilder';
|
||||
|
||||
const RULE_ANCHOR = 'actions';
|
||||
const RULE_FIELDS = ['matchAll', 'conditions', 'exceptions', 'stopProcessing', 'timeZone'] as const;
|
||||
const ABSORBED_FIELD = 'conditions';
|
||||
|
||||
function Omitted() {
|
||||
return null;
|
||||
@@ -26,18 +28,36 @@ function Omitted() {
|
||||
|
||||
const FIELD_OVERRIDES: FieldOverrides = {
|
||||
hidden: ['position'],
|
||||
untitled: [RULE_ANCHOR],
|
||||
render: {
|
||||
...Object.fromEntries(RULE_FIELDS.map((name) => [name, Omitted])),
|
||||
[ABSORBED_FIELD]: Omitted,
|
||||
[RULE_ANCHOR]: RuleBuilderRow,
|
||||
},
|
||||
};
|
||||
|
||||
function useFieldOverrides(): FieldOverrides {
|
||||
const { t } = useTranslation();
|
||||
return {
|
||||
...FIELD_OVERRIDES,
|
||||
validate: (data): FieldErrors =>
|
||||
needsAction(parseActions(data.actions)) ? { [RULE_ANCHOR]: actionRequiredMessage(t) } : {},
|
||||
};
|
||||
}
|
||||
|
||||
const VIEW_RENDERERS: ViewRenderers = {
|
||||
...Object.fromEntries(RULE_FIELDS.map((name) => [name, Omitted])),
|
||||
[ABSORBED_FIELD]: Omitted,
|
||||
[RULE_ANCHOR]: RuleSummaryRow,
|
||||
};
|
||||
|
||||
function CreateRuleForm({ viewName, accountId }: { viewName: string; accountId: string }) {
|
||||
function CreateRuleForm({
|
||||
viewName,
|
||||
accountId,
|
||||
fieldOverrides,
|
||||
}: {
|
||||
viewName: string;
|
||||
accountId: string;
|
||||
fieldOverrides: FieldOverrides;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const rules = useMailRules(accountId);
|
||||
if (rules.isError) {
|
||||
@@ -54,17 +74,20 @@ function CreateRuleForm({ viewName, accountId }: { viewName: string; accountId:
|
||||
viewName={viewName}
|
||||
objectId={null}
|
||||
accountId={accountId}
|
||||
fieldOverrides={FIELD_OVERRIDES}
|
||||
createValues={{ position: nextRulePosition(rules.data) }}
|
||||
fieldOverrides={fieldOverrides}
|
||||
createValues={newRuleValues(nextRulePosition(rules.data))}
|
||||
showCreatedValues={false}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function MailRuleFormPage({ viewName, objectId }: PageProps) {
|
||||
const accountId = useRuleAccountId();
|
||||
const fieldOverrides = useFieldOverrides();
|
||||
if (!accountId) return null;
|
||||
if (objectId === 'new') return <CreateRuleForm viewName={viewName} accountId={accountId} />;
|
||||
return <DynamicForm viewName={viewName} objectId={objectId} accountId={accountId} fieldOverrides={FIELD_OVERRIDES} />;
|
||||
if (objectId === 'new')
|
||||
return <CreateRuleForm viewName={viewName} accountId={accountId} fieldOverrides={fieldOverrides} />;
|
||||
return <DynamicForm viewName={viewName} objectId={objectId} accountId={accountId} fieldOverrides={fieldOverrides} />;
|
||||
}
|
||||
|
||||
export function MailRuleViewPage({ viewName, objectId }: PageProps) {
|
||||
|
||||
@@ -15,7 +15,7 @@ import { errorMessage } from '@/lib/jmapErrors';
|
||||
import { useSchemaStore } from '@/stores/schemaStore';
|
||||
import type { PageProps } from '@/extensions/types';
|
||||
import { useRuleAccountId } from '../account';
|
||||
import { mailboxNameResolver } from '../mailboxes';
|
||||
import { mailboxNamer } from '../mailboxes';
|
||||
import { useMailboxOptions, useMailRules } from '../queries';
|
||||
import { CustomRuleList } from './CustomRuleList';
|
||||
|
||||
@@ -41,7 +41,7 @@ export function MailRulesPage({ viewName, section }: PageProps) {
|
||||
const summary = {
|
||||
t,
|
||||
schema,
|
||||
mailboxName: mailboxes.status === 'ready' ? mailboxNameResolver(mailboxes.options) : undefined,
|
||||
mailboxName: mailboxNamer(t, mailboxes.status === 'ready' ? mailboxes.options : undefined),
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
@@ -7,58 +7,74 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { BufferedInput } from '@/components/forms/widgets/BufferedInputs';
|
||||
import type { ControlProps } from '@/components/forms/widgets/types';
|
||||
import { RemovablePill } from '@/components/forms/widgets/RemovablePill';
|
||||
import type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
import { useRuleAccountId } from '../account';
|
||||
import { toSet } from '../builder';
|
||||
import { mailboxNamer } from '../mailboxes';
|
||||
import { setValues } from '../model';
|
||||
import { useMailboxOptions } from '../queries';
|
||||
|
||||
const INDENT_REM = 0.75;
|
||||
|
||||
interface MailboxPickerProps {
|
||||
accountId: string | null;
|
||||
value: unknown;
|
||||
onChange: (value: string) => void;
|
||||
readOnly: boolean;
|
||||
control: ControlProps;
|
||||
}
|
||||
|
||||
export function MailboxPicker({ accountId, value, onChange, readOnly, control }: MailboxPickerProps) {
|
||||
export function MailboxPicker({ type, value, onChange, readOnly, control }: WidgetProps) {
|
||||
const { t } = useTranslation();
|
||||
const mailboxes = useMailboxOptions(accountId);
|
||||
const current = typeof value === 'string' ? value : '';
|
||||
const mailboxes = useMailboxOptions(useRuleAccountId());
|
||||
const ids = setValues(value);
|
||||
const isFull = type.type === 'set' && type.maxItems != null && ids.length >= type.maxItems;
|
||||
const nameOf = mailboxNamer(t, mailboxes.status === 'ready' ? mailboxes.options : undefined);
|
||||
const add = (entered: string) => {
|
||||
const id = entered.trim();
|
||||
if (id && !ids.includes(id)) onChange(toSet([...ids, id]));
|
||||
};
|
||||
const placeholder =
|
||||
ids.length > 0
|
||||
? t('mailRules.addMailbox', 'Add another mailbox')
|
||||
: t('mailRules.chooseMailbox', 'Choose a mailbox');
|
||||
|
||||
if (mailboxes.status !== 'ready') {
|
||||
return (
|
||||
<BufferedInput
|
||||
{...control}
|
||||
value={current}
|
||||
onCommit={onChange}
|
||||
readOnly={readOnly}
|
||||
disabled={mailboxes.status === 'loading'}
|
||||
placeholder={t('mailRules.mailboxId', 'Mailbox id')}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const { options } = mailboxes;
|
||||
const selected = options.find((option) => option.id === current);
|
||||
return (
|
||||
<Select value={current} onValueChange={onChange} disabled={readOnly}>
|
||||
<SelectTrigger {...control} className="w-full">
|
||||
<SelectValue placeholder={t('mailRules.chooseMailbox', 'Choose a mailbox')}>
|
||||
{selected ? selected.path.join(' / ') : undefined}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{current && !selected && (
|
||||
<SelectItem value={current}>
|
||||
{t('mailRules.unknownMailbox', 'Unknown mailbox ({{id}})', { id: current })}
|
||||
</SelectItem>
|
||||
)}
|
||||
{options.map((option) => (
|
||||
<SelectItem key={option.id} value={option.id} textValue={option.path.join(' / ')}>
|
||||
<span style={{ paddingInlineStart: `${option.depth * INDENT_REM}rem` }}>{option.name}</span>
|
||||
</SelectItem>
|
||||
<div className="space-y-2">
|
||||
{ids.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{ids.map((id) => (
|
||||
<RemovablePill
|
||||
key={id}
|
||||
label={nameOf(id)}
|
||||
onRemove={readOnly ? undefined : () => onChange(toSet(ids.filter((key) => key !== id)))}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{!readOnly &&
|
||||
!isFull &&
|
||||
(mailboxes.status === 'ready' ? (
|
||||
<Select value="" onValueChange={add}>
|
||||
<SelectTrigger {...control} className="w-full">
|
||||
<SelectValue placeholder={placeholder} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{mailboxes.options.map((option) => (
|
||||
<SelectItem
|
||||
key={option.id}
|
||||
value={option.id}
|
||||
textValue={option.path.join(' / ')}
|
||||
disabled={ids.includes(option.id)}
|
||||
>
|
||||
<span style={{ paddingInlineStart: `${option.depth * INDENT_REM}rem` }}>{option.name}</span>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
) : (
|
||||
<BufferedInput
|
||||
key={ids.length}
|
||||
{...control}
|
||||
value=""
|
||||
onCommit={add}
|
||||
disabled={mailboxes.status === 'loading'}
|
||||
placeholder={t('mailRules.mailboxId', 'Mailbox id')}
|
||||
/>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -4,106 +4,60 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useRef, useState, type KeyboardEvent, type ReactNode } from 'react';
|
||||
import { useState, type ReactNode } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { AlertTriangle, ChevronRight } from 'lucide-react';
|
||||
import { FieldError, FieldRow } from '@/components/forms/FieldRow';
|
||||
import { AlertTriangle, Plus } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { FieldError } from '@/components/forms/FieldRow';
|
||||
import { FieldScopeProvider } from '@/components/forms/FormProvider';
|
||||
import { ValueRow } from '@/components/values/FieldValue';
|
||||
import { fieldIds, useFormContext } from '@/components/forms/formContext';
|
||||
import { missingNestedFields } from '@/components/forms/formLogic';
|
||||
import type { FieldRenderProps } from '@/components/forms/useDynamicForm';
|
||||
import { usePermissionCheckers } from '@/hooks/usePermissions';
|
||||
import { embeddedEntries, resolveEmbedded } from '@/lib/embeddedSchema';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { isRecord, resolveEmbedded } from '@/lib/embeddedSchema';
|
||||
import { buildNewObjectValue } from '@/lib/schemaResolver';
|
||||
import type { ViewRenderProps } from '@/components/views/DynamicView';
|
||||
import type { Field, FieldTypeObjectList } from '@/types/schema';
|
||||
import { useRuleAccountId } from '../account';
|
||||
import { listEntries } from '../builder';
|
||||
import { mailboxNameResolver } from '../mailboxes';
|
||||
import { appendItem, listEntries, type ListItems } from '../builder';
|
||||
import { mailboxNamer } from '../mailboxes';
|
||||
import {
|
||||
hasRejectAction,
|
||||
hasScheduleCondition,
|
||||
isRejectAllowed,
|
||||
MAIL_RULE_ACTION_OBJECT,
|
||||
hasOtherAction,
|
||||
MAIL_RULE_ACTIONS_OBJECT,
|
||||
needsAction,
|
||||
MAIL_RULE_CONDITION_OBJECT,
|
||||
MAIL_RULE_OBJECT,
|
||||
MAIL_RULE_CONDITIONS_OBJECT,
|
||||
parseCustomBody,
|
||||
REJECT_ACTION,
|
||||
ruleIssues,
|
||||
type ConditionGroup,
|
||||
type RuleIssue,
|
||||
} from '../model';
|
||||
import { useMailboxOptions } from '../queries';
|
||||
import { ruleIssueMessage, ruleSentence, summarizeCustomRule } from '../summary';
|
||||
import { RuleItemList } from './RuleItemList';
|
||||
import { ActionForm } from './ActionForm';
|
||||
import { RuleItemList, type RuleItemListProps } from './RuleItemList';
|
||||
|
||||
const TRAILING_FIELDS = new Set(['stopProcessing', 'timeZone']);
|
||||
const RULE_ERROR_FIELDS = ['matchAll', 'conditions', 'exceptions'] as const;
|
||||
const STOP_PROCESSING = 'stopProcessing';
|
||||
const TOGGLE_KEYS = new Set(['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown']);
|
||||
|
||||
function listBounds(field: Field | undefined): { minItems?: number; maxItems?: number } {
|
||||
const type = field?.type as FieldTypeObjectList | undefined;
|
||||
return type?.type === 'objectList' ? { minItems: type.minItems, maxItems: type.maxItems } : {};
|
||||
}
|
||||
|
||||
function MatchModeToggle({
|
||||
matchAll,
|
||||
onChange,
|
||||
readOnly,
|
||||
}: {
|
||||
matchAll: boolean;
|
||||
onChange: (matchAll: boolean) => void;
|
||||
readOnly: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const options = [
|
||||
{ value: true, label: t('mailRules.builder.all', 'all') },
|
||||
{ value: false, label: t('mailRules.builder.any', 'any') },
|
||||
];
|
||||
const onKeyDown = (event: KeyboardEvent<HTMLSpanElement>) => {
|
||||
if (readOnly || !TOGGLE_KEYS.has(event.key)) return;
|
||||
event.preventDefault();
|
||||
onChange(!matchAll);
|
||||
event.currentTarget.querySelector<HTMLButtonElement>('[aria-checked="false"]')?.focus();
|
||||
};
|
||||
function Step({ number, heading, children }: { number: number; heading: string; children: ReactNode }) {
|
||||
return (
|
||||
<span
|
||||
role="radiogroup"
|
||||
aria-label={t('mailRules.builder.matchMode', 'Conditions that must match')}
|
||||
className="inline-flex rounded-lg bg-muted p-0.5 align-middle"
|
||||
onKeyDown={onKeyDown}
|
||||
>
|
||||
{options.map((option) => (
|
||||
<button
|
||||
key={String(option.value)}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={matchAll === option.value}
|
||||
tabIndex={matchAll === option.value ? 0 : -1}
|
||||
disabled={readOnly}
|
||||
onClick={() => onChange(option.value)}
|
||||
className={cn(
|
||||
'rounded-md px-2.5 py-0.5 text-sm font-semibold transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
|
||||
matchAll === option.value ? 'bg-primary text-primary-foreground' : 'text-muted-foreground',
|
||||
)}
|
||||
<section className="space-y-3 py-4">
|
||||
<h2 className="flex items-center gap-2.5 text-[14px] font-semibold">
|
||||
<span
|
||||
className="flex size-6 shrink-0 items-center justify-center rounded-full bg-ink text-[12px] text-ink-foreground"
|
||||
aria-hidden="true"
|
||||
>
|
||||
{option.label}
|
||||
</button>
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function Step({ heading, title, children }: { heading: string; title?: ReactNode; children: ReactNode }) {
|
||||
return (
|
||||
<section className="space-y-2 py-3">
|
||||
<h3 className={title ? 'sr-only' : 'text-[13.5px] font-semibold'}>{heading}</h3>
|
||||
{title && <div className="text-[13.5px] font-semibold">{title}</div>}
|
||||
{children}
|
||||
{number}
|
||||
</span>
|
||||
{heading}
|
||||
</h2>
|
||||
<div className="space-y-3 sm:pl-[34px]">{children}</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function Hint({ children }: { children: ReactNode }) {
|
||||
return <p className="text-[12.5px] leading-relaxed text-muted-foreground">{children}</p>;
|
||||
}
|
||||
|
||||
function IssueList({ issues }: { issues: readonly RuleIssue[] }) {
|
||||
const { t } = useTranslation();
|
||||
if (issues.length === 0) return null;
|
||||
@@ -119,178 +73,203 @@ function IssueList({ issues }: { issues: readonly RuleIssue[] }) {
|
||||
);
|
||||
}
|
||||
|
||||
export function RuleBuilderRow({ data: body, errors, readOnly, onFieldChange: set }: FieldRenderProps) {
|
||||
function RulePreview({ body, incomplete }: { body: Record<string, unknown>; incomplete: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const { schema, idPrefix } = useFormContext();
|
||||
const accountId = useRuleAccountId();
|
||||
const mailboxes = useMailboxOptions(accountId);
|
||||
const ctx = {
|
||||
t,
|
||||
schema,
|
||||
mailboxName: mailboxNamer(t, mailboxes.status === 'ready' ? mailboxes.options : undefined),
|
||||
};
|
||||
return (
|
||||
<section
|
||||
className="space-y-1.5 rounded-xl bg-muted px-4 py-3"
|
||||
aria-labelledby={`${idPrefix}-preview`}
|
||||
data-testid="mail-rule-preview"
|
||||
>
|
||||
<h2
|
||||
id={`${idPrefix}-preview`}
|
||||
className="text-[12px] font-semibold uppercase tracking-wide text-muted-foreground"
|
||||
>
|
||||
{t('mailRules.builder.preview', 'Summary')}
|
||||
</h2>
|
||||
<p className="text-[14px] leading-relaxed">
|
||||
{incomplete
|
||||
? t('mailRules.builder.previewIncomplete', 'Nothing yet: choose what to do with matching messages.')
|
||||
: ruleSentence(ctx, summarizeCustomRule(ctx, body))}
|
||||
</p>
|
||||
<Hint>
|
||||
{t(
|
||||
'mailRules.builder.whenItRuns',
|
||||
'Rules run on new mail as it arrives. Saving does not change messages already in your mailboxes.',
|
||||
)}
|
||||
</Hint>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
const OPTIONAL_GROUPS = ['matchAny', 'matchNone'] as const;
|
||||
|
||||
type OptionalGroup = (typeof OPTIONAL_GROUPS)[number];
|
||||
|
||||
export function RuleBuilderRow({ data: body, errors, readOnly, onFieldChange }: FieldRenderProps) {
|
||||
const { t } = useTranslation();
|
||||
const { schema, idPrefix } = useFormContext();
|
||||
const checkers = usePermissionCheckers();
|
||||
const exceptionsButton = useRef<HTMLButtonElement>(null);
|
||||
const custom = parseCustomBody(body);
|
||||
const resolved = resolveEmbedded(schema, MAIL_RULE_OBJECT, body);
|
||||
const entries = resolved ? embeddedEntries(resolved) : [];
|
||||
const fieldOf = (name: string) => entries.find((entry) => entry.formField.name === name);
|
||||
const [exceptionsExpanded, setExceptionsExpanded] = useState<boolean | null>(null);
|
||||
const missing = new Set(
|
||||
errors.conditions || errors.exceptions || errors.actions ? missingNestedFields(schema, MAIL_RULE_OBJECT, body) : [],
|
||||
);
|
||||
const errorOf = (name: string) => (missing.has(name) ? undefined : errors[name]);
|
||||
const [focusGroup, setFocusGroup] = useState<OptionalGroup | null>(null);
|
||||
const { conditions, actions } = parseCustomBody(body);
|
||||
const groups = isRecord(body.conditions) ? body.conditions : {};
|
||||
const groupFields = resolveEmbedded(schema, MAIL_RULE_CONDITIONS_OBJECT, groups)?.fields?.properties ?? {};
|
||||
const issues = ruleIssues({ isEnabled: true, body }, checkers);
|
||||
const hasReject = hasRejectAction(custom);
|
||||
const rejectBlocked =
|
||||
custom.actions.length > 1
|
||||
? t('mailRules.builder.rejectNotAlone', 'Reject must be the only action.')
|
||||
: isRejectAllowed(custom)
|
||||
? undefined
|
||||
: t(
|
||||
'mailRules.builder.rejectNeedsAuthentication',
|
||||
'Reject needs all conditions to match, including an authenticated sender.',
|
||||
);
|
||||
const disabledActions = rejectBlocked ? new Map([[REJECT_ACTION, rejectBlocked]]) : undefined;
|
||||
const conditionLabel = (n: number) => t('mailRules.builder.conditionN', 'Condition {{n}}', { n });
|
||||
const exceptionLabel = (n: number) => t('mailRules.builder.exceptionN', 'Exception {{n}}', { n });
|
||||
const actionLabel = (n: number) => t('mailRules.builder.actionN', 'Action {{n}}', { n });
|
||||
const showExceptions = !!errors.exceptions || (exceptionsExpanded ?? custom.exceptions.length > 0);
|
||||
const exceptionsId = `${fieldIds(idPrefix, ['exceptions']).inputId}-list`;
|
||||
const actionsErrorId = fieldIds(idPrefix, ['actions']).errorId;
|
||||
const ruleErrorField = RULE_ERROR_FIELDS.find((name) => errorOf(name));
|
||||
const actionsError =
|
||||
errors.actions &&
|
||||
(custom.actions.length === 0
|
||||
? t('mailRules.builder.actionRequired', 'Add at least one action.')
|
||||
: errorOf('actions'));
|
||||
const changeExceptions = (next: unknown) => {
|
||||
if (custom.exceptions.length > 0 && listEntries(next).length === 0) exceptionsButton.current?.focus();
|
||||
set('exceptions', next);
|
||||
const conditionsMarked =
|
||||
!!errors.conditions && missingNestedFields(schema, MAIL_RULE_CONDITIONS_OBJECT, groups).length > 0;
|
||||
const actionsMarked =
|
||||
!!errors.actions && missingNestedFields(schema, MAIL_RULE_ACTIONS_OBJECT, body.actions).length > 0;
|
||||
const hasAll = conditions.matchAll.length > 0;
|
||||
|
||||
const groupText = (group: ConditionGroup) => {
|
||||
switch (group) {
|
||||
case 'matchAll':
|
||||
return {
|
||||
title: '',
|
||||
hint: hasAll
|
||||
? t('mailRules.builder.conditionsHint', 'A message must match every condition.')
|
||||
: t('mailRules.builder.noConditions', 'No conditions: the rule applies to every message.'),
|
||||
joiner: t('mailRules.builder.and', 'and'),
|
||||
item: (n: number) => t('mailRules.builder.conditionN', 'Condition {{n}}', { n }),
|
||||
add: t('mailRules.builder.addCondition', 'Add condition'),
|
||||
addHint: '',
|
||||
};
|
||||
case 'matchAny':
|
||||
return {
|
||||
title: t('mailRules.builder.alternatives', 'Alternatives'),
|
||||
hint: hasAll
|
||||
? t('mailRules.builder.alternativesHintAnd', 'A message must also match at least one alternative.')
|
||||
: t('mailRules.builder.alternativesHint', 'A message must match at least one alternative.'),
|
||||
joiner: t('mailRules.builder.or', 'or'),
|
||||
item: (n: number) => t('mailRules.builder.alternativeN', 'Alternative {{n}}', { n }),
|
||||
add: t('mailRules.builder.addAlternative', 'Add alternative'),
|
||||
addHint: t('mailRules.builder.addAlternativeHint', 'Match one of several conditions, such as two senders.'),
|
||||
};
|
||||
case 'matchNone':
|
||||
return {
|
||||
title: t('mailRules.builder.exceptions', 'Exceptions'),
|
||||
hint: t('mailRules.builder.exceptionsHint', 'The rule skips a message that matches any exception.'),
|
||||
joiner: t('mailRules.builder.or', 'or'),
|
||||
item: (n: number) => t('mailRules.builder.exceptionN', 'Exception {{n}}', { n }),
|
||||
add: t('mailRules.builder.addException', 'Add exception'),
|
||||
addHint: t('mailRules.builder.addExceptionHint', 'Skip messages that would otherwise match.'),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const change = (group: ConditionGroup, next: ListItems) => {
|
||||
if (group !== 'matchAll' && listEntries(next).length === 0) setFocusGroup(group);
|
||||
onFieldChange('conditions', { ...groups, [group]: next });
|
||||
};
|
||||
|
||||
const listProps = (group: ConditionGroup): RuleItemListProps => {
|
||||
const type = groupFields[group]?.type;
|
||||
const text = groupText(group);
|
||||
return {
|
||||
name: group,
|
||||
objectName: MAIL_RULE_CONDITION_OBJECT,
|
||||
value: groups[group],
|
||||
onChange: (next) => change(group, next),
|
||||
readOnly,
|
||||
invalid: !!errors.conditions,
|
||||
maxItems: type?.type === 'objectList' ? type.maxItems : undefined,
|
||||
itemLabel: text.item,
|
||||
addLabel: text.add,
|
||||
joiner: text.joiner,
|
||||
};
|
||||
};
|
||||
|
||||
const group = (name: ConditionGroup) => {
|
||||
const text = groupText(name);
|
||||
if (!text.title) {
|
||||
return (
|
||||
<div key={name} className="space-y-2">
|
||||
<Hint>{text.hint}</Hint>
|
||||
<RuleItemList {...listProps(name)} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div key={name} className="space-y-2" role="group" aria-labelledby={`${idPrefix}-${name}-title`}>
|
||||
<div>
|
||||
<h3 id={`${idPrefix}-${name}-title`} className="text-[13px] font-semibold">
|
||||
{text.title}
|
||||
</h3>
|
||||
<Hint>{text.hint}</Hint>
|
||||
</div>
|
||||
<RuleItemList {...listProps(name)} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
const trailing = entries.filter(
|
||||
({ formField }) =>
|
||||
TRAILING_FIELDS.has(formField.name) && (formField.name !== 'timeZone' || hasScheduleCondition(custom)),
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="divide-y divide-border" data-testid="mail-rule-builder">
|
||||
{ruleErrorField && (
|
||||
<div className="py-3">
|
||||
<FieldError id={fieldIds(idPrefix, [ruleErrorField]).errorId} error={errorOf(ruleErrorField)} />
|
||||
</div>
|
||||
)}
|
||||
<Step
|
||||
heading={
|
||||
custom.conditions.length >= 2
|
||||
? t('mailRules.builder.conditions', 'Conditions')
|
||||
: custom.conditions.length === 1
|
||||
? t('mailRules.builder.ifOne', 'If this condition matches')
|
||||
: t('mailRules.builder.ifNone', 'For every message')
|
||||
}
|
||||
title={
|
||||
custom.conditions.length >= 2 && (
|
||||
<span className="flex flex-wrap items-center gap-1.5">
|
||||
{t('mailRules.builder.ifPrefix', 'If')}
|
||||
<MatchModeToggle
|
||||
matchAll={custom.matchAll}
|
||||
onChange={(matchAll) => set('matchAll', matchAll)}
|
||||
readOnly={readOnly}
|
||||
/>
|
||||
{t('mailRules.builder.ifSuffix', 'of these conditions match')}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
>
|
||||
{custom.conditions.length === 0 && (
|
||||
<p className="text-[12.5px] text-muted-foreground">
|
||||
{t('mailRules.builder.noConditions', 'Without conditions the rule applies to every message.')}
|
||||
</p>
|
||||
)}
|
||||
<RuleItemList
|
||||
name="conditions"
|
||||
objectName={MAIL_RULE_CONDITION_OBJECT}
|
||||
value={body.conditions}
|
||||
onChange={(next) => set('conditions', next)}
|
||||
readOnly={readOnly}
|
||||
invalid={!!errors.conditions}
|
||||
{...listBounds(fieldOf('conditions')?.field)}
|
||||
itemLabel={conditionLabel}
|
||||
addLabel={t('mailRules.builder.addCondition', 'Add condition')}
|
||||
/>
|
||||
</Step>
|
||||
<div className="space-y-1" data-testid="mail-rule-builder">
|
||||
<RulePreview body={body} incomplete={needsAction(actions)} />
|
||||
|
||||
<section className="py-3">
|
||||
<button
|
||||
ref={exceptionsButton}
|
||||
type="button"
|
||||
aria-expanded={showExceptions}
|
||||
aria-controls={exceptionsId}
|
||||
onClick={() => setExceptionsExpanded(!showExceptions)}
|
||||
className="flex items-center gap-1.5 rounded-md text-[13.5px] font-semibold focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
<ChevronRight
|
||||
className={cn('size-4 text-dim transition-transform', showExceptions && 'rotate-90')}
|
||||
aria-hidden="true"
|
||||
<div className="divide-y divide-border">
|
||||
<Step number={1} heading={t('mailRules.builder.which', 'Conditions')}>
|
||||
<FieldError
|
||||
id={fieldIds(idPrefix, ['conditions']).errorId}
|
||||
error={conditionsMarked ? undefined : errors.conditions}
|
||||
/>
|
||||
{t('mailRules.builder.except', 'Except if any of these match')}
|
||||
{!showExceptions && custom.exceptions.length > 0 && (
|
||||
<span className="font-normal text-muted-foreground">({custom.exceptions.length})</span>
|
||||
<FieldScopeProvider name="conditions" readOnly={readOnly}>
|
||||
<div className="space-y-5">
|
||||
{group('matchAll')}
|
||||
{OPTIONAL_GROUPS.map((name) => {
|
||||
if (conditions[name].length > 0) return group(name);
|
||||
if (readOnly) return null;
|
||||
const text = groupText(name);
|
||||
return (
|
||||
<div key={name} className="flex flex-wrap items-center gap-x-3 gap-y-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
autoFocus={focusGroup === name}
|
||||
onClick={() => {
|
||||
setFocusGroup(null);
|
||||
change(name, appendItem(groups[name], buildNewObjectValue(schema, MAIL_RULE_CONDITION_OBJECT)));
|
||||
}}
|
||||
>
|
||||
<Plus className="size-4" aria-hidden="true" />
|
||||
{text.add}
|
||||
</Button>
|
||||
<span className="text-[12.5px] text-muted-foreground">{text.addHint}</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</FieldScopeProvider>
|
||||
</Step>
|
||||
|
||||
<Step number={2} heading={t('mailRules.builder.what', 'Actions')}>
|
||||
<FieldError id={fieldIds(idPrefix, ['actions']).errorId} error={actionsMarked ? undefined : errors.actions} />
|
||||
<ActionForm
|
||||
value={body.actions}
|
||||
onChange={(next) => onFieldChange('actions', next)}
|
||||
readOnly={readOnly}
|
||||
invalid={!!errors.actions}
|
||||
/>
|
||||
{actions.stopProcessing && !actions.reject && !hasOtherAction(actions) && (
|
||||
<Hint>
|
||||
{t(
|
||||
'mailRules.builder.onlyStop',
|
||||
'Without other actions, a matching message only stops later rules from running.',
|
||||
)}
|
||||
</Hint>
|
||||
)}
|
||||
</button>
|
||||
{showExceptions && (
|
||||
<div id={exceptionsId} className="mt-2">
|
||||
<RuleItemList
|
||||
name="exceptions"
|
||||
objectName={MAIL_RULE_CONDITION_OBJECT}
|
||||
value={body.exceptions}
|
||||
onChange={changeExceptions}
|
||||
readOnly={readOnly}
|
||||
invalid={!!errors.exceptions}
|
||||
{...listBounds(fieldOf('exceptions')?.field)}
|
||||
itemLabel={exceptionLabel}
|
||||
addLabel={t('mailRules.builder.addException', 'Add exception')}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</Step>
|
||||
|
||||
<Step heading={t('mailRules.builder.then', 'Then')}>
|
||||
<RuleItemList
|
||||
name="actions"
|
||||
objectName={MAIL_RULE_ACTION_OBJECT}
|
||||
value={body.actions}
|
||||
onChange={(next) => set('actions', next)}
|
||||
readOnly={readOnly}
|
||||
invalid={!!errors.actions}
|
||||
{...listBounds(fieldOf('actions')?.field)}
|
||||
canAddMore={!hasReject}
|
||||
itemLabel={actionLabel}
|
||||
addLabel={t('mailRules.builder.addAction', 'Add action')}
|
||||
disabledVariants={disabledActions}
|
||||
/>
|
||||
<FieldError id={actionsErrorId} error={actionsError} />
|
||||
</Step>
|
||||
|
||||
{trailing.length > 0 && (
|
||||
<div className="@container">
|
||||
{trailing.map(({ formField, field }) =>
|
||||
hasReject && formField.name === STOP_PROCESSING ? (
|
||||
<div key={formField.name}>
|
||||
<FieldRow field={field} formField={formField} value={true} onChange={() => {}} readOnly />
|
||||
<p className="pb-3 text-[12.5px] text-muted-foreground">
|
||||
{t('mailRules.builder.rejectStops', 'A rule that rejects mail always stops processing more rules.')}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<FieldRow
|
||||
key={formField.name}
|
||||
field={field}
|
||||
formField={formField}
|
||||
value={body[formField.name]}
|
||||
onChange={(next) => set(formField.name, next)}
|
||||
error={errors[formField.name]}
|
||||
readOnly={readOnly}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<IssueList issues={issues} />
|
||||
<IssueList issues={issues} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -302,7 +281,7 @@ export function RuleSummaryRow({ schema, data }: ViewRenderProps) {
|
||||
const ctx = {
|
||||
t,
|
||||
schema,
|
||||
mailboxName: mailboxes.status === 'ready' ? mailboxNameResolver(mailboxes.options) : undefined,
|
||||
mailboxName: mailboxNamer(t, mailboxes.status === 'ready' ? mailboxes.options : undefined),
|
||||
};
|
||||
return (
|
||||
<ValueRow
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import type { ComponentType } from 'react';
|
||||
import { Markdown } from '@/components/common/Markdown';
|
||||
import { FieldError, FieldLabel, type FieldRowProps } from '@/components/forms/FieldRow';
|
||||
import { fieldIds, useFieldScope, useFormContext } from '@/components/forms/formContext';
|
||||
import { widgetTraits } from '@/extensions/widgets';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
|
||||
interface RuleFieldRowProps extends Omit<FieldRowProps, 'readOnly'> {
|
||||
Edit: ComponentType<WidgetProps>;
|
||||
}
|
||||
|
||||
export function RuleFieldRow({ field, formField, value, onChange, error, Edit }: RuleFieldRowProps) {
|
||||
const { idPrefix } = useFormContext();
|
||||
const { path, readOnly } = useFieldScope();
|
||||
const ids = fieldIds(idPrefix, [...path, formField.name]);
|
||||
const inline = widgetTraits(field.type).layout === 'inline';
|
||||
const describedBy =
|
||||
[field.description ? ids.descriptionId : null, error ? ids.errorId : null].filter(Boolean).join(' ') || undefined;
|
||||
return (
|
||||
<div
|
||||
data-slot="field-row"
|
||||
className={cn('py-4', inline ? 'grid grid-cols-[minmax(0,1fr)_auto] gap-x-8 gap-y-2' : 'field-grid')}
|
||||
>
|
||||
<div className={cn('min-w-0 space-y-1', !inline && '@xl:pt-2')}>
|
||||
<FieldLabel id={ids.labelId} htmlFor={ids.inputId} label={formField.label} marker={null} locked={false} />
|
||||
{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', inline && 'pt-0.5')}>
|
||||
<Edit
|
||||
type={field.type}
|
||||
field={field}
|
||||
formField={formField}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
readOnly={readOnly}
|
||||
control={{ id: ids.inputId, 'aria-invalid': error ? true : undefined, 'aria-describedby': describedBy }}
|
||||
/>
|
||||
<FieldError id={ids.errorId} error={error} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -17,33 +17,32 @@ import { FieldControl } from '@/components/forms/widgets/FieldControl';
|
||||
import { embeddedEntries, resolveEmbedded, switchVariantValues } from '@/lib/embeddedSchema';
|
||||
import { formatList } from '@/lib/format';
|
||||
import { buildEmbeddedDefaults, buildNewObjectValue } from '@/lib/schemaResolver';
|
||||
import { useRuleAccountId } from '../account';
|
||||
import {
|
||||
appendItem,
|
||||
isInlineField,
|
||||
KEYWORD_TEST_SCHEMA,
|
||||
KEYWORDS_FIELD,
|
||||
listEntries,
|
||||
MAILBOX_FIELD,
|
||||
MAILBOX_SCHEMA,
|
||||
removeItem,
|
||||
replaceItem,
|
||||
type ListItems,
|
||||
} from '../builder';
|
||||
import { MailboxPicker } from './MailboxPicker';
|
||||
import { KeywordInput } from './KeywordInput';
|
||||
import { RuleFieldRow } from './RuleFieldRow';
|
||||
|
||||
const NO_MISSING: ReadonlySet<string> = new Set();
|
||||
|
||||
interface RuleItemListProps {
|
||||
export interface RuleItemListProps {
|
||||
name: string;
|
||||
objectName: string;
|
||||
value: unknown;
|
||||
onChange: (value: unknown) => void;
|
||||
onChange: (value: ListItems) => void;
|
||||
readOnly: boolean;
|
||||
invalid: boolean;
|
||||
minItems?: number;
|
||||
maxItems?: number;
|
||||
canAddMore?: boolean;
|
||||
itemLabel: (n: number) => string;
|
||||
addLabel: string;
|
||||
disabledVariants?: ReadonlyMap<string, string>;
|
||||
joiner?: string;
|
||||
}
|
||||
|
||||
interface RuleItemProps {
|
||||
@@ -55,24 +54,13 @@ interface RuleItemProps {
|
||||
onRemove: (() => void) | null;
|
||||
readOnly: boolean;
|
||||
invalid: boolean;
|
||||
disabledVariants?: ReadonlyMap<string, string>;
|
||||
joiner?: string;
|
||||
}
|
||||
|
||||
function RuleItem({
|
||||
objectName,
|
||||
itemKey,
|
||||
item,
|
||||
label,
|
||||
onChange,
|
||||
onRemove,
|
||||
readOnly,
|
||||
invalid,
|
||||
disabledVariants,
|
||||
}: RuleItemProps) {
|
||||
function RuleItem({ objectName, itemKey, item, label, onChange, onRemove, readOnly, invalid, joiner }: RuleItemProps) {
|
||||
const { t } = useTranslation();
|
||||
const { schema, idPrefix, mode, baseline } = useFormContext();
|
||||
const scope = useFieldScope();
|
||||
const accountId = useRuleAccountId();
|
||||
const [initial, setInitial] = useState({ baseline, item });
|
||||
if (initial.baseline !== baseline) setInitial({ baseline, item });
|
||||
const resolved = resolveEmbedded(schema, objectName, item);
|
||||
@@ -96,66 +84,55 @@ function RuleItem({
|
||||
};
|
||||
|
||||
return (
|
||||
<li className="rounded-xl bg-card px-3 py-2.5 shadow-tile" data-testid="mail-rule-item">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Select value={variant} onValueChange={changeVariant} disabled={readOnly}>
|
||||
<SelectTrigger
|
||||
id={fieldIds(idPrefix, [...path, '@type']).inputId}
|
||||
aria-label={label}
|
||||
className="min-w-0 flex-1 gap-2 sm:min-w-56 sm:max-w-sm sm:flex-none"
|
||||
>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{(resolved.variants ?? []).map((option) => {
|
||||
const reason = option.name !== variant ? disabledVariants?.get(option.name) : undefined;
|
||||
return (
|
||||
<SelectItem key={option.name} value={option.name} disabled={!!reason}>
|
||||
{reason ? (
|
||||
<span className="flex flex-col">
|
||||
<span>{option.label}</span>
|
||||
<span className="text-xs text-muted-foreground">{reason}</span>
|
||||
</span>
|
||||
) : (
|
||||
option.label
|
||||
)}
|
||||
</SelectItem>
|
||||
);
|
||||
})}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{inline.map(({ formField, field }) => {
|
||||
const ids = fieldIds(idPrefix, [...path, formField.name]);
|
||||
const fieldValue = item[formField.name];
|
||||
const setValue = (next: unknown) => onChange({ ...item, [formField.name]: next });
|
||||
const isMissing = missing.has(formField.name);
|
||||
const control = {
|
||||
id: ids.inputId,
|
||||
'aria-label': `${label}: ${formField.label}`,
|
||||
'aria-invalid': isMissing || undefined,
|
||||
'aria-describedby': isMissing ? itemErrorId : undefined,
|
||||
};
|
||||
const isMailbox = schemaName === MAILBOX_SCHEMA && formField.name === MAILBOX_FIELD;
|
||||
return (
|
||||
<div
|
||||
key={formField.name}
|
||||
className="order-2 flex min-w-0 flex-1 basis-full items-center gap-2 sm:order-none sm:basis-40"
|
||||
<li data-testid="mail-rule-item">
|
||||
{joiner && (
|
||||
<p className="py-0.5 pl-3 text-[11.5px] font-semibold uppercase tracking-wide text-muted-foreground">
|
||||
{joiner}
|
||||
</p>
|
||||
)}
|
||||
<div className="rounded-xl bg-card px-3 py-2.5 shadow-tile">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Select value={variant} onValueChange={changeVariant} disabled={readOnly}>
|
||||
<SelectTrigger
|
||||
id={fieldIds(idPrefix, [...path, '@type']).inputId}
|
||||
aria-label={label}
|
||||
className="min-w-0 flex-1 gap-2 sm:min-w-56 sm:max-w-sm sm:flex-none"
|
||||
>
|
||||
{!isMailbox && field.type.type !== 'enum' && (
|
||||
<label htmlFor={ids.inputId} className="shrink-0 text-[12.5px] text-muted-foreground">
|
||||
{formField.label}
|
||||
</label>
|
||||
)}
|
||||
<div className="min-w-0 flex-1">
|
||||
{isMailbox ? (
|
||||
<MailboxPicker
|
||||
accountId={accountId}
|
||||
value={fieldValue}
|
||||
onChange={setValue}
|
||||
readOnly={readOnly}
|
||||
control={control}
|
||||
/>
|
||||
) : (
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{(resolved.variants ?? []).map((option) => (
|
||||
<SelectItem key={option.name} value={option.name}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{inline.map(({ formField, field }) => {
|
||||
const ids = fieldIds(idPrefix, [...path, formField.name]);
|
||||
const fieldValue = item[formField.name];
|
||||
const setValue = (next: unknown) => onChange({ ...item, [formField.name]: next });
|
||||
const isMissing = missing.has(formField.name);
|
||||
const control = {
|
||||
id: ids.inputId,
|
||||
'aria-label': t('mailRules.builder.itemField', '{{item}}: {{field}}', {
|
||||
item: label,
|
||||
field: formField.label,
|
||||
}),
|
||||
'aria-invalid': isMissing || undefined,
|
||||
'aria-describedby': isMissing ? itemErrorId : undefined,
|
||||
};
|
||||
return (
|
||||
<div
|
||||
key={formField.name}
|
||||
className="order-2 flex min-w-0 flex-1 basis-full items-center gap-2 sm:order-none sm:basis-40"
|
||||
>
|
||||
{field.type.type !== 'enum' && (
|
||||
<label htmlFor={ids.inputId} className="shrink-0 text-[12.5px] text-muted-foreground">
|
||||
{formField.label}
|
||||
</label>
|
||||
)}
|
||||
<div className="min-w-0 flex-1">
|
||||
<FieldScopeProvider name={itemKey} readOnly={readOnly}>
|
||||
<FieldControl
|
||||
type={field.type}
|
||||
@@ -167,52 +144,56 @@ function RuleItem({
|
||||
control={control}
|
||||
/>
|
||||
</FieldScopeProvider>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{onRemove && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost-danger"
|
||||
size="icon-sm"
|
||||
className="order-1 ml-auto shrink-0 sm:order-none"
|
||||
onClick={onRemove}
|
||||
aria-label={t('mailRules.removeItem', 'Remove {{label}}', { label })}
|
||||
>
|
||||
<Trash2 className="size-4" aria-hidden="true" />
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
{onRemove && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost-danger"
|
||||
size="icon-sm"
|
||||
className="order-1 ml-auto shrink-0 sm:order-none"
|
||||
onClick={onRemove}
|
||||
aria-label={t('mailRules.removeItem', 'Remove {{label}}', { label })}
|
||||
>
|
||||
<Trash2 className="size-4" aria-hidden="true" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{missingInline.length > 0 && (
|
||||
<div className="mt-1.5">
|
||||
<FieldError
|
||||
id={itemErrorId}
|
||||
error={t('mailRules.builder.missingFields', 'Fill in {{fields}}.', {
|
||||
fields: formatList(missingInline.map(({ formField }) => formField.label)),
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{block.length > 0 && (
|
||||
<FieldScopeProvider name={itemKey} readOnly={readOnly}>
|
||||
<EnclosingSchemaContext value={resolved.schemaName}>
|
||||
<div className="@container mt-1 divide-y divide-border [&>[data-slot=field-row]]:py-3">
|
||||
{block.map(({ formField, field }) => {
|
||||
const row = {
|
||||
field,
|
||||
formField,
|
||||
value: item[formField.name],
|
||||
onChange: (next: unknown) => onChange({ ...item, [formField.name]: next }),
|
||||
error: missing.has(formField.name) ? requiredMessage : undefined,
|
||||
};
|
||||
return schemaName === KEYWORD_TEST_SCHEMA && formField.name === KEYWORDS_FIELD ? (
|
||||
<RuleFieldRow key={formField.name} {...row} Edit={KeywordInput} />
|
||||
) : (
|
||||
<FieldRow key={formField.name} {...row} />
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</EnclosingSchemaContext>
|
||||
</FieldScopeProvider>
|
||||
)}
|
||||
</div>
|
||||
{missingInline.length > 0 && (
|
||||
<div className="mt-1.5">
|
||||
<FieldError
|
||||
id={itemErrorId}
|
||||
error={t('mailRules.builder.missingFields', 'Fill in {{fields}}.', {
|
||||
fields: formatList(missingInline.map(({ formField }) => formField.label)),
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{block.length > 0 && (
|
||||
<FieldScopeProvider name={itemKey} readOnly={readOnly}>
|
||||
<EnclosingSchemaContext value={resolved.schemaName}>
|
||||
<div className="@container mt-1 divide-y divide-border [&>[data-slot=field-row]]:py-3">
|
||||
{block.map(({ formField, field }) => (
|
||||
<FieldRow
|
||||
key={formField.name}
|
||||
field={field}
|
||||
formField={formField}
|
||||
value={item[formField.name]}
|
||||
onChange={(next) => onChange({ ...item, [formField.name]: next })}
|
||||
error={missing.has(formField.name) ? requiredMessage : undefined}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</EnclosingSchemaContext>
|
||||
</FieldScopeProvider>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
@@ -224,33 +205,30 @@ export function RuleItemList({
|
||||
onChange,
|
||||
readOnly,
|
||||
invalid,
|
||||
minItems,
|
||||
maxItems,
|
||||
canAddMore = true,
|
||||
itemLabel,
|
||||
addLabel,
|
||||
disabledVariants,
|
||||
joiner,
|
||||
}: RuleItemListProps) {
|
||||
const { schema } = useFormContext();
|
||||
const entries = listEntries(value);
|
||||
const canRemove = !readOnly && (minItems == null || entries.length > minItems);
|
||||
const canAdd = !readOnly && canAddMore && (maxItems == null || entries.length < maxItems);
|
||||
const canAdd = !readOnly && (maxItems == null || entries.length < maxItems);
|
||||
return (
|
||||
<FieldScopeProvider name={name} readOnly={readOnly}>
|
||||
{entries.length > 0 && (
|
||||
<ol className="space-y-2">
|
||||
<ol className="space-y-1">
|
||||
{entries.map(([key, item], index) => (
|
||||
<RuleItem
|
||||
key={key}
|
||||
joiner={index > 0 ? joiner : undefined}
|
||||
objectName={objectName}
|
||||
itemKey={key}
|
||||
item={item}
|
||||
label={itemLabel(index + 1)}
|
||||
onChange={(next) => onChange(replaceItem(value, key, next))}
|
||||
onRemove={canRemove ? () => onChange(removeItem(value, key)) : null}
|
||||
onRemove={readOnly ? null : () => onChange(removeItem(value, key))}
|
||||
readOnly={readOnly}
|
||||
invalid={invalid}
|
||||
disabledVariants={disabledVariants}
|
||||
/>
|
||||
))}
|
||||
</ol>
|
||||
|
||||
@@ -4,10 +4,14 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import type { TFunction } from 'i18next';
|
||||
import type { JmapObject } from '@/services/jmap/client';
|
||||
|
||||
export const MAILBOX_PROPERTIES = ['id', 'name', 'parentId', 'role', 'sortOrder'];
|
||||
|
||||
const TRASH_MAILBOX_ID = 'b';
|
||||
const JUNK_MAILBOX_ID = 'c';
|
||||
|
||||
export interface MailboxOption {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -73,3 +77,15 @@ export function mailboxNameResolver(options: readonly MailboxOption[]): (id: str
|
||||
const byId = new Map(options.map((option) => [option.id, option.path.join(' / ')]));
|
||||
return (id) => byId.get(id);
|
||||
}
|
||||
|
||||
export function fallbackMailboxName(t: TFunction, id: string): string {
|
||||
if (id === TRASH_MAILBOX_ID) return t('mailRules.trashMailbox', 'Trash');
|
||||
if (id === JUNK_MAILBOX_ID) return t('mailRules.junkMailbox', 'Junk');
|
||||
return id;
|
||||
}
|
||||
|
||||
export function mailboxNamer(t: TFunction, options: readonly MailboxOption[] | undefined): (id: string) => string {
|
||||
if (!options) return (id) => fallbackMailboxName(t, id);
|
||||
const known = mailboxNameResolver(options);
|
||||
return (id) => known(id) ?? t('mailRules.unknownMailbox', 'Unknown mailbox ({{id}})', { id });
|
||||
}
|
||||
+128
-56
@@ -11,7 +11,8 @@ import type { JmapObject } from '@/services/jmap/client';
|
||||
|
||||
export const MAIL_RULE_OBJECT = 'x:MailRule';
|
||||
export const MAIL_RULE_CONDITION_OBJECT = 'x:MailRuleCondition';
|
||||
export const MAIL_RULE_ACTION_OBJECT = 'x:MailRuleAction';
|
||||
export const MAIL_RULE_CONDITIONS_OBJECT = 'x:MailRuleConditions';
|
||||
export const MAIL_RULE_ACTIONS_OBJECT = 'x:MailRuleActions';
|
||||
|
||||
const FORWARD_PERMISSIONS = ['jmapSieveScriptCreate', 'jmapSieveScriptUpdate', 'sievePutScript'] as const;
|
||||
|
||||
@@ -23,21 +24,43 @@ export interface MailRule {
|
||||
body: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface CustomRuleBody {
|
||||
matchAll: boolean;
|
||||
conditions: Record<string, unknown>[];
|
||||
exceptions: Record<string, unknown>[];
|
||||
actions: Record<string, unknown>[];
|
||||
export type ConditionGroup = 'matchAll' | 'matchAny' | 'matchNone';
|
||||
|
||||
export type RuleConditions = Record<ConditionGroup, Record<string, unknown>[]>;
|
||||
|
||||
export interface RuleActions {
|
||||
addKeywords: string[];
|
||||
removeKeywords: string[];
|
||||
clearKeywords: boolean;
|
||||
setImportance: string | null;
|
||||
redirect: Record<string, unknown> | null;
|
||||
reply: Record<string, unknown> | null;
|
||||
copyTo: string[];
|
||||
moveTo: string[];
|
||||
discard: boolean;
|
||||
reject: Record<string, unknown> | null;
|
||||
stopProcessing: boolean;
|
||||
timeZone: string | null;
|
||||
}
|
||||
|
||||
export type RuleIssue =
|
||||
'rejectNotAlone' | 'rejectNeedsAuthentication' | 'forwardingNotAllowed' | 'scheduleTooManySlots';
|
||||
export interface CustomRuleBody {
|
||||
conditions: RuleConditions;
|
||||
actions: RuleActions;
|
||||
}
|
||||
|
||||
export const MAX_SCHEDULE_SLOTS = 14;
|
||||
const SCHEDULE_CONDITION = 'Schedule';
|
||||
export const REJECT_ACTION = 'Reject';
|
||||
export type KeywordSet = 'addKeywords' | 'removeKeywords';
|
||||
|
||||
export const FLAG_ACTIONS = {
|
||||
markRead: { set: 'addKeywords', keyword: '$seen' },
|
||||
flag: { set: 'addKeywords', keyword: '$flagged' },
|
||||
clearFlag: { set: 'removeKeywords', keyword: '$flagged' },
|
||||
markNotJunk: { set: 'addKeywords', keyword: '$notjunk' },
|
||||
} as const satisfies Record<string, { set: KeywordSet; keyword: string }>;
|
||||
|
||||
export type FlagAction = keyof typeof FLAG_ACTIONS;
|
||||
|
||||
export type RuleIssue = 'rejectNotAlone' | 'keywordConflict' | 'forwardingNotAllowed' | 'sizeInvalid';
|
||||
|
||||
export const MAX_SIZE_KB = 2 ** 32;
|
||||
|
||||
export function variantType(value: unknown): string | null {
|
||||
if (!isRecord(value)) return null;
|
||||
@@ -147,57 +170,108 @@ export function reorderPositions(
|
||||
return changes;
|
||||
}
|
||||
|
||||
export function parseCustomBody(body: Record<string, unknown>): CustomRuleBody {
|
||||
const list = (value: unknown) => jmapMapToArray<unknown>(value).filter(isRecord);
|
||||
const conditions = list(body.conditions);
|
||||
export function newRuleValues(position: number): JmapObject {
|
||||
return {
|
||||
matchAll: conditions.length < 2 || body.matchAll !== false,
|
||||
conditions,
|
||||
exceptions: list(body.exceptions),
|
||||
actions: list(body.actions),
|
||||
stopProcessing: body.stopProcessing === true,
|
||||
timeZone: typeof body.timeZone === 'string' && body.timeZone !== '' ? body.timeZone : null,
|
||||
position,
|
||||
conditions: { matchAll: {}, matchAny: {}, matchNone: {} },
|
||||
actions: {
|
||||
addKeywords: {},
|
||||
removeKeywords: {},
|
||||
clearKeywords: false,
|
||||
setImportance: null,
|
||||
redirect: null,
|
||||
reply: null,
|
||||
copyTo: {},
|
||||
moveTo: {},
|
||||
discard: false,
|
||||
reject: null,
|
||||
stopProcessing: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function hasVariant(items: readonly Record<string, unknown>[], type: string): boolean {
|
||||
return items.some((item) => variantType(item) === type);
|
||||
function parseConditions(value: unknown): RuleConditions {
|
||||
const groups = isRecord(value) ? value : {};
|
||||
const list = (group: ConditionGroup) => jmapMapToArray<unknown>(groups[group]).filter(isRecord);
|
||||
return { matchAll: list('matchAll'), matchAny: list('matchAny'), matchNone: list('matchNone') };
|
||||
}
|
||||
|
||||
export function hasScheduleCondition(custom: CustomRuleBody): boolean {
|
||||
return hasVariant(custom.conditions, SCHEDULE_CONDITION) || hasVariant(custom.exceptions, SCHEDULE_CONDITION);
|
||||
export function parseActions(value: unknown): RuleActions {
|
||||
const actions = isRecord(value) ? value : {};
|
||||
const { setImportance, redirect, reply, reject } = actions;
|
||||
return {
|
||||
addKeywords: setValues(actions.addKeywords),
|
||||
removeKeywords: setValues(actions.removeKeywords),
|
||||
clearKeywords: actions.clearKeywords === true,
|
||||
setImportance: typeof setImportance === 'string' && setImportance !== '' ? setImportance : null,
|
||||
redirect: isRecord(redirect) ? redirect : null,
|
||||
reply: isRecord(reply) ? reply : null,
|
||||
copyTo: setValues(actions.copyTo),
|
||||
moveTo: setValues(actions.moveTo),
|
||||
discard: actions.discard === true,
|
||||
reject: isRecord(reject) ? reject : null,
|
||||
stopProcessing: actions.stopProcessing === true,
|
||||
};
|
||||
}
|
||||
|
||||
export function mergedScheduleOverflow(items: readonly Record<string, unknown>[]): boolean {
|
||||
let run = 0;
|
||||
for (const item of items) {
|
||||
if (variantType(item) !== SCHEDULE_CONDITION) {
|
||||
run = 0;
|
||||
continue;
|
||||
}
|
||||
run += jmapMapToArray<unknown>(item.slots).length;
|
||||
if (run > MAX_SCHEDULE_SLOTS) return true;
|
||||
export function parseCustomBody(body: Record<string, unknown>): CustomRuleBody {
|
||||
return { conditions: parseConditions(body.conditions), actions: parseActions(body.actions) };
|
||||
}
|
||||
|
||||
export function hasFlag(actions: RuleActions, flag: FlagAction): boolean {
|
||||
const { set, keyword } = FLAG_ACTIONS[flag];
|
||||
return actions[set].includes(keyword);
|
||||
}
|
||||
|
||||
export function otherKeywords(actions: RuleActions, set: KeywordSet): string[] {
|
||||
const flags = new Set<string>();
|
||||
for (const action of Object.values(FLAG_ACTIONS)) {
|
||||
if (action.set === set) flags.add(action.keyword);
|
||||
}
|
||||
return false;
|
||||
return actions[set].filter((keyword) => !flags.has(keyword));
|
||||
}
|
||||
|
||||
export function hasRejectAction(custom: CustomRuleBody): boolean {
|
||||
return hasVariant(custom.actions, REJECT_ACTION);
|
||||
}
|
||||
|
||||
export function isRejectAllowed(custom: CustomRuleBody): boolean {
|
||||
return custom.matchAll && hasVariant(custom.conditions, 'SenderAuthenticated');
|
||||
}
|
||||
|
||||
function redirectTargets(custom: CustomRuleBody): number {
|
||||
return custom.actions.reduce(
|
||||
(total, action) => total + (variantType(action) === 'Redirect' ? setValues(action.addresses).length : 0),
|
||||
0,
|
||||
export function hasOtherAction(actions: RuleActions): boolean {
|
||||
return (
|
||||
actions.addKeywords.length > 0 ||
|
||||
actions.removeKeywords.length > 0 ||
|
||||
actions.clearKeywords ||
|
||||
actions.setImportance !== null ||
|
||||
actions.redirect !== null ||
|
||||
actions.reply !== null ||
|
||||
actions.copyTo.length > 0 ||
|
||||
actions.moveTo.length > 0 ||
|
||||
actions.discard
|
||||
);
|
||||
}
|
||||
|
||||
export function needsAction(actions: RuleActions): boolean {
|
||||
return !actions.stopProcessing && actions.reject === null && !hasOtherAction(actions);
|
||||
}
|
||||
|
||||
export function isEveryMessageReply(reply: Record<string, unknown> | null): boolean {
|
||||
return reply?.days === 0;
|
||||
}
|
||||
|
||||
function hasKeywordConflict(actions: RuleActions): boolean {
|
||||
const removed = new Set(actions.removeKeywords);
|
||||
return actions.addKeywords.some((keyword) => removed.has(keyword));
|
||||
}
|
||||
|
||||
export function sizeIssue(condition: Record<string, unknown>): RuleIssue | null {
|
||||
const type = variantType(condition);
|
||||
if (type !== 'SizeOver' && type !== 'SizeUnder') return null;
|
||||
const { kilobytes } = condition;
|
||||
if (typeof kilobytes !== 'number' || !Number.isFinite(kilobytes)) return null;
|
||||
return kilobytes < 1 || kilobytes > MAX_SIZE_KB ? 'sizeInvalid' : null;
|
||||
}
|
||||
|
||||
function redirectTargets(actions: RuleActions): number {
|
||||
return setValues(actions.redirect?.addresses).length;
|
||||
}
|
||||
|
||||
export function forwardingTargets(body: Record<string, unknown>): number {
|
||||
return redirectTargets(parseCustomBody(body));
|
||||
return redirectTargets(parseActions(body.actions));
|
||||
}
|
||||
|
||||
export function canForward(checkers: Pick<PermissionCheckers, 'hasPermission'>): boolean {
|
||||
@@ -209,15 +283,13 @@ export function ruleIssues(
|
||||
checkers: Pick<PermissionCheckers, 'hasPermission'>,
|
||||
): RuleIssue[] {
|
||||
const issues: RuleIssue[] = [];
|
||||
const custom = parseCustomBody(rule.body);
|
||||
if (hasRejectAction(custom)) {
|
||||
if (custom.actions.length > 1) issues.push('rejectNotAlone');
|
||||
if (!isRejectAllowed(custom)) issues.push('rejectNeedsAuthentication');
|
||||
const { conditions, actions } = parseCustomBody(rule.body);
|
||||
if (actions.reject && hasOtherAction(actions)) issues.push('rejectNotAlone');
|
||||
if (hasKeywordConflict(actions)) issues.push('keywordConflict');
|
||||
if (Object.values(conditions).some((items) => items.some((condition) => sizeIssue(condition) !== null))) {
|
||||
issues.push('sizeInvalid');
|
||||
}
|
||||
if (mergedScheduleOverflow(custom.exceptions) || (!custom.matchAll && mergedScheduleOverflow(custom.conditions))) {
|
||||
issues.push('scheduleTooManySlots');
|
||||
}
|
||||
if (rule.isEnabled && redirectTargets(custom) > 0 && !canForward(checkers)) {
|
||||
if (rule.isEnabled && redirectTargets(actions) > 0 && !canForward(checkers)) {
|
||||
issues.push('forwardingNotAllowed');
|
||||
}
|
||||
return issues;
|
||||
|
||||
@@ -18,13 +18,18 @@ import { MINUTES_PER_DAY, localTimeFromMinutes, parseLocalTime } from '@/lib/loc
|
||||
import { jmapMapToArray } from '@/lib/jmapUtils';
|
||||
import { getEnumVariant } from '@/lib/schemaResolver';
|
||||
import type { Schema } from '@/types/schema';
|
||||
import { fallbackMailboxName } from './mailboxes';
|
||||
import {
|
||||
MAIL_RULE_ACTION_OBJECT,
|
||||
hasFlag,
|
||||
isEveryMessageReply,
|
||||
MAIL_RULE_CONDITION_OBJECT,
|
||||
MAX_SCHEDULE_SLOTS,
|
||||
MAX_SIZE_KB,
|
||||
otherKeywords,
|
||||
parseCustomBody,
|
||||
setValues,
|
||||
variantType,
|
||||
type FlagAction,
|
||||
type RuleActions,
|
||||
type RuleIssue,
|
||||
} from './model';
|
||||
|
||||
@@ -37,13 +42,75 @@ export interface SummaryContext {
|
||||
}
|
||||
|
||||
export interface RuleSummary {
|
||||
conditions: string[];
|
||||
matchAll: boolean;
|
||||
exceptions: string[];
|
||||
matchAll: string[];
|
||||
matchAny: string[];
|
||||
matchNone: string[];
|
||||
actions: string[];
|
||||
stopProcessing: boolean;
|
||||
}
|
||||
|
||||
export function actionLabel(t: TFunction, action: FlagAction | keyof RuleActions): string {
|
||||
switch (action) {
|
||||
case 'markRead':
|
||||
return t('mailRules.action.markRead', 'Mark as read');
|
||||
case 'flag':
|
||||
return t('mailRules.action.flag', 'Flag');
|
||||
case 'clearFlag':
|
||||
return t('mailRules.action.clearFlag', 'Clear the flag');
|
||||
case 'markNotJunk':
|
||||
return t('mailRules.action.markNotJunk', 'Mark as not spam');
|
||||
case 'addKeywords':
|
||||
return t('mailRules.action.addKeywords', 'Add keywords');
|
||||
case 'removeKeywords':
|
||||
return t('mailRules.action.removeKeywords', 'Remove keywords');
|
||||
case 'clearKeywords':
|
||||
return t('mailRules.action.clearKeywords', 'Remove all keywords added by earlier rules');
|
||||
case 'setImportance':
|
||||
return t('mailRules.action.setImportance', 'Set the importance');
|
||||
case 'redirect':
|
||||
return t('mailRules.action.redirect', 'Redirect to other addresses');
|
||||
case 'reply':
|
||||
return t('mailRules.action.reply', 'Reply with a template');
|
||||
case 'copyTo':
|
||||
return t('mailRules.action.copyTo', 'Copy to');
|
||||
case 'moveTo':
|
||||
return t('mailRules.action.moveTo', 'Move to');
|
||||
case 'discard':
|
||||
return t('mailRules.action.discard', 'Delete permanently');
|
||||
case 'reject':
|
||||
return t('mailRules.action.reject', 'Reject with a message');
|
||||
case 'stopProcessing':
|
||||
return t('mailRules.action.stopProcessing', 'Stop processing more rules');
|
||||
}
|
||||
}
|
||||
|
||||
export function keywordName(t: TFunction, keyword: string): string | undefined {
|
||||
switch (keyword) {
|
||||
case '$seen':
|
||||
return t('mailRules.keyword.seen', 'Read');
|
||||
case '$flagged':
|
||||
return t('mailRules.keyword.flagged', 'Flagged');
|
||||
case '$answered':
|
||||
return t('mailRules.keyword.answered', 'Replied');
|
||||
case '$forwarded':
|
||||
return t('mailRules.keyword.forwarded', 'Forwarded');
|
||||
case '$draft':
|
||||
return t('mailRules.keyword.draft', 'Draft');
|
||||
case '$deleted':
|
||||
return t('mailRules.keyword.deleted', 'Marked for deletion');
|
||||
case '$important':
|
||||
return t('mailRules.keyword.important', 'Important');
|
||||
case '$junk':
|
||||
return t('mailRules.keyword.junk', 'Spam');
|
||||
case '$notjunk':
|
||||
return t('mailRules.keyword.notJunk', 'Not spam');
|
||||
case '$phishing':
|
||||
return t('mailRules.keyword.phishing', 'Phishing');
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function enumLabel(schema: Schema, enumName: string, value: unknown): string {
|
||||
if (typeof value !== 'string') return '';
|
||||
return getEnumVariant(schema, enumName, value)?.label ?? value;
|
||||
@@ -53,13 +120,61 @@ function quoted(ctx: SummaryContext, value: string): string {
|
||||
return ctx.t('mailRules.summary.quoted', '“{{value}}”', { value });
|
||||
}
|
||||
|
||||
function quotedValues(ctx: SummaryContext, value: unknown): string {
|
||||
function quotedValues(
|
||||
ctx: SummaryContext,
|
||||
values: readonly string[],
|
||||
type: 'conjunction' | 'disjunction' = 'disjunction',
|
||||
): string {
|
||||
return formatList(
|
||||
setValues(value).map((item) => quoted(ctx, item)),
|
||||
'disjunction',
|
||||
values.map((value) => quoted(ctx, value)),
|
||||
type,
|
||||
);
|
||||
}
|
||||
|
||||
function quotedKeywords(
|
||||
ctx: SummaryContext,
|
||||
keywords: readonly string[],
|
||||
type: 'conjunction' | 'disjunction' = 'disjunction',
|
||||
): string {
|
||||
return quotedValues(
|
||||
ctx,
|
||||
keywords.map((keyword) => keywordName(ctx.t, keyword) ?? keyword),
|
||||
type,
|
||||
);
|
||||
}
|
||||
|
||||
function sizeOf(value: unknown): string | null {
|
||||
return typeof value === 'number' ? formatSize(value * KILOBYTE) : null;
|
||||
}
|
||||
|
||||
function replyPhrase(ctx: SummaryContext, reply: Record<string, unknown>): string {
|
||||
const { t } = ctx;
|
||||
const subject = typeof reply.subject === 'string' && reply.subject ? quoted(ctx, reply.subject) : '';
|
||||
if (isEveryMessageReply(reply)) {
|
||||
return subject
|
||||
? t('mailRules.summary.action.replySubjectEveryMessage', 'reply with {{subject}} to every message', { subject })
|
||||
: t('mailRules.summary.action.replyEveryMessage', 'reply to every message');
|
||||
}
|
||||
if (typeof reply.days !== 'number') {
|
||||
return subject
|
||||
? t('mailRules.summary.action.replySubject', 'reply with {{subject}}', { subject })
|
||||
: t('mailRules.summary.action.reply', 'reply with a template');
|
||||
}
|
||||
const count = reply.days;
|
||||
return subject
|
||||
? t('mailRules.summary.action.replySubjectDays', {
|
||||
subject,
|
||||
count,
|
||||
defaultValue_one: 'reply with {{subject}} at most once a day per sender',
|
||||
defaultValue_other: 'reply with {{subject}} at most once every {{count}} days per sender',
|
||||
})
|
||||
: t('mailRules.summary.action.replyDays', {
|
||||
count,
|
||||
defaultValue_one: 'reply at most once a day per sender',
|
||||
defaultValue_other: 'reply at most once every {{count}} days per sender',
|
||||
});
|
||||
}
|
||||
|
||||
function detailed(ctx: SummaryContext, label: string, detail: string): string {
|
||||
if (detail === '') return label;
|
||||
return ctx.t('mailRules.summary.detail', '{{label}}: {{detail}}', { label, detail });
|
||||
@@ -68,7 +183,7 @@ function detailed(ctx: SummaryContext, label: string, detail: string): string {
|
||||
function operatorTest(ctx: SummaryContext, enumName: string, item: Record<string, unknown>): string {
|
||||
return ctx.t('mailRules.summary.test', '{{operator}} {{values}}', {
|
||||
operator: enumLabel(ctx.schema, enumName, item.operator),
|
||||
values: quotedValues(ctx, item.values),
|
||||
values: quotedValues(ctx, setValues(item.values)),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -91,7 +206,7 @@ function scheduleSlots(ctx: SummaryContext, value: unknown): string {
|
||||
end: slotEnd(slot.end),
|
||||
}),
|
||||
);
|
||||
return slots.join('; ');
|
||||
return formatList(slots, 'unit');
|
||||
}
|
||||
|
||||
export function conditionPhrase(ctx: SummaryContext, condition: Record<string, unknown>): string {
|
||||
@@ -123,11 +238,9 @@ export function conditionPhrase(ctx: SummaryContext, condition: Record<string, u
|
||||
return detailed(ctx, label, enumLabel(ctx.schema, 'MailRuleSentToMePlacement', condition.placement));
|
||||
case 'SizeOver':
|
||||
case 'SizeUnder':
|
||||
return detailed(
|
||||
ctx,
|
||||
label,
|
||||
typeof condition.kilobytes === 'number' ? formatSize(condition.kilobytes * KILOBYTE) : '',
|
||||
);
|
||||
return detailed(ctx, label, sizeOf(condition.kilobytes) ?? '');
|
||||
case 'Keyword':
|
||||
return detailed(ctx, label, quotedKeywords(ctx, setValues(condition.keywords)));
|
||||
case 'Importance':
|
||||
return detailed(ctx, label, enumLabel(ctx.schema, 'MailRuleImportanceLevel', condition.level));
|
||||
case 'Sensitivity':
|
||||
@@ -146,95 +259,247 @@ export function conditionPhrase(ctx: SummaryContext, condition: Record<string, u
|
||||
}
|
||||
}
|
||||
|
||||
function mailboxPhrase(ctx: SummaryContext, value: unknown): string {
|
||||
if (typeof value !== 'string' || value === '') return '';
|
||||
return quoted(ctx, ctx.mailboxName?.(value) ?? value);
|
||||
function mailboxNames(ctx: SummaryContext, ids: readonly string[]): string {
|
||||
return quotedValues(
|
||||
ctx,
|
||||
ids.map((id) => ctx.mailboxName?.(id) ?? fallbackMailboxName(ctx.t, id)),
|
||||
'conjunction',
|
||||
);
|
||||
}
|
||||
|
||||
export function actionPhrase(ctx: SummaryContext, action: Record<string, unknown>): string {
|
||||
const type = variantType(action) ?? '';
|
||||
const label = variantLabel(ctx.schema, MAIL_RULE_ACTION_OBJECT, type) ?? type;
|
||||
switch (type) {
|
||||
case 'MoveTo':
|
||||
case 'CopyTo':
|
||||
return detailed(ctx, label, mailboxPhrase(ctx, action.mailboxId));
|
||||
case 'AddKeywords':
|
||||
return detailed(ctx, label, quotedValues(ctx, action.keywords));
|
||||
case 'Redirect': {
|
||||
const addresses = formatList(setValues(action.addresses));
|
||||
const detail =
|
||||
action.keepCopy === false
|
||||
? ctx.t('mailRules.summary.withoutCopy', '{{addresses}} without keeping a copy', { addresses })
|
||||
: addresses;
|
||||
return detailed(ctx, label, detail);
|
||||
}
|
||||
case 'SetImportance':
|
||||
return detailed(ctx, label, enumLabel(ctx.schema, 'MailRuleImportanceLevel', action.level));
|
||||
case 'Reply':
|
||||
return detailed(
|
||||
ctx,
|
||||
label,
|
||||
typeof action.subject === 'string' && action.subject ? quoted(ctx, action.subject) : '',
|
||||
);
|
||||
case 'Reject':
|
||||
return detailed(ctx, label, typeof action.reason === 'string' && action.reason ? quoted(ctx, action.reason) : '');
|
||||
default:
|
||||
return label;
|
||||
export function actionPhrases(ctx: SummaryContext, actions: RuleActions): string[] {
|
||||
const { t } = ctx;
|
||||
const phrases: string[] = [];
|
||||
const keywords = (list: readonly string[]) => ({
|
||||
count: list.length,
|
||||
keywords: quotedKeywords(ctx, list, 'conjunction'),
|
||||
});
|
||||
|
||||
if (actions.clearKeywords) {
|
||||
phrases.push(t('mailRules.summary.action.clearKeywords', 'remove all keywords added by earlier rules'));
|
||||
}
|
||||
if (hasFlag(actions, 'clearFlag')) phrases.push(t('mailRules.summary.action.clearFlag', 'clear the flag'));
|
||||
const removed = otherKeywords(actions, 'removeKeywords');
|
||||
if (removed.length > 0) {
|
||||
phrases.push(
|
||||
t('mailRules.summary.action.removeKeywords', {
|
||||
...keywords(removed),
|
||||
defaultValue_one: 'remove the keyword {{keywords}}',
|
||||
defaultValue_other: 'remove the keywords {{keywords}}',
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (hasFlag(actions, 'markRead')) phrases.push(t('mailRules.summary.action.markRead', 'mark it as read'));
|
||||
if (hasFlag(actions, 'flag')) phrases.push(t('mailRules.summary.action.flag', 'flag it'));
|
||||
if (hasFlag(actions, 'markNotJunk')) phrases.push(t('mailRules.summary.action.markNotJunk', 'mark it as not spam'));
|
||||
const added = otherKeywords(actions, 'addKeywords');
|
||||
if (added.length > 0) {
|
||||
phrases.push(
|
||||
t('mailRules.summary.action.addKeywords', {
|
||||
...keywords(added),
|
||||
defaultValue_one: 'add the keyword {{keywords}}',
|
||||
defaultValue_other: 'add the keywords {{keywords}}',
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (actions.setImportance !== null) {
|
||||
phrases.push(
|
||||
t('mailRules.summary.action.setImportance', 'set the importance to {{level}}', {
|
||||
level: enumLabel(ctx.schema, 'MailRuleImportanceLevel', actions.setImportance),
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (actions.redirect) {
|
||||
const addresses = formatList(setValues(actions.redirect.addresses));
|
||||
phrases.push(
|
||||
actions.redirect.keepCopy === false
|
||||
? t('mailRules.summary.action.redirectWithoutCopy', 'redirect to {{addresses}} without keeping a copy', {
|
||||
addresses,
|
||||
})
|
||||
: t('mailRules.summary.action.redirect', 'redirect to {{addresses}}', { addresses }),
|
||||
);
|
||||
}
|
||||
if (actions.reply) phrases.push(replyPhrase(ctx, actions.reply));
|
||||
if (actions.copyTo.length > 0) {
|
||||
phrases.push(
|
||||
t('mailRules.summary.action.copyTo', 'copy it to {{mailboxes}}', {
|
||||
mailboxes: mailboxNames(ctx, actions.copyTo),
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (actions.moveTo.length > 0) {
|
||||
phrases.push(
|
||||
t('mailRules.summary.action.moveTo', 'move it to {{mailboxes}}', {
|
||||
mailboxes: mailboxNames(ctx, actions.moveTo),
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (actions.discard) phrases.push(t('mailRules.summary.action.discard', 'delete it permanently'));
|
||||
if (actions.reject) {
|
||||
const { reason } = actions.reject;
|
||||
phrases.push(
|
||||
typeof reason === 'string' && reason
|
||||
? t('mailRules.summary.action.rejectReason', 'reject it with {{reason}}', { reason: quoted(ctx, reason) })
|
||||
: t('mailRules.summary.action.reject', 'reject it'),
|
||||
);
|
||||
}
|
||||
return phrases;
|
||||
}
|
||||
|
||||
export function summarizeCustomRule(ctx: SummaryContext, body: Record<string, unknown>): RuleSummary {
|
||||
const custom = parseCustomBody(body);
|
||||
const { conditions, actions } = parseCustomBody(body);
|
||||
const phrase = (condition: Record<string, unknown>) => conditionPhrase(ctx, condition);
|
||||
return {
|
||||
conditions: custom.conditions.map((condition) => conditionPhrase(ctx, condition)),
|
||||
matchAll: custom.matchAll,
|
||||
exceptions: custom.exceptions.map((condition) => conditionPhrase(ctx, condition)),
|
||||
actions: custom.actions.map((action) => actionPhrase(ctx, action)),
|
||||
stopProcessing: custom.stopProcessing,
|
||||
matchAll: conditions.matchAll.map(phrase),
|
||||
matchAny: conditions.matchAny.map(phrase),
|
||||
matchNone: conditions.matchNone.map(phrase),
|
||||
actions: actionPhrases(ctx, actions),
|
||||
stopProcessing: actions.stopProcessing || actions.reject !== null,
|
||||
};
|
||||
}
|
||||
|
||||
export function ruleSentence(ctx: SummaryContext, summary: RuleSummary): string {
|
||||
const { t } = ctx;
|
||||
let when =
|
||||
summary.conditions.length === 0
|
||||
? t('mailRules.summary.always', 'For every message')
|
||||
: t('mailRules.summary.if', 'If {{conditions}}', {
|
||||
conditions: formatList(summary.conditions, summary.matchAll ? 'conjunction' : 'disjunction'),
|
||||
});
|
||||
if (summary.exceptions.length > 0) {
|
||||
when = t('mailRules.summary.except', '{{when}}, except if {{exceptions}}', {
|
||||
when,
|
||||
exceptions: formatList(summary.exceptions, 'disjunction'),
|
||||
type SentenceOpening = 'always' | 'if';
|
||||
type SentenceEnding = 'then' | 'thenStop' | 'onlyStop' | 'nothing';
|
||||
|
||||
type SentenceValues = {
|
||||
conditions: string;
|
||||
exceptions: string;
|
||||
actions: string;
|
||||
};
|
||||
|
||||
function conditionsClause(t: TFunction, { matchAll, matchAny }: RuleSummary): string {
|
||||
if (matchAll.length > 0 && matchAny.length > 1) {
|
||||
return t('mailRules.summary.allAndAny', '{{all}}, and either {{any}}', {
|
||||
all: formatList(matchAll),
|
||||
any: formatList(matchAny, 'disjunction'),
|
||||
});
|
||||
}
|
||||
const actions =
|
||||
summary.actions.length === 0 ? t('mailRules.summary.noActions', 'do nothing') : formatList(summary.actions);
|
||||
const then = summary.stopProcessing
|
||||
? t('mailRules.summary.thenStop', 'then {{actions}} and stop processing more rules', { actions })
|
||||
: t('mailRules.summary.then', 'then {{actions}}', { actions });
|
||||
return t('mailRules.summary.sentence', '{{when}}, {{then}}.', { when, then });
|
||||
return matchAll.length > 0 ? formatList([...matchAll, ...matchAny]) : formatList(matchAny, 'disjunction');
|
||||
}
|
||||
|
||||
function sentence(
|
||||
t: TFunction,
|
||||
opening: SentenceOpening,
|
||||
except: boolean,
|
||||
ending: SentenceEnding,
|
||||
values: SentenceValues,
|
||||
): string {
|
||||
switch (`${opening}${except ? 'Except' : ''}_${ending}` as const) {
|
||||
case 'always_then':
|
||||
return t('mailRules.summary.rule.always_then', 'For every message, then {{actions}}.', values);
|
||||
case 'always_thenStop':
|
||||
return t(
|
||||
'mailRules.summary.rule.always_thenStop',
|
||||
'For every message, then {{actions}}, and stop processing more rules.',
|
||||
values,
|
||||
);
|
||||
case 'always_onlyStop':
|
||||
return t('mailRules.summary.rule.always_onlyStop', 'For every message, then stop processing more rules.', values);
|
||||
case 'always_nothing':
|
||||
return t('mailRules.summary.rule.always_nothing', 'For every message, then do nothing.', values);
|
||||
case 'alwaysExcept_then':
|
||||
return t(
|
||||
'mailRules.summary.rule.alwaysExcept_then',
|
||||
'For every message, except if {{exceptions}}, then {{actions}}.',
|
||||
values,
|
||||
);
|
||||
case 'alwaysExcept_thenStop':
|
||||
return t(
|
||||
'mailRules.summary.rule.alwaysExcept_thenStop',
|
||||
'For every message, except if {{exceptions}}, then {{actions}}, and stop processing more rules.',
|
||||
values,
|
||||
);
|
||||
case 'alwaysExcept_onlyStop':
|
||||
return t(
|
||||
'mailRules.summary.rule.alwaysExcept_onlyStop',
|
||||
'For every message, except if {{exceptions}}, then stop processing more rules.',
|
||||
values,
|
||||
);
|
||||
case 'alwaysExcept_nothing':
|
||||
return t(
|
||||
'mailRules.summary.rule.alwaysExcept_nothing',
|
||||
'For every message, except if {{exceptions}}, then do nothing.',
|
||||
values,
|
||||
);
|
||||
case 'if_then':
|
||||
return t('mailRules.summary.rule.if_then', 'If {{conditions}}, then {{actions}}.', values);
|
||||
case 'if_thenStop':
|
||||
return t(
|
||||
'mailRules.summary.rule.if_thenStop',
|
||||
'If {{conditions}}, then {{actions}}, and stop processing more rules.',
|
||||
values,
|
||||
);
|
||||
case 'if_onlyStop':
|
||||
return t('mailRules.summary.rule.if_onlyStop', 'If {{conditions}}, then stop processing more rules.', values);
|
||||
case 'if_nothing':
|
||||
return t('mailRules.summary.rule.if_nothing', 'If {{conditions}}, then do nothing.', values);
|
||||
case 'ifExcept_then':
|
||||
return t(
|
||||
'mailRules.summary.rule.ifExcept_then',
|
||||
'If {{conditions}}, except if {{exceptions}}, then {{actions}}.',
|
||||
values,
|
||||
);
|
||||
case 'ifExcept_thenStop':
|
||||
return t(
|
||||
'mailRules.summary.rule.ifExcept_thenStop',
|
||||
'If {{conditions}}, except if {{exceptions}}, then {{actions}}, and stop processing more rules.',
|
||||
values,
|
||||
);
|
||||
case 'ifExcept_onlyStop':
|
||||
return t(
|
||||
'mailRules.summary.rule.ifExcept_onlyStop',
|
||||
'If {{conditions}}, except if {{exceptions}}, then stop processing more rules.',
|
||||
values,
|
||||
);
|
||||
case 'ifExcept_nothing':
|
||||
return t(
|
||||
'mailRules.summary.rule.ifExcept_nothing',
|
||||
'If {{conditions}}, except if {{exceptions}}, then do nothing.',
|
||||
values,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function ruleSentence(ctx: SummaryContext, summary: RuleSummary): string {
|
||||
const hasActions = summary.actions.length > 0;
|
||||
const ending: SentenceEnding = summary.stopProcessing
|
||||
? hasActions
|
||||
? 'thenStop'
|
||||
: 'onlyStop'
|
||||
: hasActions
|
||||
? 'then'
|
||||
: 'nothing';
|
||||
return sentence(
|
||||
ctx.t,
|
||||
summary.matchAll.length > 0 || summary.matchAny.length > 0 ? 'if' : 'always',
|
||||
summary.matchNone.length > 0,
|
||||
ending,
|
||||
{
|
||||
conditions: conditionsClause(ctx.t, summary),
|
||||
exceptions: formatList(summary.matchNone, 'disjunction'),
|
||||
actions: formatList(summary.actions),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export function actionRequiredMessage(t: TFunction): string {
|
||||
return t('mailRules.builder.actionRequired', 'Add at least one action, or stop processing more rules.');
|
||||
}
|
||||
|
||||
export function ruleIssueMessage(t: TFunction, issue: RuleIssue): string {
|
||||
switch (issue) {
|
||||
case 'rejectNotAlone':
|
||||
return t('mailRules.issue.rejectNotAlone', 'A rule that rejects mail cannot have other actions.');
|
||||
case 'rejectNeedsAuthentication':
|
||||
return t(
|
||||
'mailRules.issue.rejectNeedsAuthentication',
|
||||
'A rule that rejects mail must match all conditions and require an authenticated sender.',
|
||||
);
|
||||
case 'keywordConflict':
|
||||
return t('mailRules.issue.keywordConflict', 'A rule cannot both add and remove the same keyword.');
|
||||
case 'forwardingNotAllowed':
|
||||
return t(
|
||||
'mailRules.issue.forwardingNotAllowed',
|
||||
'Your account is not allowed to forward mail, so this rule cannot be saved while it is enabled.',
|
||||
);
|
||||
case 'scheduleTooManySlots':
|
||||
return t(
|
||||
'mailRules.issue.scheduleTooManySlots',
|
||||
'Adjacent schedule conditions are combined into one, which can have at most {{max}} time slots.',
|
||||
{ max: MAX_SCHEDULE_SLOTS },
|
||||
);
|
||||
case 'sizeInvalid':
|
||||
return t('mailRules.issue.sizeInvalid', 'A size must be at least 1 KB and at most {{max}}.', {
|
||||
max: formatSize(MAX_SIZE_KB * KILOBYTE),
|
||||
});
|
||||
}
|
||||
}
|
||||
+126
-27
@@ -151,6 +151,11 @@
|
||||
"viewDetails": "View details",
|
||||
"waiting": "Waiting for more events"
|
||||
},
|
||||
"destroyContents": {
|
||||
"AddressBook": "Every contact in it is deleted too.",
|
||||
"Calendar": "Every event in it is deleted too.",
|
||||
"Mailbox": "Every message in it is deleted too."
|
||||
},
|
||||
"duration": {
|
||||
"days": "Days",
|
||||
"hours": "Hours",
|
||||
@@ -517,20 +522,58 @@
|
||||
"detail": "{{label}}: {{detail}}",
|
||||
"test": "{{operator}} {{values}}",
|
||||
"slot": "{{days}} {{start}}–{{end}}",
|
||||
"withoutCopy": "{{addresses}} without keeping a copy",
|
||||
"always": "For every message",
|
||||
"if": "If {{conditions}}",
|
||||
"except": "{{when}}, except if {{exceptions}}",
|
||||
"noActions": "do nothing",
|
||||
"then": "then {{actions}}",
|
||||
"thenStop": "then {{actions}} and stop processing more rules",
|
||||
"sentence": "{{when}}, {{then}}."
|
||||
"allAndAny": "{{all}}, and either {{any}}",
|
||||
"rule": {
|
||||
"always_then": "For every message, then {{actions}}.",
|
||||
"always_thenStop": "For every message, then {{actions}}, and stop processing more rules.",
|
||||
"always_onlyStop": "For every message, then stop processing more rules.",
|
||||
"always_nothing": "For every message, then do nothing.",
|
||||
"alwaysExcept_then": "For every message, except if {{exceptions}}, then {{actions}}.",
|
||||
"alwaysExcept_thenStop": "For every message, except if {{exceptions}}, then {{actions}}, and stop processing more rules.",
|
||||
"alwaysExcept_onlyStop": "For every message, except if {{exceptions}}, then stop processing more rules.",
|
||||
"alwaysExcept_nothing": "For every message, except if {{exceptions}}, then do nothing.",
|
||||
"if_then": "If {{conditions}}, then {{actions}}.",
|
||||
"if_thenStop": "If {{conditions}}, then {{actions}}, and stop processing more rules.",
|
||||
"if_onlyStop": "If {{conditions}}, then stop processing more rules.",
|
||||
"if_nothing": "If {{conditions}}, then do nothing.",
|
||||
"ifExcept_then": "If {{conditions}}, except if {{exceptions}}, then {{actions}}.",
|
||||
"ifExcept_thenStop": "If {{conditions}}, except if {{exceptions}}, then {{actions}}, and stop processing more rules.",
|
||||
"ifExcept_onlyStop": "If {{conditions}}, except if {{exceptions}}, then stop processing more rules.",
|
||||
"ifExcept_nothing": "If {{conditions}}, except if {{exceptions}}, then do nothing."
|
||||
},
|
||||
"action": {
|
||||
"clearKeywords": "remove all keywords added by earlier rules",
|
||||
"clearFlag": "clear the flag",
|
||||
"removeKeywords_one": "remove the keyword {{keywords}}",
|
||||
"removeKeywords_other": "remove the keywords {{keywords}}",
|
||||
"markRead": "mark it as read",
|
||||
"flag": "flag it",
|
||||
"markNotJunk": "mark it as not spam",
|
||||
"addKeywords_one": "add the keyword {{keywords}}",
|
||||
"addKeywords_other": "add the keywords {{keywords}}",
|
||||
"setImportance": "set the importance to {{level}}",
|
||||
"redirect": "redirect to {{addresses}}",
|
||||
"redirectWithoutCopy": "redirect to {{addresses}} without keeping a copy",
|
||||
"reply": "reply with a template",
|
||||
"replySubject": "reply with {{subject}}",
|
||||
"replyEveryMessage": "reply to every message",
|
||||
"replySubjectEveryMessage": "reply with {{subject}} to every message",
|
||||
"replyDays_one": "reply at most once a day per sender",
|
||||
"replyDays_other": "reply at most once every {{count}} days per sender",
|
||||
"replySubjectDays_one": "reply with {{subject}} at most once a day per sender",
|
||||
"replySubjectDays_other": "reply with {{subject}} at most once every {{count}} days per sender",
|
||||
"copyTo": "copy it to {{mailboxes}}",
|
||||
"moveTo": "move it to {{mailboxes}}",
|
||||
"discard": "delete it permanently",
|
||||
"reject": "reject it",
|
||||
"rejectReason": "reject it with {{reason}}"
|
||||
}
|
||||
},
|
||||
"issue": {
|
||||
"rejectNotAlone": "A rule that rejects mail cannot have other actions.",
|
||||
"rejectNeedsAuthentication": "A rule that rejects mail must match all conditions and require an authenticated sender.",
|
||||
"forwardingNotAllowed": "Your account is not allowed to forward mail, so this rule cannot be saved while it is enabled.",
|
||||
"scheduleTooManySlots": "Adjacent schedule conditions are combined into one, which can have at most {{max}} time slots."
|
||||
"sizeInvalid": "A size must be at least 1 KB and at most {{max}}.",
|
||||
"keywordConflict": "A rule cannot both add and remove the same keyword."
|
||||
},
|
||||
"loadFailed": "Failed to load the mail rules.",
|
||||
"enableRule": "Enable {{name}}",
|
||||
@@ -558,30 +601,86 @@
|
||||
"chooseMailbox": "Choose a mailbox",
|
||||
"unknownMailbox": "Unknown mailbox ({{id}})",
|
||||
"builder": {
|
||||
"all": "all",
|
||||
"any": "any",
|
||||
"matchMode": "Conditions that must match",
|
||||
"rejectNeedsAuthentication": "Reject needs all conditions to match, including an authenticated sender.",
|
||||
"conditionN": "Condition {{n}}",
|
||||
"exceptionN": "Exception {{n}}",
|
||||
"actionN": "Action {{n}}",
|
||||
"ifPrefix": "If",
|
||||
"ifSuffix": "of these conditions match",
|
||||
"ifOne": "If this condition matches",
|
||||
"ifNone": "For every message",
|
||||
"noConditions": "Without conditions the rule applies to every message.",
|
||||
"noConditions": "No conditions: the rule applies to every message.",
|
||||
"addCondition": "Add condition",
|
||||
"except": "Except if any of these match",
|
||||
"addException": "Add exception",
|
||||
"then": "Then",
|
||||
"addAction": "Add action",
|
||||
"conditions": "Conditions",
|
||||
"rejectNotAlone": "Reject must be the only action.",
|
||||
"rejectStops": "A rule that rejects mail always stops processing more rules.",
|
||||
"actionRequired": "Add at least one action.",
|
||||
"missingFields": "Fill in {{fields}}."
|
||||
"actionRequired": "Add at least one action, or stop processing more rules.",
|
||||
"missingFields": "Fill in {{fields}}.",
|
||||
"replyEveryMessage": "With 0 days between replies, every message gets a reply.",
|
||||
"onlyStop": "Without other actions, a matching message only stops later rules from running.",
|
||||
"moveToHint": "Moving to Junk also marks the message as spam.",
|
||||
"markNotJunkHint": "Keeps the message out of Junk.",
|
||||
"keywordsToAdd": "Keywords to add",
|
||||
"keywordsToRemove": "Keywords to remove",
|
||||
"discardHint": "The message does not go to Trash.",
|
||||
"rejectHint": "Reject must be the only action. The sender is told only when their address can be verified; otherwise the message is deleted without notice.",
|
||||
"alternativeN": "Alternative {{n}}",
|
||||
"addAlternative": "Add alternative",
|
||||
"which": "Conditions",
|
||||
"what": "Actions",
|
||||
"conditionsHint": "A message must match every condition.",
|
||||
"alternatives": "Alternatives",
|
||||
"alternativesHint": "A message must match at least one alternative.",
|
||||
"alternativesHintAnd": "A message must also match at least one alternative.",
|
||||
"addAlternativeHint": "Match one of several conditions, such as two senders.",
|
||||
"exceptions": "Exceptions",
|
||||
"exceptionsHint": "The rule skips a message that matches any exception.",
|
||||
"addExceptionHint": "Skip messages that would otherwise match.",
|
||||
"and": "and",
|
||||
"or": "or",
|
||||
"preview": "Summary",
|
||||
"previewIncomplete": "Nothing yet: choose what to do with matching messages.",
|
||||
"whenItRuns": "Rules run on new mail as it arrives. Saving does not change messages already in your mailboxes.",
|
||||
"noActions": "No actions yet. Choose at least one below.",
|
||||
"noActionsReadOnly": "No actions.",
|
||||
"addAction": "Add an action",
|
||||
"addAnotherAction": "Add another action",
|
||||
"stopHint": "Rules below this one in the list are skipped for matching messages.",
|
||||
"group": {
|
||||
"file": "File",
|
||||
"mark": "Mark",
|
||||
"answer": "Answer",
|
||||
"remove": "Delete"
|
||||
},
|
||||
"itemField": "{{item}}: {{field}}"
|
||||
},
|
||||
"removeItem": "Remove {{label}}"
|
||||
"removeItem": "Remove {{label}}",
|
||||
"action": {
|
||||
"markRead": "Mark as read",
|
||||
"flag": "Flag",
|
||||
"clearFlag": "Clear the flag",
|
||||
"markNotJunk": "Mark as not spam",
|
||||
"addKeywords": "Add keywords",
|
||||
"removeKeywords": "Remove keywords",
|
||||
"clearKeywords": "Remove all keywords added by earlier rules",
|
||||
"setImportance": "Set the importance",
|
||||
"redirect": "Redirect to other addresses",
|
||||
"reply": "Reply with a template",
|
||||
"copyTo": "Copy to",
|
||||
"moveTo": "Move to",
|
||||
"discard": "Delete permanently",
|
||||
"reject": "Reject with a message",
|
||||
"stopProcessing": "Stop processing more rules"
|
||||
},
|
||||
"keyword": {
|
||||
"seen": "Read",
|
||||
"flagged": "Flagged",
|
||||
"answered": "Replied",
|
||||
"forwarded": "Forwarded",
|
||||
"draft": "Draft",
|
||||
"deleted": "Marked for deletion",
|
||||
"important": "Important",
|
||||
"junk": "Spam",
|
||||
"notJunk": "Not spam",
|
||||
"phishing": "Phishing"
|
||||
},
|
||||
"trashMailbox": "Trash",
|
||||
"junkMailbox": "Junk",
|
||||
"addMailbox": "Add another mailbox"
|
||||
},
|
||||
"schedule": {
|
||||
"add": "Add interval",
|
||||
|
||||
+4
-4
@@ -80,8 +80,8 @@
|
||||
--shadow-c2: rgb(62 44 26 / 0.05);
|
||||
--hi: rgb(255 255 255 / 0);
|
||||
|
||||
--chart-1: #db2d54;
|
||||
--chart-2: #2a9d8f;
|
||||
--chart-1: #2a9d8f;
|
||||
--chart-2: #db2d54;
|
||||
--chart-3: #d9822b;
|
||||
--chart-4: #4a3f8f;
|
||||
--chart-5: #8b7e6e;
|
||||
@@ -153,8 +153,8 @@
|
||||
--shadow-c2: rgb(0 0 0 / 0.3);
|
||||
--hi: rgb(255 255 255 / 0.045);
|
||||
|
||||
--chart-1: #ff5c7f;
|
||||
--chart-2: #4cc3b3;
|
||||
--chart-1: #4cc3b3;
|
||||
--chart-2: #ff5c7f;
|
||||
--chart-3: #f0a35a;
|
||||
--chart-4: #a99bf0;
|
||||
--chart-5: #9e9ea4;
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import i18n from '@/i18n';
|
||||
|
||||
export function destroyContentsNotice(objectName: string): string | null {
|
||||
switch (objectName) {
|
||||
case 'Mailbox':
|
||||
return i18n.t('destroyContents.Mailbox', 'Every message in it is deleted too.');
|
||||
case 'Calendar':
|
||||
return i18n.t('destroyContents.Calendar', 'Every event in it is deleted too.');
|
||||
case 'AddressBook':
|
||||
return i18n.t('destroyContents.AddressBook', 'Every contact in it is deleted too.');
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function withDestroyContentsNotice(description: string, objectName: string): string {
|
||||
const notice = destroyContentsNotice(objectName);
|
||||
return notice ? `${description} ${notice}` : description;
|
||||
}
|
||||
+4
-1
@@ -235,7 +235,10 @@ export function localeClock(): LocaleClock {
|
||||
|
||||
const listFormats = new Map<string, Intl.ListFormat>();
|
||||
|
||||
export function formatList(items: readonly string[], type: 'conjunction' | 'disjunction' = 'conjunction'): string {
|
||||
export function formatList(
|
||||
items: readonly string[],
|
||||
type: 'conjunction' | 'disjunction' | 'unit' = 'conjunction',
|
||||
): string {
|
||||
const locale = getFormatLocale();
|
||||
const key = `${locale}|${type}`;
|
||||
let fmt = listFormats.get(key);
|
||||
|
||||
@@ -224,7 +224,6 @@ export async function startAuthFlow(username: string, returnUrl?: string | null)
|
||||
code_challenge_method: codeChallengeMethod,
|
||||
state,
|
||||
login_hint: username,
|
||||
prompt: 'login',
|
||||
});
|
||||
|
||||
const scope = selectScopes(discovery);
|
||||
|
||||
@@ -168,11 +168,21 @@ export function jmapQuery(
|
||||
return jmapCall<JmapQueryResponse>(`${objectType}/query`, args, options.signal);
|
||||
}
|
||||
|
||||
const DESTROY_CONTENTS_ARGS: ReadonlyMap<string, string> = new Map([
|
||||
['Mailbox', 'onDestroyRemoveEmails'],
|
||||
['Calendar', 'onDestroyRemoveEvents'],
|
||||
['AddressBook', 'onDestroyRemoveContents'],
|
||||
]);
|
||||
|
||||
export function jmapSetArgs(objectType: string, set: JmapSetOptions, accountId?: string): Record<string, unknown> {
|
||||
const args: Record<string, unknown> = { accountId: accountId ?? getAccountId(objectType) };
|
||||
if (set.create && Object.keys(set.create).length > 0) args.create = set.create;
|
||||
if (set.update && Object.keys(set.update).length > 0) args.update = set.update;
|
||||
if (set.destroy && set.destroy.length > 0) args.destroy = set.destroy;
|
||||
if (set.destroy && set.destroy.length > 0) {
|
||||
args.destroy = set.destroy;
|
||||
const destroyContents = DESTROY_CONTENTS_ARGS.get(objectType);
|
||||
if (destroyContents) args[destroyContents] = true;
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user