commit 80fa7b96286b7a00791c4b7ea42af408f4ea548a Author: Tizian 「ティツィアーン」 Date: Sun Oct 18 21:46:55 2026 +0200 Halkyon's shared packages A pub workspace of the Dart packages Halkyon's apps share: halkyon_ui, Halkyon's look (the theme, fonts, layout and shared widgets, with texts in English and German), halkyon_core's low-level primitives and halkyon_interop's cross-app contracts. Dart 3.13 with LeanCode's lints, configured once at the root; apps take a package by git, pinned to a signed commit. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Tizian 「ティツィアーン」 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..dd5eb98 --- /dev/null +++ b/.gitignore @@ -0,0 +1,31 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. +/pubspec.lock +**/doc/api/ +.dart_tool/ +.flutter-plugins-dependencies +/build/ +/coverage/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..63becf7 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,19 @@ +# Contributing to halkyon_shared + +Thanks for your interest in contributing. + +## License + +By contributing, you agree that your contributions will be licensed under +AGPL-3.0-or-later. See LICENSE. + +## Developer Certificate of Origin + +All commits must be signed off per the Developer Certificate of Origin. +Add `-s` to your git commit command, or set `git config format.signoff true`. + +## Pull requests + +- Target `main`. +- Keep PRs focused. +- Tests must pass in CI. \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..8e085dc --- /dev/null +++ b/LICENSE @@ -0,0 +1,235 @@ +GNU AFFERO GENERAL PUBLIC LICENSE +Version 3, 19 November 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + + Preamble + +The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. + +A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. + +The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. + +An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. + +The precise terms and conditions for copying, distribution and modification follow. + + TERMS AND CONDITIONS + +0. Definitions. + +"This License" refers to version 3 of the GNU Affero General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based on the Program. + +To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +1. Source Code. +The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. + +A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". + + c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. + +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + + a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. + + d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + +"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or authors of the material; or + + e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. + +All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +8. Termination. + +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +11. Patents. + +A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + +13. Remote Network Interaction; Use with the GNU General Public License. + +Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. + +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. + +14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. + + halkyon_shared + Copyright (C) 2026 project_halkyon + + This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. + +You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . diff --git a/README.md b/README.md new file mode 100644 index 0000000..9e595f5 --- /dev/null +++ b/README.md @@ -0,0 +1,18 @@ +# halkyon_shared + +Shared Dart packages across Halkyon apps, a pub workspace: + +- [`halkyon_ui`](packages/halkyon_ui): Halkyon's look, the theme, fonts, layout + and shared widgets (Flutter). +- [`halkyon_core`](packages/halkyon_core): low-level primitives (pure Dart). +- [`halkyon_interop`](packages/halkyon_interop): cross-app contracts (pure Dart). + +Dart 3.13 and Flutter 3.47, with LeanCode's lints (`leancode_lint`), configured +once in `analysis_options.yaml` here, which every package includes: its +analyzer plugin only reaches packages of a workspace from the root. Run +`flutter pub get` and `dart analyze --fatal-infos` here, and each package's +tests in its folder (`dart test`, or `flutter test` for `halkyon_ui` and its +example). + +Apps take a package by git, pinned to a signed commit; see +[`halkyon_ui`'s README](packages/halkyon_ui/README.md). diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..365234d --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,8 @@ +# Security Policy + +Please report security issues by email to security@halkyon.eu. +Do not open public issues for security vulnerabilities. + +We will acknowledge receipt within 72 hours and work to resolve +confirmed issues within a reasonable timeframe, coordinating disclosure +with the reporter. \ No newline at end of file diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..6a49755 --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,12 @@ +# Lint rules for the whole pub workspace, as the Halkyon apps have them: LeanCode's +# strict set (leancode_lint), which raises most rules to warnings and turns on strict +# casts, inference and raw types, plus its analyzer plugin with rules for blocs, +# Equatable and Flutter layout. +# +# Analyzer plugins can only be enabled here, at the root of a pub workspace, and they +# only apply to packages whose analysis_options.yaml includes this file. Every package +# here includes it. +include: package:leancode_lint/analysis_options.yaml + +plugins: + leancode_lint: ^27.0.0 diff --git a/packages/halkyon_core/.gitignore b/packages/halkyon_core/.gitignore new file mode 100644 index 0000000..dd5eb98 --- /dev/null +++ b/packages/halkyon_core/.gitignore @@ -0,0 +1,31 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. +/pubspec.lock +**/doc/api/ +.dart_tool/ +.flutter-plugins-dependencies +/build/ +/coverage/ diff --git a/packages/halkyon_core/.metadata b/packages/halkyon_core/.metadata new file mode 100644 index 0000000..4449ab3 --- /dev/null +++ b/packages/halkyon_core/.metadata @@ -0,0 +1,10 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "cc0734ac716fbb8b90f3f9db8020958b1553afa7" + channel: "stable" + +project_type: package diff --git a/packages/halkyon_core/CHANGELOG.md b/packages/halkyon_core/CHANGELOG.md new file mode 100644 index 0000000..41cc7d8 --- /dev/null +++ b/packages/halkyon_core/CHANGELOG.md @@ -0,0 +1,3 @@ +## 0.0.1 + +* TODO: Describe initial release. diff --git a/packages/halkyon_core/LICENSE b/packages/halkyon_core/LICENSE new file mode 100644 index 0000000..ba75c69 --- /dev/null +++ b/packages/halkyon_core/LICENSE @@ -0,0 +1 @@ +TODO: Add your license here. diff --git a/packages/halkyon_core/README.md b/packages/halkyon_core/README.md new file mode 100644 index 0000000..4a260d8 --- /dev/null +++ b/packages/halkyon_core/README.md @@ -0,0 +1,39 @@ + + +TODO: Put a short description of the package here that helps potential users +know whether this package might be useful for them. + +## Features + +TODO: List what your package can do. Maybe include images, gifs, or videos. + +## Getting started + +TODO: List prerequisites and provide or point to information on how to +start using the package. + +## Usage + +TODO: Include short and useful examples for package users. Add longer examples +to `/example` folder. + +```dart +const like = 'sample'; +``` + +## Additional information + +TODO: Tell users more about the package: where to find more information, how to +contribute to the package, how to file issues, what response they can expect +from the package authors, and more. diff --git a/packages/halkyon_core/analysis_options.yaml b/packages/halkyon_core/analysis_options.yaml new file mode 100644 index 0000000..6b029ec --- /dev/null +++ b/packages/halkyon_core/analysis_options.yaml @@ -0,0 +1,2 @@ +# The workspace's lint rules (see ../../analysis_options.yaml). +include: ../../analysis_options.yaml diff --git a/packages/halkyon_core/lib/halkyon_core.dart b/packages/halkyon_core/lib/halkyon_core.dart new file mode 100644 index 0000000..e55e132 --- /dev/null +++ b/packages/halkyon_core/lib/halkyon_core.dart @@ -0,0 +1,17 @@ +/// Low-level primitives shared across Halkyon apps. +/// +/// This package is pure Dart and has no Flutter dependency. It provides: +/// - A re-export of `package:clock`'s `Clock` for testable time access. +/// - A thin `generateUuid` wrapper for v4 UUID generation. +/// - A `Logger` interface and basic `ConsoleLogger` implementation. +/// - The optional `HalkyonException` marker interface. +library; + +// Re-export the clock package directly. Halkyon apps depend on `Clock` for +// testable time access; re-exporting here means they get it via halkyon_core +// without needing a separate `clock` dependency. +export 'package:clock/clock.dart' show Clock, clock; + +export 'src/exceptions.dart'; +export 'src/logger.dart'; +export 'src/uuid.dart'; diff --git a/packages/halkyon_core/lib/src/exceptions.dart b/packages/halkyon_core/lib/src/exceptions.dart new file mode 100644 index 0000000..0767299 --- /dev/null +++ b/packages/halkyon_core/lib/src/exceptions.dart @@ -0,0 +1,11 @@ +/// Marker interface for exceptions originating in Halkyon code. +/// +/// Implementing this is optional. It exists so callers can distinguish +/// "this came from Halkyon" from "this came from a library we use" using +/// `on HalkyonException catch (e)` if they want that granularity. +/// +/// Most Halkyon exceptions should also extend a more specific type +/// (e.g., `AuthException`, `SyncException`) defined in the relevant feature. +abstract class HalkyonException() implements Exception { + String get message; +} diff --git a/packages/halkyon_core/lib/src/logger.dart b/packages/halkyon_core/lib/src/logger.dart new file mode 100644 index 0000000..6dfd12a --- /dev/null +++ b/packages/halkyon_core/lib/src/logger.dart @@ -0,0 +1,54 @@ +/// Severity levels for log messages. +enum LogLevel() { + debug, + info, + warning, + error, +} + +/// A minimal logging interface. +/// +/// Implementations are injected via the app's `Dependencies` composition root +/// rather than imported globally, so tests can swap in fakes. +abstract interface class Logger() { + void log( + LogLevel level, + String message, { + Object? error, + StackTrace? stackTrace, + }); +} + +/// A logger that writes to stdout. Suitable for development and tests. +/// +/// Production apps should use a logger that forwards to Sentry or similar, +/// configured at the composition root. +class const ConsoleLogger() implements Logger { + @override + void log( + LogLevel level, + String message, { + Object? error, + StackTrace? stackTrace, + }) { + final prefix = switch (level) { + LogLevel.debug => '[DEBUG]', + LogLevel.info => '[INFO]', + LogLevel.warning => '[WARN]', + LogLevel.error => '[ERROR]', + }; + // Writing to stdout is this logger's whole purpose. + // ignore: avoid_print + print('$prefix $message'); + if (error != null) { + // As above: stdout is where this logger writes. + // ignore: avoid_print + print(' error: $error'); + } + if (stackTrace != null) { + // As above: stdout is where this logger writes. + // ignore: avoid_print + print(' stack: $stackTrace'); + } + } +} diff --git a/packages/halkyon_core/lib/src/uuid.dart b/packages/halkyon_core/lib/src/uuid.dart new file mode 100644 index 0000000..98de1a9 --- /dev/null +++ b/packages/halkyon_core/lib/src/uuid.dart @@ -0,0 +1,10 @@ +import 'package:uuid/uuid.dart'; + +const _uuid = Uuid(); + +/// Generates a v4 (random) UUID as a lowercase hyphenated string. +/// +/// Thin wrapper over `package:uuid` so Halkyon code doesn't need to import +/// it directly. If we ever need to swap the UUID library, this is the only +/// site that changes. +String generateUuid() => _uuid.v4(); diff --git a/packages/halkyon_core/pubspec.yaml b/packages/halkyon_core/pubspec.yaml new file mode 100644 index 0000000..0df91da --- /dev/null +++ b/packages/halkyon_core/pubspec.yaml @@ -0,0 +1,15 @@ +name: halkyon_core +description: "Low-level primitives shared across Halkyon apps. Pure Dart, no Flutter." +version: 0.0.1 +publish_to: none +resolution: workspace + +environment: + sdk: ^3.13.0 + +dependencies: + clock: ^1.1.1 + uuid: ^4.5.0 + +dev_dependencies: + test: ^1.25.0 diff --git a/packages/halkyon_core/test/halkyon_core_test.dart b/packages/halkyon_core/test/halkyon_core_test.dart new file mode 100644 index 0000000..663bab1 --- /dev/null +++ b/packages/halkyon_core/test/halkyon_core_test.dart @@ -0,0 +1,52 @@ +import 'package:halkyon_core/halkyon_core.dart'; +import 'package:test/test.dart'; + +void main() { + group('generateUuid', () { + test('produces a non-empty string', () { + expect(generateUuid(), isNotEmpty); + }); + + test('produces a valid v4 UUID format', () { + // v4 UUID: 8-4-4-4-12 hex characters, with version 4 in the third group. + final uuid = generateUuid(); + expect( + uuid, + matches( + RegExp( + r'^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$', + ), + ), + ); + }); + + test('produces different values on successive calls', () { + final a = generateUuid(); + final b = generateUuid(); + expect(a, isNot(equals(b))); + }); + }); + + group('ConsoleLogger', () { + test('can be instantiated as const', () { + const logger = ConsoleLogger(); + expect(logger, isA()); + }); + + // Note: we don't test that ConsoleLogger actually prints, because + // capturing stdout in tests is fragile and the implementation is trivial. + // If we add structured logging later, we'll test that more carefully. + }); + + group('HalkyonException', () { + test('is implementable', () { + final ex = _TestException('boom'); + expect(ex, isA()); + expect(ex, isA()); + expect(ex.message, equals('boom')); + }); + }); +} + +class _TestException(@override final String message) + implements HalkyonException; diff --git a/packages/halkyon_interop/.gitignore b/packages/halkyon_interop/.gitignore new file mode 100644 index 0000000..dd5eb98 --- /dev/null +++ b/packages/halkyon_interop/.gitignore @@ -0,0 +1,31 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. +/pubspec.lock +**/doc/api/ +.dart_tool/ +.flutter-plugins-dependencies +/build/ +/coverage/ diff --git a/packages/halkyon_interop/.metadata b/packages/halkyon_interop/.metadata new file mode 100644 index 0000000..4449ab3 --- /dev/null +++ b/packages/halkyon_interop/.metadata @@ -0,0 +1,10 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "cc0734ac716fbb8b90f3f9db8020958b1553afa7" + channel: "stable" + +project_type: package diff --git a/packages/halkyon_interop/CHANGELOG.md b/packages/halkyon_interop/CHANGELOG.md new file mode 100644 index 0000000..41cc7d8 --- /dev/null +++ b/packages/halkyon_interop/CHANGELOG.md @@ -0,0 +1,3 @@ +## 0.0.1 + +* TODO: Describe initial release. diff --git a/packages/halkyon_interop/LICENSE b/packages/halkyon_interop/LICENSE new file mode 100644 index 0000000..ba75c69 --- /dev/null +++ b/packages/halkyon_interop/LICENSE @@ -0,0 +1 @@ +TODO: Add your license here. diff --git a/packages/halkyon_interop/README.md b/packages/halkyon_interop/README.md new file mode 100644 index 0000000..4a260d8 --- /dev/null +++ b/packages/halkyon_interop/README.md @@ -0,0 +1,39 @@ + + +TODO: Put a short description of the package here that helps potential users +know whether this package might be useful for them. + +## Features + +TODO: List what your package can do. Maybe include images, gifs, or videos. + +## Getting started + +TODO: List prerequisites and provide or point to information on how to +start using the package. + +## Usage + +TODO: Include short and useful examples for package users. Add longer examples +to `/example` folder. + +```dart +const like = 'sample'; +``` + +## Additional information + +TODO: Tell users more about the package: where to find more information, how to +contribute to the package, how to file issues, what response they can expect +from the package authors, and more. diff --git a/packages/halkyon_interop/analysis_options.yaml b/packages/halkyon_interop/analysis_options.yaml new file mode 100644 index 0000000..6b029ec --- /dev/null +++ b/packages/halkyon_interop/analysis_options.yaml @@ -0,0 +1,2 @@ +# The workspace's lint rules (see ../../analysis_options.yaml). +include: ../../analysis_options.yaml diff --git a/packages/halkyon_interop/lib/halkyon_interop.dart b/packages/halkyon_interop/lib/halkyon_interop.dart new file mode 100644 index 0000000..a1ca00b --- /dev/null +++ b/packages/halkyon_interop/lib/halkyon_interop.dart @@ -0,0 +1,13 @@ +/// Cross-app interoperability contracts for the Halkyon ecosystem. +/// +/// This package is pure Dart and defines: +/// - `TaskShape`: a minimal type for representing tasks across apps +/// (e.g., a Halkyon Learn review session surfaced in Halkyon ToDo). +/// - `HalkyonEvent`: a sealed class hierarchy for cross-app events. +/// - `EventPublisher`: an interface for emitting events to other apps, +/// with `DormantPublisher` as a no-op default for apps running standalone. +library; + +export 'src/event_publisher.dart'; +export 'src/events.dart'; +export 'src/task_shape.dart'; diff --git a/packages/halkyon_interop/lib/src/event_publisher.dart b/packages/halkyon_interop/lib/src/event_publisher.dart new file mode 100644 index 0000000..83a3cf4 --- /dev/null +++ b/packages/halkyon_interop/lib/src/event_publisher.dart @@ -0,0 +1,24 @@ +import 'package:halkyon_interop/src/events.dart'; + +/// Publishes [HalkyonEvent]s to other Halkyon apps installed alongside this one. +/// +/// The actual transport (platform channels, intents, App Group containers, +/// etc.) is implementation-specific and lives in the app's composition root, +/// not in this package. +abstract interface class EventPublisher() { + /// Publish an event. Implementations should be non-blocking and best-effort: + /// failing to deliver to peer apps must not fail the originating action. + Future publish(HalkyonEvent event); +} + +/// A no-op [EventPublisher] for apps running in isolation. +/// +/// When a Halkyon app starts and detects no peer apps to broadcast to (or +/// when the user has disabled cross-app communication), inject this. All +/// `publish` calls are silently dropped. +class const DormantPublisher() implements EventPublisher { + @override + Future publish(HalkyonEvent event) async { + // Intentionally empty. Events are dropped when there are no peers. + } +} diff --git a/packages/halkyon_interop/lib/src/events.dart b/packages/halkyon_interop/lib/src/events.dart new file mode 100644 index 0000000..64d64ac --- /dev/null +++ b/packages/halkyon_interop/lib/src/events.dart @@ -0,0 +1,43 @@ +import 'package:meta/meta.dart'; + +/// Base type for events published across Halkyon apps. +/// +/// Sealed: all subtypes must be declared in this file. Adding a new event +/// type is a deliberate cross-app contract change, not something that should +/// happen incidentally inside a feature. +@immutable +sealed class const HalkyonEvent({ + /// When the event occurred. Use the app's injected `Clock` to set this, + /// not `DateTime.now()` directly, so tests can control time. + required final DateTime occurredAt, +}); + +/// Emitted when a Halkyon Learn review becomes due for the user. +/// +/// Consuming apps (e.g., Halkyon ToDo) can subscribe to surface this as a +/// task or notification. +final class const ReviewDueEvent({ + required super.occurredAt, + + /// Identifier of the studyset whose cards are due. + required final String studysetId, + + /// Number of cards in this studyset currently due for review. + required final int dueCount, +}) extends HalkyonEvent { + @override + bool operator ==(Object other) => + identical(this, other) || + other is ReviewDueEvent && + runtimeType == other.runtimeType && + occurredAt == other.occurredAt && + studysetId == other.studysetId && + dueCount == other.dueCount; + + @override + int get hashCode => Object.hash(occurredAt, studysetId, dueCount); + + @override + String toString() => + 'ReviewDueEvent(studyset=$studysetId, due=$dueCount, at=$occurredAt)'; +} diff --git a/packages/halkyon_interop/lib/src/task_shape.dart b/packages/halkyon_interop/lib/src/task_shape.dart new file mode 100644 index 0000000..b78f2a4 --- /dev/null +++ b/packages/halkyon_interop/lib/src/task_shape.dart @@ -0,0 +1,53 @@ +import 'package:meta/meta.dart'; + +/// A minimal cross-app representation of a task. +/// +/// This is the contract for surfacing one app's actionable items in another +/// app's task views. Halkyon Learn might surface "review 12 cards in Spanish" +/// as a [TaskShape] that Halkyon ToDo displays alongside native todos. +/// +/// Kept deliberately minimal. Apps consuming a [TaskShape] should treat it +/// as opaque metadata; deep-linking back to the originating app is via +/// [deepLink], not by interpreting [sourceAppId] or [externalId]. +@immutable +class const TaskShape({ + /// Identifier of the app that owns this task. Conventionally a reverse-DNS + /// string like `eu.halkyon.learn`. + required final String sourceAppId, + + /// The originating app's stable identifier for this task. Opaque to + /// consumers; used together with [sourceAppId] for deduplication. + required final String externalId, + + /// Human-readable title displayed in the consuming app's task list. + required final String title, + + /// A URI the consuming app can open to hand off back to the originating + /// app. Format is app-specific (custom scheme or universal link). + required final Uri deepLink, + + /// When the task becomes actionable or overdue. Null means "no due date." + final DateTime? dueAt, + + /// Optional secondary line. Keep short — consumers may truncate. + final String? subtitle, +}) { + @override + bool operator ==(Object other) => + identical(this, other) || + other is TaskShape && + runtimeType == other.runtimeType && + sourceAppId == other.sourceAppId && + externalId == other.externalId && + title == other.title && + subtitle == other.subtitle && + dueAt == other.dueAt && + deepLink == other.deepLink; + + @override + int get hashCode => + Object.hash(sourceAppId, externalId, title, subtitle, dueAt, deepLink); + + @override + String toString() => 'TaskShape($sourceAppId/$externalId: $title)'; +} diff --git a/packages/halkyon_interop/pubspec.yaml b/packages/halkyon_interop/pubspec.yaml new file mode 100644 index 0000000..f9b5c01 --- /dev/null +++ b/packages/halkyon_interop/pubspec.yaml @@ -0,0 +1,14 @@ +name: halkyon_interop +description: "Cross-app interoperability types and contracts for the Halkyon ecosystem. Pure Dart, no Flutter." +version: 0.0.1 +publish_to: none +resolution: workspace + +environment: + sdk: ^3.13.0 + +dependencies: + meta: ^1.16.0 + +dev_dependencies: + test: ^1.25.0 diff --git a/packages/halkyon_interop/test/halkyon_interop_test.dart b/packages/halkyon_interop/test/halkyon_interop_test.dart new file mode 100644 index 0000000..33a0bcc --- /dev/null +++ b/packages/halkyon_interop/test/halkyon_interop_test.dart @@ -0,0 +1,174 @@ +import 'package:halkyon_interop/halkyon_interop.dart'; +import 'package:test/test.dart'; + +void main() { + group('TaskShape', () { + final fixedTime = DateTime.utc(2026, 1, 15, 12); + final deepLink = Uri.parse('halkyon-learn://review/spanish-vocab'); + + TaskShape build({ + String sourceAppId = 'eu.halkyon.learn', + String externalId = 'review-12', + String title = 'Review 12 cards', + String? subtitle = 'Spanish vocabulary', + DateTime? dueAt, + Uri? linkOverride, + }) => TaskShape( + sourceAppId: sourceAppId, + externalId: externalId, + title: title, + subtitle: subtitle, + dueAt: dueAt ?? fixedTime, + deepLink: linkOverride ?? deepLink, + ); + + test('exposes provided fields', () { + final task = build(); + expect(task.sourceAppId, 'eu.halkyon.learn'); + expect(task.externalId, 'review-12'); + expect(task.title, 'Review 12 cards'); + expect(task.subtitle, 'Spanish vocabulary'); + expect(task.dueAt, fixedTime); + expect(task.deepLink, deepLink); + }); + + test('allows null for optional fields', () { + final task = TaskShape( + sourceAppId: 'eu.halkyon.learn', + externalId: 'review-12', + title: 'Review', + deepLink: deepLink, + ); + expect(task.subtitle, isNull); + expect(task.dueAt, isNull); + }); + + test('two instances with identical fields are equal', () { + expect(build(), equals(build())); + expect(build().hashCode, equals(build().hashCode)); + }); + + test('differs on any field change', () { + expect(build(), isNot(equals(build(title: 'Different')))); + expect(build(), isNot(equals(build(externalId: 'different-id')))); + expect(build(), isNot(equals(build(sourceAppId: 'eu.halkyon.todo')))); + expect(build(), isNot(equals(build(dueAt: DateTime.utc(2026, 2))))); + expect( + build(), + isNot(equals(build(linkOverride: Uri.parse('halkyon-todo://x')))), + ); + }); + + test('toString includes identifying fields', () { + final str = build().toString(); + expect(str, contains('eu.halkyon.learn')); + expect(str, contains('review-12')); + expect(str, contains('Review 12 cards')); + }); + }); + + group('HalkyonEvent / ReviewDueEvent', () { + final fixedTime = DateTime.utc(2026, 1, 15, 12); + + test('ReviewDueEvent is a HalkyonEvent', () { + final event = ReviewDueEvent( + occurredAt: fixedTime, + studysetId: 'spanish-vocab', + dueCount: 12, + ); + expect(event, isA()); + }); + + test('exposes provided fields', () { + final event = ReviewDueEvent( + occurredAt: fixedTime, + studysetId: 'spanish-vocab', + dueCount: 12, + ); + expect(event.occurredAt, fixedTime); + expect(event.studysetId, 'spanish-vocab'); + expect(event.dueCount, 12); + }); + + test('events with identical fields are equal', () { + final a = ReviewDueEvent( + occurredAt: fixedTime, + studysetId: 'spanish-vocab', + dueCount: 12, + ); + final b = ReviewDueEvent( + occurredAt: fixedTime, + studysetId: 'spanish-vocab', + dueCount: 12, + ); + expect(a, equals(b)); + expect(a.hashCode, equals(b.hashCode)); + }); + + test('differs on field changes', () { + final base = ReviewDueEvent( + occurredAt: fixedTime, + studysetId: 'spanish-vocab', + dueCount: 12, + ); + expect( + base, + isNot( + equals( + ReviewDueEvent( + occurredAt: fixedTime, + studysetId: 'spanish-vocab', + dueCount: 13, + ), + ), + ), + ); + expect( + base, + isNot( + equals( + ReviewDueEvent( + occurredAt: fixedTime, + studysetId: 'french-vocab', + dueCount: 12, + ), + ), + ), + ); + }); + + test('switch on sealed type is exhaustive', () { + final HalkyonEvent event = ReviewDueEvent( + occurredAt: fixedTime, + studysetId: 'spanish-vocab', + dueCount: 12, + ); + + // If a new HalkyonEvent subtype is added without updating this switch, + // the analyzer/compiler will flag it. That's the value of `sealed`. + final description = switch (event) { + ReviewDueEvent(:final studysetId, :final dueCount) => + '$dueCount cards due in $studysetId', + }; + + expect(description, '12 cards due in spanish-vocab'); + }); + }); + + group('DormantPublisher', () { + test('accepts publish calls without throwing', () async { + const publisher = DormantPublisher(); + final event = ReviewDueEvent( + occurredAt: DateTime.utc(2026, 1, 15), + studysetId: 'spanish-vocab', + dueCount: 5, + ); + await expectLater(publisher.publish(event), completes); + }); + + test('implements EventPublisher', () { + const publisher = DormantPublisher(); + expect(publisher, isA()); + }); + }); +} diff --git a/packages/halkyon_ui/.gitignore b/packages/halkyon_ui/.gitignore new file mode 100644 index 0000000..dd5eb98 --- /dev/null +++ b/packages/halkyon_ui/.gitignore @@ -0,0 +1,31 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. +/pubspec.lock +**/doc/api/ +.dart_tool/ +.flutter-plugins-dependencies +/build/ +/coverage/ diff --git a/packages/halkyon_ui/.metadata b/packages/halkyon_ui/.metadata new file mode 100644 index 0000000..4449ab3 --- /dev/null +++ b/packages/halkyon_ui/.metadata @@ -0,0 +1,10 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "cc0734ac716fbb8b90f3f9db8020958b1553afa7" + channel: "stable" + +project_type: package diff --git a/packages/halkyon_ui/CHANGELOG.md b/packages/halkyon_ui/CHANGELOG.md new file mode 100644 index 0000000..469c576 --- /dev/null +++ b/packages/halkyon_ui/CHANGELOG.md @@ -0,0 +1,11 @@ +## 0.1.0 + +* Halkyon Learn's look, for every Halkyon app: + `appTheme(brightness, extensions: …)` with the hand-written light and dark + schemes around cobalt and copper, `Brand`, `ThemeExtras` (success, warning, + info), `PaletteColor`, `FittedSnackBars`; Noto Sans bundled + (`appFontFamily`, `appFontFallback`, `appFontFallbackFor`, + `registerFontLicenses`); `WindowSize` and `readableContentMaxWidth`; the + shared widgets (sheets, frames and gradients, spinners, fields, lists, + `BrandWordmark` and `LaunchScreen` taking an app's word and icon) with their + texts in English and German (`HalkyonUiLocalizations`). diff --git a/packages/halkyon_ui/LICENSE b/packages/halkyon_ui/LICENSE new file mode 100644 index 0000000..8e085dc --- /dev/null +++ b/packages/halkyon_ui/LICENSE @@ -0,0 +1,235 @@ +GNU AFFERO GENERAL PUBLIC LICENSE +Version 3, 19 November 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + + Preamble + +The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. + +A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. + +The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. + +An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. + +The precise terms and conditions for copying, distribution and modification follow. + + TERMS AND CONDITIONS + +0. Definitions. + +"This License" refers to version 3 of the GNU Affero General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based on the Program. + +To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +1. Source Code. +The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. + +A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". + + c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. + +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + + a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. + + d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + +"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or authors of the material; or + + e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. + +All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +8. Termination. + +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +11. Patents. + +A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + +13. Remote Network Interaction; Use with the GNU General Public License. + +Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. + +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. + +14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. + + halkyon_shared + Copyright (C) 2026 project_halkyon + + This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. + +You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . diff --git a/packages/halkyon_ui/README.md b/packages/halkyon_ui/README.md new file mode 100644 index 0000000..b61001e --- /dev/null +++ b/packages/halkyon_ui/README.md @@ -0,0 +1,106 @@ +# halkyon_ui + +Halkyon's look, shared by its apps (Learn, Todo, Train): one theme around the +kingfisher's cobalt and copper, the bundled Noto Sans, Material 3's window +sizes, and the widgets every app's screens are built of, with their texts in +British English, American English and German. + +Written as the apps are: Dart 3.13's primary constructors, Material from +`package:material_ui` (never `package:flutter/material.dart`), Lucide icons, +LeanCode's lints. + +## What it holds + +- **Theme** (`lib/src/theme/`): `appTheme(brightness, extensions: …)`, Material + 3 with hand-written light and dark schemes (primary cobalt, tertiary copper, + cobalt-tinted neutrals), Material 3 Expressive's 64 dp navigation bar, flat + app bars, floating snack bars; `Brand`; `ThemeExtras`, the status colours + Material has no role for (`Theme.of(context).extras`); `PaletteColor`, the + 20 colours a person can give content, each with a text colour held to WCAG + AA by a test; `FittedSnackBars`. +- **Fonts**: Noto Sans for Latin, Greek and Cyrillic, every weight in one + variable file, as `appFontFamily` (`packages/halkyon_ui/Noto Sans`). Chinese, + Japanese and Korean fall back to `Noto Sans JP`, `SC`, `TC` and `KR`, which + an app bundles itself if it needs them (`appFontFallbackFor` puts a + language's own first). +- **Layout** (`lib/src/layout/`): `WindowSize` (`context.windowSize`) and + `readableContentMaxWidth`. +- **Widgets** (`lib/src/widget/`): `showAdaptiveSheet` with `SheetScaffold`; + `TopGradient`, `ScreenTint`, `ScreenColor`, `TintFrame`, `FramedScreen` + and `TabVisibility`; `FloatingNavigationBar`; `AppLoadingIndicator`, + `ButtonLoadingIndicator`, `AppRefreshIndicator`; `SectionCard`, + `SliverCentered`, `EmptyListMessage`, `CountBadge`, `TitleWithKicker`, + `CollapsingRow`, `ScrollHidingFab`, `liftWhileDragged`, `ReorderToggle`, + `ReorderGrip`; `ChevronField`, `requiredDecoration`, `FieldInfoButton`, + `CountStepper`, `PaletteColorPicker`, `TextLimits` with + `nearLimitCounter`; `confirmDestructiveAction`, `showUndoSnackBar`, + `showMoreInfoSheet`; `FoundById`; `KeyboardBackOnResume`; `BrandWordmark` + and `LaunchScreen`, which take the app's word and icon. + +What belongs to one app stays in it: its own colours (an extension passed to +`appTheme`), routes, repositories, editors and texts. + +## Using it in an app + +Depend on it by git, pinned to a signed commit, as the apps pin their forks: + +```yaml +dependencies: + halkyon_ui: + git: + url: https://code.halkyon.app/project-halkyon/halkyon_shared.git + path: packages/halkyon_ui + ref: +``` + +While changing both at once, point the app at a local checkout with a +git-ignored `pubspec_overrides.yaml` beside the app's workspace root: + +```yaml +dependency_overrides: + halkyon_ui: + path: ../halkyon_shared/packages/halkyon_ui +``` + +The lockfile then records the path: never commit it so, as CI has no such +folder. + +Then set the app up as `example/lib/main.dart` does: + +```dart +MaterialApp( + theme: appTheme(Brightness.light, extensions: [MyColors.light]), + darkTheme: appTheme(Brightness.dark, extensions: [MyColors.dark]), + localizationsDelegates: const [ + AppLocalizations.delegate, + HalkyonUiLocalizations.delegate, + // material_ui's: flutter_localizations' serve only the SDK's Material. + ...GlobalMaterialLocalizations.delegates, + ], + supportedLocales: AppLocalizations.supportedLocales, + builder: (context, child) => FittedSnackBars(child: child!), + … +); +``` + +and call `registerFontLicenses()` at start. An app bundling the CJK fonts +declares them in its own `pubspec.yaml` under exactly the names +`appFontFallback` lists (no `packages/` prefix) and registers their licence +itself. + +## Texts + +`lib/l10n/halkyon_ui_en.arb` is the template (British English, also the +fallback); `halkyon_ui_de.arb` German, informal "du"; `halkyon_ui_en_US.arb` +only what American English spells differently; `halkyon_ui_en_GB.arb` empty. A +new text goes into the template and German together (`test/l10n/` fails +otherwise). `flutter pub get` writes `lib/l10n/halkyon_ui_localizations*.dart`, +which are committed (apps take the package by git) and never edited or +formatted by hand. + +## Checks + +From the workspace root: `dart analyze --fatal-infos`; then `flutter test` in +`packages/halkyon_ui` and in `packages/halkyon_ui/example`, whose tests check +what only an app sees (the font under the name an app finds it by, its +licence). diff --git a/packages/halkyon_ui/analysis_options.yaml b/packages/halkyon_ui/analysis_options.yaml new file mode 100644 index 0000000..3e3dd34 --- /dev/null +++ b/packages/halkyon_ui/analysis_options.yaml @@ -0,0 +1,11 @@ +# The workspace's lint rules (see ../../analysis_options.yaml). +include: ../../analysis_options.yaml + +analyzer: + exclude: + - build/** + # Generated by gen-l10n (see l10n.yaml). + - lib/l10n/halkyon_ui_localizations*.dart + +formatter: + trailing_commas: preserve diff --git a/packages/halkyon_ui/assets/fonts/ATTRIBUTION.md b/packages/halkyon_ui/assets/fonts/ATTRIBUTION.md new file mode 100644 index 0000000..8fa9b7f --- /dev/null +++ b/packages/halkyon_ui/assets/fonts/ATTRIBUTION.md @@ -0,0 +1,16 @@ +# Fonts + +The package brings Halkyon's font with it and never fetches any: text looks the +same on every device, whatever fonts it has. + +| File | Font | Source | Licence | +|---|---|---|---| +| `NotoSans-Variable.ttf`, `NotoSans-Italic-Variable.ttf` | Noto Sans (Latin, Greek incl. polytonic, Cyrillic), every weight | [notofonts/latin-greek-cyrillic](https://github.com/notofonts/latin-greek-cyrillic) release NotoSans-v2.015, `unhinted/slim-variable-ttf` | SIL Open Font License 1.1, `OFL-NotoSans.txt` | + +The files are renamed only; their glyphs are unchanged. `registerFontLicenses()` +adds the licence to an app's licence list. + +The fonts for Chinese, Japanese and Korean (Noto Sans JP, SC, TC, KR; some +42 MB) are not here: each app bundles those it needs under those family names, +with their licence, and the theme names them as the fallback +(`lib/src/theme/app_fonts.dart`). diff --git a/packages/halkyon_ui/assets/fonts/NotoSans-Italic-Variable.ttf b/packages/halkyon_ui/assets/fonts/NotoSans-Italic-Variable.ttf new file mode 100644 index 0000000..186383a Binary files /dev/null and b/packages/halkyon_ui/assets/fonts/NotoSans-Italic-Variable.ttf differ diff --git a/packages/halkyon_ui/assets/fonts/NotoSans-Variable.ttf b/packages/halkyon_ui/assets/fonts/NotoSans-Variable.ttf new file mode 100644 index 0000000..18e7353 Binary files /dev/null and b/packages/halkyon_ui/assets/fonts/NotoSans-Variable.ttf differ diff --git a/packages/halkyon_ui/assets/fonts/OFL-NotoSans.txt b/packages/halkyon_ui/assets/fonts/OFL-NotoSans.txt new file mode 100644 index 0000000..6843f31 --- /dev/null +++ b/packages/halkyon_ui/assets/fonts/OFL-NotoSans.txt @@ -0,0 +1,93 @@ +Copyright 2022 The Noto Project Authors (https://github.com/notofonts/latin-greek-cyrillic) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/packages/halkyon_ui/example/.gitignore b/packages/halkyon_ui/example/.gitignore new file mode 100644 index 0000000..e43d3a1 --- /dev/null +++ b/packages/halkyon_ui/example/.gitignore @@ -0,0 +1,3 @@ +# Flutter/Dart/Pub related +.dart_tool/ +build/ diff --git a/packages/halkyon_ui/example/analysis_options.yaml b/packages/halkyon_ui/example/analysis_options.yaml new file mode 100644 index 0000000..65eb568 --- /dev/null +++ b/packages/halkyon_ui/example/analysis_options.yaml @@ -0,0 +1,9 @@ +# The workspace's lint rules (see ../../../analysis_options.yaml). +include: ../../../analysis_options.yaml + +analyzer: + exclude: + - build/** + +formatter: + trailing_commas: preserve diff --git a/packages/halkyon_ui/example/lib/main.dart b/packages/halkyon_ui/example/lib/main.dart new file mode 100644 index 0000000..57baff0 --- /dev/null +++ b/packages/halkyon_ui/example/lib/main.dart @@ -0,0 +1,75 @@ +import 'package:halkyon_ui/halkyon_ui.dart'; +import 'package:material_ui/material_ui.dart'; + +void main() { + registerFontLicenses(); + runApp(const ExampleApp()); +} + +/// An app set up as Halkyon's are: the shared theme in both brightnesses, +/// the package's texts beside Material's (from material_ui, whose own +/// delegates serve its widgets), and snack bars fitted to the window. +class const ExampleApp({ + /// The language, the device's when null. + final Locale? locale, + super.key, +}) extends StatelessWidget { + @override + Widget build(BuildContext context) => MaterialApp( + title: 'Halkyon Example', + theme: appTheme(Brightness.light), + darkTheme: appTheme(Brightness.dark), + locale: locale, + localizationsDelegates: const [ + HalkyonUiLocalizations.delegate, + ...GlobalMaterialLocalizations.delegates, + ], + supportedLocales: HalkyonUiLocalizations.supportedLocales, + builder: (context, child) => FittedSnackBars(child: child!), + home: const _Home(), + ); +} + +class const _Home() extends StatelessWidget { + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + return TopGradient( + background: scheme.surface, + child: Scaffold( + backgroundColor: Colors.transparent, + appBar: AppBar(backgroundColor: Colors.transparent), + body: Center( + child: ConstrainedBox( + constraints: const BoxConstraints( + maxWidth: readableContentMaxWidth, + ), + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const BrandWordmark(product: 'Example'), + const SizedBox(height: 24), + SectionCard( + child: Builder( + builder: (context) => FilledButton.tonal( + onPressed: () => confirmDestructiveAction( + context, + title: 'Delete everything?', + message: 'It can’t be undone.', + confirmLabel: 'Delete', + ), + child: const Text('Delete'), + ), + ), + ), + ], + ), + ), + ), + ), + ), + ); + } +} diff --git a/packages/halkyon_ui/example/pubspec.yaml b/packages/halkyon_ui/example/pubspec.yaml new file mode 100644 index 0000000..1ba3e2a --- /dev/null +++ b/packages/halkyon_ui/example/pubspec.yaml @@ -0,0 +1,18 @@ +name: halkyon_ui_example +description: "An app built on halkyon_ui, as Halkyon's apps are: shows how one sets it up, and checks what only an app can see (the package's font by the name an app finds it under, its licence)." +publish_to: none +resolution: workspace + +environment: + sdk: ^3.13.0 + flutter: ^3.44.4 + +dependencies: + flutter: + sdk: flutter + halkyon_ui: ^0.1.0 + material_ui: ^1.5.0 + +dev_dependencies: + flutter_test: + sdk: flutter diff --git a/packages/halkyon_ui/example/test/example_app_test.dart b/packages/halkyon_ui/example/test/example_app_test.dart new file mode 100644 index 0000000..bafa8a1 --- /dev/null +++ b/packages/halkyon_ui/example/test/example_app_test.dart @@ -0,0 +1,99 @@ +import 'dart:convert'; +import 'dart:ui' as ui; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:halkyon_ui/halkyon_ui.dart'; +import 'package:halkyon_ui_example/main.dart'; +import 'package:material_ui/material_ui.dart'; + +/// How many pixels [text] inks in [family] at [weight]: heavier strokes ink +/// more. +Future ink(String text, String family, FontWeight weight) async { + final painter = TextPainter( + text: TextSpan( + text: text, + style: TextStyle( + fontFamily: family, + fontSize: 40, + fontWeight: weight, + color: const Color(0xFF000000), + ), + ), + textDirection: TextDirection.ltr, + )..layout(); + final recorder = ui.PictureRecorder(); + painter.paint(Canvas(recorder), Offset.zero); + final image = await recorder.endRecording().toImage( + painter.width.ceil(), + painter.height.ceil(), + ); + final pixels = (await image.toByteData())!; + var inked = 0; + for (var alpha = 3; alpha < pixels.lengthInBytes; alpha += 4) { + if (pixels.getUint8(alpha) > 128) { + inked++; + } + } + return inked; +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test("an app finds the package's Noto Sans under the theme's name, and " + 'draws every weight with it', () async { + final manifest = jsonDecode( + await rootBundle.loadString('FontManifest.json'), + ) as List; + final noto = manifest.cast>().singleWhere( + (font) => font['family'] == appFontFamily, + ); + final assets = [ + for (final font + in (noto['fonts']! as List).cast>()) + font['asset']! as String, + ]; + expect( + assets, + contains('packages/halkyon_ui/assets/fonts/NotoSans-Variable.ttf'), + ); + + // Loaded as the engine loads an app's fonts as it starts: by the + // manifest's family and files. + final loader = FontLoader(appFontFamily); + for (final asset in assets) { + loader.addFont(rootBundle.load(asset)); + } + await loader.load(); + const text = 'Ἀθῆναι Halkyon'; + final regular = await ink(text, appFontFamily, FontWeight.w400); + final bold = await ink(text, appFontFamily, FontWeight.w700); + expect(bold, greaterThan(regular * 1.2)); + }); + + test("Noto Sans's licence joins the app's licence list", () async { + registerFontLicenses(); + + final notices = [ + await for (final entry in LicenseRegistry.licenses) + if (entry.packages.contains('Noto Sans')) entry, + ]; + expect(notices, hasLength(1)); + expect( + notices.single.paragraphs.map((paragraph) => paragraph.text).join(), + contains('SIL OPEN FONT LICENSE'), + ); + }); + + testWidgets("the app speaks German with the package's texts", (tester) async { + await tester.pumpWidget(const ExampleApp(locale: Locale('de'))); + + expect(find.text('Halkyon'), findsOneWidget); + expect(find.text('Example'), findsOneWidget); + await tester.tap(find.text('Delete')); + await tester.pumpAndSettle(); + expect(find.text('Abbrechen'), findsOneWidget); + }); +} diff --git a/packages/halkyon_ui/l10n.yaml b/packages/halkyon_ui/l10n.yaml new file mode 100644 index 0000000..9f51e21 --- /dev/null +++ b/packages/halkyon_ui/l10n.yaml @@ -0,0 +1,14 @@ +# Flutter's gen-l10n: the strings in lib/l10n/*.arb become HalkyonUiLocalizations, +# generated into lib/l10n/halkyon_ui_localizations*.dart (committed, never edited or +# formatted by hand, as apps take this package by git). halkyon_ui_en.arb, the +# template, is British English, also the fallback; halkyon_ui_en_US.arb overrides +# what American English spells differently; halkyon_ui_en_GB.arb is empty; German +# says "du". +arb-dir: lib/l10n +template-arb-file: halkyon_ui_en.arb +output-dir: lib/l10n +output-localization-file: halkyon_ui_localizations.dart +output-class: HalkyonUiLocalizations +# `HalkyonUiLocalizations.of(context).foo` without a `!`: apps install the +# delegate. +nullable-getter: false diff --git a/packages/halkyon_ui/lib/halkyon_ui.dart b/packages/halkyon_ui/lib/halkyon_ui.dart new file mode 100644 index 0000000..3b647dc --- /dev/null +++ b/packages/halkyon_ui/lib/halkyon_ui.dart @@ -0,0 +1,44 @@ +/// Halkyon's look, shared by its apps: the theme around cobalt and copper +/// (`appTheme`), the bundled Noto Sans (`appFontFamily`), Material 3's +/// window sizes (`WindowSize`), and the widgets every app's screens are +/// built of, with their texts in English and German +/// (`HalkyonUiLocalizations`, whose delegate an app adds to its own). +library; + +export 'l10n/halkyon_ui_localizations.dart'; +export 'src/layout/readable_width.dart'; +export 'src/layout/window_size.dart'; +export 'src/theme/app_fonts.dart'; +export 'src/theme/app_theme.dart'; +export 'src/theme/brand.dart'; +export 'src/theme/palette_color.dart'; +export 'src/theme/theme_extras.dart'; +export 'src/widget/adaptive_sheet.dart'; +export 'src/widget/app_loading_indicator.dart'; +export 'src/widget/brand_wordmark.dart'; +export 'src/widget/chevron_field.dart'; +export 'src/widget/collapsing_row.dart'; +export 'src/widget/confirm_dialog.dart'; +export 'src/widget/count_badge.dart'; +export 'src/widget/count_stepper.dart'; +export 'src/widget/empty_list_message.dart'; +export 'src/widget/field_label.dart'; +export 'src/widget/floating_navigation_bar.dart'; +export 'src/widget/found_by_id.dart'; +export 'src/widget/keyboard_back_on_resume.dart'; +export 'src/widget/launch_screen.dart'; +export 'src/widget/lift_while_dragged.dart'; +export 'src/widget/more_info_sheet.dart'; +export 'src/widget/palette_color_picker.dart'; +export 'src/widget/reorder_grip.dart'; +export 'src/widget/reorder_toggle.dart'; +export 'src/widget/screen_tint.dart'; +export 'src/widget/scroll_hiding_fab.dart'; +export 'src/widget/section_card.dart'; +export 'src/widget/sliver_centered.dart'; +export 'src/widget/tab_visibility.dart'; +export 'src/widget/text_limits.dart'; +export 'src/widget/tinted_frame.dart'; +export 'src/widget/title_with_kicker.dart'; +export 'src/widget/top_gradient.dart'; +export 'src/widget/undo_snack_bar.dart'; diff --git a/packages/halkyon_ui/lib/l10n/halkyon_ui_de.arb b/packages/halkyon_ui/lib/l10n/halkyon_ui_de.arb new file mode 100644 index 0000000..065f951 --- /dev/null +++ b/packages/halkyon_ui/lib/l10n/halkyon_ui_de.arb @@ -0,0 +1,21 @@ +{ + "@@locale": "de", + + "brand": "Halkyon", + "close": "Schließen", + "cancel": "Abbrechen", + "undo": "Rückgängig", + "dragToReorder": "Zum Umsortieren ziehen", + "reorder": "Umsortieren", + "reorderDone": "Fertig", + "requiredField": "Pflichtfeld", + "decrease": "Verringern", + "increase": "Erhöhen", + "typeANumber": "Zahl eingeben", + "gone": "Das gibt es nicht mehr. Vielleicht wurde es auf einem anderen Gerät gelöscht.", + "moreInfo": "Weitere Informationen", + "copiedToClipboard": "In die Zwischenablage kopiert", + "copy": "Kopieren", + "paletteColorName": "{name, select, carrot{Karotte} cerise{Kirschrot} cobalt{Kobalt} copper{Kupfer} enzian{Enzian} fern{Farn} forest{Wald} ocean{Ozean} olive{Olive} pacific{Pazifik} pickle{Essiggurke} pine{Kiefer} pink{Rosa} plum{Pflaume} purple{Lila} reef{Riff} sahara{Sahara} slateblue{Schieferblau} soil{Erde} strawberry{Erdbeere} other{{name}}}", + "colorPickerLabel": "Farbe: {color}" +} diff --git a/packages/halkyon_ui/lib/l10n/halkyon_ui_en.arb b/packages/halkyon_ui/lib/l10n/halkyon_ui_en.arb new file mode 100644 index 0000000..7c81d5f --- /dev/null +++ b/packages/halkyon_ui/lib/l10n/halkyon_ui_en.arb @@ -0,0 +1,42 @@ +{ + "@@locale": "en", + + "brand": "Halkyon", + "@brand": { + "description": "The brand's word, above an app's own in its wordmark (\"Halkyon\" over \"Learn\")." + }, + "close": "Close", + "cancel": "Cancel", + "undo": "Undo", + "dragToReorder": "Drag to reorder", + "reorder": "Reorder", + "reorderDone": "Done", + "requiredField": "Required", + "@requiredField": { + "description": "Below a required field while it is empty." + }, + "decrease": "Decrease", + "increase": "Increase", + "typeANumber": "Type a number", + "gone": "This no longer exists. It may have been deleted on another device.", + "moreInfo": "More info", + "copiedToClipboard": "Copied to clipboard", + "copy": "Copy", + "paletteColorName": "{name, select, carrot{Carrot} cerise{Cerise} cobalt{Cobalt} copper{Copper} enzian{Enzian} fern{Fern} forest{Forest} ocean{Ocean} olive{Olive} pacific{Pacific} pickle{Pickle} pine{Pine} pink{Pink} plum{Plum} purple{Purple} reef{Reef} sahara{Sahara} slateblue{Slate blue} soil{Soil} strawberry{Strawberry} other{{name}}}", + "@paletteColorName": { + "description": "A colour of the palette content can take, by its stored name.", + "placeholders": { + "name": { + "type": "String" + } + } + }, + "colorPickerLabel": "Colour: {color}", + "@colorPickerLabel": { + "placeholders": { + "color": { + "type": "String" + } + } + } +} diff --git a/packages/halkyon_ui/lib/l10n/halkyon_ui_en_GB.arb b/packages/halkyon_ui/lib/l10n/halkyon_ui_en_GB.arb new file mode 100644 index 0000000..2a45d90 --- /dev/null +++ b/packages/halkyon_ui/lib/l10n/halkyon_ui_en_GB.arb @@ -0,0 +1,3 @@ +{ + "@@locale": "en_GB" +} diff --git a/packages/halkyon_ui/lib/l10n/halkyon_ui_en_US.arb b/packages/halkyon_ui/lib/l10n/halkyon_ui_en_US.arb new file mode 100644 index 0000000..7517274 --- /dev/null +++ b/packages/halkyon_ui/lib/l10n/halkyon_ui_en_US.arb @@ -0,0 +1,5 @@ +{ + "@@locale": "en_US", + + "colorPickerLabel": "Color: {color}" +} diff --git a/packages/halkyon_ui/lib/l10n/halkyon_ui_localizations.dart b/packages/halkyon_ui/lib/l10n/halkyon_ui_localizations.dart new file mode 100644 index 0000000..d250ed8 --- /dev/null +++ b/packages/halkyon_ui/lib/l10n/halkyon_ui_localizations.dart @@ -0,0 +1,257 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:intl/intl.dart' as intl; + +import 'halkyon_ui_localizations_de.dart'; +import 'halkyon_ui_localizations_en.dart'; + +// ignore_for_file: type=lint + +/// Callers can lookup localized strings with an instance of HalkyonUiLocalizations +/// returned by `HalkyonUiLocalizations.of(context)`. +/// +/// Applications need to include `HalkyonUiLocalizations.delegate()` in their app's +/// `localizationDelegates` list, and the locales they support in the app's +/// `supportedLocales` list. For example: +/// +/// ```dart +/// import 'l10n/halkyon_ui_localizations.dart'; +/// +/// return MaterialApp( +/// localizationsDelegates: HalkyonUiLocalizations.localizationsDelegates, +/// supportedLocales: HalkyonUiLocalizations.supportedLocales, +/// home: MyApplicationHome(), +/// ); +/// ``` +/// +/// ## Update pubspec.yaml +/// +/// Please make sure to update your pubspec.yaml to include the following +/// packages: +/// +/// ```yaml +/// dependencies: +/// # Internationalization support. +/// flutter_localizations: +/// sdk: flutter +/// intl: any # Use the pinned version from flutter_localizations +/// +/// # Rest of dependencies +/// ``` +/// +/// ## iOS Applications +/// +/// iOS applications define key application metadata, including supported +/// locales, in an Info.plist file that is built into the application bundle. +/// To configure the locales supported by your app, you’ll need to edit this +/// file. +/// +/// First, open your project’s ios/Runner.xcworkspace Xcode workspace file. +/// Then, in the Project Navigator, open the Info.plist file under the Runner +/// project’s Runner folder. +/// +/// Next, select the Information Property List item, select Add Item from the +/// Editor menu, then select Localizations from the pop-up menu. +/// +/// Select and expand the newly-created Localizations item then, for each +/// locale your application supports, add a new item and select the locale +/// you wish to add from the pop-up menu in the Value field. This list should +/// be consistent with the languages listed in the HalkyonUiLocalizations.supportedLocales +/// property. +abstract class HalkyonUiLocalizations { + HalkyonUiLocalizations(String locale) + : localeName = intl.Intl.canonicalizedLocale(locale.toString()); + + final String localeName; + + static HalkyonUiLocalizations of(BuildContext context) { + return Localizations.of( + context, + HalkyonUiLocalizations, + )!; + } + + static const LocalizationsDelegate delegate = + _HalkyonUiLocalizationsDelegate(); + + /// A list of this localizations delegate along with the default localizations + /// delegates. + /// + /// Returns a list of localizations delegates containing this delegate along with + /// GlobalMaterialLocalizations.delegate, GlobalCupertinoLocalizations.delegate, + /// and GlobalWidgetsLocalizations.delegate. + /// + /// Additional delegates can be added by appending to this list in + /// MaterialApp. This list does not have to be used at all if a custom list + /// of delegates is preferred or required. + static const List> localizationsDelegates = + >[ + delegate, + GlobalMaterialLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + ]; + + /// A list of this localizations delegate's supported locales. + static const List supportedLocales = [ + Locale('de'), + Locale('en'), + Locale('en', 'GB'), + Locale('en', 'US'), + ]; + + /// The brand's word, above an app's own in its wordmark ("Halkyon" over "Learn"). + /// + /// In en, this message translates to: + /// **'Halkyon'** + String get brand; + + /// No description provided for @close. + /// + /// In en, this message translates to: + /// **'Close'** + String get close; + + /// No description provided for @cancel. + /// + /// In en, this message translates to: + /// **'Cancel'** + String get cancel; + + /// No description provided for @undo. + /// + /// In en, this message translates to: + /// **'Undo'** + String get undo; + + /// No description provided for @dragToReorder. + /// + /// In en, this message translates to: + /// **'Drag to reorder'** + String get dragToReorder; + + /// No description provided for @reorder. + /// + /// In en, this message translates to: + /// **'Reorder'** + String get reorder; + + /// No description provided for @reorderDone. + /// + /// In en, this message translates to: + /// **'Done'** + String get reorderDone; + + /// Below a required field while it is empty. + /// + /// In en, this message translates to: + /// **'Required'** + String get requiredField; + + /// No description provided for @decrease. + /// + /// In en, this message translates to: + /// **'Decrease'** + String get decrease; + + /// No description provided for @increase. + /// + /// In en, this message translates to: + /// **'Increase'** + String get increase; + + /// No description provided for @typeANumber. + /// + /// In en, this message translates to: + /// **'Type a number'** + String get typeANumber; + + /// No description provided for @gone. + /// + /// In en, this message translates to: + /// **'This no longer exists. It may have been deleted on another device.'** + String get gone; + + /// No description provided for @moreInfo. + /// + /// In en, this message translates to: + /// **'More info'** + String get moreInfo; + + /// No description provided for @copiedToClipboard. + /// + /// In en, this message translates to: + /// **'Copied to clipboard'** + String get copiedToClipboard; + + /// No description provided for @copy. + /// + /// In en, this message translates to: + /// **'Copy'** + String get copy; + + /// A colour of the palette content can take, by its stored name. + /// + /// In en, this message translates to: + /// **'{name, select, carrot{Carrot} cerise{Cerise} cobalt{Cobalt} copper{Copper} enzian{Enzian} fern{Fern} forest{Forest} ocean{Ocean} olive{Olive} pacific{Pacific} pickle{Pickle} pine{Pine} pink{Pink} plum{Plum} purple{Purple} reef{Reef} sahara{Sahara} slateblue{Slate blue} soil{Soil} strawberry{Strawberry} other{{name}}}'** + String paletteColorName(String name); + + /// No description provided for @colorPickerLabel. + /// + /// In en, this message translates to: + /// **'Colour: {color}'** + String colorPickerLabel(String color); +} + +class _HalkyonUiLocalizationsDelegate + extends LocalizationsDelegate { + const _HalkyonUiLocalizationsDelegate(); + + @override + Future load(Locale locale) { + return SynchronousFuture( + lookupHalkyonUiLocalizations(locale), + ); + } + + @override + bool isSupported(Locale locale) => + ['de', 'en'].contains(locale.languageCode); + + @override + bool shouldReload(_HalkyonUiLocalizationsDelegate old) => false; +} + +HalkyonUiLocalizations lookupHalkyonUiLocalizations(Locale locale) { + // Lookup logic when language+country codes are specified. + switch (locale.languageCode) { + case 'en': + { + switch (locale.countryCode) { + case 'GB': + return HalkyonUiLocalizationsEnGb(); + case 'US': + return HalkyonUiLocalizationsEnUs(); + } + break; + } + } + + // Lookup logic when only language code is specified. + switch (locale.languageCode) { + case 'de': + return HalkyonUiLocalizationsDe(); + case 'en': + return HalkyonUiLocalizationsEn(); + } + + throw FlutterError( + 'HalkyonUiLocalizations.delegate failed to load unsupported locale "$locale". This is likely ' + 'an issue with the localizations generation tool. Please file an issue ' + 'on GitHub with a reproducible sample app and the gen-l10n configuration ' + 'that was used.', + ); +} diff --git a/packages/halkyon_ui/lib/l10n/halkyon_ui_localizations_de.dart b/packages/halkyon_ui/lib/l10n/halkyon_ui_localizations_de.dart new file mode 100644 index 0000000..e4ac77c --- /dev/null +++ b/packages/halkyon_ui/lib/l10n/halkyon_ui_localizations_de.dart @@ -0,0 +1,93 @@ +// ignore: unused_import +import 'package:intl/intl.dart' as intl; + +import 'halkyon_ui_localizations.dart'; + +// ignore_for_file: type=lint + +/// The translations for German (`de`). +class HalkyonUiLocalizationsDe extends HalkyonUiLocalizations { + HalkyonUiLocalizationsDe([String locale = 'de']) : super(locale); + + @override + String get brand => 'Halkyon'; + + @override + String get close => 'Schließen'; + + @override + String get cancel => 'Abbrechen'; + + @override + String get undo => 'Rückgängig'; + + @override + String get dragToReorder => 'Zum Umsortieren ziehen'; + + @override + String get reorder => 'Umsortieren'; + + @override + String get reorderDone => 'Fertig'; + + @override + String get requiredField => 'Pflichtfeld'; + + @override + String get decrease => 'Verringern'; + + @override + String get increase => 'Erhöhen'; + + @override + String get typeANumber => 'Zahl eingeben'; + + @override + String get gone => + 'Das gibt es nicht mehr. Vielleicht wurde es auf einem anderen Gerät gelöscht.'; + + @override + String get moreInfo => 'Weitere Informationen'; + + @override + String get copiedToClipboard => 'In die Zwischenablage kopiert'; + + @override + String get copy => 'Kopieren'; + + @override + String paletteColorName(String name) { + String _temp0 = intl.Intl.selectLogic( + name, + { + 'carrot': 'Karotte', + 'cerise': 'Kirschrot', + 'cobalt': 'Kobalt', + 'copper': 'Kupfer', + 'enzian': 'Enzian', + 'fern': 'Farn', + 'forest': 'Wald', + 'ocean': 'Ozean', + 'olive': 'Olive', + 'pacific': 'Pazifik', + 'pickle': 'Essiggurke', + 'pine': 'Kiefer', + 'pink': 'Rosa', + 'plum': 'Pflaume', + 'purple': 'Lila', + 'reef': 'Riff', + 'sahara': 'Sahara', + 'slateblue': 'Schieferblau', + 'soil': 'Erde', + 'strawberry': 'Erdbeere', + 'other': '$name', + }, + ); + return '$_temp0'; + } + + @override + String colorPickerLabel(String color) { + return 'Farbe: $color'; + } +} diff --git a/packages/halkyon_ui/lib/l10n/halkyon_ui_localizations_en.dart b/packages/halkyon_ui/lib/l10n/halkyon_ui_localizations_en.dart new file mode 100644 index 0000000..d89786a --- /dev/null +++ b/packages/halkyon_ui/lib/l10n/halkyon_ui_localizations_en.dart @@ -0,0 +1,108 @@ +// ignore: unused_import +import 'package:intl/intl.dart' as intl; + +import 'halkyon_ui_localizations.dart'; + +// ignore_for_file: type=lint + +/// The translations for English (`en`). +class HalkyonUiLocalizationsEn extends HalkyonUiLocalizations { + HalkyonUiLocalizationsEn([String locale = 'en']) : super(locale); + + @override + String get brand => 'Halkyon'; + + @override + String get close => 'Close'; + + @override + String get cancel => 'Cancel'; + + @override + String get undo => 'Undo'; + + @override + String get dragToReorder => 'Drag to reorder'; + + @override + String get reorder => 'Reorder'; + + @override + String get reorderDone => 'Done'; + + @override + String get requiredField => 'Required'; + + @override + String get decrease => 'Decrease'; + + @override + String get increase => 'Increase'; + + @override + String get typeANumber => 'Type a number'; + + @override + String get gone => + 'This no longer exists. It may have been deleted on another device.'; + + @override + String get moreInfo => 'More info'; + + @override + String get copiedToClipboard => 'Copied to clipboard'; + + @override + String get copy => 'Copy'; + + @override + String paletteColorName(String name) { + String _temp0 = intl.Intl.selectLogic( + name, + { + 'carrot': 'Carrot', + 'cerise': 'Cerise', + 'cobalt': 'Cobalt', + 'copper': 'Copper', + 'enzian': 'Enzian', + 'fern': 'Fern', + 'forest': 'Forest', + 'ocean': 'Ocean', + 'olive': 'Olive', + 'pacific': 'Pacific', + 'pickle': 'Pickle', + 'pine': 'Pine', + 'pink': 'Pink', + 'plum': 'Plum', + 'purple': 'Purple', + 'reef': 'Reef', + 'sahara': 'Sahara', + 'slateblue': 'Slate blue', + 'soil': 'Soil', + 'strawberry': 'Strawberry', + 'other': '$name', + }, + ); + return '$_temp0'; + } + + @override + String colorPickerLabel(String color) { + return 'Colour: $color'; + } +} + +/// The translations for English, as used in the United Kingdom (`en_GB`). +class HalkyonUiLocalizationsEnGb extends HalkyonUiLocalizationsEn { + HalkyonUiLocalizationsEnGb() : super('en_GB'); +} + +/// The translations for English, as used in the United States (`en_US`). +class HalkyonUiLocalizationsEnUs extends HalkyonUiLocalizationsEn { + HalkyonUiLocalizationsEnUs() : super('en_US'); + + @override + String colorPickerLabel(String color) { + return 'Color: $color'; + } +} diff --git a/packages/halkyon_ui/lib/src/layout/readable_width.dart b/packages/halkyon_ui/lib/src/layout/readable_width.dart new file mode 100644 index 0000000..b75575d --- /dev/null +++ b/packages/halkyon_ui/lib/src/layout/readable_width.dart @@ -0,0 +1,3 @@ +/// The widest body text should run: about 720 dp, which keeps lines within +/// the 60 to 80 characters that read most easily. +const double readableContentMaxWidth = 720; diff --git a/packages/halkyon_ui/lib/src/layout/window_size.dart b/packages/halkyon_ui/lib/src/layout/window_size.dart new file mode 100644 index 0000000..9b5b5c6 --- /dev/null +++ b/packages/halkyon_ui/lib/src/layout/window_size.dart @@ -0,0 +1,41 @@ +import 'package:material_ui/material_ui.dart'; + +/// Material 3's window size classes, by width in logical pixels: compact +/// below 600, medium to 840, expanded to 1200, large to 1600, extra large +/// beyond. +/// +/// Layouts branch on two of the lines: from medium on, navigation is a rail +/// at the side instead of a bar at the bottom; from expanded on, the layout +/// is a desktop one (sheets open as dialogs, a screen may show two +/// columns). Expanded rather than medium for the latter because medium +/// windows are mostly tablets, used by touch, and expanded ones mostly +/// desktops. +enum WindowSize { + compact, + medium, + expanded, + large, + extraLarge; + + /// The class of a window [width] wide. + factory fromWidth(double width) => switch (width) { + < 600 => compact, + < 840 => medium, + < 1200 => expanded, + < 1600 => large, + _ => extraLarge, + }; + + /// Whether navigation is a rail rather than a bottom bar. + bool get isAtLeastMedium => index >= medium.index; + + /// Whether the layout is a desktop one. + bool get isAtLeastExpanded => index >= expanded.index; +} + +/// `context.windowSize`: the class of the window [BuildContext] is in. +extension WindowSizeOf on BuildContext { + /// Rebuilds the caller when the window's width changes. + WindowSize get windowSize => + WindowSize.fromWidth(MediaQuery.sizeOf(this).width); +} diff --git a/packages/halkyon_ui/lib/src/theme/app_fonts.dart b/packages/halkyon_ui/lib/src/theme/app_fonts.dart new file mode 100644 index 0000000..ef5be42 --- /dev/null +++ b/packages/halkyon_ui/lib/src/theme/app_fonts.dart @@ -0,0 +1,77 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +/// The font of every Halkyon app, the same on every device: Noto Sans, for +/// Latin, Greek (polytonic too) and Cyrillic. Bundled with this package, +/// never fetched, so text looks alike everywhere and needs nothing the +/// device may lack; an app finds a package's font by this name. +const appFontFamily = 'packages/halkyon_ui/Noto Sans'; + +/// The fonts for Chinese, Japanese and Korean, which fill in where +/// [appFontFamily] has no glyph. They take some 42 MB, so each app bundles +/// those it needs itself, declaring them under exactly these family names +/// (an app's own fonts take no `packages/` prefix); a name no font answers +/// to falls through to the device's own fonts. +/// +/// They share most Han characters but draw them differently, and the first +/// in a list that has a character draws it: so Japanese comes first unless +/// the text's language asks for another ([appFontFallbackFor]). The scripts +/// none of them covers (Arabic, Hebrew, Thai, …) come from the device's own +/// fonts. +const _japanese = 'Noto Sans JP'; +const _simplifiedChinese = 'Noto Sans SC'; +const _traditionalChinese = 'Noto Sans TC'; +const _korean = 'Noto Sans KR'; + +/// What fills in where [appFontFamily] has no glyph, with no language +/// given: Japanese shapes first, then Chinese and Korean (Hangul only the +/// Korean font has). +const appFontFallback = [ + _japanese, + _simplifiedChinese, + _traditionalChinese, + _korean, +]; + +/// [appFontFallback] for text in [language], a BCP 47 tag: its own font +/// first when it is Chinese, Japanese or Korean, so that the Han characters +/// it shares with the others take its shapes; for any other language, or +/// none, [appFontFallback]. +List appFontFallbackFor(String? language) { + final first = _ownFont(language); + return switch (first) { + null => appFontFallback, + final first => [first, ...appFontFallback.where((font) => font != first)], + }; +} + +/// Whether [language] (a BCP 47 tag) has a font of its own among the CJK +/// fonts: Chinese, Japanese and Korean, whose Han characters each draw in +/// their own shapes. +bool hasOwnFont(String? language) => _ownFont(language) != null; + +String? _ownFont(String? language) { + final parts = (language ?? '').toLowerCase().split('-'); + return switch (parts.first) { + 'ja' => _japanese, + 'ko' => _korean, + // Traditional characters by their script (`zh-Hant`) or a region that + // writes them (Taiwan, Hong Kong, Macau). + 'zh' when const ['hant', 'tw', 'hk', 'mo'].any(parts.contains) => + _traditionalChinese, + 'zh' => _simplifiedChinese, + _ => null, + }; +} + +/// Adds Noto Sans's licence to the app's licence list, beside the packages' +/// own: the SIL Open Font License asks that it travels with the font. An +/// app bundling the CJK fonts adds their licence itself. +void registerFontLicenses() => LicenseRegistry.addLicense(() async* { + yield LicenseEntryWithLineBreaks( + ['Noto Sans'], + await rootBundle.loadString( + 'packages/halkyon_ui/assets/fonts/OFL-NotoSans.txt', + ), + ); +}); diff --git a/packages/halkyon_ui/lib/src/theme/app_theme.dart b/packages/halkyon_ui/lib/src/theme/app_theme.dart new file mode 100644 index 0000000..d2a5b9c --- /dev/null +++ b/packages/halkyon_ui/lib/src/theme/app_theme.dart @@ -0,0 +1,201 @@ +import 'package:halkyon_ui/src/layout/window_size.dart'; +import 'package:halkyon_ui/src/theme/app_fonts.dart'; +import 'package:halkyon_ui/src/theme/brand.dart'; +import 'package:halkyon_ui/src/theme/theme_extras.dart'; +import 'package:material_ui/material_ui.dart'; + +/// A Halkyon app's theme for [brightness]: Material 3 with a hand-authored +/// colour scheme around cobalt and copper, Halkyon's font +/// ([appFontFamily]), [ThemeExtras] and the app's own [extensions] beside +/// them, the current style of progress indicators, Material 3 Expressive's +/// shorter navigation bar, and snack bars floating above it +/// ([FittedSnackBars]). +ThemeData appTheme( + Brightness brightness, { + Iterable> extensions = const [], +}) { + final theme = _baseTheme(brightness, extensions); + return theme.copyWith(navigationBarTheme: _flexibleNavigationBar(theme)); +} + +/// Material 3 Expressive's flexible navigation bar, which Flutter's Material +/// library doesn't have yet (checked with v1.6.0): 64 dp high instead of 80, +/// the label of the tab in view in the secondary colour (the tokens of +/// Compose's `ShortNavigationBar`). Its pill stays Flutter's, 64 dp wide +/// rather than the 56 dp the tokens give, as Flutter fixes it. +NavigationBarThemeData _flexibleNavigationBar(ThemeData theme) { + final scheme = theme.colorScheme; + final label = theme.textTheme.labelMedium; + return NavigationBarThemeData( + height: 64, + labelTextStyle: WidgetStateProperty.resolveWith( + (states) => label?.copyWith( + color: states.contains(WidgetState.disabled) + ? scheme.onSurfaceVariant.withValues(alpha: 0.38) + : states.contains(WidgetState.selected) + ? scheme.secondary + : scheme.onSurfaceVariant, + ), + ), + ); +} + +ThemeData _baseTheme( + Brightness brightness, + Iterable> extensions, +) => ThemeData( + useMaterial3: true, + fontFamily: appFontFamily, + fontFamilyFallback: appFontFallback, + colorScheme: switch (brightness) { + Brightness.light => _lightScheme(), + Brightness.dark => _darkScheme(), + }, + // Rounded ends, a gap in the track and a stop indicator, instead of the + // older style. `false` is the only way to opt in so far; the flag is + // deprecated because it will become the default. + // ignore: deprecated_member_use + progressIndicatorTheme: const ProgressIndicatorThemeData(year2023: false), + // App bars stay flat when content scrolls under them: the tint and shadow + // Material 3 adds flicker as an overscroll crosses the edge again and + // again (Flutter issue 124296), and the app reads flat throughout. + appBarTheme: const AppBarThemeData( + scrolledUnderElevation: 0, + surfaceTintColor: Colors.transparent, + ), + // Floating, as Material 3 places snack bars: above the navigation bar + // rather than across the window's foot beneath it, in Material 3's + // inverse colours and corners (4 dp); in from the sides and above the bar + // as far as the floating bar stands in and above the system's + // (FloatingNavigationBar.sideMargin and lift). Flutter's default is the + // fixed snack bar of Material 2. + snackBarTheme: const SnackBarThemeData( + behavior: SnackBarBehavior.floating, + insetPadding: EdgeInsets.fromLTRB(16, 8, 16, 8), + ), + extensions: [ + switch (brightness) { + Brightness.light => ThemeExtras.light, + Brightness.dark => ThemeExtras.dark, + }, + ...extensions, + ], +); + +// The colour schemes are written by hand rather than derived from the cobalt +// seed, so that the whole interface, surfaces and neutrals included, reads as +// one family with the picker palette (PaletteColor) instead of Material's +// grey with vivid chips on top. The chromatic roles are palette colours: +// primary cobalt, secondary slate blue (a livelier blue for the rarely used +// role), tertiary copper (the warm accent), error cerise. The neutrals carry a +// cool, cobalt-tinted undertone: near-white blues in light mode, a deep +// navy-slate in dark mode. `fromSeed` still fills the roles the interface +// rarely shows (shadow, scrim, the fixed colours). + +const _white = Color(0xFFFFFFFF); + +ColorScheme _lightScheme() => + ColorScheme.fromSeed( + seedColor: Brand.primary, + tertiary: Brand.accent, + ).copyWith( + primary: Brand.primary, + onPrimary: _white, + primaryContainer: const Color(0xFFDFE2F9), + onPrimaryContainer: const Color(0xFF0A175C), + secondary: const Color(0xFF415DF0), + onSecondary: _white, + secondaryContainer: const Color(0xFFE1E5FB), + onSecondaryContainer: const Color(0xFF101A66), + tertiary: Brand.accent, + onTertiary: _white, + tertiaryContainer: const Color(0xFFFFDCC9), + onTertiaryContainer: const Color(0xFF481500), + error: const Color(0xFFBA1E55), + onError: _white, + errorContainer: const Color(0xFFFFD9E1), + onErrorContainer: const Color(0xFF45001B), + surface: const Color(0xFFF7F9FF), + onSurface: const Color(0xFF191B24), + onSurfaceVariant: const Color(0xFF474B5C), + surfaceDim: const Color(0xFFD6DDF0), + surfaceBright: const Color(0xFFF8FAFF), + surfaceContainerLowest: _white, + surfaceContainerLow: const Color(0xFFEDF1FC), + surfaceContainer: const Color(0xFFE3E9F8), + surfaceContainerHigh: const Color(0xFFD8E0F3), + surfaceContainerHighest: const Color(0xFFCDD7EF), + outline: const Color(0xFF757A8C), + outlineVariant: const Color(0xFFC4CADB), + inverseSurface: const Color(0xFF2D2F3B), + onInverseSurface: const Color(0xFFEEF1FB), + inversePrimary: const Color(0xFFAEB9FF), + surfaceTint: Brand.primary, + ); + +ColorScheme _darkScheme() => + ColorScheme.fromSeed( + seedColor: Brand.primary, + brightness: Brightness.dark, + tertiary: Brand.accent, + ).copyWith( + primary: const Color(0xFFAEB9FF), + onPrimary: const Color(0xFF0A1668), + primaryContainer: const Color(0xFF1E2E8C), + onPrimaryContainer: const Color(0xFFDFE2F9), + secondary: const Color(0xFFB7C0F7), + onSecondary: const Color(0xFF14225E), + secondaryContainer: const Color(0xFF2E3C9E), + onSecondaryContainer: const Color(0xFFE3E7FD), + tertiary: const Color(0xFFFFB694), + onTertiary: const Color(0xFF5A1E00), + tertiaryContainer: const Color(0xFF9A3600), + onTertiaryContainer: const Color(0xFFFFDCC9), + error: const Color(0xFFFF9EBB), + onError: const Color(0xFF5E0022), + errorContainer: const Color(0xFF8E1244), + onErrorContainer: const Color(0xFFFFD9E1), + surface: const Color(0xFF131520), + onSurface: const Color(0xFFE5E7F2), + onSurfaceVariant: const Color(0xFFC0C4D6), + surfaceDim: const Color(0xFF131520), + surfaceBright: const Color(0xFF363948), + surfaceContainerLowest: const Color(0xFF0D0F18), + surfaceContainerLow: const Color(0xFF191C2A), + surfaceContainer: const Color(0xFF1D2130), + surfaceContainerHigh: const Color(0xFF272B3C), + surfaceContainerHighest: const Color(0xFF323648), + outline: const Color(0xFF8A8FA3), + outlineVariant: const Color(0xFF434862), + inverseSurface: const Color(0xFFE5E7F2), + onInverseSurface: const Color(0xFF1D2130), + inversePrimary: Brand.primary, + surfaceTint: const Color(0xFFAEB9FF), + ); + +/// Snack bars no wider than [maxWidth] from medium windows on, centred, +/// rather than across the whole window; below, the theme's margins line +/// them up with the floating navigation bar. Around the app's navigator +/// (`MaterialApp.builder`), since the theme can't know the window. +class const FittedSnackBars({required final Widget child, super.key}) + extends StatelessWidget { + /// How wide a snack bar is at most, from medium windows on. + static const maxWidth = 560.0; + + /// The same widgets above [child] in every window, only the theme in + /// them changing: a widget added or left out above it as the window + /// crosses a size would build the app's navigator, and every screen in + /// it, anew. + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Theme( + data: context.windowSize.isAtLeastMedium + ? theme.copyWith( + snackBarTheme: theme.snackBarTheme.copyWith(width: maxWidth), + ) + : theme, + child: child, + ); + } +} diff --git a/packages/halkyon_ui/lib/src/theme/brand.dart b/packages/halkyon_ui/lib/src/theme/brand.dart new file mode 100644 index 0000000..f31411a --- /dev/null +++ b/packages/halkyon_ui/lib/src/theme/brand.dart @@ -0,0 +1,13 @@ +import 'package:material_ui/material_ui.dart'; + +/// Halkyon's brand colours, taken from the kingfisher of its icon, the same +/// in every Halkyon app. +abstract final class Brand() { + /// Cobalt blue: the primary colour, recurring across the icon's gradients. + static const Color primary = Color(0xFF273EB2); + + /// Deep copper orange: the accent, a warm contrast to the cobalt. Set as + /// the colour scheme's tertiary, so it stays this exact orange instead of + /// one derived from the cobalt. + static const Color accent = Color(0xFFC44800); +} diff --git a/packages/halkyon_ui/lib/src/theme/palette_color.dart b/packages/halkyon_ui/lib/src/theme/palette_color.dart new file mode 100644 index 0000000..14592b1 --- /dev/null +++ b/packages/halkyon_ui/lib/src/theme/palette_color.dart @@ -0,0 +1,58 @@ +import 'package:material_ui/material_ui.dart'; + +/// The colours a person can give content (a set of cards, a list, a tag): +/// twenty named colours, the names of Proton's label colours. +/// +/// They are not theme colours: something someone made cobalt stays cobalt in +/// light and dark mode alike. Content stores a colour by its [name], the +/// same in every Halkyon app. +/// +/// Each colour is a triple: the [background] fill (bars, chips, dots), the +/// [foreground] for text and icons on that fill (black or white, whichever +/// contrasts more; every pair reaches WCAG AA, which a test guards), and a +/// darker [outline] for borders and focus rings. +enum PaletteColor( + /// The fill. + final Color background, + + /// Text and icons on [background]. + final Color foreground, + + /// Borders and focus rings, where the fill alone lacks definition. + final Color outline, +) { + carrot(Color(0xFFF78400), _black, Color(0xFFBA680A)), + cerise(Color(0xFFBA1E55), _white, Color(0xFF861F43)), + cobalt(Color(0xFF273EB2), _white, Color(0xFF263580)), + copper(Color(0xFFC44800), _white, Color(0xFF8A3707)), + enzian(Color(0xFF5252CC), _white, Color(0xFF4141AA)), + fern(Color(0xFF3CBB3A), _black, Color(0xFF398A38)), + forest(Color(0xFF258723), _white, Color(0xFF20591E)), + ocean(Color(0xFF0A77A6), _white, Color(0xFF0D5270)), + olive(Color(0xFFB4A40E), _black, Color(0xFF7D7311)), + pacific(Color(0xFF179FD9), _black, Color(0xFF1C79A1)), + pickle(Color(0xFF807304), _white, Color(0xFF4A4307)), + pine(Color(0xFF0F735A), _white, Color(0xFF0D4235)), + pink(Color(0xFFDB60D7), _black, Color(0xFFC543C0)), + plum(Color(0xFFA939A4), _white, Color(0xFF793577)), + purple(Color(0xFF8080FF), _black, Color(0xFF5656F6)), + reef(Color(0xFF1DA583), _black, Color(0xFF1D725D)), + sahara(Color(0xFF936D59), _white, Color(0xFF6A584E)), + slateblue(Color(0xFF415DF0), _white, Color(0xFF1F3EDF)), + soil(Color(0xFF54473F), _white, Color(0xFF32302E)), + strawberry(Color(0xFFEC3E7C), _black, Color(0xFFD52263)); + + /// The colour stored as [name], or null for none or an unknown name, e.g. + /// one a newer app version added. + static PaletteColor? byName(String? name) { + for (final color in values) { + if (color.name == name) { + return color; + } + } + return null; + } +} + +const _black = Color(0xFF000000); +const _white = Color(0xFFFFFFFF); diff --git a/packages/halkyon_ui/lib/src/theme/theme_extras.dart b/packages/halkyon_ui/lib/src/theme/theme_extras.dart new file mode 100644 index 0000000..e6750ff --- /dev/null +++ b/packages/halkyon_ui/lib/src/theme/theme_extras.dart @@ -0,0 +1,73 @@ +import 'package:material_ui/material_ui.dart'; + +/// The status colours Material's colour scheme has no role for, for +/// feedback: success, warning and info (error is in the scheme). An app's +/// own colours (a study app's ratings, say) are an extension of its own, +/// passed to `appTheme` beside these. +final class const ThemeExtras({ + required final Color success, + required final Color onSuccess, + required final Color warning, + required final Color onWarning, + required final Color info, + required final Color onInfo, +}) extends ThemeExtension { + /// On light surfaces. + static const light = ThemeExtras( + success: Color(0xFF1EA885), + onSuccess: Color(0xFFFFFFFF), + warning: Color(0xFFFF9900), + onWarning: Color(0xFF000000), + info: Color(0xFF239ECE), + onInfo: Color(0xFFFFFFFF), + ); + + /// On dark surfaces: a little brighter, for contrast. + static const dark = ThemeExtras( + success: Color(0xFF35B191), + onSuccess: Color(0xFFFFFFFF), + warning: Color(0xFFFFA31A), + onWarning: Color(0xFF000000), + info: Color(0xFF39A8D3), + onInfo: Color(0xFFFFFFFF), + ); + + @override + ThemeExtras copyWith({ + Color? success, + Color? onSuccess, + Color? warning, + Color? onWarning, + Color? info, + Color? onInfo, + }) => ThemeExtras( + success: success ?? this.success, + onSuccess: onSuccess ?? this.onSuccess, + warning: warning ?? this.warning, + onWarning: onWarning ?? this.onWarning, + info: info ?? this.info, + onInfo: onInfo ?? this.onInfo, + ); + + @override + ThemeExtras lerp(ThemeExtras? other, double t) { + if (other == null) { + return this; + } + Color mix(Color a, Color b) => Color.lerp(a, b, t)!; + return ThemeExtras( + success: mix(success, other.success), + onSuccess: mix(onSuccess, other.onSuccess), + warning: mix(warning, other.warning), + onWarning: mix(onWarning, other.onWarning), + info: mix(info, other.info), + onInfo: mix(onInfo, other.onInfo), + ); + } +} + +/// `Theme.of(context).extras`. +extension ThemeExtrasOf on ThemeData { + /// This theme's [ThemeExtras]; every theme from `appTheme` has them. + ThemeExtras get extras => extension()!; +} diff --git a/packages/halkyon_ui/lib/src/widget/adaptive_sheet.dart b/packages/halkyon_ui/lib/src/widget/adaptive_sheet.dart new file mode 100644 index 0000000..5ad20e7 --- /dev/null +++ b/packages/halkyon_ui/lib/src/widget/adaptive_sheet.dart @@ -0,0 +1,392 @@ +import 'dart:math' as math; + +import 'package:flutter/foundation.dart'; + +import 'package:halkyon_ui/l10n/halkyon_ui_localizations.dart'; +import 'package:halkyon_ui/src/layout/window_size.dart'; +import 'package:lucide_icons_flutter/lucide_icons.dart'; +import 'package:material_ui/material_ui.dart'; + +/// Shows [builder]'s sheet, usually a [SheetScaffold], as a bottom sheet in +/// windows below expanded and as a dialog from there on; completes with the +/// sheet's result either way. +/// +/// Expanded rather than Material's medium, because a bottom sheet is a touch +/// surface: medium windows are mostly tablets, expanded ones mostly +/// desktops, where a sheet rising from the bottom of a monitor reads as a +/// phone screen moved over. +/// +/// A sheet that asks before discarding changes (with a `PopScope`) passes +/// [swipeable] false: a bottom sheet swiped away closes without asking its +/// `PopScope` (Flutter issue 152120, open with v3.47), so it then has no +/// drag handle, and closes by its close button, the back gesture or a tap +/// beside it, which all ask. +Future showAdaptiveSheet( + BuildContext context, { + required WidgetBuilder builder, + bool swipeable = true, +}) { + if (!context.windowSize.isAtLeastExpanded) { + return showModalBottomSheet( + context: context, + useRootNavigator: true, + isScrollControlled: true, + // A sheet as tall as the window, as one is with the keyboard open, + // would otherwise reach under the status bar. + useSafeArea: true, + showDragHandle: swipeable, + enableDrag: swipeable, + builder: (context) => _Presentation( + isDialog: false, + hasDragHandle: swipeable, + child: builder(context), + ), + ); + } + return showDialog( + context: context, + builder: (context) => Dialog( + // More room than an alert's default: sheets hold forms and lists. + insetPadding: const EdgeInsets.symmetric(horizontal: 40, vertical: 32), + clipBehavior: Clip.antiAlias, + child: _Presentation( + isDialog: true, + hasDragHandle: false, + child: builder(context), + ), + ), + ); +} + +/// Tells a [SheetScaffold] how it shows: as a dialog or a bottom sheet, and +/// whether a drag handle sits above it. +class const _Presentation({ + required final bool isDialog, + required final bool hasDragHandle, + required super.child, +}) extends InheritedWidget { + /// How the sheet at [context] shows; a sheet shown some other way is a + /// bottom sheet with a handle, as Material's own are. + static ({bool isDialog, bool hasDragHandle}) at(BuildContext context) => + switch (context.dependOnInheritedWidgetOfExactType<_Presentation>()) { + final presentation? => ( + isDialog: presentation.isDialog, + hasDragHandle: presentation.hasDragHandle, + ), + null => (isDialog: false, hasDragHandle: true), + }; + + @override + bool updateShouldNotify(_Presentation oldWidget) => + isDialog != oldWidget.isDialog || + hasDragHandle != oldWidget.hasDragHandle; +} + +/// The frame of a sheet from [showAdaptiveSheet]: the [title] with a close +/// button on top, the [body] below, and the [footer], usually the action that +/// completes the sheet, at the bottom. Only the body scrolls, so the close +/// button and the footer stay in view however long the body grows. +/// +/// As a bottom sheet it hugs its content up to 85 % of the window's height, +/// or always takes [heightFactor] of it when that is set: a long form whose +/// optional parts come and go then doesn't jump. It stays above the keyboard. +/// As a dialog it hugs its content, at most 640 dp high and 720 dp wide +/// however large the monitor, since a share of a big screen is a slab. +class const SheetScaffold({ + /// The sheet's title. + required final String title, + + /// The content; a scroll view holds it, so it is a plain column rather + /// than a list. + required final Widget body, + + /// Below the content, always in view. + final Widget? footer, + + /// Beside the title, before the close button: an action on the sheet as a + /// whole, such as managing what it lists. + final Widget? action, + + /// What the close button does; by default it asks the sheet's route to + /// close, which a `PopScope` in the sheet can stop (to ask before + /// discarding changes, say). + final VoidCallback? onClose, + + /// The share of the window's height a bottom sheet takes; it hugs its + /// content when null. + final double? heightFactor, + + /// Whether snack bars shown from inside the sheet show on it, where they + /// can be acted on (an Undo, say); those of the screens below would sit + /// behind its barrier. The sheet then always takes its largest height. + final bool hasSnackBars = false, + + /// Whether something runs that mustn't be cut off, as an import: the + /// close button is off, greyed, and back does nothing until it ends. A + /// sheet that can be busy is shown with `swipeable` false, as a bottom + /// sheet swiped away closes whatever it holds says. + final bool busy = false, + super.key, +}) extends StatelessWidget { + /// The widest a sheet grows as a dialog. + static const dialogMaxWidth = 720.0; + + /// The tallest a sheet grows as a dialog. + static const dialogMaxHeight = 640.0; + + /// The line under the title while some of the body lies above. + static const moreAboveKey = ValueKey('sheet-more-above'); + + /// The line above the footer while some of the body lies below. + static const moreBelowKey = ValueKey('sheet-more-below'); + + @override + Widget build(BuildContext context) { + final media = MediaQuery.of(context); + final presentation = _Presentation.at(context); + final isDialog = presentation.isDialog; + final heightFactor = this.heightFactor; + // The sides' room goes inside the scroll view, not around it: a scroll + // view cuts what it holds at its edges, outlines' outer half pixel + // included, and its scrollbar runs along its edge. + final side = isDialog ? 24.0 : 20.0; + Widget inset(Widget child) => Padding( + padding: EdgeInsets.symmetric(horizontal: side), + child: child, + ); + final column = Column( + mainAxisSize: isDialog || heightFactor == null + ? MainAxisSize.min + : MainAxisSize.max, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + inset( + _Header( + title: title, + action: action, + onClose: busy + ? null + : onClose ?? () => Navigator.of(context).maybePop(), + ), + ), + // Loose, so a short body keeps the sheet short; tight at a fixed + // height, so the footer sits at the bottom. + if (!isDialog && heightFactor != null) + Expanded( + child: _ScrollingBody( + body: body, + side: side, + fill: true, + footer: footer, + ), + ) + else + Flexible( + child: _ScrollingBody(body: body, side: side, footer: footer), + ), + if (footer case final footer?) ...[ + const SizedBox(height: 12), + inset(footer), + ], + ], + ); + final content = PopScope( + canPop: !busy, + child: hasSnackBars + ? ScaffoldMessenger( + child: Scaffold( + backgroundColor: Colors.transparent, + // The sheet keeps clear of the keyboard itself. + resizeToAvoidBottomInset: false, + body: column, + ), + ) + : column, + ); + if (isDialog) { + // The dialog keeps clear of the window's edges and the keyboard + // itself; insetting here as well would count them twice. + return ConstrainedBox( + constraints: BoxConstraints( + maxWidth: dialogMaxWidth, + maxHeight: math.min(dialogMaxHeight, media.size.height - 64), + ), + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 20), + child: content, + ), + ); + } + // A drag handle above gives the top its space. + final padding = EdgeInsets.fromLTRB( + 0, + presentation.hasDragHandle ? 0 : 16, + 0, + 16, + ); + // What's left once the keyboard and the system's bottom inset are + // taken: raising the keyboard shrinks the body rather than pushing the + // sheet off the window. + final available = + media.size.height - + media.viewInsets.bottom - + media.padding.bottom - + padding.vertical; + return Padding( + padding: EdgeInsets.only(bottom: media.viewInsets.bottom), + child: SafeArea( + top: false, + child: Padding( + padding: padding, + child: heightFactor == null + ? ConstrainedBox( + constraints: BoxConstraints( + maxHeight: math.min(media.size.height * 0.85, available), + ), + child: content, + ) + : SizedBox( + height: math.min(media.size.height * heightFactor, available), + child: content, + ), + ), + ), + ); + } +} + +/// The sheet's title and its close button, off without [onClose]. The +/// button is there beside swiping the sheet away, which fails with wet +/// fingers, gloves or a sheet taller than the window, and a dialog can't be +/// swiped at all. +class const _Header({ + required final String title, + required final Widget? action, + required final VoidCallback? onClose, +}) extends StatelessWidget { + @override + Widget build(BuildContext context) => Row( + children: [ + Expanded( + child: Text( + title, + style: Theme.of(context).textTheme.titleMedium, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + ?action, + IconButton( + tooltip: HalkyonUiLocalizations.of(context).close, + icon: const Icon(LucideIcons.x), + onPressed: onClose, + ), + ], + ); +} + +/// The sheet's body, scrolling, with a scrollbar beside it (always shown on +/// the desktop, where a wheel or touchpad scrolls without showing one) and, +/// as Material 3 has scrolling dialogs, a line under the title while some of +/// it lies above, and one above the [footer] while some of it lies below +/// (a form's last switches went unnoticed below the buttons without). [fill] takes the whole height given, rather than hugging the +/// body. +class const _ScrollingBody({ + required final Widget body, + required final Widget? footer, + + /// The room at its sides, inside the scroll view. + required final double side, + final bool fill = false, +}) extends StatefulWidget { + @override + State<_ScrollingBody> createState() => _ScrollingBodyState(); +} + +const _bodyKey = ValueKey('sheet-body'); + +class _ScrollingBodyState() extends State<_ScrollingBody> { + final _scroll = ScrollController(); + var _moreAbove = false; + var _moreBelow = false; + + void _update(ScrollMetrics metrics) { + final moreAbove = metrics.pixels > metrics.minScrollExtent; + final moreBelow = metrics.pixels < metrics.maxScrollExtent; + if (moreAbove != _moreAbove || moreBelow != _moreBelow) { + setState(() { + _moreAbove = moreAbove; + _moreBelow = moreBelow; + }); + } + } + + @override + void dispose() { + _scroll.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final desktop = switch (defaultTargetPlatform) { + TargetPlatform.linux || + TargetPlatform.windows || + TargetPlatform.macOS => true, + _ => false, + }; + // The lines keep their room while hidden, so the body doesn't jump. + Widget line({required bool shown, required Key key}) => shown + ? Divider( + key: key, + height: 1, + indent: widget.side, + endIndent: widget.side, + ) + : const SizedBox(height: 1); + final scrolling = NotificationListener( + // Also when the body's size changes, as a section opens. + onNotification: (notification) { + _update(notification.metrics); + return false; + }, + child: NotificationListener( + onNotification: (notification) { + _update(notification.metrics); + return false; + }, + child: Scrollbar( + controller: _scroll, + thumbVisibility: desktop, + // In place of the one Material's scroll behaviour adds on the + // desktop, shown only while scrolling. + child: ScrollConfiguration( + behavior: ScrollConfiguration.of( + context, + ).copyWith(scrollbars: false), + child: SingleChildScrollView( + controller: _scroll, + padding: EdgeInsets.symmetric(horizontal: widget.side), + child: widget.body, + ), + ), + ), + ), + ); + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + line(shown: _moreAbove, key: SheetScaffold.moreAboveKey), + // Keyed, so that a line coming or going beside it keeps the scroll + // view and its position. + if (widget.fill) + Expanded(key: _bodyKey, child: scrolling) + else + Flexible(key: _bodyKey, child: scrolling), + if (widget.footer != null) + line(shown: _moreBelow, key: SheetScaffold.moreBelowKey), + ], + ); + } +} diff --git a/packages/halkyon_ui/lib/src/widget/app_loading_indicator.dart b/packages/halkyon_ui/lib/src/widget/app_loading_indicator.dart new file mode 100644 index 0000000..9788eea --- /dev/null +++ b/packages/halkyon_ui/lib/src/widget/app_loading_indicator.dart @@ -0,0 +1,154 @@ +import 'package:expressive_loading_indicator/expressive_loading_indicator.dart'; +import 'package:material_ui/material_ui.dart'; + +/// The app's spinner for anything still loading: Material 3 Expressive's +/// morphing indicator, which Flutter doesn't ship yet. Every loading state +/// shows this widget, a button's too ([ButtonLoadingIndicator]) and pulling +/// a list down ([AppRefreshIndicator]), so swapping in the SDK's own +/// indicator one day changes one file. Determinate progress (a mastery +/// ring) stays a [CircularProgressIndicator]. +class const AppLoadingIndicator({ + /// The side of its square; Material's 48 dp when null. + final double? size, + + /// Its colour; the theme's primary colour when null. + final Color? color, + super.key, +}) extends StatelessWidget { + @override + Widget build(BuildContext context) => ExpressiveLoadingIndicator( + color: color, + constraints: switch (size) { + final size? => BoxConstraints.tightFor(width: size, height: size), + null => null, + }, + ); +} + +/// The app's spinner in a button, in place of its icon or label while what +/// it started is under way: small, in the button's own colour. +class const ButtonLoadingIndicator({super.key}) extends StatelessWidget { + @override + Widget build(BuildContext context) => AppLoadingIndicator( + size: 20, + color: + IconTheme.of(context).color ?? DefaultTextStyle.of(context).style.color, + ); +} + +/// Pulling [child] down runs [onRefresh], the app's spinner showing +/// meanwhile, as Material 3 Expressive's pull to refresh has it: in a small +/// round container that comes down with the pull and stays while it +/// refreshes. Flutter's own [RefreshIndicator] draws the older spinner, so +/// it only does the pulling here (its `noSpinner` kind). +class const AppRefreshIndicator({ + required final RefreshCallback onRefresh, + required final Widget child, + super.key, +}) extends StatefulWidget { + /// How far down the container comes at most, and stays while refreshing. + static const restingTop = 24.0; + + /// The container's side. + static const containerSize = 44.0; + + @override + State createState() => _AppRefreshIndicatorState(); +} + +class _AppRefreshIndicatorState() extends State { + RefreshIndicatorStatus? _status; + + /// How far the list was pulled past its top, in logical pixels. + var _pulled = 0.0; + + bool _tracked(ScrollNotification notification) { + if (notification.depth != 0 || notification.metrics.axis != Axis.vertical) { + return false; + } + switch (notification) { + case ScrollStartNotification(): + if (_status != RefreshIndicatorStatus.refresh) { + _pulled = 0; + } + case OverscrollNotification(:final overscroll) + when overscroll < 0 && notification.metrics.extentBefore == 0: + setState(() => _pulled -= overscroll); + case ScrollUpdateNotification(:final scrollDelta?) + when _pulled > 0 && scrollDelta > 0: + setState(() => _pulled = (_pulled - scrollDelta).clamp(0, _pulled)); + // A list that bounces (iOS) goes past its top by itself. + case ScrollUpdateNotification(:final metrics) + when metrics.pixels < metrics.minScrollExtent: + setState(() => _pulled = metrics.minScrollExtent - metrics.pixels); + default: + break; + } + return false; + } + + @override + Widget build(BuildContext context) { + final colors = Theme.of(context).colorScheme; + final status = _status; + final refreshing = + status == RefreshIndicatorStatus.refresh || + status == RefreshIndicatorStatus.snap; + final pulling = + status == RefreshIndicatorStatus.drag || + status == RefreshIndicatorStatus.armed; + const size = AppRefreshIndicator.containerSize; + // Comes down with the pull, half as fast as the finger, to rest. + final top = refreshing + ? AppRefreshIndicator.restingTop + : (_pulled / 2 - size).clamp(-size, AppRefreshIndicator.restingTop); + final shown = refreshing || (pulling && _pulled > 0); + return Stack( + children: [ + NotificationListener( + onNotification: _tracked, + child: RefreshIndicator.noSpinner( + onRefresh: widget.onRefresh, + onStatusChange: (status) => setState(() { + _status = status; + if (status == RefreshIndicatorStatus.done || + status == RefreshIndicatorStatus.canceled) { + _pulled = 0; + } + }), + child: widget.child, + ), + ), + Positioned( + top: top, + left: 0, + right: 0, + child: IgnorePointer( + child: AnimatedOpacity( + opacity: shown ? 1 : 0, + duration: const Duration(milliseconds: 150), + child: Center( + child: Material( + color: colors.primaryContainer, + shape: const CircleBorder(), + elevation: 3, + child: SizedBox.square( + dimension: size, + child: Padding( + padding: const EdgeInsets.all(4), + child: shown + ? AppLoadingIndicator( + color: colors.onPrimaryContainer, + ) + : null, + ), + ), + ), + ), + ), + ), + ), + ], + ); + } +} diff --git a/packages/halkyon_ui/lib/src/widget/brand_wordmark.dart b/packages/halkyon_ui/lib/src/widget/brand_wordmark.dart new file mode 100644 index 0000000..7177f34 --- /dev/null +++ b/packages/halkyon_ui/lib/src/widget/brand_wordmark.dart @@ -0,0 +1,33 @@ +import 'package:halkyon_ui/l10n/halkyon_ui_localizations.dart'; +import 'package:material_ui/material_ui.dart'; + +/// "Halkyon" over the app's [product] word ("Learn", "Todo"), in Halkyon's +/// font, cobalt and copper as the logo has them. The logo's own typeface +/// (ITC Avant Garde) isn't free to ship with an app. Screen readers don't +/// hear it: the screen showing it names the app its own way. +class const BrandWordmark({ + /// The app's own word below the brand's. + required final String product, + super.key, +}) extends StatelessWidget { + @override + Widget build(BuildContext context) { + final l10n = HalkyonUiLocalizations.of(context); + final theme = Theme.of(context); + final scheme = theme.colorScheme; + final word = theme.textTheme.displaySmall?.copyWith( + fontWeight: FontWeight.w800, + height: 1.05, + letterSpacing: -0.5, + ); + return ExcludeSemantics( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text(l10n.brand, style: word?.copyWith(color: scheme.primary)), + Text(product, style: word?.copyWith(color: scheme.tertiary)), + ], + ), + ); + } +} diff --git a/packages/halkyon_ui/lib/src/widget/chevron_field.dart b/packages/halkyon_ui/lib/src/widget/chevron_field.dart new file mode 100644 index 0000000..176de8e --- /dev/null +++ b/packages/halkyon_ui/lib/src/widget/chevron_field.dart @@ -0,0 +1,79 @@ +import 'package:lucide_icons_flutter/lucide_icons.dart'; +import 'package:material_ui/material_ui.dart'; + +/// A form's field whose value is set on a screen of its own, or in a +/// dialog: it shows the [value], up to [maxLines] lines, or the +/// [placeholder] in italics while there is none, and a chevron leads on, as +/// tapping opens it. So the form never holds what needs a whole window (an +/// editor, a map) or a check of its own (a handle). Without [onTap] it only +/// shows the value. +class const ChevronField({ + /// What the field holds, above it. + required final String label, + + /// The value as text; null while there is none. + required final String? value, + + /// What shows while there is no value, inviting to set one. + required final String placeholder, + + /// Opens what sets the value; null where it can't change. + required final VoidCallback? onTap, + final int maxLines = 3, + + /// What is said below the field. + final String? helperText, + + /// Why the value was refused, below the field in place of [helperText]. + final String? errorText, + super.key, +}) extends StatelessWidget { + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final colors = theme.colorScheme; + return InputDecorator( + decoration: InputDecoration( + labelText: label, + border: const OutlineInputBorder(), + contentPadding: const EdgeInsets.fromLTRB(12, 12, 4, 12), + helperText: helperText, + helperMaxLines: 3, + errorText: errorText, + errorMaxLines: 3, + ), + child: InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(4), + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Row( + children: [ + Expanded( + child: Text( + value ?? placeholder, + maxLines: maxLines, + overflow: TextOverflow.ellipsis, + style: theme.textTheme.bodyMedium?.copyWith( + color: value == null + ? colors.onSurfaceVariant + : colors.onSurface, + fontStyle: value == null ? FontStyle.italic : null, + ), + ), + ), + if (onTap != null) ...[ + const SizedBox(width: 8), + Icon( + LucideIcons.chevronRight, + size: 18, + color: colors.onSurfaceVariant, + ), + ], + ], + ), + ), + ), + ); + } +} diff --git a/packages/halkyon_ui/lib/src/widget/collapsing_row.dart b/packages/halkyon_ui/lib/src/widget/collapsing_row.dart new file mode 100644 index 0000000..aec42e3 --- /dev/null +++ b/packages/halkyon_ui/lib/src/widget/collapsing_row.dart @@ -0,0 +1,175 @@ +import 'dart:math' as math; + +import 'package:flutter/rendering.dart'; +import 'package:material_ui/material_ui.dart'; + +/// A row of `leading` (tabs, a title) and, at its end, the first of +/// `levels` that leaves `leading` all the width it would take: the levels +/// are the same tools from the widest (every button with its label) to +/// the narrowest (all of them in a ⋮ menu), so where room runs short the +/// tools fold one by one rather than cutting `leading` off. `leading` +/// takes what the level chosen leaves, its natural width at most; the +/// level stands at the row's end. Only the level chosen shows; the others +/// are kept, unseen and untouchable, so their state stays. +// Not const: its children are a list made of the leading child and the +// levels. +// ignore: prefer_const_constructors_in_immutables +class CollapsingRow({ + required Widget leading, + required List levels, + super.key, +}) extends MultiChildRenderObjectWidget { + this + : assert(levels.isNotEmpty, 'There is always a level to choose'), + super(children: [leading, ...levels]); + + @override + RenderObject createRenderObject(BuildContext context) => + RenderCollapsingRow(); +} + +/// Lays out a [CollapsingRow]: its first child the leading one, the rest +/// the levels, widest first. +class RenderCollapsingRow() + extends RenderBox + with + ContainerRenderObjectMixin, + RenderBoxContainerDefaultsMixin { + /// The level shown, by its index among the levels. + @visibleForTesting + int chosen = 0; + + @override + void setupParentData(RenderBox child) { + if (child.parentData is! _RowParentData) { + child.parentData = _RowParentData(); + } + } + + List get _children => getChildrenAsList(); + + RenderBox get _leading => _children.first; + + List get _levels => _children.sublist(1); + + /// The widest level leaving the leading child its natural width in + /// [width]; the narrowest when none does. + int _choose(double width) { + final need = _leading.getMaxIntrinsicWidth(double.infinity); + final levels = _levels; + for (final (index, level) in levels.indexed) { + if (need + level.getMaxIntrinsicWidth(double.infinity) <= width) { + return index; + } + } + return levels.length - 1; + } + + @override + double computeMinIntrinsicWidth(double height) => + _levels.last.getMinIntrinsicWidth(height); + + @override + double computeMaxIntrinsicWidth(double height) => + _leading.getMaxIntrinsicWidth(height) + + _levels.first.getMaxIntrinsicWidth(height); + + @override + double computeMinIntrinsicHeight(double width) => _children.fold( + 0, + (most, child) => math.max(most, child.getMinIntrinsicHeight(width)), + ); + + @override + double computeMaxIntrinsicHeight(double width) => _children.fold( + 0, + (most, child) => math.max(most, child.getMaxIntrinsicHeight(width)), + ); + + @override + Size computeDryLayout(BoxConstraints constraints) { + final width = constraints.maxWidth; + final level = _levels[_choose(width)].getDryLayout( + BoxConstraints(maxHeight: constraints.maxHeight), + ); + final leading = _leading.getDryLayout( + BoxConstraints( + maxWidth: math.max(0, width - level.width), + maxHeight: constraints.maxHeight, + ), + ); + return constraints.constrain( + Size(width, math.max(level.height, leading.height)), + ); + } + + @override + void performLayout() { + final width = constraints.maxWidth; + chosen = _choose(width); + final levels = _levels; + for (final (index, level) in levels.indexed) { + level.layout( + index == chosen + ? BoxConstraints(maxHeight: constraints.maxHeight) + : BoxConstraints.tight(Size.zero), + parentUsesSize: true, + ); + } + final level = levels[chosen]; + final leading = _leading + ..layout( + BoxConstraints( + maxWidth: math.max(0, width - level.size.width), + maxHeight: constraints.maxHeight, + ), + parentUsesSize: true, + ); + size = constraints.constrain( + Size(width, math.max(level.size.height, leading.size.height)), + ); + (leading.parentData! as _RowParentData).offset = Offset( + 0, + (size.height - leading.size.height) / 2, + ); + (level.parentData! as _RowParentData).offset = Offset( + size.width - level.size.width, + (size.height - level.size.height) / 2, + ); + } + + /// The children that show: the leading one and the level chosen. + Iterable get _shown => [_leading, _levels[chosen]]; + + @override + void paint(PaintingContext context, Offset offset) { + for (final child in _shown) { + context.paintChild( + child, + (child.parentData! as _RowParentData).offset + offset, + ); + } + } + + @override + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { + for (final child in _shown.toList().reversed) { + final offset = (child.parentData! as _RowParentData).offset; + if (result.addWithPaintOffset( + offset: offset, + position: position, + hitTest: (result, transformed) => + child.hitTest(result, position: transformed), + )) { + return true; + } + } + return false; + } + + @override + void visitChildrenForSemantics(RenderObjectVisitor visitor) => + _shown.forEach(visitor); +} + +class _RowParentData() extends ContainerBoxParentData; diff --git a/packages/halkyon_ui/lib/src/widget/confirm_dialog.dart b/packages/halkyon_ui/lib/src/widget/confirm_dialog.dart new file mode 100644 index 0000000..a5daf72 --- /dev/null +++ b/packages/halkyon_ui/lib/src/widget/confirm_dialog.dart @@ -0,0 +1,31 @@ +import 'package:halkyon_ui/l10n/halkyon_ui_localizations.dart'; +import 'package:material_ui/material_ui.dart'; + +/// Asks before something that can't be taken back: true only when the person +/// confirms; cancelling or dismissing the dialog is false. +Future confirmDestructiveAction( + BuildContext context, { + required String title, + required String message, + required String confirmLabel, +}) async { + final l10n = HalkyonUiLocalizations.of(context); + final confirmed = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text(title), + content: Text(message), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), + child: Text(l10n.cancel), + ), + FilledButton.tonal( + onPressed: () => Navigator.of(context).pop(true), + child: Text(confirmLabel), + ), + ], + ), + ); + return confirmed ?? false; +} diff --git a/packages/halkyon_ui/lib/src/widget/count_badge.dart b/packages/halkyon_ui/lib/src/widget/count_badge.dart new file mode 100644 index 0000000..75a1fee --- /dev/null +++ b/packages/halkyon_ui/lib/src/widget/count_badge.dart @@ -0,0 +1,21 @@ +import 'package:material_ui/material_ui.dart'; + +/// How many something holds, in a small box beside its name: a tab, a +/// section, a screen's title. +class const CountBadge({required final int count, super.key}) + extends StatelessWidget { + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return DecoratedBox( + decoration: BoxDecoration( + color: theme.colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(6), + ), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + child: Text('$count', style: theme.textTheme.labelMedium), + ), + ); + } +} diff --git a/packages/halkyon_ui/lib/src/widget/count_stepper.dart b/packages/halkyon_ui/lib/src/widget/count_stepper.dart new file mode 100644 index 0000000..d587e0c --- /dev/null +++ b/packages/halkyon_ui/lib/src/widget/count_stepper.dart @@ -0,0 +1,180 @@ +import 'dart:math' as math; + +import 'package:flutter/services.dart'; +import 'package:halkyon_ui/l10n/halkyon_ui_localizations.dart'; +import 'package:lucide_icons_flutter/lucide_icons.dart'; +import 'package:material_ui/material_ui.dart'; + +/// A number between a minus and a plus, the width of what holds it, in an +/// outlined box: the number bold ([style], body text by default), [suffix] +/// (" / day") lighter after it. A null action can't go further. +/// +/// With [onTyped], tapping the number lets one type another in its place, +/// such as 12 between steps of 5 ([stepUp], [stepDown]); it is handed over +/// once confirmed or left, if it is a number from 1. +class const CountStepper({ + required final String value, + required final VoidCallback? onFewer, + required final VoidCallback? onMore, + + /// Said after the number, lighter. + final String suffix = '', + + /// The number's style, before it is made bold. + final TextStyle? style, + + /// The number typed, from 1; none to type without. + final ValueChanged? onTyped, + + /// The number to start typing over: [value] as a number. + final int? number, + super.key, +}) extends StatefulWidget { + /// The most digits a number typed has. + static const maxDigits = 4; + + @override + State createState() => _CountStepperState(); +} + +class _CountStepperState() extends State { + var _typing = false; + final _field = TextEditingController(); + final _focus = FocusNode(); + + @override + void initState() { + super.initState(); + _focus.addListener(() { + if (!_focus.hasFocus && _typing) { + _confirm(); + } + }); + } + + @override + void dispose() { + _field.dispose(); + _focus.dispose(); + super.dispose(); + } + + void _type() { + _field.text = '${widget.number ?? ''}'; + _field.selection = TextSelection( + baseOffset: 0, + extentOffset: _field.text.length, + ); + setState(() => _typing = true); + _focus.requestFocus(); + } + + void _confirm() { + final typed = int.tryParse(_field.text); + setState(() => _typing = false); + if (typed != null && typed >= 1) { + widget.onTyped?.call(typed); + } + } + + @override + Widget build(BuildContext context) { + final l10n = HalkyonUiLocalizations.of(context); + final theme = Theme.of(context); + final colors = theme.colorScheme; + final numberStyle = (widget.style ?? theme.textTheme.bodyLarge)?.copyWith( + color: colors.onSurface, + fontWeight: FontWeight.w600, + ); + final shown = Text.rich( + TextSpan( + text: widget.value, + children: [ + if (widget.suffix.isNotEmpty) + TextSpan( + text: widget.suffix, + style: theme.textTheme.bodyMedium?.copyWith( + color: colors.onSurfaceVariant, + fontWeight: FontWeight.w400, + ), + ), + ], + ), + textAlign: TextAlign.center, + style: numberStyle, + ); + final typable = widget.onTyped != null; + return DecoratedBox( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(12), + border: Border.all(color: colors.outlineVariant), + ), + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Row( + children: [ + IconButton( + tooltip: l10n.decrease, + onPressed: _typing ? null : widget.onFewer, + icon: const Icon(LucideIcons.minus), + ), + Expanded( + child: _typing + ? TextField( + controller: _field, + focusNode: _focus, + textAlign: TextAlign.center, + style: numberStyle, + keyboardType: TextInputType.number, + textInputAction: TextInputAction.done, + inputFormatters: [ + FilteringTextInputFormatter.digitsOnly, + LengthLimitingTextInputFormatter( + CountStepper.maxDigits, + ), + ], + decoration: InputDecoration( + isDense: true, + border: InputBorder.none, + hintText: l10n.typeANumber, + ), + onSubmitted: (_) => _focus.unfocus(), + ) + : typable + ? Tooltip( + message: l10n.typeANumber, + child: InkWell( + borderRadius: BorderRadius.circular(8), + onTap: _type, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 8), + child: shown, + ), + ), + ) + : shown, + ), + IconButton( + tooltip: l10n.increase, + onPressed: _typing ? null : widget.onMore, + icon: const Icon(LucideIcons.plus), + ), + ], + ), + ), + ); + } +} + +/// [value] up to the next multiple of [step], at most [max]: 12 to 15 in +/// steps of 5. +int stepUp(int value, int step, {required int max}) => + math.min(max, (value ~/ step + 1) * step); + +/// [value] down to the multiple of [step] below it, never below the first +/// step: 12 to 10, 15 to 10 in steps of 5. Smaller numbers are typed. +int stepDown(int value, int step) => + math.max(step, ((value - 1) ~/ step) * step); + +/// Whether [value] can step down: it is above the first step. +bool canStepDown(int value, int step) => value > step; diff --git a/packages/halkyon_ui/lib/src/widget/empty_list_message.dart b/packages/halkyon_ui/lib/src/widget/empty_list_message.dart new file mode 100644 index 0000000..cc7cfc4 --- /dev/null +++ b/packages/halkyon_ui/lib/src/widget/empty_list_message.dart @@ -0,0 +1,44 @@ +import 'package:material_ui/material_ui.dart'; + +/// What a list shows while it holds nothing yet, every list alike: an +/// [icon] for what it lists, a [title] saying there is none yet, +/// and a [hint] saying how to add some. +class const EmptyListMessage({ + /// What the list holds, e.g. a folder for files. + required final IconData icon, + + /// That there is nothing yet, e.g. "No files yet". + required final String title, + + /// How to add something, naming the menus to go through. + required final String hint, + super.key, +}) extends StatelessWidget { + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 40, color: theme.colorScheme.onSurfaceVariant), + const SizedBox(height: 12), + Text( + title, + textAlign: TextAlign.center, + style: theme.textTheme.titleMedium, + ), + const SizedBox(height: 4), + Text( + hint, + textAlign: TextAlign.center, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ); + } +} diff --git a/packages/halkyon_ui/lib/src/widget/field_label.dart b/packages/halkyon_ui/lib/src/widget/field_label.dart new file mode 100644 index 0000000..07a22b8 --- /dev/null +++ b/packages/halkyon_ui/lib/src/widget/field_label.dart @@ -0,0 +1,53 @@ +import 'package:halkyon_ui/l10n/halkyon_ui_localizations.dart'; +import 'package:lucide_icons_flutter/lucide_icons.dart'; +import 'package:material_ui/material_ui.dart'; + +/// [decoration] marked as a required field's, as every required field is +/// (in place of an asterisk): while [missing], nothing +/// but spaces written, its outline (or its line) stronger, in the primary +/// colour, and "Required" below it, before its own helper text; once +/// written, its own helper text, or an empty line in its place, so nothing +/// below moves. +InputDecoration requiredDecoration( + BuildContext context, + InputDecoration decoration, { + required bool missing, +}) { + final own = decoration.helperText; + if (!missing) { + return decoration.copyWith(helperText: own ?? ' '); + } + final theme = Theme.of(context); + final required = HalkyonUiLocalizations.of(context).requiredField; + final side = BorderSide(color: theme.colorScheme.primary, width: 2); + return decoration.copyWith( + enabledBorder: switch (decoration.border ?? + theme.inputDecorationTheme.border) { + final OutlineInputBorder outline => outline.copyWith(borderSide: side), + _ => UnderlineInputBorder(borderSide: side), + }, + helperText: own == null ? required : '$required · $own', + helperStyle: (decoration.helperStyle ?? theme.textTheme.bodySmall) + ?.copyWith(color: theme.colorScheme.primary), + ); +} + +/// A question mark at a field's end that explains it: [message] shows on a +/// tap (or hovering) and stays for a while to be read. +class const FieldInfoButton(final String message, {super.key}) + extends StatelessWidget { + @override + Widget build(BuildContext context) => Tooltip( + message: message, + triggerMode: TooltipTriggerMode.tap, + showDuration: const Duration(seconds: 8), + child: Padding( + padding: const EdgeInsets.all(8), + child: Icon( + LucideIcons.circleQuestionMark, + size: 18, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + ); +} diff --git a/packages/halkyon_ui/lib/src/widget/floating_navigation_bar.dart b/packages/halkyon_ui/lib/src/widget/floating_navigation_bar.dart new file mode 100644 index 0000000..7d59d5e --- /dev/null +++ b/packages/halkyon_ui/lib/src/widget/floating_navigation_bar.dart @@ -0,0 +1,59 @@ +import 'dart:math' as math; + +import 'package:material_ui/material_ui.dart'; + +/// A navigation bar detached from the window's bottom edge, as iOS 26's tab +/// bar floats: [bar] in a rounded bar [sideMargin] in from the sides and +/// [lift] above the system's own bar, lifted as the navigation bar is +/// (elevation level 2). Material 3 has no floating navigation bar for +/// phones (only in its guidelines for headsets); this one keeps the +/// Expressive bar's height and colours. Around it shows the scaffold's +/// background, which the app's shell takes from the screen in view. +class const FloatingNavigationBar({ + /// The bar: a [NavigationBar] without a background or elevation of its + /// own. + required final Widget bar, + super.key, +}) extends StatelessWidget { + /// How far in from the window's sides the bar stands. + static const sideMargin = 16.0; + + /// How far above the system's own bar (a phone's gesture bar or buttons) + /// the bar floats. + static const lift = 8.0; + + /// How much of the window's foot the bar covers beyond the system's own + /// bar, for what [context] shows beneath it; none without it. A floating + /// button keeps clear of the system's bar by itself, but not of this. + static double coverOf(BuildContext context) => math.max( + 0, + MediaQuery.paddingOf(context).bottom - + MediaQuery.viewPaddingOf(context).bottom, + ); + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + return Padding( + padding: EdgeInsets.fromLTRB( + sideMargin, + 0, + sideMargin, + MediaQuery.paddingOf(context).bottom + lift, + ), + child: Material( + color: scheme.surfaceContainer, + elevation: 3, + shape: const StadiumBorder(), + clipBehavior: Clip.antiAlias, + // The bar's own safe area would keep it clear of the system's bar + // a second time. + child: MediaQuery.removePadding( + context: context, + removeBottom: true, + child: bar, + ), + ), + ); + } +} diff --git a/packages/halkyon_ui/lib/src/widget/found_by_id.dart b/packages/halkyon_ui/lib/src/widget/found_by_id.dart new file mode 100644 index 0000000..52f10ce --- /dev/null +++ b/packages/halkyon_ui/lib/src/widget/found_by_id.dart @@ -0,0 +1,98 @@ +import 'package:halkyon_ui/l10n/halkyon_ui_localizations.dart'; +import 'package:halkyon_ui/src/widget/app_loading_indicator.dart'; +import 'package:material_ui/material_ui.dart'; + +/// Builds a screen for the item a route's [id] names, found in a live list of +/// items: a spinner until the first list arrives, and a "no longer exists" +/// screen while the list has no such item (deleted, perhaps on another +/// device), with [wayBack] below it if given. +/// +/// A screen that closes as its item goes, having deleted it, keeps showing +/// the item on its way out. +class const FoundById({ + /// The id from the route. + required final String id, + + /// The live list to look in; subscribed to once. + required final Stream> Function() items, + + /// An item's id. + required final String Function(T item) idOf, + + /// The screen for the item found, given the whole list too. + required final Widget Function(T item, List items) builder, + + /// What the "no longer exists" screen's button says, and where it leads. + final ({String label, VoidCallback onPressed})? wayBack, + super.key, +}) extends StatefulWidget { + @override + State> createState() => _FoundByIdState(); +} + +class _FoundByIdState() extends State> { + late final Stream> _items = widget.items(); + + /// The item as last found, and the list it was in. + T? _found; + List _foundIn = const []; + + @override + Widget build(BuildContext context) => StreamBuilder>( + stream: _items, + builder: (context, snapshot) { + final items = snapshot.data; + if (items == null) { + return Scaffold( + appBar: AppBar(), + body: const Center(child: AppLoadingIndicator()), + ); + } + for (final item in items) { + if (widget.idOf(item) == widget.id) { + _found = item; + _foundIn = items; + return widget.builder(item, items); + } + } + // A route stops being active as soon as it is popped, while its + // closing transition still shows it. + final found = _found; + if (found != null && !(ModalRoute.of(context)?.isActive ?? true)) { + return widget.builder(found, _foundIn); + } + return _Gone(wayBack: widget.wayBack); + }, + ); +} + +class const _Gone({ + required final ({String label, VoidCallback onPressed})? wayBack, +}) extends StatelessWidget { + @override + Widget build(BuildContext context) { + final l10n = HalkyonUiLocalizations.of(context); + final way = wayBack; + return Scaffold( + appBar: AppBar(), + body: Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text(l10n.gone, textAlign: TextAlign.center), + if (way != null) ...[ + const SizedBox(height: 12), + FilledButton( + onPressed: way.onPressed, + child: Text(way.label), + ), + ], + ], + ), + ), + ), + ); + } +} diff --git a/packages/halkyon_ui/lib/src/widget/keyboard_back_on_resume.dart b/packages/halkyon_ui/lib/src/widget/keyboard_back_on_resume.dart new file mode 100644 index 0000000..5d3f7d2 --- /dev/null +++ b/packages/halkyon_ui/lib/src/widget/keyboard_back_on_resume.dart @@ -0,0 +1,46 @@ +import 'package:material_ui/material_ui.dart'; + +/// Coming back to the app with a text field focused brings its keyboard +/// back, as other apps on Android do. +/// +/// Flutter (checked with v3.47.5) gives the window back its keyboard's +/// height after the app was left while the keyboard was moving, though no +/// keyboard shows: the screen stays pushed up, as if it were there +/// ([flutter#191156](https://github.com/flutter/flutter/issues/191156), +/// open). With the keyboard back, the height is the keyboard's again. +/// Remove this once that is fixed. +class const KeyboardBackOnResume({required final Widget child, super.key}) + extends StatefulWidget { + @override + State createState() => _KeyboardBackOnResumeState(); +} + +class _KeyboardBackOnResumeState() extends State { + late final AppLifecycleListener _lifecycle; + + @override + void initState() { + super.initState(); + _lifecycle = AppLifecycleListener(onResume: _resumed); + } + + @override + void dispose() { + _lifecycle.dispose(); + super.dispose(); + } + + void _resumed() { + // Once the window is back, when the keyboard may show. + WidgetsBinding.instance.addPostFrameCallback((_) { + final field = FocusManager.instance.primaryFocus?.context + ?.findAncestorStateOfType(); + if (field != null && field.mounted && field.widget.focusNode.hasFocus) { + field.requestKeyboard(); + } + }); + } + + @override + Widget build(BuildContext context) => widget.child; +} diff --git a/packages/halkyon_ui/lib/src/widget/launch_screen.dart b/packages/halkyon_ui/lib/src/widget/launch_screen.dart new file mode 100644 index 0000000..ee77480 --- /dev/null +++ b/packages/halkyon_ui/lib/src/widget/launch_screen.dart @@ -0,0 +1,56 @@ +import 'package:halkyon_ui/src/widget/brand_wordmark.dart'; +import 'package:material_ui/material_ui.dart'; + +/// What shows while an app opens (its instance, the session, the person's +/// data): the app's [icon], and beneath it the [BrandWordmark] with its +/// [product] word, then a quiet line of progress; read out as the app's +/// [name]. +class const LaunchScreen({ + /// The app's icon, square; it shows rounded as a launcher rounds it. + required final ImageProvider icon, + + /// The app's own word, below "Halkyon". + required final String product, + + /// The app's name, as screen readers hear the screen. + required final String name, + super.key, +}) extends StatelessWidget { + /// How large the icon shows. + static const iconSize = 112.0; + + @override + Widget build(BuildContext context) => Scaffold( + body: Center( + child: Semantics( + label: name, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + ExcludeSemantics( + child: ClipRRect( + // As the launcher rounds it. + borderRadius: BorderRadius.circular(iconSize * 0.22), + child: Image( + // No more than three times its size in memory, whatever + // the source's. + image: ResizeImage.resizeIfNeeded( + (iconSize * 3).round(), + null, + icon, + ), + width: iconSize, + height: iconSize, + ), + ), + ), + const SizedBox(height: 24), + BrandWordmark(product: product), + const SizedBox(height: 32), + const SizedBox(width: 120, child: LinearProgressIndicator()), + ], + ), + ), + ), + ); +} diff --git a/packages/halkyon_ui/lib/src/widget/lift_while_dragged.dart b/packages/halkyon_ui/lib/src/widget/lift_while_dragged.dart new file mode 100644 index 0000000..22ddf5c --- /dev/null +++ b/packages/halkyon_ui/lib/src/widget/lift_while_dragged.dart @@ -0,0 +1,17 @@ +import 'package:material_ui/material_ui.dart'; + +/// How a row of a [SliverReorderableList] shows while it is dragged +/// elsewhere: rising onto a shadow, on a surface of its own, as Material's +/// own reorderable lists show it. +Widget liftWhileDragged( + Widget child, + int index, + Animation animation, +) => AnimatedBuilder( + animation: animation, + builder: (context, child) => Material( + elevation: 6 * Curves.easeInOut.transform(animation.value), + child: child, + ), + child: child, +); diff --git a/packages/halkyon_ui/lib/src/widget/more_info_sheet.dart b/packages/halkyon_ui/lib/src/widget/more_info_sheet.dart new file mode 100644 index 0000000..54a11c3 --- /dev/null +++ b/packages/halkyon_ui/lib/src/widget/more_info_sheet.dart @@ -0,0 +1,114 @@ +import 'package:flutter/services.dart'; +import 'package:halkyon_ui/l10n/halkyon_ui_localizations.dart'; +import 'package:halkyon_ui/src/widget/adaptive_sheet.dart'; +import 'package:halkyon_ui/src/widget/section_card.dart'; +import 'package:intl/intl.dart'; +import 'package:lucide_icons_flutter/lucide_icons.dart'; +import 'package:material_ui/material_ui.dart'; + +/// A fact about something: its name, and its value; a copyable one (an +/// id) is set in a monospace font and copied with a tap. +typedef InfoRow = ({String label, String value, bool copyable}); + +/// Facts that belong together, under a title if any. +typedef InfoSection = ({String? title, List rows}); + +/// [at] as a fact shows a moment: the date and the time of day, local. +String infoTime(BuildContext context, DateTime at) => DateFormat.yMMMd( + Localizations.localeOf(context).toLanguageTag(), +).add_jm().format(at.toLocal()); + +/// Shows [sections] of facts about something, each in a card of its own: +/// "More info". +Future showMoreInfoSheet( + BuildContext context, + List sections, +) => showAdaptiveSheet( + context, + builder: (context) => SheetScaffold( + title: HalkyonUiLocalizations.of(context).moreInfo, + body: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (final (:title, :rows) in sections) + if (rows.isNotEmpty) + Padding( + padding: const EdgeInsets.only(bottom: 12), + child: SectionCard( + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 10, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (title != null) + Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Text( + title, + style: Theme.of(context).textTheme.titleSmall, + ), + ), + for (final row in rows) _Row(row), + ], + ), + ), + ), + ], + ), + ), +); + +class const _Row(final InfoRow row) extends StatelessWidget { + void _copy(BuildContext context) { + final messenger = ScaffoldMessenger.of(context); + final l10n = HalkyonUiLocalizations.of(context); + Clipboard.setData(ClipboardData(text: row.value)); + messenger + ..hideCurrentSnackBar() + ..showSnackBar(SnackBar(content: Text(l10n.copiedToClipboard))); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final text = Padding( + padding: const EdgeInsets.symmetric(vertical: 6), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + row.label, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + const SizedBox(height: 2), + Text( + row.value, + style: row.copyable + ? theme.textTheme.bodyMedium?.copyWith(fontFamily: 'monospace') + : theme.textTheme.bodyMedium, + ), + ], + ), + ); + if (!row.copyable) { + return text; + } + return InkWell( + onTap: () => _copy(context), + child: Row( + children: [ + Expanded(child: text), + IconButton( + tooltip: HalkyonUiLocalizations.of(context).copy, + icon: const Icon(LucideIcons.copy, size: 18), + onPressed: () => _copy(context), + ), + ], + ), + ); + } +} diff --git a/packages/halkyon_ui/lib/src/widget/palette_color_picker.dart b/packages/halkyon_ui/lib/src/widget/palette_color_picker.dart new file mode 100644 index 0000000..2d4512a --- /dev/null +++ b/packages/halkyon_ui/lib/src/widget/palette_color_picker.dart @@ -0,0 +1,145 @@ +import 'package:halkyon_ui/l10n/halkyon_ui_localizations.dart'; +import 'package:halkyon_ui/src/theme/palette_color.dart'; +import 'package:lucide_icons_flutter/lucide_icons.dart'; +import 'package:material_ui/material_ui.dart'; + +/// A field holding one of the palette's colours: it shows the colour with its +/// name, and opens a grid of all twenty to choose from. +class const PaletteColorPicker({ + /// The colour chosen. + required final PaletteColor selected, + + /// Called with the colour the person chooses. + required final ValueChanged onChanged, + super.key, +}) extends StatefulWidget { + @override + State createState() => _PaletteColorPickerState(); +} + +class _PaletteColorPickerState() extends State { + final _menu = MenuController(); + var _open = false; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final l10n = HalkyonUiLocalizations.of(context); + final name = l10n.paletteColorName(widget.selected.name); + return MenuAnchor( + controller: _menu, + onOpen: () => setState(() => _open = true), + onClose: () => setState(() => _open = false), + style: MenuStyle( + padding: const WidgetStatePropertyAll(EdgeInsets.all(12)), + backgroundColor: WidgetStatePropertyAll( + theme.colorScheme.surfaceContainer, + ), + shape: WidgetStatePropertyAll( + RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + ), + ), + menuChildren: [ + _Grid( + selected: widget.selected, + onChanged: (color) { + widget.onChanged(color); + _menu.close(); + }, + ), + ], + builder: (context, menu, _) => Semantics( + button: true, + label: l10n.colorPickerLabel(name), + excludeSemantics: true, + child: InkWell( + onTap: () => menu.isOpen ? menu.close() : menu.open(), + borderRadius: BorderRadius.circular(8), + child: Container( + decoration: BoxDecoration( + // Like an outlined text field: its outline thickens and takes + // the primary colour while open. + border: Border.all( + color: _open + ? theme.colorScheme.primary + : theme.colorScheme.outline, + width: _open ? 2 : 1, + ), + borderRadius: BorderRadius.circular(8), + ), + padding: EdgeInsets.all(_open ? 11 : 12), + child: Row( + children: [ + _Dot(color: widget.selected.background, size: 16), + const SizedBox(width: 12), + Expanded(child: Text(name, style: theme.textTheme.bodyMedium)), + Icon( + _open ? LucideIcons.chevronUp : LucideIcons.chevronDown, + size: 18, + color: theme.colorScheme.onSurfaceVariant, + ), + ], + ), + ), + ), + ), + ); + } +} + +/// All twenty colours, the chosen one ringed in the primary colour. +class const _Grid({ + required final PaletteColor selected, + required final ValueChanged onChanged, +}) extends StatelessWidget { + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final l10n = HalkyonUiLocalizations.of(context); + return ConstrainedBox( + // Five colours a row. + constraints: const BoxConstraints(maxWidth: 232), + child: Wrap( + spacing: 8, + runSpacing: 8, + children: [ + for (final color in PaletteColor.values) + Semantics( + label: l10n.paletteColorName(color.name), + selected: color == selected, + button: true, + excludeSemantics: true, + child: InkResponse( + onTap: () => onChanged(color), + radius: 24, + child: Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: color.background, + shape: BoxShape.circle, + border: Border.all( + color: color == selected + ? theme.colorScheme.primary + : color.outline, + width: color == selected ? 3 : 1, + ), + ), + ), + ), + ), + ], + ), + ); + } +} + +class const _Dot({required final Color color, required final double size}) + extends StatelessWidget { + @override + Widget build(BuildContext context) => Container( + width: size, + height: size, + decoration: BoxDecoration(color: color, shape: BoxShape.circle), + ); +} diff --git a/packages/halkyon_ui/lib/src/widget/reorder_grip.dart b/packages/halkyon_ui/lib/src/widget/reorder_grip.dart new file mode 100644 index 0000000..8cf0c46 --- /dev/null +++ b/packages/halkyon_ui/lib/src/widget/reorder_grip.dart @@ -0,0 +1,22 @@ +import 'package:halkyon_ui/l10n/halkyon_ui_localizations.dart'; +import 'package:lucide_icons_flutter/lucide_icons.dart'; +import 'package:material_ui/material_ui.dart'; + +/// The handle a row is dragged by while its list is reordered, in place of +/// its options: the row at [index] of the [SliverReorderableList] around. +class const ReorderGrip({required final int index, super.key}) + extends StatelessWidget { + @override + Widget build(BuildContext context) => ReorderableDragStartListener( + index: index, + child: IconButton( + tooltip: HalkyonUiLocalizations.of(context).dragToReorder, + // The drag starts on the pointer going down; a tap does nothing. + onPressed: () {}, + icon: Icon( + LucideIcons.gripHorizontal, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + ); +} diff --git a/packages/halkyon_ui/lib/src/widget/reorder_toggle.dart b/packages/halkyon_ui/lib/src/widget/reorder_toggle.dart new file mode 100644 index 0000000..564efc0 --- /dev/null +++ b/packages/halkyon_ui/lib/src/widget/reorder_toggle.dart @@ -0,0 +1,40 @@ +import 'package:halkyon_ui/l10n/halkyon_ui_localizations.dart'; +import 'package:lucide_icons_flutter/lucide_icons.dart'; +import 'package:material_ui/material_ui.dart'; + +/// Beside a list that can be put in another order: Reorder, and Done while +/// [reordering]; [labelled] with its word, else an icon alone whose +/// [tooltip] says what it reorders. +class const ReorderToggle({ + /// Whether the list shows handles to drag its rows by. + required final bool reordering, + + /// Whether there is room for the word beside the icon. + required final bool labelled, + + /// What the icon alone reorders, e.g. "Reorder lists". + required final String tooltip, + + /// Starts reordering, or ends it. + required final VoidCallback onToggle, + super.key, +}) extends StatelessWidget { + @override + Widget build(BuildContext context) { + final l10n = HalkyonUiLocalizations.of(context); + final icon = reordering ? LucideIcons.check : LucideIcons.arrowUpDown; + return labelled + ? TextButton.icon( + onPressed: onToggle, + icon: Icon(icon, size: 18), + label: Text( + reordering ? l10n.reorderDone : l10n.reorder, + ), + ) + : IconButton( + tooltip: reordering ? l10n.reorderDone : tooltip, + onPressed: onToggle, + icon: Icon(icon), + ); + } +} diff --git a/packages/halkyon_ui/lib/src/widget/screen_tint.dart b/packages/halkyon_ui/lib/src/widget/screen_tint.dart new file mode 100644 index 0000000..881a6ae --- /dev/null +++ b/packages/halkyon_ui/lib/src/widget/screen_tint.dart @@ -0,0 +1,58 @@ +import 'package:halkyon_ui/src/theme/brand.dart'; +import 'package:material_ui/material_ui.dart'; + +/// The colour of the screen in view, for the frame around the tabs to take +/// (as Vaia does): from medium windows on, the navigation rail and the +/// margin around the content panel show it, maroon beside something a +/// person made cerise, cobalt elsewhere. A screen with a `TopGradient` claims +/// its colour while it is the one in view; cobalt until one does. On phones, +/// its background shows around the floating navigation bar. +class ScreenTint() extends ChangeNotifier { + Color _color = Brand.primary; + Color? _background; + + /// The colour claimed last. + Color get color => _color; + + /// The background claimed last; none before a screen claims one. + Color? get background => _background; + + /// Shows [color] and [background] from now on. + void show(Color color, {required Color background}) { + if (color != _color || background != _background) { + _color = color; + _background = background; + notifyListeners(); + } + } +} + +/// Hands the [ScreenTint] of the frame around the tabs down to their screens. +class const ScreenTintScope({ + required super.notifier, + required super.child, + super.key, +}) extends InheritedNotifier { + /// The tint above [context], without depending on its changes: for a screen + /// that claims it; null outside the tabs. + static ScreenTint? maybeOf(BuildContext context) => + context.getInheritedWidgetOfExactType()?.notifier; +} + +/// The colour of the screens below it: the colour a person gave something +/// (a collection, a list), or that of the nearest one above it, for every +/// screen of it, as Vaia carries a set's colour; cobalt without. +class const ScreenColor({ + /// The colour. + required final Color color, + required super.child, + super.key, +}) extends InheritedWidget { + /// The colour above [context]; cobalt where none is. + static Color of(BuildContext context) => + context.dependOnInheritedWidgetOfExactType()?.color ?? + Brand.primary; + + @override + bool updateShouldNotify(ScreenColor oldWidget) => color != oldWidget.color; +} diff --git a/packages/halkyon_ui/lib/src/widget/scroll_hiding_fab.dart b/packages/halkyon_ui/lib/src/widget/scroll_hiding_fab.dart new file mode 100644 index 0000000..70a2058 --- /dev/null +++ b/packages/halkyon_ui/lib/src/widget/scroll_hiding_fab.dart @@ -0,0 +1,70 @@ +import 'package:flutter/rendering.dart'; +import 'package:material_ui/material_ui.dart'; + +/// A floating action button that slides away while the person scrolls down, +/// reading onwards, and comes back as soon as they scroll up. [builder] +/// builds the screen around the button it is handed (as its scaffold's +/// floating action button); the scrolling in that screen moves it. +/// +/// While hidden, the button can't be tapped through its fading ghost. A list +/// short enough not to scroll keeps it in view: it covers nothing there. +class const ScrollHidingFab({ + /// The button; none when null, as in windows that put the action in the + /// app bar instead. + required final Widget? fab, + + /// The screen, given the button to place. + required final Widget Function(BuildContext context, Widget? fab) builder, + super.key, +}) extends StatefulWidget { + @override + State createState() => _ScrollHidingFabState(); +} + +class _ScrollHidingFabState() extends State { + var _visible = true; + + bool _onScroll(UserScrollNotification notification) { + // Only the screen's own vertical scrolling: a sideways swipe between + // tabs moves nothing. + if (notification.metrics.axis != Axis.vertical) { + return false; + } + final visible = switch (notification.direction) { + // A list that doesn't scroll covers nothing behind the button, and an + // overscroll bounce there mustn't hide it. + ScrollDirection.reverse => notification.metrics.maxScrollExtent <= 0, + ScrollDirection.forward => true, + ScrollDirection.idle => _visible, + }; + if (visible != _visible) { + setState(() => _visible = visible); + } + return false; + } + + @override + Widget build(BuildContext context) { + final fab = widget.fab; + return NotificationListener( + onNotification: _onScroll, + child: widget.builder( + context, + fab == null + ? null + : AnimatedSlide( + duration: const Duration(milliseconds: 200), + curve: Curves.easeOut, + // Twice its own height clears the window's edge whatever + // the button's size. + offset: _visible ? Offset.zero : const Offset(0, 2), + child: AnimatedOpacity( + duration: const Duration(milliseconds: 200), + opacity: _visible ? 1 : 0, + child: IgnorePointer(ignoring: !_visible, child: fab), + ), + ), + ), + ); + } +} diff --git a/packages/halkyon_ui/lib/src/widget/section_card.dart b/packages/halkyon_ui/lib/src/widget/section_card.dart new file mode 100644 index 0000000..b0dfc8a --- /dev/null +++ b/packages/halkyon_ui/lib/src/widget/section_card.dart @@ -0,0 +1,54 @@ +import 'package:material_ui/material_ui.dart'; + +/// A block of a screen: a card with a 16 dp corner radius, a thin outline and +/// no shadow, meant for the lightly tinted background screens use +/// (`surfaceContainerLow`), against which its surface stands out. +/// +/// [padding] is 16 dp inside by default; content that brings its own gutter, +/// such as a tab bar flush with the edge, passes [EdgeInsets.zero]. +class const SectionCard({ + /// The block's content. + required final Widget child, + + /// The space inside the card, around [child]. + final EdgeInsetsGeometry padding = const EdgeInsets.all(16), + + /// Whether a list scrolls inside it: pulled past its end on Android, the + /// whole card stretches, its frame with it, rather than the list within a + /// frame that stays put. + final bool scrolls = false, + super.key, +}) extends StatelessWidget { + @override + Widget build(BuildContext context) { + final stretches = + scrolls && Theme.of(context).platform == TargetPlatform.android; + final card = Card( + margin: EdgeInsets.zero, + elevation: 0, + clipBehavior: Clip.antiAlias, + shape: RoundedRectangleBorder( + side: BorderSide(color: Theme.of(context).colorScheme.outlineVariant), + borderRadius: BorderRadius.circular(16), + ), + child: Padding( + padding: padding, + child: stretches + // The list's own stretch is off: the card's takes its place. + ? ScrollConfiguration( + behavior: ScrollConfiguration.of( + context, + ).copyWith(overscroll: false), + child: child, + ) + : child, + ), + ); + return stretches + ? StretchingOverscrollIndicator( + axisDirection: AxisDirection.down, + child: card, + ) + : card; + } +} diff --git a/packages/halkyon_ui/lib/src/widget/sliver_centered.dart b/packages/halkyon_ui/lib/src/widget/sliver_centered.dart new file mode 100644 index 0000000..f0333cc --- /dev/null +++ b/packages/halkyon_ui/lib/src/widget/sliver_centered.dart @@ -0,0 +1,26 @@ +import 'package:material_ui/material_ui.dart'; + +/// [child] in the middle of the room a scrolling list leaves below what +/// comes before it, inside [padding]: what a list shows in place of its rows +/// while they load, or when there are none. +/// +/// The padding sits inside the room rather than around it, as a +/// [SliverPadding] would put its bottom below the screen's edge. +class const SliverCentered({ + /// What it shows. + required final Widget child, + + /// The space kept clear around the room, e.g. for a bar floating over the + /// list's bottom. + final EdgeInsets padding = EdgeInsets.zero, + super.key, +}) extends StatelessWidget { + @override + Widget build(BuildContext context) => SliverFillRemaining( + hasScrollBody: false, + child: Padding( + padding: padding, + child: Center(child: child), + ), + ); +} diff --git a/packages/halkyon_ui/lib/src/widget/tab_visibility.dart b/packages/halkyon_ui/lib/src/widget/tab_visibility.dart new file mode 100644 index 0000000..1ec745e --- /dev/null +++ b/packages/halkyon_ui/lib/src/widget/tab_visibility.dart @@ -0,0 +1,23 @@ +import 'package:material_ui/material_ui.dart'; + +/// Whether the tab a screen is in is the one showing. An app whose tabs stay +/// alive while hidden, each keeping its place, puts one around each tab; a +/// screen that should stop something once its tab is out of view depends on +/// this, and a `TopGradient` gives the frame its colour only while its tab +/// shows. +class const TabVisibility({ + /// Whether the tab shows. + required final bool visible, + required super.child, + super.key, +}) extends InheritedWidget { + /// Whether the tab of [context] shows; true outside the tabs, such as on a + /// screen covering them. + static bool of(BuildContext context) => + context.dependOnInheritedWidgetOfExactType()?.visible ?? + true; + + @override + bool updateShouldNotify(TabVisibility oldWidget) => + visible != oldWidget.visible; +} diff --git a/packages/halkyon_ui/lib/src/widget/text_limits.dart b/packages/halkyon_ui/lib/src/widget/text_limits.dart new file mode 100644 index 0000000..fbbf916 --- /dev/null +++ b/packages/halkyon_ui/lib/src/widget/text_limits.dart @@ -0,0 +1,70 @@ +import 'package:material_ui/material_ui.dart'; + +/// How long what people type into an app's fields may be, by what it is: +/// enough for any real one, short enough to show without breaking a row. A +/// field stops there ([TextField.maxLength]) and counts only near the end +/// ([nearLimitCounter]). Text can still be longer where it came from +/// elsewhere (an older app, an import, another person), so every place that +/// shows it cuts it short as well. A server keeps its own limits where it +/// checks what is sent; an app's fields for those take the server's. +abstract final class TextLimits() { + /// A name shown in a menu, on a chip or a button: a profile, a tag, a + /// button's label. + static const name = 40; + + /// A short line beside a title or above a word: a secondary title, a + /// reading set above characters. + static const secondary = 60; + + /// The title of something holding content: a collection, a note, a + /// document, a video's caption; who holds a licence. + static const title = 120; + + /// One answer or item: a meaning, an option, a category, a task, an + /// answer typed. + static const phrase = 200; + + /// What is searched for. + static const search = 200; + + /// A part of a citation: its authors, title, publisher, and so on. + static const reference = 500; + + /// A message to someone: a report's note, a reply, a question asked. + static const message = 2000; + + /// A web address: a link, a search engine's, an instance's. + static const address = 2000; + + /// An email address: as long as mail allows one (RFC 5321). + static const emailAddress = 254; + + /// A longer text typed as one field: a passage with gaps, a formula. + static const passage = 5000; + + /// The share of a limit from which a field counts its characters. + static const countFrom = 0.8; +} + +/// A text field's counter ([TextField.buildCounter]) that shows only once +/// the text is near its limit, "38 / 40", in the error colour at the limit: +/// a counter under every title would only be noise. +Widget? nearLimitCounter( + BuildContext context, { + required int currentLength, + required int? maxLength, + required bool isFocused, +}) { + if (maxLength == null || currentLength < maxLength * TextLimits.countFrom) { + return null; + } + final theme = Theme.of(context); + return Text( + '$currentLength / $maxLength', + style: theme.textTheme.bodySmall?.copyWith( + color: currentLength >= maxLength + ? theme.colorScheme.error + : theme.colorScheme.onSurfaceVariant, + ), + ); +} diff --git a/packages/halkyon_ui/lib/src/widget/tinted_frame.dart b/packages/halkyon_ui/lib/src/widget/tinted_frame.dart new file mode 100644 index 0000000..c483346 --- /dev/null +++ b/packages/halkyon_ui/lib/src/widget/tinted_frame.dart @@ -0,0 +1,128 @@ +import 'package:halkyon_ui/src/layout/window_size.dart'; +import 'package:halkyon_ui/src/widget/screen_tint.dart'; +import 'package:halkyon_ui/src/widget/top_gradient.dart'; +import 'package:material_ui/material_ui.dart'; + +/// The frame around a screen from medium windows on, as Vaia lays it out: +/// the window takes [tint]'s colour, fading out down +/// the way ([TopGradient.frame]); [rail], if any, sits on it; and the screen +/// is a rounded panel inset beside it. A colour change fades in. +class const TintFrame({ + /// The colour of the screen in view. + required final ScreenTint tint, + + /// The screen. + required final Widget child, + + /// The navigation rail, for the tabs; none for a screen over them. + final Widget? rail, + super.key, +}) extends StatelessWidget { + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final rail = this.rail; + return Scaffold( + backgroundColor: scheme.surface, + body: ListenableBuilder( + listenable: tint, + builder: (context, child) => TweenAnimationBuilder( + tween: ColorTween(end: tint.color), + duration: const Duration(milliseconds: 250), + builder: (context, color, child) => DecoratedBox( + decoration: BoxDecoration( + gradient: TopGradient.frame(scheme, color ?? tint.color), + ), + child: child, + ), + child: child, + ), + child: Row( + children: [ + ?rail, + Expanded( + child: _Panel(alone: rail == null, child: child), + ), + ], + ), + ), + ); + } +} + +/// A screen over the tabs (a session, an editor, settings), framed from medium windows on as the tabs' screens are, without +/// the rail; as it is below that. +class const FramedScreen({required final Widget child, super.key}) + extends StatefulWidget { + @override + State createState() => _FramedScreenState(); +} + +class _FramedScreenState() extends State { + final _tint = ScreenTint(); + + /// Keeps the screen, and what it holds, as the frame comes and goes with + /// the window's size: without, the screen would be built anew at a + /// different depth (a session started over). + final _screen = GlobalKey(); + + @override + void dispose() { + _tint.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final screen = KeyedSubtree(key: _screen, child: widget.child); + return context.windowSize.isAtLeastMedium + ? ScreenTintScope( + notifier: _tint, + child: TintFrame(tint: _tint, child: screen), + ) + : screen; + } +} + +/// The screen: a rounded panel inset on the frame, beside the rail or +/// [alone], with a faint edge. The window's own insets (a tablet's status +/// bar) are outside it, so the screen inside has none. +class const _Panel({required final Widget child, required final bool alone}) + extends StatelessWidget { + /// The margin around it. + static const _gap = 12.0; + + /// How round its corners are. + static const _radius = 16.0; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final insets = MediaQuery.paddingOf(context); + final shape = RoundedRectangleBorder( + borderRadius: BorderRadius.circular(_radius), + side: BorderSide(color: scheme.outlineVariant.withValues(alpha: 0.6)), + ); + return Padding( + padding: EdgeInsets.fromLTRB( + alone ? insets.left + _gap : 0, + insets.top + _gap, + insets.right + _gap, + insets.bottom + _gap, + ), + child: Container( + clipBehavior: Clip.antiAlias, + decoration: ShapeDecoration(color: scheme.surface, shape: shape), + foregroundDecoration: ShapeDecoration(shape: shape), + child: MediaQuery.removePadding( + context: context, + removeLeft: alone, + removeTop: true, + removeRight: true, + removeBottom: true, + child: child, + ), + ), + ); + } +} diff --git a/packages/halkyon_ui/lib/src/widget/title_with_kicker.dart b/packages/halkyon_ui/lib/src/widget/title_with_kicker.dart new file mode 100644 index 0000000..24890e0 --- /dev/null +++ b/packages/halkyon_ui/lib/src/widget/title_with_kicker.dart @@ -0,0 +1,93 @@ +import 'package:material_ui/material_ui.dart'; + +/// A title with an optional kicker above it: a short qualifier, uppercased, +/// letter-spaced and in the primary colour, such as a collection's secondary +/// title. Without a kicker the title shows alone. +/// +/// The title's style is the caller's, to suit each surface (a card, a list +/// row, an app bar); the kicker looks the same everywhere. +class const TitleWithKicker({ + /// The title. + required final String title, + + /// The kicker; none when null or empty. + final String? kicker, + + /// The title's style. + final TextStyle? titleStyle, + + /// The lines the title may take before it is cut short. + final int titleMaxLines = 2, + + /// Beside the title, usually an action. It lines up with the title's + /// first line rather than with the kicker, and the title takes the rest + /// of the width. + final Widget? trailing, + + /// Shown on hovering the title with a mouse, as the whole of a title cut + /// short; never on touch, where a long press means something else. + final String? tooltip, + + /// Keeps the kicker's line free when there is no kicker, so titles (and + /// their [trailing] actions) side by side line up whether or not each has + /// one, as in a grid of cards. + final bool reserveKickerSpace = false, + super.key, +}) extends StatelessWidget { + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final kickerStyle = theme.textTheme.labelSmall?.copyWith( + color: theme.colorScheme.primary, + fontWeight: FontWeight.w600, + letterSpacing: 0.6, + ); + final kicker = this.kicker; + final hasKicker = kicker != null && kicker.isNotEmpty; + final text = Text( + title, + style: titleStyle, + maxLines: titleMaxLines, + overflow: TextOverflow.ellipsis, + ); + final titleText = switch (tooltip) { + final message? => Tooltip( + message: message, + triggerMode: TooltipTriggerMode.manual, + child: text, + ), + null => text, + }; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + if (hasKicker) + Text( + kicker.toUpperCase(), + style: kickerStyle, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ) + else if (reserveKickerSpace) + // A line of the kicker's height, invisible; the no-break space + // gives it a height on every text engine. + Visibility.maintain( + visible: false, + child: Text(' ', style: kickerStyle, maxLines: 1), + ), + if (hasKicker || reserveKickerSpace) const SizedBox(height: 2), + switch (trailing) { + final trailing? => Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded(child: titleText), + trailing, + ], + ), + null => titleText, + }, + ], + ); + } +} diff --git a/packages/halkyon_ui/lib/src/widget/top_gradient.dart b/packages/halkyon_ui/lib/src/widget/top_gradient.dart new file mode 100644 index 0000000..554760b --- /dev/null +++ b/packages/halkyon_ui/lib/src/widget/top_gradient.dart @@ -0,0 +1,210 @@ +import 'package:flutter/services.dart'; +import 'package:halkyon_ui/src/layout/window_size.dart'; +import 'package:halkyon_ui/src/theme/brand.dart'; +import 'package:halkyon_ui/src/widget/screen_tint.dart'; +import 'package:halkyon_ui/src/widget/tab_visibility.dart'; +import 'package:material_ui/material_ui.dart'; + +/// A colour washing down from the top of a screen into its [background]: +/// cobalt on the tabs' screens and settings, the colour a person gave +/// something on its screen and every screen of it ([ScreenColor]), as Vaia +/// does. While the screen is the one in view (its tab showing, its +/// route on top), it gives the frame around it its colour too +/// ([ScreenTint]): the navigation rail takes it. +/// +/// The wash starts in dark mode as a deep shade of [color] (42 % of it over +/// black, as Vaia's: cerise a maroon, cobalt a navy), in light mode as a +/// pastel tint (35 % of it over the background); less where the theme's +/// text on it would fall below WCAG AA (4.5:1), so the app bar reads on +/// every palette colour. It fades out over [extent] below the status bar +/// and stays put while the screen's content scrolls. Inside the frame's +/// panel, where the frame already carries the colour, it is half as +/// strong. +/// +/// The screen's Scaffold and AppBar are transparent on top of it, the app +/// bar with [overlayStyle], since a transparent bar can't tell the status +/// bar's icons which tone they sit on. Content laid out below the app bar +/// (the Scaffold's default) never scrolls under its title. +class const TopGradient({ + /// The colour washed in; the [ScreenColor] above without. + final Color? color, + + /// What the wash fades into: the screen's background. + required final Color background, + + /// The screen, transparent where the wash should show. + required final Widget child, + + /// How far below the status bar the wash reaches: far on Home, about as + /// far as the header elsewhere. + final double extent = 160, + super.key, +}) extends StatefulWidget { + /// The share of [color] over black at the top in dark mode. + static const darkShade = 0.42; + + /// The share of [color] at the top in light mode. + static const lightMix = 0.35; + + /// The contrast text keeps on a tone (WCAG AA). + static const minContrast = 4.5; + + /// How far down the frame fades into the background, as a share of its + /// height. + static const frameFade = 0.6; + + /// How much of its strength the wash keeps inside the frame's panel. + static const panelShare = 0.5; + + @override + State createState() => _TopGradientState(); + + /// The tone at the very top for [color] over [background] in [scheme]: as + /// much of [color] as the scheme's brightness allows ([share] of it), less + /// until [text] (the scheme's `onSurface` without) keeps [minContrast] on + /// it. + static Color topTone( + ColorScheme scheme, + Color color, + Color background, { + Color? text, + double share = 1, + }) { + final on = text ?? scheme.onSurface; + final dark = scheme.brightness == Brightness.dark; + // In dark mode a shade of the colour, faded into the background by + // [share]; in light mode a tint of it over the background. + final full = dark + ? Color.lerp(const Color(0xFF000000), color, darkShade)! + : Color.lerp(background, color, lightMix)!; + for (var step = 0; step <= 20; step++) { + final tone = Color.lerp(background, full, share * (1 - step / 20))!; + if (contrast(tone, on) >= minContrast) { + return tone; + } + } + return background; + } + + /// The frame around a panel from medium windows on (the navigation rail, + /// the margin around the panel): [color] from the top, as strong as the + /// rail's labels (`onSurfaceVariant`) allow, faded into the background + /// [frameFade] of the way down. + static LinearGradient frame(ColorScheme scheme, Color color) => + LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + stops: const [0, frameFade], + colors: [ + topTone(scheme, color, scheme.surface, text: scheme.onSurfaceVariant), + scheme.surface, + ], + ); + + /// The contrast ratio of [a] and [b], as WCAG defines it: 1 to 21. + static double contrast(Color a, Color b) { + final la = a.computeLuminance(); + final lb = b.computeLuminance(); + final (lighter, darker) = la > lb ? (la, lb) : (lb, la); + return (lighter + 0.05) / (darker + 0.05); + } + + /// The status bar's style above the wash: light icons on the dark + /// theme's deep tone, dark ones on the light theme's tint. Only the + /// status bar's fields, as an app bar's own style has; the navigation + /// bar stays as it is. + static SystemUiOverlayStyle overlayStyle(BuildContext context) { + final dark = Theme.of(context).brightness == Brightness.dark; + return SystemUiOverlayStyle( + statusBarColor: Colors.transparent, + statusBarIconBrightness: dark ? Brightness.light : Brightness.dark, + // iOS names the bar's background instead of its icons. + statusBarBrightness: dark ? Brightness.dark : Brightness.light, + systemStatusBarContrastEnforced: false, + ); + } +} + +class _TopGradientState() extends State { + /// Whether the screen is the one in view: its tab showing, its route on + /// top. + var _inView = false; + + /// The colour washed in: the widget's, else the screen's. + var _color = Brand.primary; + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _inView = + TabVisibility.of(context) && + (ModalRoute.of(context)?.isCurrent ?? true); + _color = widget.color ?? ScreenColor.of(context); + _claim(); + } + + @override + void didUpdateWidget(TopGradient oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.color != widget.color || + oldWidget.background != widget.background) { + _color = widget.color ?? ScreenColor.of(context); + _claim(); + } + } + + /// Gives the frame this screen's colour and background while it is in + /// view, after the frame being built, as the frame is built above it. + void _claim() { + final tint = ScreenTintScope.maybeOf(context); + if (tint == null || !_inView) { + return; + } + final color = _color; + final background = widget.background; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted && _inView) { + tint.show(color, background: background); + } + }); + } + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + // In the frame's panel, the frame carries the colour already. + final inPanel = + ScreenTintScope.maybeOf(context) != null && + context.windowSize.isAtLeastMedium; + final top = TopGradient.topTone( + scheme, + _color, + widget.background, + share: inPanel ? TopGradient.panelShare : 1, + ); + return ColoredBox( + color: widget.background, + child: Stack( + fit: StackFit.expand, + children: [ + Positioned( + left: 0, + right: 0, + top: 0, + height: MediaQuery.paddingOf(context).top + widget.extent, + child: DecoratedBox( + decoration: BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [top, widget.background], + ), + ), + ), + ), + widget.child, + ], + ), + ); + } +} diff --git a/packages/halkyon_ui/lib/src/widget/undo_snack_bar.dart b/packages/halkyon_ui/lib/src/widget/undo_snack_bar.dart new file mode 100644 index 0000000..1a8e552 --- /dev/null +++ b/packages/halkyon_ui/lib/src/widget/undo_snack_bar.dart @@ -0,0 +1,27 @@ +import 'package:halkyon_ui/l10n/halkyon_ui_localizations.dart'; +import 'package:material_ui/material_ui.dart'; + +/// Says what just happened ([message]) and offers to undo it for three +/// seconds; [onUndo] runs when the person takes that offer. A new message +/// replaces the one showing. +void showUndoSnackBar( + BuildContext context, { + required String message, + required VoidCallback onUndo, +}) { + final l10n = HalkyonUiLocalizations.of(context); + ScaffoldMessenger.of(context) + ..hideCurrentSnackBar() + ..showSnackBar( + SnackBar( + content: Text(message), + // Shorter than the default four seconds, which feel slow for + // something that already happened. + duration: const Duration(seconds: 3), + // A snack bar with an action stays until dismissed unless told + // otherwise; this one goes, like any other. + persist: false, + action: SnackBarAction(label: l10n.undo, onPressed: onUndo), + ), + ); +} diff --git a/packages/halkyon_ui/pubspec.yaml b/packages/halkyon_ui/pubspec.yaml new file mode 100644 index 0000000..5458fc3 --- /dev/null +++ b/packages/halkyon_ui/pubspec.yaml @@ -0,0 +1,45 @@ +name: halkyon_ui +description: "Halkyon's look, shared by its apps: the theme around cobalt and copper, the bundled Noto Sans, window sizes, and the widgets every app's screens are built of." +version: 0.1.0 +publish_to: none +resolution: workspace + +environment: + sdk: ^3.13.0 + flutter: ^3.44.4 + +dependencies: + # Material 3 Expressive's loading indicator, which Flutter doesn't ship yet + # (AppLoadingIndicator). + expressive_loading_indicator: ^0.0.1 + flutter: + sdk: flutter + # gen-l10n's output imports it; apps take Material's texts from material_ui. + flutter_localizations: + sdk: flutter + intl: ^0.20.3 + lucide_icons_flutter: ^3.1.20 + material_ui: ^1.5.0 + +dev_dependencies: + flutter_test: + sdk: flutter + +flutter: + # Generates HalkyonUiLocalizations from lib/l10n (see l10n.yaml). + generate: true + + assets: + # Noto Sans's licence, for the licence list (registerFontLicenses). + - assets/fonts/OFL-NotoSans.txt + + # Noto Sans for Latin, Greek (polytonic too) and Cyrillic, the same on every + # device and never fetched; each file holds every weight (variable fonts). An + # app reaches it as `packages/halkyon_ui/Noto Sans` (appFontFamily). The CJK + # fonts behind it are the apps' own to bundle (appFontFallback). + fonts: + - family: Noto Sans + fonts: + - asset: assets/fonts/NotoSans-Variable.ttf + - asset: assets/fonts/NotoSans-Italic-Variable.ttf + style: italic diff --git a/packages/halkyon_ui/test/l10n/arb_files_test.dart b/packages/halkyon_ui/test/l10n/arb_files_test.dart new file mode 100644 index 0000000..4d0d667 --- /dev/null +++ b/packages/halkyon_ui/test/l10n/arb_files_test.dart @@ -0,0 +1,70 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; + +/// The messages of the `.arb` file [name] in `lib/l10n/`, without metadata. +Map _messages(String name) => { + for (final MapEntry(:key, :value) in (jsonDecode( + File('lib/l10n/$name').readAsStringSync(), + ) as Map).entries) + if (!key.startsWith('@')) key: value! as String, +}; + +/// The names of the placeholders in [message], with plural and select +/// arguments; the words of their branches don't count. (gen-l10n reads +/// quotes as text here: `use-escaping` is off.) +Set _placeholders(String message) { + final names = {}; + // Even depths hold text and placeholders, odd ones a plural's branches. + var depth = 0; + for (var i = 0; i < message.length; i++) { + switch (message[i]) { + case '{': + final name = RegExp(r'\{\s*(\w+)\s*[,}]').matchAsPrefix(message, i); + if (name != null && depth.isEven) { + names.add(name.group(1)!); + } + depth++; + case '}': + depth--; + } + } + return names; +} + +void main() { + final template = _messages('halkyon_ui_en.arb'); + + test('German has every message, with the same placeholders', () { + final german = _messages('halkyon_ui_de.arb'); + + expect( + template.keys.where((key) => !german.containsKey(key)), + isEmpty, + reason: 'untranslated', + ); + expect( + german.keys.where((key) => !template.containsKey(key)), + isEmpty, + reason: 'not in the template', + ); + for (final MapEntry(:key, :value) in german.entries) { + expect(_placeholders(value), _placeholders(template[key]!), reason: key); + } + }); + + test("the English variants override the template's messages only, with " + 'the same placeholders', () { + for (final variant in ['halkyon_ui_en_GB.arb', 'halkyon_ui_en_US.arb']) { + for (final MapEntry(:key, :value) in _messages(variant).entries) { + expect(template, contains(key), reason: '$variant: $key'); + expect( + _placeholders(value), + _placeholders(template[key]!), + reason: '$variant: $key', + ); + } + } + }); +} diff --git a/packages/halkyon_ui/test/l10n/halkyon_ui_localizations_test.dart b/packages/halkyon_ui/test/l10n/halkyon_ui_localizations_test.dart new file mode 100644 index 0000000..e7b5a14 --- /dev/null +++ b/packages/halkyon_ui/test/l10n/halkyon_ui_localizations_test.dart @@ -0,0 +1,47 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:halkyon_ui/halkyon_ui.dart'; +import 'package:material_ui/material_ui.dart'; + +import '../support/test_app.dart'; + +void main() { + test('speaks British English, American English and German', () { + expect( + lookupHalkyonUiLocalizations(const Locale('en')).colorPickerLabel('X'), + 'Colour: X', + ); + expect( + lookupHalkyonUiLocalizations( + const Locale('en', 'GB'), + ).colorPickerLabel('X'), + 'Colour: X', + ); + expect( + lookupHalkyonUiLocalizations( + const Locale('en', 'US'), + ).colorPickerLabel('X'), + 'Color: X', + ); + expect( + lookupHalkyonUiLocalizations(const Locale('de')).colorPickerLabel('X'), + 'Farbe: X', + ); + }); + + testWidgets("an app adding the package's delegate gets its texts in the " + "app's language", (tester) async { + await tester.pumpWidget( + testApp( + locale: const Locale('de'), + ReorderToggle( + reordering: false, + labelled: true, + tooltip: 'Pfade umsortieren', + onToggle: () {}, + ), + ), + ); + + expect(find.text('Umsortieren'), findsOneWidget); + }); +} diff --git a/packages/halkyon_ui/test/layout/window_size_test.dart b/packages/halkyon_ui/test/layout/window_size_test.dart new file mode 100644 index 0000000..f381f14 --- /dev/null +++ b/packages/halkyon_ui/test/layout/window_size_test.dart @@ -0,0 +1,24 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:halkyon_ui/halkyon_ui.dart'; + +void main() { + test("Material 3's classes, by the window's width", () { + expect(WindowSize.fromWidth(0), WindowSize.compact); + expect(WindowSize.fromWidth(599.9), WindowSize.compact); + expect(WindowSize.fromWidth(600), WindowSize.medium); + expect(WindowSize.fromWidth(839.9), WindowSize.medium); + expect(WindowSize.fromWidth(840), WindowSize.expanded); + expect(WindowSize.fromWidth(1199.9), WindowSize.expanded); + expect(WindowSize.fromWidth(1200), WindowSize.large); + expect(WindowSize.fromWidth(1599.9), WindowSize.large); + expect(WindowSize.fromWidth(1600), WindowSize.extraLarge); + }); + + test('a rail from medium on, desktop layouts from expanded on', () { + expect(WindowSize.compact.isAtLeastMedium, isFalse); + expect(WindowSize.medium.isAtLeastMedium, isTrue); + expect(WindowSize.medium.isAtLeastExpanded, isFalse); + expect(WindowSize.expanded.isAtLeastExpanded, isTrue); + expect(WindowSize.extraLarge.isAtLeastExpanded, isTrue); + }); +} diff --git a/packages/halkyon_ui/test/support/test_app.dart b/packages/halkyon_ui/test/support/test_app.dart new file mode 100644 index 0000000..f1906d4 --- /dev/null +++ b/packages/halkyon_ui/test/support/test_app.dart @@ -0,0 +1,19 @@ +import 'package:halkyon_ui/halkyon_ui.dart'; +import 'package:material_ui/material_ui.dart'; + +/// [home] in an app as a Halkyon app builds one: the theme, and the +/// package's texts beside Material's, in [locale]. +Widget testApp( + Widget home, { + Locale locale = const Locale('en'), + Brightness brightness = Brightness.light, +}) => MaterialApp( + theme: appTheme(brightness), + locale: locale, + localizationsDelegates: const [ + HalkyonUiLocalizations.delegate, + ...GlobalMaterialLocalizations.delegates, + ], + supportedLocales: HalkyonUiLocalizations.supportedLocales, + home: home, +); diff --git a/packages/halkyon_ui/test/theme/app_fonts_test.dart b/packages/halkyon_ui/test/theme/app_fonts_test.dart new file mode 100644 index 0000000..384f707 --- /dev/null +++ b/packages/halkyon_ui/test/theme/app_fonts_test.dart @@ -0,0 +1,89 @@ +import 'dart:ui' as ui; + +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:halkyon_ui/halkyon_ui.dart'; +import 'package:material_ui/material_ui.dart'; + +/// How many pixels [text] inks in [family] at [weight]: heavier strokes ink +/// more. +Future ink(String text, String family, FontWeight weight) async { + final painter = TextPainter( + text: TextSpan( + text: text, + style: TextStyle( + fontFamily: family, + fontSize: 40, + fontWeight: weight, + color: const Color(0xFF000000), + ), + ), + textDirection: TextDirection.ltr, + )..layout(); + final recorder = ui.PictureRecorder(); + painter.paint(Canvas(recorder), Offset.zero); + final image = await recorder.endRecording().toImage( + painter.width.ceil(), + painter.height.ceil(), + ); + final pixels = (await image.toByteData())!; + var inked = 0; + for (var alpha = 3; alpha < pixels.lengthInBytes; alpha += 4) { + if (pixels.getUint8(alpha) > 128) { + inked++; + } + } + return inked; +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test("the font is the package's own, as an app finds a package's font", () { + expect(appFontFamily, 'packages/halkyon_ui/Noto Sans'); + }); + + test("the theme sets text in Noto Sans, with the apps' CJK fonts for what " + 'it lacks, named as an app declares them', () { + for (final brightness in Brightness.values) { + final style = appTheme(brightness).textTheme.bodyLarge!; + expect(style.fontFamily, appFontFamily); + expect(style.fontFamilyFallback, [ + 'Noto Sans JP', + 'Noto Sans SC', + 'Noto Sans TC', + 'Noto Sans KR', + ]); + } + }); + + test("a language's own CJK font comes first, so shared Han characters " + 'take its shapes', () { + expect(appFontFallbackFor(null).first, 'Noto Sans JP'); + expect(appFontFallbackFor('en'), appFontFallback); + expect(appFontFallbackFor('ja').first, 'Noto Sans JP'); + expect(appFontFallbackFor('zh-Hans').first, 'Noto Sans SC'); + expect(appFontFallbackFor('zh').first, 'Noto Sans SC'); + expect(appFontFallbackFor('zh-Hant').first, 'Noto Sans TC'); + expect(appFontFallbackFor('zh-TW').first, 'Noto Sans TC'); + expect(appFontFallbackFor('ko').first, 'Noto Sans KR'); + expect(hasOwnFont('ko'), isTrue); + expect(hasOwnFont('de'), isFalse); + // Every font stays, once. + expect(appFontFallbackFor('ko').toSet(), appFontFallback.toSet()); + expect(appFontFallbackFor('ko'), hasLength(4)); + }); + + test('Noto Sans draws every weight from its one file', () async { + // In this package's own tests it is the root project, whose assets have + // no `packages/` prefix; an app's test of the name is in example/. + final loader = FontLoader(appFontFamily) + ..addFont(rootBundle.load('assets/fonts/NotoSans-Variable.ttf')); + await loader.load(); + + const text = 'Ἀθῆναι Halkyon'; + final regular = await ink(text, appFontFamily, FontWeight.w400); + final bold = await ink(text, appFontFamily, FontWeight.w700); + expect(bold, greaterThan(regular * 1.2)); + }); +} diff --git a/packages/halkyon_ui/test/theme/theme_test.dart b/packages/halkyon_ui/test/theme/theme_test.dart new file mode 100644 index 0000000..e63e49b --- /dev/null +++ b/packages/halkyon_ui/test/theme/theme_test.dart @@ -0,0 +1,99 @@ +import 'dart:math'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:halkyon_ui/halkyon_ui.dart'; +import 'package:material_ui/material_ui.dart'; + +/// WCAG's contrast ratio of two colours, from 1 (none) to 21. +double _contrast(Color a, Color b) { + final (lighter, darker) = ( + max(a.computeLuminance(), b.computeLuminance()), + min(a.computeLuminance(), b.computeLuminance()), + ); + return (lighter + 0.05) / (darker + 0.05); +} + +/// An app's own colours, beside the shared ones. +final class const _AppColors(final Color special) + extends ThemeExtension<_AppColors> { + @override + _AppColors copyWith({Color? special}) => _AppColors(special ?? this.special); + + @override + _AppColors lerp(_AppColors? other, double t) => + other == null ? this : _AppColors(Color.lerp(special, other.special, t)!); +} + +void main() { + group('the picker palette', () { + test('has the 20 colours content can be given', () { + expect(PaletteColor.values, hasLength(20)); + }); + + for (final color in PaletteColor.values) { + test( + '${color.name}: its text colour is readable on its fill (WCAG AA)', + () { + expect( + _contrast(color.foreground, color.background), + greaterThanOrEqualTo(4.5), + ); + }, + ); + } + + test( + 'finds a colour by its stored name, and nothing for an unknown one', + () { + expect(PaletteColor.byName('cobalt'), PaletteColor.cobalt); + expect(PaletteColor.byName('ultraviolet'), isNull); + expect(PaletteColor.byName(null), isNull); + }, + ); + }); + + group('the theme', () { + for (final brightness in Brightness.values) { + test('$brightness: Material 3, with the status colours', () { + final theme = appTheme(brightness); + + expect(theme.useMaterial3, isTrue); + expect(theme.colorScheme.brightness, brightness); + expect(theme.extras, isA()); + }); + } + + test("takes an app's own extensions beside the shared ones", () { + const colors = _AppColors(Color(0xFF123456)); + + final theme = appTheme(Brightness.light, extensions: [colors]); + + expect(theme.extension<_AppColors>(), colors); + expect(theme.extras, ThemeExtras.light); + }); + + test('light: cobalt is the primary colour, copper the accent', () { + final scheme = appTheme(Brightness.light).colorScheme; + + expect(scheme.primary, Brand.primary); + expect(scheme.tertiary, Brand.accent); + }); + + test("dark: the primary colour's text stays readable", () { + final scheme = appTheme(Brightness.dark).colorScheme; + + expect( + _contrast(scheme.onPrimary, scheme.primary), + greaterThanOrEqualTo(4.5), + ); + expect( + _contrast(scheme.onSurface, scheme.surface), + greaterThanOrEqualTo(4.5), + ); + }); + + test("the navigation bar is Material 3 Expressive's shorter one", () { + expect(appTheme(Brightness.light).navigationBarTheme.height, 64); + }); + }); +} diff --git a/packages/halkyon_ui/test/widget/adaptive_sheet_test.dart b/packages/halkyon_ui/test/widget/adaptive_sheet_test.dart new file mode 100644 index 0000000..21037a7 --- /dev/null +++ b/packages/halkyon_ui/test/widget/adaptive_sheet_test.dart @@ -0,0 +1,216 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:halkyon_ui/halkyon_ui.dart'; +import 'package:material_ui/material_ui.dart'; + +void main() { + /// Opens a sheet titled "New studyset" with [body] and a Create button, in + /// a window [width] wide, with a status bar [statusBar] high on top. + Future open( + WidgetTester tester, { + required double width, + Widget body = const Text('Body'), + double statusBar = 0, + bool busy = false, + }) async { + tester.view.physicalSize = Size(width, 900); + tester.view.devicePixelRatio = 1; + tester.view.padding = FakeViewPadding(top: statusBar); + tester.view.viewPadding = FakeViewPadding(top: statusBar); + addTearDown(tester.view.reset); + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: HalkyonUiLocalizations.localizationsDelegates, + supportedLocales: HalkyonUiLocalizations.supportedLocales, + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + onPressed: () => showAdaptiveSheet( + context, + swipeable: !busy, + builder: (context) => SheetScaffold( + title: 'New studyset', + busy: busy, + body: body, + footer: FilledButton( + onPressed: () {}, + child: const Text('Create'), + ), + ), + ), + child: const Text('Open'), + ), + ), + ), + ), + ); + await tester.tap(find.text('Open')); + await tester.pumpAndSettle(); + } + + testWidgets('is a bottom sheet below expanded windows', (tester) async { + await open(tester, width: 839); + + expect(find.byType(BottomSheet), findsOneWidget); + expect(find.byType(Dialog), findsNothing); + }); + + testWidgets('is a dialog from expanded windows on', (tester) async { + await open(tester, width: 840); + + expect(find.byType(Dialog), findsOneWidget); + expect(find.byType(BottomSheet), findsNothing); + }); + + for (final width in [400.0, 1200.0]) { + testWidgets('keeps its close button and footer in view above a long body ' + '(${width.round()} wide)', (tester) async { + await open( + tester, + width: width, + body: Column( + children: [for (var i = 0; i < 80; i++) Text('Line $i')], + ), + ); + + expect(find.byTooltip('Close').hitTestable(), findsOneWidget); + expect(find.text('Create').hitTestable(), findsOneWidget); + }); + } + + testWidgets('stays below the status bar with the keyboard open', ( + tester, + ) async { + await open( + tester, + width: 400, + statusBar: 48, + body: Column( + children: [for (var i = 0; i < 80; i++) Text('Line $i')], + ), + ); + + tester.view.viewInsets = const FakeViewPadding(bottom: 400); + await tester.pumpAndSettle(); + + expect(tester.getTopLeft(find.byType(BottomSheet)).dy, 48); + expect(find.byTooltip('Close').hitTestable(), findsOneWidget); + expect(find.text('Create').hitTestable(), findsOneWidget); + }); + + testWidgets('closes with its close button', (tester) async { + await open(tester, width: 400); + + await tester.tap(find.byTooltip('Close')); + await tester.pumpAndSettle(); + + expect(find.text('New studyset'), findsNothing); + }); + + testWidgets('while busy, its close button is off and back keeps it open', ( + tester, + ) async { + await open(tester, width: 400, busy: true); + + expect( + tester + .widget( + find.ancestor( + of: find.byTooltip('Close'), + matching: find.byType(IconButton), + ), + ) + .onPressed, + isNull, + ); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + expect(find.text('New studyset'), findsOneWidget); + }); + + group('a body longer than the sheet', () { + final tall = Column( + children: [for (var i = 0; i < 40; i++) const Text('Line')], + ); + Finder below() => find.byKey(SheetScaffold.moreBelowKey); + Finder above() => find.byKey(SheetScaffold.moreAboveKey); + + testWidgets('shows a line above the buttons while more lies below, and ' + 'one under the title while more lies above', (tester) async { + // As a dialog: a modal bottom sheet takes a test's drag itself. + await open(tester, width: 1000, body: tall); + + expect(below(), findsOneWidget); + expect(above(), findsNothing); + + await tester.drag( + find.byType(SingleChildScrollView), + const Offset(0, -300), + ); + await tester.pumpAndSettle(); + expect(below(), findsOneWidget); + expect(above(), findsOneWidget); + expect( + tester + .state( + find.descendant( + of: find.byType(SingleChildScrollView), + matching: find.byType(Scrollable), + ), + ) + .position + .pixels, + greaterThan(0), + reason: 'the line coming keeps where the body was scrolled to', + ); + + await tester.drag( + find.byType(SingleChildScrollView), + const Offset(0, -5000), + ); + await tester.pumpAndSettle(); + expect(below(), findsNothing); + expect(above(), findsOneWidget); + }); + + testWidgets('has a scrollbar, always shown on the desktop', (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.linux; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + await open(tester, width: 1000, body: tall); + + final scrollbar = tester.widget(find.byType(Scrollbar)); + expect(scrollbar.thumbVisibility, isTrue); + debugDefaultTargetPlatformOverride = null; + }); + }); + + testWidgets('a body that fits shows no lines', (tester) async { + await open(tester, width: 400); + + expect(find.byKey(SheetScaffold.moreBelowKey), findsNothing); + expect(find.byKey(SheetScaffold.moreAboveKey), findsNothing); + }); + + testWidgets("the body keeps clear of the scroll view's edges, where it is " + 'cut and the scrollbar runs', (tester) async { + for (final width in [400.0, 1000.0]) { + await open( + tester, + width: width, + body: const TextField( + decoration: InputDecoration(border: OutlineInputBorder()), + ), + ); + + final scrolling = tester.getRect(find.byType(SingleChildScrollView)); + final field = tester.getRect(find.byType(TextField)); + expect(field.left - scrolling.left, greaterThanOrEqualTo(16)); + expect(scrolling.right - field.right, greaterThanOrEqualTo(16)); + // The title and the button stay in line with the body. + expect(tester.getTopLeft(find.text('New studyset')).dx, field.left); + expect(tester.getTopRight(find.byType(FilledButton)).dx, field.right); + await tester.tap(find.byTooltip('Close')); + await tester.pumpAndSettle(); + } + }); +} diff --git a/packages/halkyon_ui/test/widget/app_refresh_indicator_test.dart b/packages/halkyon_ui/test/widget/app_refresh_indicator_test.dart new file mode 100644 index 0000000..05dc9aa --- /dev/null +++ b/packages/halkyon_ui/test/widget/app_refresh_indicator_test.dart @@ -0,0 +1,43 @@ +import 'dart:async'; + +import 'package:expressive_loading_indicator/expressive_loading_indicator.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:halkyon_ui/halkyon_ui.dart'; +import 'package:material_ui/material_ui.dart'; + +void main() { + testWidgets("pulled down, it refreshes with the app's spinner, Material 3 " + "Expressive's, not Flutter's older one", (tester) async { + final refreshing = Completer(); + var refreshes = 0; + await tester.pumpWidget( + MaterialApp( + theme: appTheme(Brightness.light), + home: Scaffold( + body: AppRefreshIndicator( + onRefresh: () { + refreshes++; + return refreshing.future; + }, + child: ListView( + physics: const AlwaysScrollableScrollPhysics(), + children: const [Text('Japanese')], + ), + ), + ), + ), + ); + expect(find.byType(ExpressiveLoadingIndicator), findsNothing); + + await tester.fling(find.text('Japanese'), const Offset(0, 400), 1000); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + expect(refreshes, 1); + expect(find.byType(ExpressiveLoadingIndicator), findsOneWidget); + expect(find.byType(CircularProgressIndicator), findsNothing); + + refreshing.complete(); + await tester.pumpAndSettle(); + expect(find.byType(ExpressiveLoadingIndicator), findsNothing); + }); +} diff --git a/packages/halkyon_ui/test/widget/count_stepper_test.dart b/packages/halkyon_ui/test/widget/count_stepper_test.dart new file mode 100644 index 0000000..42ee7c7 --- /dev/null +++ b/packages/halkyon_ui/test/widget/count_stepper_test.dart @@ -0,0 +1,17 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:halkyon_ui/halkyon_ui.dart'; + +void main() { + test('steps go to the next multiple of the step, never below the first', () { + expect(stepUp(12, 5, max: 100), 15); + expect(stepUp(15, 5, max: 100), 20); + expect(stepUp(98, 5, max: 100), 100); + expect(stepDown(12, 5), 10); + expect(stepDown(15, 5), 10); + expect(stepDown(7, 5), 5); + expect(canStepDown(5, 5), isFalse); + expect(canStepDown(6, 5), isTrue); + expect(stepUp(1, 25, max: 1000), 25); + expect(stepDown(230, 25), 225); + }); +} diff --git a/packages/halkyon_ui/test/widget/found_by_id_test.dart b/packages/halkyon_ui/test/widget/found_by_id_test.dart new file mode 100644 index 0000000..55c31d6 --- /dev/null +++ b/packages/halkyon_ui/test/widget/found_by_id_test.dart @@ -0,0 +1,121 @@ +import 'dart:async'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:halkyon_ui/halkyon_ui.dart'; +import 'package:material_ui/material_ui.dart'; + +import '../support/test_app.dart'; + +void main() { + late StreamController> items; + + setUp(() => items = StreamController()); + tearDown(() => items.close()); + + /// Opens the screen of the item [id] over a first screen. + Future open( + WidgetTester tester, + String id, { + ({String label, VoidCallback onPressed})? wayBack, + }) async { + await tester.pumpWidget( + testApp( + Builder( + builder: (context) => TextButton( + onPressed: () => Navigator.of(context).push( + MaterialPageRoute( + builder: (context) => FoundById( + id: id, + items: () => items.stream, + idOf: (item) => item, + builder: (item, items) => + Scaffold(body: Text('Item $item of ${items.length}')), + wayBack: wayBack, + ), + ), + ), + child: const Text('Open'), + ), + ), + ), + ); + await tester.tap(find.text('Open')); + // Through the opening transition; the spinner never settles. + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + } + + testWidgets('shows a spinner until the list arrives, then the item', ( + tester, + ) async { + await open(tester, 'a'); + expect(find.byType(AppLoadingIndicator), findsOneWidget); + + items.add(['a', 'b']); + await tester.pump(); + + expect(find.text('Item a of 2'), findsOneWidget); + expect(find.byType(AppLoadingIndicator), findsNothing); + }); + + testWidgets('says that an item missing from the list no longer exists', ( + tester, + ) async { + await open(tester, 'c'); + + items.add(['a', 'b']); + await tester.pump(); + + expect(find.textContaining('no longer exists'), findsOneWidget); + }); + + testWidgets('leads the way back from there, as the app says', ( + tester, + ) async { + var ledBack = 0; + await open( + tester, + 'c', + wayBack: (label: 'To the library', onPressed: () => ledBack++), + ); + items.add(['a']); + await tester.pump(); + + await tester.tap(find.text('To the library')); + + expect(ledBack, 1); + }); + + testWidgets('says so once the item goes while its screen is open', ( + tester, + ) async { + await open(tester, 'a'); + items.add(['a']); + await tester.pump(); + + // Deleted on another device, say. + items.add([]); + await tester.pump(); + + expect(find.text('Item a of 1'), findsNothing); + expect(find.textContaining('no longer exists'), findsOneWidget); + }); + + testWidgets('a screen that closes as its item goes keeps showing the item ' + 'on its way out', (tester) async { + await open(tester, 'a'); + items.add(['a']); + await tester.pump(); + + // As when the screen deleted its item and closes. + Navigator.of(tester.element(find.text('Item a of 1'))).pop(); + items.add([]); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + + expect(find.text('Item a of 1'), findsOneWidget); + expect(find.textContaining('no longer exists'), findsNothing); + await tester.pumpAndSettle(); + expect(find.text('Open'), findsOneWidget); + }); +} diff --git a/packages/halkyon_ui/test/widget/keyboard_back_on_resume_test.dart b/packages/halkyon_ui/test/widget/keyboard_back_on_resume_test.dart new file mode 100644 index 0000000..38237f2 --- /dev/null +++ b/packages/halkyon_ui/test/widget/keyboard_back_on_resume_test.dart @@ -0,0 +1,50 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:halkyon_ui/halkyon_ui.dart'; +import 'package:material_ui/material_ui.dart'; + +void main() { + Future leaveAndComeBack(WidgetTester tester) async { + [ + AppLifecycleState.inactive, + AppLifecycleState.hidden, + AppLifecycleState.paused, + AppLifecycleState.hidden, + AppLifecycleState.inactive, + AppLifecycleState.resumed, + ].forEach(tester.binding.handleAppLifecycleStateChanged); + await tester.pump(); + } + + bool keyboardAskedFor(WidgetTester tester) => + tester.testTextInput.log.any((call) => call.method == 'TextInput.show'); + + testWidgets('a field focused when the app was left has its keyboard back ' + 'on return', (tester) async { + await tester.pumpWidget( + const MaterialApp( + home: KeyboardBackOnResume( + child: Scaffold(body: TextField(autofocus: true)), + ), + ), + ); + await tester.pump(); + tester.testTextInput.log.clear(); + + await leaveAndComeBack(tester); + + expect(keyboardAskedFor(tester), isTrue); + }); + + testWidgets('without a field focused, no keyboard', (tester) async { + await tester.pumpWidget( + const MaterialApp( + home: KeyboardBackOnResume(child: Scaffold(body: TextField())), + ), + ); + tester.testTextInput.log.clear(); + + await leaveAndComeBack(tester); + + expect(keyboardAskedFor(tester), isFalse); + }); +} diff --git a/packages/halkyon_ui/test/widget/launch_screen_test.dart b/packages/halkyon_ui/test/widget/launch_screen_test.dart new file mode 100644 index 0000000..f15b3b4 --- /dev/null +++ b/packages/halkyon_ui/test/widget/launch_screen_test.dart @@ -0,0 +1,53 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:halkyon_ui/halkyon_ui.dart'; +import 'package:material_ui/material_ui.dart'; + +import '../support/test_app.dart'; + +/// A transparent PNG of one pixel, standing in for an app's icon. +final _icon = MemoryImage( + Uint8List.fromList(const [ + 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, // + 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, + 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, + 0x0D, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, + 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x49, + 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82, + ]), +); + +void main() { + testWidgets("shows the app's icon, and \"Halkyon\" over the app's word, " + "read out as the app's name", (tester) async { + await tester.pumpWidget( + testApp(LaunchScreen(icon: _icon, product: 'Todo', name: 'Halkyon Todo')), + ); + + expect(find.byType(Image), findsOneWidget); + final brand = tester.getRect(find.text('Halkyon')); + final product = tester.getRect(find.text('Todo')); + expect(product.top, greaterThanOrEqualTo(brand.bottom - 1)); + expect(product.center.dx, moreOrLessEquals(brand.center.dx)); + expect(find.bySemanticsLabel('Halkyon Todo'), findsOneWidget); + }); + + testWidgets('the wordmark is cobalt over copper, and silent to screen ' + 'readers', (tester) async { + await tester.pumpWidget( + testApp(const Scaffold(body: BrandWordmark(product: 'Train'))), + ); + + final scheme = appTheme(Brightness.light).colorScheme; + expect( + tester.widget(find.text('Halkyon')).style?.color, + scheme.primary, + ); + expect( + tester.widget(find.text('Train')).style?.color, + scheme.tertiary, + ); + expect(find.bySemanticsLabel('Train'), findsNothing); + }); +} diff --git a/packages/halkyon_ui/test/widget/scroll_hiding_fab_test.dart b/packages/halkyon_ui/test/widget/scroll_hiding_fab_test.dart new file mode 100644 index 0000000..c6f78c6 --- /dev/null +++ b/packages/halkyon_ui/test/widget/scroll_hiding_fab_test.dart @@ -0,0 +1,58 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:halkyon_ui/halkyon_ui.dart'; +import 'package:material_ui/material_ui.dart'; + +void main() { + /// A list of [lines] with a button that hides while reading onwards. + Future show(WidgetTester tester, {int lines = 100}) async { + tester.view.physicalSize = const Size(400, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget( + MaterialApp( + home: ScrollHidingFab( + builder: (context, fab) => Scaffold( + floatingActionButton: fab, + body: ListView( + children: [ + for (var i = 0; i < lines; i++) + SizedBox(height: 48, child: Text('Line $i')), + ], + ), + ), + fab: FloatingActionButton( + tooltip: 'New studyset', + onPressed: () {}, + child: const Icon(Icons.add), + ), + ), + ), + ); + } + + Finder fab() => find.byTooltip('New studyset').hitTestable(); + + testWidgets('hides while scrolling down and returns when scrolling up', ( + tester, + ) async { + await show(tester); + expect(fab(), findsOneWidget); + + await tester.drag(find.byType(ListView), const Offset(0, -300)); + await tester.pumpAndSettle(); + expect(fab(), findsNothing); + + await tester.drag(find.byType(ListView), const Offset(0, 100)); + await tester.pumpAndSettle(); + expect(fab(), findsOneWidget); + }); + + testWidgets('stays when the list fits without scrolling', (tester) async { + await show(tester, lines: 3); + + await tester.drag(find.byType(ListView), const Offset(0, -300)); + await tester.pumpAndSettle(); + + expect(fab(), findsOneWidget); + }); +} diff --git a/packages/halkyon_ui/test/widget/tab_visibility_test.dart b/packages/halkyon_ui/test/widget/tab_visibility_test.dart new file mode 100644 index 0000000..3ef5c78 --- /dev/null +++ b/packages/halkyon_ui/test/widget/tab_visibility_test.dart @@ -0,0 +1,64 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:halkyon_ui/halkyon_ui.dart'; +import 'package:material_ui/material_ui.dart'; + +import '../support/test_app.dart'; + +void main() { + /// Pumps [child] under a screen tint, in a medium window, so a gradient + /// in it claims its colour while in view. + Future show(WidgetTester tester, {required bool visible}) async { + tester.view.physicalSize = const Size(800, 600); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final tint = ScreenTint(); + addTearDown(tint.dispose); + await tester.pumpWidget( + testApp( + ScreenTintScope( + notifier: tint, + child: TabVisibility( + visible: visible, + child: const TopGradient( + color: Color(0xFFBA1E55), + background: Color(0xFFFFFFFF), + child: SizedBox.expand(), + ), + ), + ), + ), + ); + await tester.pump(); + return tint; + } + + testWidgets('a screen whose tab shows gives the frame its colour', ( + tester, + ) async { + final tint = await show(tester, visible: true); + + expect(tint.color, const Color(0xFFBA1E55)); + }); + + testWidgets("a hidden tab's screen leaves the frame's colour alone", ( + tester, + ) async { + final tint = await show(tester, visible: false); + + expect(tint.color, Brand.primary); + }); + + testWidgets('outside any tabs, a screen counts as shown', (tester) async { + late bool visible; + await tester.pumpWidget( + Builder( + builder: (context) { + visible = TabVisibility.of(context); + return const SizedBox(); + }, + ), + ); + + expect(visible, isTrue); + }); +} diff --git a/packages/halkyon_ui/test/widget/text_limits_test.dart b/packages/halkyon_ui/test/widget/text_limits_test.dart new file mode 100644 index 0000000..1692785 --- /dev/null +++ b/packages/halkyon_ui/test/widget/text_limits_test.dart @@ -0,0 +1,44 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:halkyon_ui/halkyon_ui.dart'; +import 'package:material_ui/material_ui.dart'; + +void main() { + Future show(WidgetTester tester) async { + final controller = TextEditingController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: TextField( + controller: controller, + maxLength: TextLimits.name, + buildCounter: nearLimitCounter, + ), + ), + ), + ); + return controller; + } + + testWidgets('a field counts only near its limit, and stops there', ( + tester, + ) async { + final controller = await show(tester); + + await tester.enterText(find.byType(TextField), 'a' * 10); + await tester.pump(); + expect(find.textContaining(' / ${TextLimits.name}'), findsNothing); + + await tester.enterText(find.byType(TextField), 'a' * 35); + await tester.pump(); + expect(find.text('35 / ${TextLimits.name}'), findsOneWidget); + + await tester.enterText(find.byType(TextField), 'a' * 100); + await tester.pump(); + expect(controller.text, hasLength(TextLimits.name)); + expect( + find.text('${TextLimits.name} / ${TextLimits.name}'), + findsOneWidget, + ); + }); +} diff --git a/packages/halkyon_ui/test/widget/tinted_frame_test.dart b/packages/halkyon_ui/test/widget/tinted_frame_test.dart new file mode 100644 index 0000000..06c8113 --- /dev/null +++ b/packages/halkyon_ui/test/widget/tinted_frame_test.dart @@ -0,0 +1,48 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:halkyon_ui/halkyon_ui.dart'; +import 'package:material_ui/material_ui.dart'; + +void main() { + /// A screen with something typed into it, as a study session or a card + /// being written holds what was done. + Future typeIn( + WidgetTester tester, + Widget Function(Widget) around, + ) async { + tester.view.physicalSize = const Size(1200, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget( + MaterialApp( + theme: appTheme(Brightness.light), + home: around(const Scaffold(body: TextField())), + ), + ); + await tester.enterText(find.byType(TextField), 'kept'); + } + + /// Crosses every line where the frame or the snack bars change: medium, + /// compact, medium again. + Future resize(WidgetTester tester) async { + for (final width in const [700.0, 400.0, 1200.0]) { + tester.view.physicalSize = Size(width, 800); + await tester.pumpAndSettle(); + } + } + + testWidgets('a framed screen keeps what it holds when the window crosses ' + 'from medium to compact and back', (tester) async { + await typeIn(tester, (screen) => FramedScreen(child: screen)); + await resize(tester); + + expect(find.text('kept'), findsOneWidget); + }); + + testWidgets('so does every screen under the snack bars fitted to the ' + 'window', (tester) async { + await typeIn(tester, (screen) => FittedSnackBars(child: screen)); + await resize(tester); + + expect(find.text('kept'), findsOneWidget); + }); +} diff --git a/packages/halkyon_ui/test/widget/title_with_kicker_test.dart b/packages/halkyon_ui/test/widget/title_with_kicker_test.dart new file mode 100644 index 0000000..010d80d --- /dev/null +++ b/packages/halkyon_ui/test/widget/title_with_kicker_test.dart @@ -0,0 +1,85 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:halkyon_ui/halkyon_ui.dart'; +import 'package:material_ui/material_ui.dart'; + +void main() { + Future show(WidgetTester tester, Widget child) => tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Align( + alignment: Alignment.topLeft, + child: SizedBox(width: 400, child: child), + ), + ), + ), + ); + + double top(WidgetTester tester, Finder finder) => + tester.getTopLeft(finder).dy; + + testWidgets('shows the kicker uppercased above the title', (tester) async { + await show( + tester, + const TitleWithKicker(title: 'Vocabulary', kicker: 'Japanese'), + ); + + expect(find.text('JAPANESE'), findsOneWidget); + expect( + top(tester, find.text('JAPANESE')), + lessThan(top(tester, find.text('Vocabulary'))), + ); + }); + + testWidgets('shows the title alone without a kicker', (tester) async { + await show(tester, const TitleWithKicker(title: 'Vocabulary', kicker: '')); + + expect(top(tester, find.text('Vocabulary')), 0); + }); + + testWidgets('can keep the kicker line free, so titles side by side line ' + 'up', (tester) async { + await show( + tester, + const Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: TitleWithKicker(title: 'Vocabulary', kicker: 'JLPT'), + ), + Expanded( + child: TitleWithKicker(title: 'Grammar', reserveKickerSpace: true), + ), + ], + ), + ); + + expect( + top(tester, find.text('Grammar')), + top(tester, find.text('Vocabulary')), + ); + }); + + testWidgets('puts the trailing widget beside the title, not the kicker', ( + tester, + ) async { + const action = Key('action'); + await show( + tester, + const TitleWithKicker( + title: 'Vocabulary', + kicker: 'Japanese', + trailing: SizedBox(key: action, width: 48, height: 48), + ), + ); + + expect( + top(tester, find.byKey(action)), + top(tester, find.text('Vocabulary')), + ); + expect( + tester.getTopRight(find.byKey(action)).dx, + 400, + reason: 'the title takes the rest of the width', + ); + }); +} diff --git a/packages/halkyon_ui/test/widget/top_gradient_test.dart b/packages/halkyon_ui/test/widget/top_gradient_test.dart new file mode 100644 index 0000000..9bd24ac --- /dev/null +++ b/packages/halkyon_ui/test/widget/top_gradient_test.dart @@ -0,0 +1,139 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:halkyon_ui/halkyon_ui.dart'; +import 'package:material_ui/material_ui.dart'; + +void main() { + group('The tone at the top', () { + for (final brightness in Brightness.values) { + final scheme = appTheme(brightness).colorScheme; + for (final background in [scheme.surface, scheme.surfaceContainerLow]) { + test('keeps the text readable on every palette colour, ' + '${brightness.name}, $background', () { + for (final color in PaletteColor.values) { + final top = TopGradient.topTone( + scheme, + color.background, + background, + ); + expect( + TopGradient.contrast(top, scheme.onSurface), + greaterThanOrEqualTo(TopGradient.minContrast), + reason: color.name, + ); + } + }); + } + } + + test("the frame around the tabs keeps the rail's labels readable on " + 'every palette colour, top and foot', () { + for (final brightness in Brightness.values) { + final scheme = appTheme(brightness).colorScheme; + for (final color in PaletteColor.values) { + for (final tone in TopGradient.frame( + scheme, + color.background, + ).colors) { + expect( + TopGradient.contrast(tone, scheme.onSurfaceVariant), + greaterThanOrEqualTo(TopGradient.minContrast), + reason: '${brightness.name} ${color.name}', + ); + } + } + } + }); + + test('is a deep shade of cobalt in dark mode, a tint in light mode', () { + final dark = appTheme(Brightness.dark).colorScheme; + final light = appTheme(Brightness.light).colorScheme; + + expect( + TopGradient.topTone(dark, Brand.primary, dark.surface), + Color.lerp( + const Color(0xFF000000), + Brand.primary, + TopGradient.darkShade, + ), + ); + expect( + TopGradient.topTone(light, Brand.primary, light.surface), + Color.lerp(light.surface, Brand.primary, TopGradient.lightMix), + ); + }); + + test('half as strong inside the panel', () { + final dark = appTheme(Brightness.dark).colorScheme; + final full = Color.lerp( + const Color(0xFF000000), + Brand.primary, + TopGradient.darkShade, + )!; + + expect( + TopGradient.topTone( + dark, + Brand.primary, + dark.surface, + share: TopGradient.panelShare, + ), + Color.lerp(dark.surface, full, TopGradient.panelShare), + ); + }); + + test('mixes in less where the full share would be unreadable', () { + final dark = appTheme(Brightness.dark).colorScheme; + // Light text can't sit on a shade of white at 42 %. + const white = Color(0xFFFFFFFF); + + final top = TopGradient.topTone(dark, white, dark.surface); + + expect( + top, + isNot( + Color.lerp(const Color(0xFF000000), white, TopGradient.darkShade), + ), + ); + expect( + TopGradient.contrast(top, dark.onSurface), + greaterThanOrEqualTo(TopGradient.minContrast), + ); + }); + }); + + testWidgets('fades from the tone into the background below the status bar', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + theme: appTheme(Brightness.dark), + home: MediaQuery( + data: const MediaQueryData(padding: EdgeInsets.only(top: 24)), + child: Builder( + builder: (context) => TopGradient( + color: Brand.primary, + background: Theme.of(context).colorScheme.surface, + extent: 100, + child: const SizedBox.expand(), + ), + ), + ), + ), + ); + + final box = tester.widget( + find.descendant( + of: find.byType(TopGradient), + matching: find.byType(DecoratedBox), + ), + ); + final gradient = + (box.decoration as BoxDecoration).gradient! as LinearGradient; + final scheme = appTheme(Brightness.dark).colorScheme; + expect(gradient.colors, [ + TopGradient.topTone(scheme, Brand.primary, scheme.surface), + scheme.surface, + ]); + expect(tester.getSize(find.byWidget(box)).height, 124); + }); +} diff --git a/packages/halkyon_ui/test/widget/undo_snack_bar_test.dart b/packages/halkyon_ui/test/widget/undo_snack_bar_test.dart new file mode 100644 index 0000000..a916d18 --- /dev/null +++ b/packages/halkyon_ui/test/widget/undo_snack_bar_test.dart @@ -0,0 +1,54 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:halkyon_ui/halkyon_ui.dart'; +import 'package:material_ui/material_ui.dart'; + +void main() { + late int undos; + + setUp(() => undos = 0); + + /// Shows "Studyset archived" with a way to undo it. + Future archive(WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: HalkyonUiLocalizations.localizationsDelegates, + supportedLocales: HalkyonUiLocalizations.supportedLocales, + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + onPressed: () => showUndoSnackBar( + context, + message: 'Studyset archived', + onUndo: () => undos++, + ), + child: const Text('Archive'), + ), + ), + ), + ), + ); + await tester.tap(find.text('Archive')); + await tester.pumpAndSettle(); + } + + testWidgets('offers to undo', (tester) async { + await archive(tester); + expect(find.text('Studyset archived'), findsOneWidget); + + await tester.tap(find.text('Undo')); + await tester.pumpAndSettle(); + + expect(undos, 1); + expect(find.text('Studyset archived'), findsNothing); + }); + + testWidgets('goes by itself after three seconds', (tester) async { + await archive(tester); + + await tester.pump(const Duration(seconds: 3)); + await tester.pumpAndSettle(); + + expect(find.text('Studyset archived'), findsNothing); + expect(undos, 0); + }); +} diff --git a/packages/halkyon_ui/test/widget/widget_texts_test.dart b/packages/halkyon_ui/test/widget/widget_texts_test.dart new file mode 100644 index 0000000..8242333 --- /dev/null +++ b/packages/halkyon_ui/test/widget/widget_texts_test.dart @@ -0,0 +1,99 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:halkyon_ui/halkyon_ui.dart'; +import 'package:material_ui/material_ui.dart'; + +import '../support/test_app.dart'; + +void main() { + /// Shows [child] on a screen, in German. + Future show(WidgetTester tester, Widget child) => tester.pumpWidget( + testApp(locale: const Locale('de'), Scaffold(body: child)), + ); + + testWidgets("a required field says so in the app's language", ( + tester, + ) async { + await show( + tester, + Builder( + builder: (context) => TextField( + decoration: requiredDecoration( + context, + const InputDecoration(labelText: 'Name'), + missing: true, + ), + ), + ), + ); + + expect(find.text('Pflichtfeld'), findsOneWidget); + }); + + testWidgets('a count stepper names its buttons', (tester) async { + await show( + tester, + CountStepper(value: '5', onFewer: () {}, onMore: () {}, onTyped: (_) {}), + ); + + expect(find.byTooltip('Verringern'), findsOneWidget); + expect(find.byTooltip('Erhöhen'), findsOneWidget); + expect(find.byTooltip('Zahl eingeben'), findsOneWidget); + }); + + testWidgets('a reorderable row is dragged by its grip', (tester) async { + await show( + tester, + CustomScrollView( + slivers: [ + SliverReorderableList( + itemCount: 1, + onReorderItem: (_, _) {}, + itemBuilder: (context, index) => ListTile( + key: const ValueKey('row'), + title: const Text('Row'), + trailing: ReorderGrip(index: index), + ), + ), + ], + ), + ); + + expect(find.byTooltip('Zum Umsortieren ziehen'), findsOneWidget); + }); + + testWidgets('More info names itself, and copies a value with a tap', ( + tester, + ) async { + await show( + tester, + Builder( + builder: (context) => TextButton( + onPressed: () => showMoreInfoSheet(context, [ + ( + title: null, + rows: [(label: 'ID', value: '0199a', copyable: true)], + ), + ]), + child: const Text('Open'), + ), + ), + ); + await tester.tap(find.text('Open')); + await tester.pumpAndSettle(); + + expect(find.text('Weitere Informationen'), findsOneWidget); + await tester.tap(find.byTooltip('Kopieren')); + await tester.pump(); + expect(find.text('In die Zwischenablage kopiert'), findsOneWidget); + }); + + testWidgets('the palette picker names its colour', (tester) async { + await show( + tester, + PaletteColorPicker(selected: PaletteColor.copper, onChanged: (_) {}), + ); + + expect(find.text('Kupfer'), findsOneWidget); + expect(find.bySemanticsLabel('Farbe: Kupfer'), findsOneWidget); + }); +} diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 0000000..f0200ef --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,15 @@ +name: _halkyon_shared_workspace +publish_to: none + +environment: + sdk: ^3.13.0 + +workspace: + - packages/halkyon_core + - packages/halkyon_interop + - packages/halkyon_ui + - packages/halkyon_ui/example + +dev_dependencies: + # Referenced by analysis_options.yaml in this directory. + leancode_lint: ^27.0.0