From 2f32ca09823b698ebb49bcb289870a032a1e0e57 Mon Sep 17 00:00:00 2001 From: Kinneyzhang Date: Thu, 6 Aug 2026 19:13:33 +0800 Subject: [PATCH] feat(ecss): establish independent cascade engine Create the lowercase ecss repository as a pure selector and CSS cascade package with no TP, Ebox, or historical ECSS dependency.\n\nVerified with 47 ERT tests, warning-free byte compilation, checkdoc, and git diff checks. --- .gitignore | 3 + LICENSE | 674 ++++++++++++++++++++++++ Makefile | 49 ++ README.en.md | 52 ++ README.md | 52 ++ docs/api.en.md | 55 ++ docs/api.zh.md | 55 ++ docs/architecture.en.md | 54 ++ docs/architecture.zh.md | 54 ++ ecss-cascade.el | 986 +++++++++++++++++++++++++++++++++++ ecss-selector.el | 665 +++++++++++++++++++++++ ecss.el | 27 + tests/ecss-cascade-tests.el | 620 ++++++++++++++++++++++ tests/ecss-package-tests.el | 70 +++ tests/ecss-selector-tests.el | 151 ++++++ 15 files changed, 3567 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 Makefile create mode 100644 README.en.md create mode 100644 README.md create mode 100644 docs/api.en.md create mode 100644 docs/api.zh.md create mode 100644 docs/architecture.en.md create mode 100644 docs/architecture.zh.md create mode 100644 ecss-cascade.el create mode 100644 ecss-selector.el create mode 100644 ecss.el create mode 100644 tests/ecss-cascade-tests.el create mode 100644 tests/ecss-package-tests.el create mode 100644 tests/ecss-selector-tests.el diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..dd2fc6c --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +*.elc +*~ +/.DS_Store diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 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 General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is 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. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + 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. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + 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 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. Use with the GNU Affero General Public License. + + 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 Affero 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 special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU 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 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 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 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. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + 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 GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..1099b76 --- /dev/null +++ b/Makefile @@ -0,0 +1,49 @@ +# Makefile for the ecss library. + +EMACS ?= emacs +LOADPATH = -L . -L tests +PACKAGE_LINT_LOAD_EXTRA ?= +SRC = ecss-selector.el ecss-cascade.el ecss.el +TESTS = $(wildcard tests/*-tests.el) + +.PHONY: test compile compile-all checkdoc package-lint check clean diff-check + +test: clean + $(EMACS) -Q --batch $(LOADPATH) -l ecss.el \ + $(patsubst %,-l %,$(TESTS)) -f ert-run-tests-batch-and-exit + +compile: clean + $(EMACS) -Q --batch $(LOADPATH) \ + --eval '(setq byte-compile-error-on-warn t)' \ + -f batch-byte-compile $(SRC) + +compile-all: clean + $(EMACS) -Q --batch $(LOADPATH) \ + --eval '(setq byte-compile-error-on-warn t)' \ + -f batch-byte-compile $(SRC) $(TESTS) + +checkdoc: + $(EMACS) -Q --batch $(LOADPATH) \ + --eval '(progn (require (quote cl-lib)) (require (quote checkdoc)) \ + (cl-letf (((symbol-function (quote display-warning)) \ + (lambda (_type message &rest _args) (error "%s" message)))) \ + (dolist (file (quote ("ecss-selector.el" "ecss-cascade.el" "ecss.el"))) \ + (checkdoc-file file))))' + +package-lint: + $(EMACS) -Q --batch $(LOADPATH) $(PACKAGE_LINT_LOAD_EXTRA) \ + --eval '(progn (require (quote package-lint)) \ + (setq package-lint-main-file "ecss.el") \ + (dolist (file (quote ("ecss-selector.el" "ecss-cascade.el" "ecss.el"))) \ + (with-current-buffer (find-file-noselect file) \ + (let ((issues (package-lint-buffer))) \ + (when issues (error "package-lint failed for %s: %S" file issues))))))' + +diff-check: + git diff --check + +check: compile-all test checkdoc diff-check + $(MAKE) clean + +clean: + rm -f *.elc tests/*.elc diff --git a/README.en.md b/README.en.md new file mode 100644 index 0000000..46ef7e3 --- /dev/null +++ b/README.en.md @@ -0,0 +1,52 @@ +# ecss + +[中文](README.md) + +`ecss` is an independent, pure, extensible CSS cascade engine for Emacs Lisp. It owns selectors, specificity, stylesheets, origins and importance, cascade layers, CSS-wide values, custom properties, `var()`, inheritance, computed styles, and provenance. It does not own text-property writes, reactive updates, buffer publication, or Box/Flex/Grid layout. + +This repository is a new lowercase `ecss` project. It neither modifies nor depends on the historical uppercase `ECSS` repository, and it provides no forwarding compatibility layer to that project. + +## Independent use + +`ecss` does not embed Ebox properties and does not require TP. Any program can register its own property vocabulary, expose nodes through built-in `ecss-subject` values or an adapter, and receive a pure-data computed style. The caller decides whether those values drive text, widgets, a DOM, layout, diagnostics, or another domain. + +```elisp +(require 'ecss) + +(let ((schemas (ecss-schema-set-create)) + (sheet (ecss-stylesheet-create)) + (button (ecss-subject-create + :type "button" :classes '("primary")))) + (ecss-schema-set-define + schemas 'demo/color :initial "black" :inherits t :validator #'stringp) + (ecss-stylesheet-add-rule + sheet schemas "button.primary" '(demo/color "royalblue")) + (ecss-computed-style-value + (ecss-compute-style schemas button :stylesheet sheet) + 'demo/color)) +;; => "royalblue" +``` + +## Core boundary + +- `ecss-selector.el` owns the selector AST, parser, matcher, specificity, and generic subject adapter. +- `ecss-cascade.el` owns explicit schema sets, stylesheets, complete winner ordering, inheritance, variable resolution, and provenance. +- `ecss.el` is the public package facade and has no behavioral load side effects. +- Schema sets and stylesheets change only through explicit authoring APIs. `ecss-compute-style` mutates neither its inputs nor the current buffer. +- An ordinary function value always remains a value. ECSS calls code only through an explicitly supplied `:value-resolver`; ECSS itself knows nothing about TP bindings, Ebox nodes, or consumer-specific value-source types. + +See [Architecture](docs/architecture.en.md) and [API Reference](docs/api.en.md) for the complete contract. + +## Verification + +```sh +make test EMACS=/Applications/Emacs.app/Contents/MacOS/Emacs +make compile EMACS=/Applications/Emacs.app/Contents/MacOS/Emacs +make checkdoc EMACS=/Applications/Emacs.app/Contents/MacOS/Emacs +make package-lint EMACS=/Applications/Emacs.app/Contents/MacOS/Emacs +make diff-check +``` + +`package-lint` is an external development tool. If it is absent from the `emacs -Q` load path, provide it explicitly with `PACKAGE_LINT_LOAD_EXTRA='-L /path/to/package-lint'`. It is not an `ecss` runtime dependency. + +The minimum Emacs version is 28.1. The current package version is 0.1.0. diff --git a/README.md b/README.md new file mode 100644 index 0000000..9b894e5 --- /dev/null +++ b/README.md @@ -0,0 +1,52 @@ +# ecss + +[English](README.en.md) + +`ecss` 是一个独立、纯计算、可扩展的 Emacs Lisp CSS 层叠引擎。它负责 selector、specificity、stylesheet、origin/importance、cascade layer、CSS-wide value、custom property、`var()`、inheritance、computed style 与 provenance;它不负责文本属性写入、响应式更新、Buffer 提交或 Box/Flex/Grid 布局。 + +这个仓库是全新的小写 `ecss` 项目,不修改、不依赖、也不兼容转发到历史大写 `ECSS` 仓库。 + +## 为什么能独立使用 + +`ecss` 不内置 Ebox 属性,也不要求 TP。普通程序可以注册自己的属性 vocabulary,用内置 `ecss-subject` 或 adapter 暴露任意树节点,然后取得纯数据 computed style。调用者自行决定这些值用于文本、Widget、DOM、布局、日志还是其他领域。 + +```elisp +(require 'ecss) + +(let ((schemas (ecss-schema-set-create)) + (sheet (ecss-stylesheet-create)) + (button (ecss-subject-create + :type "button" :classes '("primary")))) + (ecss-schema-set-define + schemas 'demo/color :initial "black" :inherits t :validator #'stringp) + (ecss-stylesheet-add-rule + sheet schemas "button.primary" '(demo/color "royalblue")) + (ecss-computed-style-value + (ecss-compute-style schemas button :stylesheet sheet) + 'demo/color)) +;; => "royalblue" +``` + +## 核心边界 + +- `ecss-selector.el`:selector AST/parser/matcher/specificity 与通用 subject adapter。 +- `ecss-cascade.el`:显式 schema set、stylesheet、完整 winner 顺序、继承、变量解析和 provenance。 +- `ecss.el`:公开 package facade;加载时没有行为副作用。 +- schema set 和 stylesheet 只在显式 authoring API 中修改;`ecss-compute-style` 不修改输入对象或当前 Buffer。 +- 普通 function value 永远是普通值。只有调用者显式传入 `:value-resolver` 时,ECSS 才调用该 resolver;ECSS 自己不认识 TP binding、Ebox node 或任何业务 value-source 类型。 + +详细设计见 [架构](docs/architecture.zh.md) 与 [API 参考](docs/api.zh.md)。 + +## 验证 + +```sh +make test EMACS=/Applications/Emacs.app/Contents/MacOS/Emacs +make compile EMACS=/Applications/Emacs.app/Contents/MacOS/Emacs +make checkdoc EMACS=/Applications/Emacs.app/Contents/MacOS/Emacs +make package-lint EMACS=/Applications/Emacs.app/Contents/MacOS/Emacs +make diff-check +``` + +`package-lint` 是开发期外部工具;如果它不在 `emacs -Q` 的 load-path 中,通过 `PACKAGE_LINT_LOAD_EXTRA='-L /path/to/package-lint'` 显式提供。它不是 `ecss` 的运行时依赖。 + +最低 Emacs 版本是 28.1。当前 package 版本是 0.1.0。 diff --git a/docs/api.en.md b/docs/api.en.md new file mode 100644 index 0000000..c5752d1 --- /dev/null +++ b/docs/api.en.md @@ -0,0 +1,55 @@ +# ecss API Reference + +[中文](api.zh.md) + +## Schemas + +- `(ecss-schema-set-create)` creates an isolated registry. +- `(ecss-schema-set-define SCHEMAS ID &rest OPTIONS)` atomically registers a namespaced property. OPTIONS are `:initial`, `:inherits`, `:normalizer`, `:validator`, `:equality`, and `:shorthand`. +- `(ecss-schema-set-property SCHEMAS ID)` returns a defensive schema copy. +- `(ecss-schema-set-property-ids SCHEMAS)` returns stable registration order. +- `(ecss-expand-declarations SCHEMAS DECLARATIONS)` validates properties and expands each shorthand once. + +A property ID is a symbol containing `/`, such as `ebox/color`. Custom properties need no schema and use `--name` symbols. `initial` is normalized and validated once at schema registration; already computed initial and inherited values do not run the normalizer again. + +## Subjects and selectors + +- `(ecss-subject-create &key type id classes attributes states parent children)` creates a built-in subject. +- `(ecss-subject-adapter-create &key type id classes attributes states parent children)` adapts caller-owned nodes. +- `(ecss-selector-parse STRING)` returns an AST. +- `(ecss-selector-normalize SELECTOR)` accepts a string or AST and returns a defensive AST. +- `(ecss-selector-match-p SELECTOR SUBJECT &optional ADAPTER)` matches a subject. +- `(ecss-selector-specificity SELECTOR)` returns `(ID CLASS TYPE)`. + +The parser supports selector lists, compound selectors, type/id/class, attribute presence/equality/token/language/prefix/suffix/substring matching, state pseudos, `:is()`, `:where()`, `:not()`, `:has()`, and descendant/child/adjacent/general-sibling combinators. `:has()` accepts relative selector lists, including `:has(> child)`, `:has(+ sibling)`, `:has(~ sibling)`, and chained relationships. An unknown functional pseudo is preserved as a state token; the adapter's `states` result determines whether it matches. + +## Stylesheets + +- `(ecss-stylesheet-create)` creates an isolated stylesheet. +- `(ecss-stylesheet-declare-layers STYLESHEET LAYERS &optional ORIGIN)` predeclares an independent layer order for one origin. ORIGIN defaults to `author`. +- `(ecss-stylesheet-add-rule STYLESHEET SCHEMAS SELECTOR DECLARATIONS &key origin layer scope)` atomically adds a rule. +- `(ecss-stylesheet-rules STYLESHEET)` and `(ecss-stylesheet-layers STYLESHEET &optional ORIGIN)` return defensive copies. +- `(ecss-stylesheet-clear STYLESHEET)` clears the explicit object. + +ORIGIN is `ua`, `user`, `author`, `animation`, or `transition`. Inline declarations do not enter a stylesheet; pass them as compute-time `:declarations`. + +## Values and computation + +- `(ecss-important VALUE)` tags `!important`. +- `(ecss-wide-value KIND)` creates a tagged `initial`, `inherit`, `unset`, `revert`, or `revert-layer` value. An ordinary symbol with the same name remains ordinary data. +- `(ecss-var NAME &optional FALLBACK)` creates a custom-property reference. +- `(ecss-compute-style SCHEMAS SUBJECT &key stylesheet rules declarations parent-style adapter provenance value-resolver)` returns an `ecss-computed-style`. + +Do not pass both `:stylesheet` and `:rules`. `:rules` accepts the rule list returned by `ecss-stylesheet-rules` for immutable snapshot storage and replay. `:parent-style` may be a computed style or an already computed values plist. Winner facts are retained only with `:provenance t`. `:value-resolver` has signature `(VALUE PROPERTY SUBJECT)`; without it ECSS calls no property value. + +## Computed styles + +- `(ecss-computed-style-values STYLE)` returns a defensive values plist. +- `(ecss-computed-style-custom-properties STYLE)` returns a deterministic custom-property plist. +- `(ecss-computed-style-active-properties STYLE)` returns property IDs supplied by valid declarations or active inheritance, preserving explicit nil versus absence. An invalid winner falling back to the initial value is not presented as an active declaration. +- `(ecss-computed-style-provenance STYLE)` returns winner, origin, importance, layer, specificity, scope/source/declaration order, validity, and fallback facts. +- `(ecss-computed-style-diagnostics STYLE)` returns deterministic diagnostics such as custom-property cycles. +- `(ecss-computed-style-value STYLE PROPERTY &optional FALLBACK)` reads one value. +- `(ecss-computed-style-present-p STYLE PROPERTY)` detects an active property even when its value is nil. + +Every aggregate getter returns a defensive copy. Mutating a returned value cannot change a computed style, schema set, or stylesheet. diff --git a/docs/api.zh.md b/docs/api.zh.md new file mode 100644 index 0000000..c421e46 --- /dev/null +++ b/docs/api.zh.md @@ -0,0 +1,55 @@ +# ecss API 参考 + +[English](api.en.md) + +## Schema + +- `(ecss-schema-set-create)` 创建隔离 registry。 +- `(ecss-schema-set-define SCHEMAS ID &rest OPTIONS)` 原子注册 namespaced property。OPTIONS 是 `:initial`、`:inherits`、`:normalizer`、`:validator`、`:equality`、`:shorthand`。 +- `(ecss-schema-set-property SCHEMAS ID)` 返回 defensive schema copy。 +- `(ecss-schema-set-property-ids SCHEMAS)` 返回稳定注册顺序。 +- `(ecss-expand-declarations SCHEMAS DECLARATIONS)` 校验属性并只展开一次 shorthand。 + +Property ID 必须是包含 `/` 的 symbol,例如 `ebox/color`。Custom property 不需要 schema,使用 `--name` symbol。`initial` 在 schema 注册时规范化并校验一次;已计算的 initial/inherited value 不会再次执行 normalizer。 + +## Subject 与 selector + +- `(ecss-subject-create &key type id classes attributes states parent children)` 创建内置 subject。 +- `(ecss-subject-adapter-create &key type id classes attributes states parent children)` 为 caller-owned node 创建 adapter。 +- `(ecss-selector-parse STRING)` 返回 AST。 +- `(ecss-selector-normalize SELECTOR)` 接受 string 或 AST,返回 defensive AST。 +- `(ecss-selector-match-p SELECTOR SUBJECT &optional ADAPTER)` 执行匹配。 +- `(ecss-selector-specificity SELECTOR)` 返回 `(ID CLASS TYPE)`。 + +Parser 支持 selector list、compound selector、type/id/class、attribute presence/equality/token/language/prefix/suffix/substring、state pseudo、`:is()`、`:where()`、`:not()`、`:has()`,以及 descendant/child/adjacent/general-sibling combinator。`:has()` 使用相对 selector list,支持 `:has(> child)`、`:has(+ sibling)`、`:has(~ sibling)` 及其后续复合关系。未知 functional pseudo 被保存为 state token,由 adapter 的 `states` 决定是否匹配。 + +## Stylesheet + +- `(ecss-stylesheet-create)` 创建隔离 stylesheet。 +- `(ecss-stylesheet-declare-layers STYLESHEET LAYERS &optional ORIGIN)` 为一个 origin 预声明独立 layer order;ORIGIN 默认是 `author`。 +- `(ecss-stylesheet-add-rule STYLESHEET SCHEMAS SELECTOR DECLARATIONS &key origin layer scope)` 原子添加 rule。 +- `(ecss-stylesheet-rules STYLESHEET)` 与 `(ecss-stylesheet-layers STYLESHEET &optional ORIGIN)` 返回 defensive copies。 +- `(ecss-stylesheet-clear STYLESHEET)` 清空显式对象。 + +ORIGIN 是 `ua`、`user`、`author`、`animation` 或 `transition`。Inline declarations 不放入 stylesheet,而通过 compute 的 `:declarations` 传入。 + +## Values 与 computation + +- `(ecss-important VALUE)` 标记 `!important`。 +- `(ecss-wide-value KIND)` 创建 `initial`、`inherit`、`unset`、`revert` 或 `revert-layer` tagged value;同名普通 symbol 保持普通值。 +- `(ecss-var NAME &optional FALLBACK)` 创建 custom-property reference。 +- `(ecss-compute-style SCHEMAS SUBJECT &key stylesheet rules declarations parent-style adapter provenance value-resolver)` 返回 `ecss-computed-style`。 + +不能同时传 `:stylesheet` 与 `:rules`。`:rules` 接受 `ecss-stylesheet-rules` 返回的 rule list,适用于不可变 snapshot 的保存和重放。`:parent-style` 可以是 computed style,也可以是已经计算完成的 values plist。`:provenance t` 才保留 winner facts。`:value-resolver` 的签名是 `(VALUE PROPERTY SUBJECT)`;未提供时 ECSS 不调用任何 property value。 + +## Computed style + +- `(ecss-computed-style-values STYLE)` 返回 defensive values plist。 +- `(ecss-computed-style-custom-properties STYLE)` 返回 deterministic custom-property plist。 +- `(ecss-computed-style-active-properties STYLE)` 返回由有效 declaration 或 active inheritance 实际提供的 property ids,保留 explicit nil 与 absence 的区别;invalid winner 回退到 initial 时不伪装成 active declaration。 +- `(ecss-computed-style-provenance STYLE)` 返回 winner、origin、important、layer、specificity、scope/source/declaration order、valid/fallback 等事实。 +- `(ecss-computed-style-diagnostics STYLE)` 返回 custom-property cycle 等 deterministic diagnostics。 +- `(ecss-computed-style-value STYLE PROPERTY &optional FALLBACK)` 读取单值。 +- `(ecss-computed-style-present-p STYLE PROPERTY)` 判断 property 是否 active,即使值为 nil。 + +所有 aggregate getter 都返回 defensive copy。调用者修改返回值不会改变 computed style、schema set 或 stylesheet。 diff --git a/docs/architecture.en.md b/docs/architecture.en.md new file mode 100644 index 0000000..3a48566 --- /dev/null +++ b/docs/architecture.en.md @@ -0,0 +1,54 @@ +# ecss Architecture + +[中文](architecture.zh.md) + +## Position + +`ecss` is the generic pure-computation layer that answers which rule wins and what each final property value is. It transforms consumer-provided property schemas, subjects, stylesheets, inline declarations, and a parent computed style into computed values, custom properties, active properties, provenance, and diagnostics. + +```text +consumer schemas + subject adapter + stylesheet + parent style + │ + ▼ + selector match → candidate collection → cascade winner + │ + ▼ + CSS-wide/custom-property resolution → normalize/validate + │ + ▼ + computed style + provenance + diagnostics +``` + +`ecss` does not know how computed values are displayed. TP may convert final text-property contributions into retained surface patches. Ebox may interpret final Box/Flex/Grid properties as measurement, layout, and painting consequences. Ordinary callers may use `ecss` without either package. + +## Explicit objects instead of process-global state + +Each consumer creates its own `ecss-schema-set` and `ecss-stylesheet`. Two applications can use the same selector tokens, different property vocabularies, and different layer orders in one Emacs process without interference. UA, user, and author origins inside one stylesheet also keep independent layer orders. Schema registration and rule addition are explicit atomic authoring operations. Failure cannot leave a partial schema, a half-added layer, or an incorrect source order. + +## Subjects and adapters + +Simple callers use `ecss-subject` directly. Existing tree models use `ecss-subject-adapter-create` to provide type, id, classes, attributes, states, parent, and children callbacks without copying business nodes into ECSS nodes. Selector queries and stylesheets share one parser, matcher, and specificity implementation, so query matching cannot drift from rule matching. + +## Cascade order + +Candidates compare by CSS order: relevance and matching, origin plus importance, cascade layer, specificity, scope proximity, source order, and declaration order. Standard origin levels are UA normal, user normal, author normal, animation, author important, user important, UA important, and transition. Later normal layers win and unlayered normal declarations beat layered ones. Important layers reverse order. Inline author declarations retain the highest priority inside the author origin. + +`revert` removes the entire current origin, across normal and important declarations, before choosing again. `revert-layer` removes the entire current layer inside that origin. An invalid-at-computed-value winner never recascades to a lower candidate; it uses the inherited or initial fallback and records the invalid winner in provenance. + +## Value-source boundary + +ECSS never calls an ordinary function stored in a property and defines no reactive or computed wrapper. A caller that needs evaluation explicitly passes `:value-resolver` to `ecss-compute-style`. The resolver receives value, property, and subject. ECSS invokes it once for each selected source and never executes its result a second time. Resolver errors propagate. Because computation is pure, ECSS has no buffer or runtime state to roll back. + +## Custom properties + +Custom properties use `--name` symbols. Their raw values first pass through ordinary cascade, inherit from the parent computed style by default, and then resolve through `ecss-var`. References may occur inside lists or vectors. Missing values and cycles can use fallback at the reference site. A cycle does not destroy the whole computed style: it creates a deterministic diagnostic and makes the affected value invalid at computed-value time. + +## Three-package boundary + +```text +ecss: selector / stylesheet / cascade / computed values +tp: text-property contributions / reactive runtime / diff / transaction / buffer commit +ebox: box semantics / measurement / flex-grid layout / painting / dirty ownership +``` + +Ebox may consume both `ecss` and TP. `ecss` and TP remain independently usable and do not depend on each other. The `ecss` public API contains no TP object, binding, or mount; no Ebox node; and no marker, patch, or buffer mutation. diff --git a/docs/architecture.zh.md b/docs/architecture.zh.md new file mode 100644 index 0000000..67e0933 --- /dev/null +++ b/docs/architecture.zh.md @@ -0,0 +1,54 @@ +# ecss 架构 + +[English](architecture.en.md) + +## 定位 + +`ecss` 是“规则如何赢、最终属性值是什么”的通用纯计算层。它把 consumer 提供的 property schemas、subjects、stylesheets、inline declarations 与 parent computed style 转换成 computed values、custom properties、active properties、provenance 和 diagnostics。 + +```text +consumer schemas + subject adapter + stylesheet + parent style + │ + ▼ + selector match → candidate collection → cascade winner + │ + ▼ + CSS-wide/custom-property resolution → normalize/validate + │ + ▼ + computed style + provenance + diagnostics +``` + +`ecss` 不知道 computed values 最终如何显示。TP 可以把最终文本属性贡献转换成 retained surface patch;Ebox 可以把最终 Box/Flex/Grid 属性解释成 measurement、layout 与 painting 后果;普通调用者也可以完全不用 TP/Ebox。 + +## 显式对象而不是进程全局状态 + +每个 consumer 创建自己的 `ecss-schema-set` 与 `ecss-stylesheet`。两个应用可以在同一 Emacs 中使用同名 selector token、不同 property vocabulary 和不同 layer 顺序而互不污染;同一 stylesheet 中的 UA、user 与 author origin 也分别维护自己的 layer order。schema 注册与 rule 添加是显式、原子的 authoring 操作;一次失败不会留下半注册 schema、半添加 layer 或错误 source order。 + +## Subject 与 adapter + +简单场景直接使用 `ecss-subject`。已有树模型通过 `ecss-subject-adapter-create` 提供 type、id、classes、attributes、states、parent 与 children callback,不需要把业务节点复制成 ECSS node。selector query 与 stylesheet 都调用同一个 parser、matcher 和 specificity 实现,因此不会出现“查询能匹配但样式规则不能匹配”的两套语义。 + +## Cascade 顺序 + +候选值按 CSS 顺序比较:relevance/match、origin+importance、cascade layer、specificity、scope proximity、source order、declaration order。标准 origin level 是 UA normal、user normal、author normal、animation、author important、user important、UA important、transition。normal layer 后声明者优先且 unlayered 高于 layered;important layer 反向,inline author declaration 在 author origin 内保持最高优先级。 + +`revert` 删除当前整个 origin 后重新选择,不区分 normal 与 important;`revert-layer` 删除当前 origin 中的整个 layer 后重新选择。invalid-at-computed-value 不会退回较低候选,而是使用 inherited/initial fallback,并在 provenance 中记录 invalid winner。 + +## Value source 边界 + +ECSS 不自动调用属性里的 function,也不定义自己的 reactive/computed wrapper。调用者需要求值时,显式向 `ecss-compute-style` 传入 `:value-resolver`。resolver 接收 value、property、subject,ECSS 对每个被选中的 source 只调用一次,resolver 返回值不会被二次执行。resolver error 直接向外传播;由于 computation 是纯计算,不存在需要 ECSS 回滚的 Buffer 或 runtime state。 + +## Custom properties + +Custom properties 使用 `--name` symbol,通过普通 cascade 选出 raw value,默认从 parent computed style 继承,再用 `ecss-var` 解析。引用可以嵌套在 list/vector 中;缺失值与 cycle 可使用引用处 fallback。cycle 不破坏整个 computed style,而产生 deterministic diagnostic,并把受影响 value 标记为 invalid-at-computed-value。 + +## 三包边界 + +```text +ecss: selector / stylesheet / cascade / computed values +tp: text-property contributions / reactive runtime / diff / transaction / buffer commit +ebox: box semantics / measurement / flex-grid layout / painting / dirty ownership +``` + +允许的依赖方向是 Ebox 消费 `ecss` 与 TP;`ecss` 和 TP 可以彼此完全独立使用。`ecss` public API 不出现 TP object/binding/mount、Ebox node、marker、patch 或 buffer mutation。 diff --git a/ecss-cascade.el b/ecss-cascade.el new file mode 100644 index 0000000..fb14cce --- /dev/null +++ b/ecss-cascade.el @@ -0,0 +1,986 @@ +;;; ecss-cascade.el --- Pure CSS cascade computation -*- lexical-binding: t; -*- + +;; Copyright (C) 2026 Geekinney +;; SPDX-License-Identifier: GPL-3.0-or-later + +;;; Commentary: + +;; This module owns property schemas, stylesheets, cascade precedence, +;; inheritance, CSS-wide values, custom properties, and provenance. All +;; computation is independent of buffers, text properties, TP, and Ebox. + +;;; Code: + +(require 'cl-lib) +(require 'seq) +(require 'subr-x) +(require 'ecss-selector) + +(define-error 'ecss-invalid-property-schema + "Invalid ECSS property schema" 'ecss-error) +(define-error 'ecss-invalid-declaration + "Invalid ECSS declaration" 'ecss-error) +(define-error 'ecss-invalid-rule "Invalid ECSS rule" 'ecss-error) + +(cl-defstruct (ecss-property-schema + (:constructor ecss--make-property-schema)) + "Schema governing one namespaced cascade property." + id initial inherits normalizer validator equality shorthand) + +(cl-defstruct (ecss-schema-set + (:constructor ecss--make-schema-set) + (:conc-name ecss--schema-set-)) + "Explicit registry of consumer-owned property schemas." + table order) + +(cl-defstruct (ecss-stylesheet + (:constructor ecss--make-stylesheet) + (:conc-name ecss--stylesheet-)) + "Ordered rules and cascade layers with no global state." + rules layers source-order) + +(cl-defstruct (ecss-rule (:constructor ecss--make-rule)) + "One validated stylesheet rule." + selector declarations origin layer layer-rank scope source-order) + +(cl-defstruct (ecss-computed-style + (:constructor ecss--make-computed-style) + (:conc-name ecss--computed-style-)) + "Computed declarations, custom properties, provenance, and diagnostics." + values custom-properties active-properties provenance diagnostics) + +(cl-defstruct (ecss--wide (:constructor ecss--make-wide)) kind) +(cl-defstruct (ecss--important (:constructor ecss--make-important)) value) +(cl-defstruct (ecss--var-ref (:constructor ecss--make-var-ref)) + name fallback-present-p fallback) + +(cl-defstruct (ecss--candidate (:constructor ecss--make-candidate)) + property value origin important inline layer layer-rank specificity + scope-distance source-order declaration-order selector) + +(defconst ecss--schema-option-keys + '(:initial :inherits :normalizer :validator :equality :shorthand) + "Accepted property schema option keys.") + +(defconst ecss--origins '(ua user author animation transition) + "Supported standard CSS cascade origins.") + +(defconst ecss--wide-kinds '(initial inherit unset revert revert-layer) + "Supported CSS-wide value kinds.") + +(defconst ecss--invalid (make-symbol "ecss-invalid-value")) +(defconst ecss--absent (make-symbol "ecss-absent-value")) + +(defun ecss-schema-set-create () + "Create an empty independent property schema set." + (ecss--make-schema-set :table (make-hash-table :test #'eq) :order nil)) + +(defun ecss--schema-set-check (schemas) + "Return SCHEMAS or signal when it is not a schema set." + (unless (ecss-schema-set-p schemas) + (signal 'wrong-type-argument (list 'ecss-schema-set-p schemas))) + schemas) + +(defun ecss--canonical-property-id-p (id) + "Return non-nil when ID is a namespaced property symbol." + (and (symbolp id) + (let ((name (symbol-name id))) + (and (string-match-p "/" name) + (not (string-prefix-p "/" name)) + (not (string-suffix-p "/" name)))))) + +(defun ecss--custom-property-p (property) + "Return non-nil when PROPERTY names a custom property." + (and (symbolp property) + (string-prefix-p "--" (symbol-name property)))) + +(defun ecss--options-valid-p (options) + "Return non-nil when OPTIONS is an accepted property option plist." + (and (listp options) + (zerop (% (length options) 2)) + (cl-loop for key in options by #'cddr + always (memq key ecss--schema-option-keys)))) + +(defun ecss--schema-option (options key fallback) + "Return KEY from OPTIONS when present, otherwise FALLBACK." + (if (plist-member options key) (plist-get options key) fallback)) + +(defun ecss--validate-schema-functions (options) + "Validate callable schema fields in OPTIONS." + (dolist (key '(:normalizer :validator :equality :shorthand)) + (let ((value (plist-get options key))) + (unless (or (null value) (functionp value)) + (signal 'ecss-invalid-property-schema (list key value)))))) + +(defun ecss--normalize-schema-initial (initial normalizer validator) + "Normalize and validate schema INITIAL with NORMALIZER and VALIDATOR." + (let ((normalized (funcall normalizer (copy-tree initial)))) + (unless (funcall validator normalized) + (signal 'ecss-invalid-property-schema + (list :invalid-initial initial))) + normalized)) + +(defun ecss--build-property-schema (id options) + "Build a validated property schema for ID from OPTIONS." + (unless (and (ecss--canonical-property-id-p id) + (ecss--options-valid-p options)) + (signal 'ecss-invalid-property-schema (list :property id options))) + (ecss--validate-schema-functions options) + (let* ((normalizer (ecss--schema-option options :normalizer #'identity)) + (validator (ecss--schema-option + options :validator (lambda (_value) t))) + (initial (ecss--normalize-schema-initial + (plist-get options :initial) normalizer validator))) + (ecss--make-property-schema + :id id :initial initial + :inherits (and (plist-get options :inherits) t) + :normalizer normalizer :validator validator + :equality (ecss--schema-option options :equality #'equal) + :shorthand (plist-get options :shorthand)))) + +;;;###autoload +(defun ecss-schema-set-define (schemas id &rest options) + "Atomically define property ID with OPTIONS in SCHEMAS." + (ecss--schema-set-check schemas) + (let* ((schema (ecss--build-property-schema id options)) + (table (ecss--schema-set-table schemas))) + (unless (gethash id table) + (setf (ecss--schema-set-order schemas) + (append (ecss--schema-set-order schemas) (list id)))) + (puthash id schema table) + (ecss--copy-property-schema schema))) + +(defun ecss--copy-property-schema (schema) + "Return a defensive copy of SCHEMA." + (let ((copy (copy-ecss-property-schema schema))) + (setf (ecss-property-schema-initial copy) + (copy-tree (ecss-property-schema-initial schema))) + copy)) + +(defun ecss-schema-set-property (schemas id) + "Return a defensive copy of property ID from SCHEMAS, or nil." + (ecss--schema-set-check schemas) + (when-let ((schema (gethash id (ecss--schema-set-table schemas)))) + (ecss--copy-property-schema schema))) + +(defun ecss-schema-set-property-ids (schemas) + "Return property identifiers from SCHEMAS in registration order." + (ecss--schema-set-check schemas) + (copy-sequence (ecss--schema-set-order schemas))) + +(defun ecss-schema-set-clear (schemas) + "Remove every property schema from SCHEMAS." + (ecss--schema-set-check schemas) + (clrhash (ecss--schema-set-table schemas)) + (setf (ecss--schema-set-order schemas) nil) + schemas) + +(defun ecss-property-equal-p (schemas property left right) + "Return whether PROPERTY values LEFT and RIGHT are equal in SCHEMAS." + (ecss--schema-set-check schemas) + (let ((schema (gethash property (ecss--schema-set-table schemas)))) + (unless schema + (signal 'ecss-invalid-declaration (list :unknown-property property))) + (funcall (ecss-property-schema-equality schema) left right))) + +;;;###autoload +(defun ecss-wide-value (kind) + "Return a tagged CSS-wide value of KIND." + (unless (memq kind ecss--wide-kinds) + (signal 'ecss-invalid-declaration (list :wide-value kind))) + (ecss--make-wide :kind kind)) + +;;;###autoload +(defun ecss-important (value) + "Return VALUE tagged as an important declaration." + (ecss--make-important :value value)) + +;;;###autoload +(defun ecss-var (name &rest fallback) + "Return a custom property reference to NAME with optional FALLBACK." + (unless (ecss--custom-property-p name) + (signal 'ecss-invalid-declaration (list :custom-property name))) + (when (> (length fallback) 1) + (signal 'wrong-number-of-arguments + (list 'ecss-var (+ 1 (length fallback))))) + (ecss--make-var-ref + :name name :fallback-present-p (and fallback t) :fallback (car fallback))) + +(defun ecss--declaration-list-p (declarations) + "Return non-nil when DECLARATIONS is an even property/value list." + (and (listp declarations) (zerop (% (length declarations) 2)))) + +(defun ecss--schema-for (schemas property) + "Return PROPERTY schema from SCHEMAS, or nil." + (gethash property (ecss--schema-set-table schemas))) + +(defun ecss--validate-declaration-property (schemas property) + "Return PROPERTY when it is valid for SCHEMAS." + (unless (or (ecss--custom-property-p property) + (ecss--schema-for schemas property)) + (signal 'ecss-invalid-declaration (list :unknown-property property))) + property) + +(defun ecss--unwrap-important (value) + "Return VALUE paired with whether it carries an important tag." + (if (ecss--important-p value) + (cons (ecss--important-value value) t) + (cons value nil))) + +(defun ecss--tag-important (declarations important) + "Tag DECLARATIONS as IMPORTANT when requested." + (if (not important) + declarations + (cl-loop for (property value) on declarations by #'cddr + append (list property (ecss-important value))))) + +(defun ecss--validate-expanded-longhands (schemas shorthand declarations) + "Validate SHORTHAND expansion DECLARATIONS against SCHEMAS." + (unless (ecss--declaration-list-p declarations) + (signal 'ecss-invalid-declaration + (list :shorthand shorthand declarations))) + (cl-loop for (property _value) on declarations by #'cddr + for schema = (progn + (ecss--validate-declaration-property schemas property) + (ecss--schema-for schemas property)) + when (and schema (ecss-property-schema-shorthand schema)) + do (signal 'ecss-invalid-declaration + (list :nested-shorthand shorthand property)))) + +(defun ecss--expand-declaration (schemas property value) + "Expand one PROPERTY VALUE declaration using SCHEMAS." + (ecss--validate-declaration-property schemas property) + (let ((schema (ecss--schema-for schemas property))) + (if-let ((expander (and schema + (ecss-property-schema-shorthand schema)))) + (pcase-let* ((`(,raw . ,important) (ecss--unwrap-important value)) + (expanded (funcall expander raw))) + (ecss--validate-expanded-longhands schemas property expanded) + (ecss--tag-important expanded important)) + (list property value)))) + +;;;###autoload +(defun ecss-expand-declarations (schemas declarations) + "Validate and expand DECLARATIONS through SCHEMAS." + (ecss--schema-set-check schemas) + (unless (ecss--declaration-list-p declarations) + (signal 'ecss-invalid-declaration (list :declarations declarations))) + (cl-loop for (property value) on declarations by #'cddr + append (ecss--expand-declaration schemas property value))) + +(defun ecss-stylesheet-create () + "Create an empty independent stylesheet." + (ecss--make-stylesheet :rules nil :layers nil :source-order 0)) + +(defun ecss--stylesheet-check (stylesheet) + "Return STYLESHEET or signal when it is invalid." + (unless (ecss-stylesheet-p stylesheet) + (signal 'wrong-type-argument (list 'ecss-stylesheet-p stylesheet))) + stylesheet) + +(defun ecss--copy-rule (rule) + "Return a defensive copy of RULE." + (let ((copy (copy-ecss-rule rule))) + (setf (ecss-rule-selector copy) (copy-tree (ecss-rule-selector rule)) + (ecss-rule-declarations copy) (copy-tree (ecss-rule-declarations rule)) + (ecss-rule-scope copy) (copy-tree (ecss-rule-scope rule))) + copy)) + +(defun ecss-stylesheet-rules (stylesheet) + "Return defensive rule copies from STYLESHEET." + (ecss--stylesheet-check stylesheet) + (mapcar #'ecss--copy-rule (ecss--stylesheet-rules stylesheet))) + +(defun ecss--origin-layers (stylesheet origin) + "Return internal STYLESHEET layer order for ORIGIN." + (cdr (assq origin (ecss--stylesheet-layers stylesheet)))) + +(defun ecss--set-origin-layers (stylesheet origin layers) + "Set STYLESHEET ORIGIN order to LAYERS." + (if-let ((cell (assq origin (ecss--stylesheet-layers stylesheet)))) + (setcdr cell layers) + (setf (ecss--stylesheet-layers stylesheet) + (append (ecss--stylesheet-layers stylesheet) + (list (cons origin layers)))))) + +(defun ecss-stylesheet-layers (stylesheet &optional origin) + "Return STYLESHEET layers for ORIGIN in declared order. +ORIGIN defaults to `author'." + (ecss--stylesheet-check stylesheet) + (copy-tree + (ecss--origin-layers + stylesheet (ecss--validate-origin (or origin 'author))))) + +(defun ecss-stylesheet-clear (stylesheet) + "Remove all rules and layers from STYLESHEET." + (ecss--stylesheet-check stylesheet) + (setf (ecss--stylesheet-rules stylesheet) nil + (ecss--stylesheet-layers stylesheet) nil + (ecss--stylesheet-source-order stylesheet) 0) + stylesheet) + +(defun ecss-stylesheet-declare-layers (stylesheet layers &optional origin) + "Append unseen LAYERS to STYLESHEET for ORIGIN and return their order. +ORIGIN defaults to `author'." + (ecss--stylesheet-check stylesheet) + (setq origin (ecss--validate-origin (or origin 'author))) + (unless (and (listp layers) (cl-every (lambda (layer) layer) layers)) + (signal 'ecss-invalid-rule (list :layers layers))) + (let ((result (copy-tree (ecss--origin-layers stylesheet origin)))) + (dolist (layer layers) + (unless (member layer result) + (setq result (append result (list (copy-tree layer)))))) + (ecss--set-origin-layers stylesheet origin result) + (copy-tree result))) + +(defun ecss--validate-origin (origin) + "Return ORIGIN when it is a standard cascade origin." + (unless (memq origin ecss--origins) + (signal 'ecss-invalid-rule (list :origin origin))) + origin) + +(defun ecss--prospective-layer-rank (stylesheet origin layer) + "Return ORIGIN LAYER rank in STYLESHEET without mutation." + (when layer + (let ((layers (ecss--origin-layers stylesheet origin))) + (or (cl-position layer layers :test #'equal) (length layers))))) + +(defun ecss--commit-rule (stylesheet rule layer) + "Commit RULE and optional new LAYER to STYLESHEET." + (let* ((origin (ecss-rule-origin rule)) + (layers (ecss--origin-layers stylesheet origin))) + (when (and layer (not (member layer layers))) + (ecss--set-origin-layers + stylesheet origin (append layers (list (copy-tree layer)))))) + (setf (ecss--stylesheet-source-order stylesheet) + (ecss-rule-source-order rule) + (ecss--stylesheet-rules stylesheet) + (append (ecss--stylesheet-rules stylesheet) (list rule)))) + +;;;###autoload +(cl-defun ecss-stylesheet-add-rule + (stylesheet schemas selector declarations + &key (origin 'author) layer scope) + "Add SELECTOR and DECLARATIONS to STYLESHEET using SCHEMAS. +ORIGIN defaults to `author'. LAYER follows declaration order. SCOPE is an +optional selector limiting the rule to a matching subject or ancestor." + (ecss--stylesheet-check stylesheet) + (ecss--schema-set-check schemas) + (let* ((selector (ecss-selector-normalize selector)) + (scope (and scope (ecss-selector-normalize scope))) + (origin (ecss--validate-origin origin)) + (expanded (ecss-expand-declarations schemas declarations)) + (source-order (1+ (ecss--stylesheet-source-order stylesheet))) + (rule (ecss--make-rule + :selector selector :declarations (copy-tree expanded) + :origin origin :layer (copy-tree layer) + :layer-rank (ecss--prospective-layer-rank + stylesheet origin layer) + :scope scope :source-order source-order))) + (ecss--commit-rule stylesheet rule layer) + (ecss--copy-rule rule))) + +(defun ecss--scope-distance (scope subject adapter) + "Return SUBJECT distance to matching SCOPE through ADAPTER, or nil." + (if (null scope) + most-positive-fixnum + (cl-loop for current = subject then (ecss--subject-parent current adapter) + for distance from 0 while current + when (ecss-selector-match-p scope current adapter) + return distance))) + +(defun ecss--rule-match-facts (rule subject adapter) + "Return RULE match facts for SUBJECT through ADAPTER, or nil." + (when-let ((specificity + (ecss--selector-matched-specificity + (ecss-rule-selector rule) subject adapter))) + (let ((distance (ecss--scope-distance + (ecss-rule-scope rule) subject adapter))) + (when (numberp distance) (cons specificity distance))))) + +(defun ecss--candidate-from-rule + (rule property value specificity distance declaration-order) + "Create a candidate from RULE, PROPERTY, and VALUE. +SPECIFICITY, DISTANCE, and DECLARATION-ORDER are the match precedence facts." + (pcase-let ((`(,raw . ,important) (ecss--unwrap-important value))) + (ecss--make-candidate + :property property :value raw :origin (ecss-rule-origin rule) + :important important :inline nil :layer (ecss-rule-layer rule) + :layer-rank (ecss-rule-layer-rank rule) :specificity specificity + :scope-distance distance :source-order (ecss-rule-source-order rule) + :declaration-order declaration-order + :selector (copy-tree (ecss-rule-selector rule))))) + +(defun ecss--rule-candidates (rule subject adapter) + "Return candidates from matching RULE for SUBJECT through ADAPTER." + (when-let ((facts (ecss--rule-match-facts rule subject adapter))) + (cl-loop for (property value) on (ecss-rule-declarations rule) by #'cddr + for declaration-order from 0 + collect (ecss--candidate-from-rule + rule property value (car facts) (cdr facts) + declaration-order)))) + +(defun ecss--max-source-order (rules) + "Return greatest source order in RULES." + (cl-loop for rule in rules maximize (ecss-rule-source-order rule) into value + finally return (or value 0))) + +(defun ecss--inline-candidates (schemas declarations source-order) + "Return inline candidates from DECLARATIONS using SCHEMAS and SOURCE-ORDER." + (when declarations + (cl-loop for (property value) + on (ecss-expand-declarations schemas declarations) by #'cddr + for declaration-order from 0 + collect + (pcase-let ((`(,raw . ,important) (ecss--unwrap-important value))) + (ecss--make-candidate + :property property :value raw :origin 'author + :important important :inline t :layer nil :layer-rank nil + :specificity '(0 0 0) + :scope-distance most-positive-fixnum + :source-order source-order :declaration-order declaration-order + :selector :inline))))) + +(defun ecss--collect-candidates + (schemas subject adapter declarations rules) + "Collect candidates for SUBJECT, DECLARATIONS, and RULES. +SCHEMAS validates inline declarations and ADAPTER exposes SUBJECT." + (append + (cl-loop for rule in rules + append (ecss--rule-candidates rule subject adapter)) + (ecss--inline-candidates + schemas declarations (1+ (ecss--max-source-order rules))))) + +(defun ecss--cascade-level-rank (candidate) + "Return standard CSS origin and importance rank for CANDIDATE." + (let ((origin (ecss--candidate-origin candidate)) + (important (ecss--candidate-important candidate))) + (cond ((eq origin 'transition) 7) + ((and important (eq origin 'ua)) 6) + ((and important (eq origin 'user)) 5) + ((and important (eq origin 'author)) 4) + ((eq origin 'animation) 3) + ((eq origin 'author) 2) + ((eq origin 'user) 1) + ((eq origin 'ua) 0)))) + +(defun ecss--candidate-cascade-layer-rank (candidate) + "Return cascade layer rank for CANDIDATE." + (let ((layer (ecss--candidate-layer candidate)) + (rank (ecss--candidate-layer-rank candidate)) + (important (ecss--candidate-important candidate))) + (cond ((ecss--candidate-inline candidate) 2000000) + ((and important (null layer)) -1000000) + ((null layer) 1000000) + (important (- (or rank 0))) + (t (or rank 0))))) + +(defun ecss--compare-number (left right) + "Compare LEFT and RIGHT, returning 1, -1, or 0." + (cond ((> left right) 1) ((< left right) -1) (t 0))) + +(defun ecss--rank-list-comparison (left right) + "Compare numeric rank lists LEFT and RIGHT." + (catch 'comparison + (cl-mapc (lambda (a b) + (let ((value (ecss--compare-number a b))) + (unless (zerop value) (throw 'comparison value)))) + left right) + 0)) + +(defun ecss--candidate-primary-ranks (candidate) + "Return primary cascade ranks for CANDIDATE." + (list (ecss--cascade-level-rank candidate) + (ecss--candidate-cascade-layer-rank candidate))) + +(defun ecss--candidate-higher-p (left right) + "Return non-nil when candidate LEFT outranks RIGHT." + (let ((rank (ecss--rank-list-comparison + (ecss--candidate-primary-ranks left) + (ecss--candidate-primary-ranks right)))) + (cond ((not (zerop rank)) (> rank 0)) + ((not (equal (ecss--candidate-specificity left) + (ecss--candidate-specificity right))) + (ecss--specificity-greater-p + (ecss--candidate-specificity left) + (ecss--candidate-specificity right))) + ((/= (ecss--candidate-scope-distance left) + (ecss--candidate-scope-distance right)) + (< (ecss--candidate-scope-distance left) + (ecss--candidate-scope-distance right))) + ((/= (ecss--candidate-source-order left) + (ecss--candidate-source-order right)) + (> (ecss--candidate-source-order left) + (ecss--candidate-source-order right))) + (t (> (ecss--candidate-declaration-order left) + (ecss--candidate-declaration-order right)))))) + +(defun ecss--group-candidates (candidates) + "Group and sort CANDIDATES by property." + (let ((table (make-hash-table :test #'eq))) + (dolist (candidate candidates) + (let ((property (ecss--candidate-property candidate))) + (puthash property (cons candidate (gethash property table)) table))) + (maphash (lambda (property values) + (puthash property + (sort values #'ecss--candidate-higher-p) table)) + table) + table)) + +(defun ecss--skip-reverted-origin (candidates winner) + "Remove WINNER origin from CANDIDATES." + (seq-remove + (lambda (candidate) + (eq (ecss--candidate-origin candidate) + (ecss--candidate-origin winner))) + candidates)) + +(defun ecss--skip-reverted-layer (candidates winner) + "Remove WINNER origin and layer from CANDIDATES." + (seq-remove + (lambda (candidate) + (and (eq (ecss--candidate-origin candidate) + (ecss--candidate-origin winner)) + (equal (ecss--candidate-layer candidate) + (ecss--candidate-layer winner)))) + candidates)) + +(defun ecss--resolve-source (value property subject resolver) + "Resolve VALUE for PROPERTY and SUBJECT only through explicit RESOLVER." + (if resolver (funcall resolver value property subject) value)) + +(defun ecss--parent-values (parent-style) + "Return computed values from PARENT-STYLE." + (cond ((ecss-computed-style-p parent-style) + (ecss--computed-style-values parent-style)) + ((listp parent-style) parent-style))) + +(defun ecss--parent-custom-properties (parent-style) + "Return custom properties from PARENT-STYLE." + (when (ecss-computed-style-p parent-style) + (ecss--computed-style-custom-properties parent-style))) + +(defun ecss--parent-property-active-p (parent-style property) + "Return non-nil when PARENT-STYLE actively supplies PROPERTY." + (cond ((ecss-computed-style-p parent-style) + (memq property (ecss--computed-style-active-properties parent-style))) + ((listp parent-style) (and (plist-member parent-style property) t)))) + +(defun ecss--property-default (schema parent-style) + "Return default value and source for SCHEMA using PARENT-STYLE." + (let* ((property (ecss-property-schema-id schema)) + (values (ecss--parent-values parent-style))) + (if (and (ecss-property-schema-inherits schema) + (plist-member values property)) + (cons (copy-tree (plist-get values property)) 'inherit) + (cons (copy-tree (ecss-property-schema-initial schema)) 'initial)))) + +(defun ecss--wide-default (wide schema parent-style) + "Resolve non-revert WIDE value for SCHEMA using PARENT-STYLE." + (pcase (ecss--wide-kind wide) + ('initial (cons (ecss-property-schema-initial schema) 'initial)) + ('inherit + (let ((values (ecss--parent-values parent-style)) + (property (ecss-property-schema-id schema))) + (if (plist-member values property) + (cons (copy-tree (plist-get values property)) 'inherit) + (cons (copy-tree (ecss-property-schema-initial schema)) 'initial)))) + ('unset (if (ecss-property-schema-inherits schema) + (ecss--wide-default (ecss-wide-value 'inherit) + schema parent-style) + (cons (copy-tree (ecss-property-schema-initial schema)) + 'initial))))) + +(defun ecss--candidate-provenance (candidate &rest extra) + "Return public provenance for CANDIDATE followed by EXTRA facts." + (append + (if candidate + (list :source 'declaration + :selector (copy-tree (ecss--candidate-selector candidate)) + :origin (ecss--candidate-origin candidate) + :important (and (ecss--candidate-important candidate) t) + :inline (and (ecss--candidate-inline candidate) t) + :layer (copy-tree (ecss--candidate-layer candidate)) + :specificity (copy-sequence + (ecss--candidate-specificity candidate)) + :scope-distance (ecss--candidate-scope-distance candidate) + :source-order (ecss--candidate-source-order candidate) + :declaration-order (ecss--candidate-declaration-order candidate)) + '(:source initial :origin ua)) + extra)) + +(defun ecss--select-custom-candidate + (candidates inherited property subject resolver) + "Select custom PROPERTY from CANDIDATES and INHERITED values." + (let ((remaining candidates) selected winner done) + (while (and remaining (not done)) + (setq winner (pop remaining)) + (let ((value (ecss--resolve-source + (ecss--candidate-value winner) property subject resolver))) + (if (not (ecss--wide-p value)) + (setq selected value done t) + (pcase (ecss--wide-kind value) + ('revert (setq remaining + (ecss--skip-reverted-origin remaining winner))) + ('revert-layer (setq remaining + (ecss--skip-reverted-layer remaining winner))) + ((or 'inherit 'unset) + (setq selected (gethash property inherited ecss--absent) + done t)) + ('initial (setq selected ecss--absent done t)))))) + (unless done + (setq selected (gethash property inherited ecss--absent) + winner nil)) + (cons selected winner))) + +(defun ecss--custom-candidate-properties (candidate-table) + "Return custom property keys from CANDIDATE-TABLE in stable order." + (let (properties) + (maphash (lambda (property _candidates) + (when (ecss--custom-property-p property) + (push property properties))) + candidate-table) + (sort properties + (lambda (left right) + (string< (symbol-name left) (symbol-name right)))))) + +(defun ecss--custom-raw-table + (candidate-table parent-style subject resolver provenance-p) + "Build raw custom properties from CANDIDATE-TABLE. +PARENT-STYLE supplies inheritance. SUBJECT and RESOLVER handle explicit value +sources. Retain winner facts when PROVENANCE-P is non-nil." + (let ((table (make-hash-table :test #'eq)) provenance) + (cl-loop for (property value) on (ecss--parent-custom-properties parent-style) + by #'cddr + do (puthash property value table) + when provenance-p + do (setq provenance + (plist-put provenance property '(:source inherit)))) + (dolist (property (ecss--custom-candidate-properties candidate-table)) + (pcase-let ((`(,value . ,winner) + (ecss--select-custom-candidate + (gethash property candidate-table) table property + subject resolver))) + (if (eq value ecss--absent) + (remhash property table) + (puthash property value table)) + (when provenance-p + (setq provenance + (plist-put provenance property + (if winner (ecss--candidate-provenance winner) + '(:source inherit))))))) + (list table provenance))) + +(defun ecss--record-cycle (stack name diagnostics) + "Record a custom property cycle from STACK through NAME in DIAGNOSTICS." + (let ((path (reverse (cons name stack)))) + (unless (member (list :type 'variable-cycle :path path) (car diagnostics)) + (push (list :type 'variable-cycle :path path) (car diagnostics))))) + +(defun ecss--resolve-var-fallback + (reference raw resolved stack diagnostics) + "Resolve REFERENCE fallback using RAW, RESOLVED, STACK, and DIAGNOSTICS." + (if (ecss--var-ref-fallback-present-p reference) + (ecss--resolve-variable-value + (ecss--var-ref-fallback reference) raw resolved stack diagnostics) + ecss--invalid)) + +(defun ecss--resolve-custom-property + (name raw resolved stack diagnostics) + "Resolve custom property NAME using RAW, RESOLVED, STACK, and DIAGNOSTICS." + (let ((memo (gethash name resolved ecss--absent))) + (cond ((not (eq memo ecss--absent)) memo) + ((memq name stack) + (ecss--record-cycle stack name diagnostics) + ecss--invalid) + (t + (let ((value (gethash name raw ecss--absent))) + (if (eq value ecss--absent) + ecss--invalid + (let ((answer (ecss--resolve-variable-value + value raw resolved (cons name stack) + diagnostics))) + (puthash name answer resolved) + answer))))))) + +(defun ecss--resolve-compound-value + (value raw resolved stack diagnostics) + "Resolve custom references recursively inside VALUE. +RAW and RESOLVED are custom-property tables. STACK detects cycles and +DIAGNOSTICS records them." + (cond ((functionp value) value) + ((vectorp value) + (let ((items (mapcar + (lambda (item) + (ecss--resolve-variable-value + item raw resolved stack diagnostics)) + (append value nil)))) + (if (memq ecss--invalid items) ecss--invalid (vconcat items)))) + ((consp value) + (let ((car-value (ecss--resolve-variable-value + (car value) raw resolved stack diagnostics)) + (cdr-value (ecss--resolve-variable-value + (cdr value) raw resolved stack diagnostics))) + (if (or (eq car-value ecss--invalid) + (eq cdr-value ecss--invalid)) + ecss--invalid + (cons car-value cdr-value)))) + (t value))) + +(defun ecss--resolve-variable-value + (value raw resolved stack diagnostics) + "Resolve custom references in VALUE using RAW and RESOLVED tables. +STACK detects cycles and DIAGNOSTICS records them." + (if (not (ecss--var-ref-p value)) + (ecss--resolve-compound-value value raw resolved stack diagnostics) + (let ((answer (ecss--resolve-custom-property + (ecss--var-ref-name value) raw resolved stack diagnostics))) + (if (eq answer ecss--invalid) + (ecss--resolve-var-fallback + value raw resolved stack diagnostics) + answer)))) + +(defun ecss--resolved-custom-properties (raw diagnostics) + "Return resolved custom properties from RAW with DIAGNOSTICS." + (let ((resolved (make-hash-table :test #'eq)) names result) + (maphash (lambda (name _value) (push name names)) raw) + (dolist (name (sort names + (lambda (left right) + (string< (symbol-name left) (symbol-name right))))) + (let ((value (ecss--resolve-custom-property + name raw resolved nil diagnostics))) + (unless (eq value ecss--invalid) + (setq result (plist-put result name value))))) + result)) + +(defun ecss--custom-value-tables (custom) + "Build RAW and RESOLVED tables from computed CUSTOM properties." + (let ((raw (make-hash-table :test #'eq)) + (resolved (make-hash-table :test #'eq))) + (cl-loop for (name value) on custom by #'cddr + do (puthash name value raw) + do (puthash name value resolved)) + (cons raw resolved))) + +(defun ecss--resolve-property-value + (value schema parent-style custom diagnostics) + "Resolve VALUE for SCHEMA using PARENT-STYLE, CUSTOM, and DIAGNOSTICS." + (cond ((and (ecss--wide-p value) + (memq (ecss--wide-kind value) '(initial inherit unset))) + (ecss--wide-default value schema parent-style)) + (t + (pcase-let ((`(,raw . ,resolved) + (ecss--custom-value-tables custom))) + (cons (ecss--resolve-variable-value + value raw resolved nil diagnostics) + 'declaration))))) + +(defun ecss--normalize-property-value (schema value) + "Normalize and validate VALUE for SCHEMA, or return invalid sentinel." + (if (eq value ecss--invalid) + value + (let ((normalized + (funcall (ecss-property-schema-normalizer schema) value))) + (if (funcall (ecss-property-schema-validator schema) normalized) + normalized + ecss--invalid)))) + +(defun ecss--compute-candidate-value + (candidate schema parent-style custom subject resolver diagnostics) + "Resolve CANDIDATE for SCHEMA and computation context. +PARENT-STYLE and CUSTOM supply inherited values. SUBJECT and RESOLVER handle +explicit sources, and DIAGNOSTICS records variable failures." + (let* ((property (ecss-property-schema-id schema)) + (source (ecss--resolve-source + (ecss--candidate-value candidate) + property subject resolver)) + (resolved (ecss--resolve-property-value + source schema parent-style custom diagnostics))) + (cons (if (eq (cdr resolved) 'declaration) + (ecss--normalize-property-value schema (car resolved)) + (copy-tree (car resolved))) + (cdr resolved)))) + +(defun ecss--fallback-value (schema parent-style) + "Return the computed default for SCHEMA using PARENT-STYLE." + (pcase-let ((`(,value . ,source) + (ecss--property-default schema parent-style))) + (cons value source))) + +(defun ecss--resolve-property-candidates + (schema candidates parent-style custom subject resolver diagnostics) + "Resolve SCHEMA from ordered CANDIDATES. +PARENT-STYLE and CUSTOM supply inherited values. SUBJECT and RESOLVER handle +explicit sources, and DIAGNOSTICS records variable failures." + (let ((remaining candidates) winner resolved) + (while (and remaining (null winner)) + (let* ((candidate (pop remaining)) + (raw (ecss--resolve-source + (ecss--candidate-value candidate) + (ecss-property-schema-id schema) subject resolver))) + (cond ((and (ecss--wide-p raw) (eq (ecss--wide-kind raw) 'revert)) + (setq remaining (ecss--skip-reverted-origin + remaining candidate))) + ((and (ecss--wide-p raw) + (eq (ecss--wide-kind raw) 'revert-layer)) + (setq remaining (ecss--skip-reverted-layer + remaining candidate))) + (t + (setq winner candidate + resolved + (ecss--compute-candidate-value + candidate schema parent-style custom subject + (lambda (_value _property _subject) raw) diagnostics)))))) + (let* ((invalid (and winner (eq (car resolved) ecss--invalid))) + (final (if (or (null winner) invalid) + (ecss--fallback-value schema parent-style) + resolved))) + (list (car final) winner invalid (cdr final))))) + +(defun ecss--property-provenance (winner invalid source) + "Return provenance from WINNER, INVALID state, and fallback SOURCE." + (if winner + (ecss--candidate-provenance + winner :valid (not invalid) + :value-source source + :fallback (and invalid source)) + (list :source source :origin (if (eq source 'initial) 'ua 'inherit)))) + +(defun ecss--compute-property-values + (schemas table parent-style custom subject resolver diagnostics provenance-p) + "Compute SCHEMAS property values from TABLE and context. +PARENT-STYLE and CUSTOM supply inherited values. SUBJECT and RESOLVER handle +explicit sources. DIAGNOSTICS records failures; PROVENANCE-P retains facts." + (let (values active provenance) + (dolist (property (ecss--schema-set-order schemas)) + (let ((schema (ecss--schema-for schemas property))) + (unless (ecss-property-schema-shorthand schema) + (pcase-let ((`(,value ,winner ,invalid ,source) + (ecss--resolve-property-candidates + schema (gethash property table) parent-style custom + subject resolver diagnostics))) + (setq values (plist-put values property value)) + (when (or (and winner (not invalid)) + (and (ecss-property-schema-inherits schema) + (ecss--parent-property-active-p parent-style property))) + (push property active)) + (when provenance-p + (setq provenance + (plist-put provenance property + (ecss--property-provenance + winner invalid source)))))))) + (list values (nreverse active) provenance))) + +(defun ecss--validate-rule-declarations (schemas rule) + "Validate canonical declarations in RULE against SCHEMAS." + (unless (ecss--declaration-list-p (ecss-rule-declarations rule)) + (signal 'ecss-invalid-rule (list :declarations rule))) + (cl-loop for (property _value) on (ecss-rule-declarations rule) by #'cddr + do (ecss--validate-declaration-property schemas property) + for schema = (ecss--schema-for schemas property) + when (and schema (ecss-property-schema-shorthand schema)) + do (signal 'ecss-invalid-rule (list :shorthand-snapshot property)))) + +(defun ecss--validate-rule-snapshot (schemas rule) + "Return RULE after validating it against SCHEMAS." + (unless (ecss-rule-p rule) + (signal 'ecss-invalid-rule (list :rule rule))) + (ecss--validate-selector (ecss-rule-selector rule)) + (when (ecss-rule-scope rule) + (ecss--validate-selector (ecss-rule-scope rule))) + (ecss--validate-origin (ecss-rule-origin rule)) + (unless (natnump (ecss-rule-source-order rule)) + (signal 'ecss-invalid-rule (list :source-order rule))) + (ecss--validate-rule-declarations schemas rule) + rule) + +(defun ecss--active-rules (schemas stylesheet rules) + "Return active rules for SCHEMAS from STYLESHEET or RULES." + (when (and stylesheet rules) + (signal 'ecss-invalid-rule (list :stylesheet-and-rules))) + (let ((active (cond (stylesheet + (ecss--stylesheet-check stylesheet) + (ecss--stylesheet-rules stylesheet)) + (rules rules)))) + (when rules + (mapc (lambda (rule) (ecss--validate-rule-snapshot schemas rule)) active)) + active)) + +;;;###autoload +(cl-defun ecss-compute-style + (schemas subject &key stylesheet rules declarations parent-style + adapter provenance value-resolver) + "Compute a deterministic style for SUBJECT using SCHEMAS. +STYLESHEET or RULES supplies validated rules. DECLARATIONS are inline. +PARENT-STYLE may be another computed style or a values plist. ADAPTER exposes +caller-owned subjects. PROVENANCE retains winner facts. VALUE-RESOLVER, when +non-nil, is the only function allowed to evaluate caller-owned value sources; + it receives VALUE, PROPERTY, and SUBJECT." + (ecss--schema-set-check schemas) + (let ((adapter (or adapter ecss-default-subject-adapter))) + (unless (ecss-subject-adapter-p adapter) + (signal 'wrong-type-argument (list 'ecss-subject-adapter-p adapter))) + (let* ((rules (ecss--active-rules schemas stylesheet rules)) + (table (ecss--group-candidates + (ecss--collect-candidates + schemas subject adapter declarations rules))) + (diagnostics (list nil)) + (raw-facts (ecss--custom-raw-table + table parent-style subject value-resolver provenance)) + (custom (ecss--resolved-custom-properties + (car raw-facts) diagnostics))) + (pcase-let ((`(,values ,active ,property-facts) + (ecss--compute-property-values + schemas table parent-style custom subject value-resolver + diagnostics provenance))) + (ecss--make-computed-style + :values values :custom-properties custom :active-properties active + :provenance (and provenance + (append (cadr raw-facts) property-facts)) + :diagnostics (nreverse (car diagnostics))))))) + +(defun ecss--computed-style-check (style) + "Return STYLE or signal when it is not a computed style." + (unless (ecss-computed-style-p style) + (signal 'wrong-type-argument (list 'ecss-computed-style-p style))) + style) + +(defun ecss-computed-style-values (style) + "Return a defensive values plist from computed STYLE." + (ecss--computed-style-check style) + (copy-tree (ecss--computed-style-values style))) + +(defun ecss-computed-style-custom-properties (style) + "Return a defensive custom property plist from computed STYLE." + (ecss--computed-style-check style) + (copy-tree (ecss--computed-style-custom-properties style))) + +(defun ecss-computed-style-active-properties (style) + "Return actively supplied property identifiers from computed STYLE." + (ecss--computed-style-check style) + (copy-sequence (ecss--computed-style-active-properties style))) + +(defun ecss-computed-style-provenance (style) + "Return defensive winner provenance from computed STYLE." + (ecss--computed-style-check style) + (copy-tree (ecss--computed-style-provenance style))) + +(defun ecss-computed-style-diagnostics (style) + "Return defensive diagnostics from computed STYLE." + (ecss--computed-style-check style) + (copy-tree (ecss--computed-style-diagnostics style))) + +(defun ecss-computed-style-value (style property &optional fallback) + "Return PROPERTY from computed STYLE, or FALLBACK when absent." + (let ((values (ecss--computed-style-values + (ecss--computed-style-check style)))) + (if (plist-member values property) (plist-get values property) fallback))) + +(defun ecss-computed-style-present-p (style property) + "Return non-nil when PROPERTY is actively supplied in computed STYLE." + (memq property + (ecss--computed-style-active-properties + (ecss--computed-style-check style)))) + +(provide 'ecss-cascade) +;;; ecss-cascade.el ends here diff --git a/ecss-selector.el b/ecss-selector.el new file mode 100644 index 0000000..c377304 --- /dev/null +++ b/ecss-selector.el @@ -0,0 +1,665 @@ +;;; ecss-selector.el --- Generic CSS selector model -*- lexical-binding: t; -*- + +;; Copyright (C) 2026 Geekinney +;; SPDX-License-Identifier: GPL-3.0-or-later + +;;; Commentary: + +;; This module parses, validates, matches, and scores CSS-like selectors over +;; either `ecss-subject' values or caller-owned values exposed through an +;; `ecss-subject-adapter'. It has no dependency on buffers or rendering code. + +;;; Code: + +(require 'cl-lib) +(require 'seq) +(require 'subr-x) + +(define-error 'ecss-error "ECSS error") +(define-error 'ecss-invalid-selector "Invalid ECSS selector" 'ecss-error) +(define-error 'ecss-invalid-subject-adapter + "Invalid ECSS subject adapter" 'ecss-error) + +(cl-defstruct (ecss-subject (:constructor ecss--make-subject)) + "Generic selector subject independent of a rendering consumer." + type id classes attributes states parent children) + +(cl-defstruct (ecss-subject-adapter + (:constructor ecss--make-subject-adapter)) + "Functions exposing caller-owned subjects to the selector engine." + type id classes attributes states parent children) + +(cl-defstruct (ecss--selector-parser + (:constructor ecss--make-selector-parser)) + input position length) + +(defconst ecss--attribute-operators '("=" "~=" "|=" "^=" "$=" "*=") + "Supported attribute selector operators.") + +(defconst ecss--selector-delimiters + '(?\s ?\t ?\n ?\r ?\f ?. ?# ?\[ ?\] ?: ?, ?> ?+ ?~ ?\( ?\) ?* + ?= ?| ?^ ?$ ?' ?\" ?/) + "Characters that terminate an unescaped selector identifier.") + +(defvar ecss--selector-anchor nil + "Dynamically bound subject anchoring a relative selector.") + +(defun ecss--adapter-callback-p (value) + "Return non-nil when VALUE is a valid adapter callback." + (functionp value)) + +(cl-defun ecss-subject-adapter-create + (&key type id classes attributes states parent children) + "Create a subject adapter from the supplied callbacks. +TYPE, ID, CLASSES, ATTRIBUTES, STATES, PARENT, and CHILDREN each accept one +caller-owned subject and return the named field." + (let ((callbacks (list type id classes attributes states parent children))) + (unless (cl-every #'ecss--adapter-callback-p callbacks) + (signal 'ecss-invalid-subject-adapter callbacks))) + (ecss--make-subject-adapter + :type type :id id :classes classes :attributes attributes + :states states :parent parent :children children)) + +(defconst ecss-default-subject-adapter + (ecss--make-subject-adapter + :type #'ecss-subject-type + :id #'ecss-subject-id + :classes #'ecss-subject-classes + :attributes #'ecss-subject-attributes + :states #'ecss-subject-states + :parent #'ecss-subject-parent + :children #'ecss-subject-children) + "Adapter for built-in `ecss-subject' values.") + +(cl-defun ecss-subject-create + (&key type id classes attributes states parent children) + "Create a generic subject. +TYPE and ID identify it. CLASSES and STATES are token lists. ATTRIBUTES is +an alist. PARENT and CHILDREN establish its initial tree position." + (when (and parent (not (ecss-subject-p parent))) + (signal 'wrong-type-argument (list 'ecss-subject-p parent))) + (let ((subject (ecss--make-subject + :type type :id id :classes (copy-sequence classes) + :attributes (copy-tree attributes) + :states (copy-sequence states)))) + (ecss-subject-set-children subject children) + (when parent + (ecss-subject-set-children + parent (append (ecss-subject-children parent) (list subject)))) + subject)) + +(defun ecss-subject-set-children (subject children) + "Replace SUBJECT's CHILDREN and maintain their parent links." + (unless (ecss-subject-p subject) + (signal 'wrong-type-argument (list 'ecss-subject-p subject))) + (unless (cl-every #'ecss-subject-p children) + (signal 'wrong-type-argument (list 'ecss-subject-p children))) + (dolist (old-child (ecss-subject-children subject)) + (when (eq (ecss-subject-parent old-child) subject) + (setf (ecss-subject-parent old-child) nil))) + (setf (ecss-subject-children subject) (copy-sequence children)) + (dolist (child children) + (when-let ((old-parent (ecss-subject-parent child))) + (unless (eq old-parent subject) + (setf (ecss-subject-children old-parent) + (delq child (ecss-subject-children old-parent))))) + (setf (ecss-subject-parent child) subject)) + subject) + +(defun ecss--adapter-call (adapter field subject) + "Call ADAPTER callback FIELD for SUBJECT." + (funcall + (pcase field + ('type (ecss-subject-adapter-type adapter)) + ('id (ecss-subject-adapter-id adapter)) + ('classes (ecss-subject-adapter-classes adapter)) + ('attributes (ecss-subject-adapter-attributes adapter)) + ('states (ecss-subject-adapter-states adapter)) + ('parent (ecss-subject-adapter-parent adapter)) + ('children (ecss-subject-adapter-children adapter))) + subject)) + +(defun ecss--subject-parent (subject adapter) + "Return SUBJECT's parent through ADAPTER." + (ecss--adapter-call adapter 'parent subject)) + +(defun ecss--subject-children (subject adapter) + "Return SUBJECT's children through ADAPTER." + (ecss--adapter-call adapter 'children subject)) + +(defun ecss--parser-end-p (parser) + "Return non-nil when PARSER reached the input end." + (>= (ecss--selector-parser-position parser) + (ecss--selector-parser-length parser))) + +(defun ecss--parser-peek (parser &optional offset) + "Return PARSER character at optional OFFSET without consuming it." + (let ((position (+ (ecss--selector-parser-position parser) (or offset 0)))) + (when (< position (ecss--selector-parser-length parser)) + (aref (ecss--selector-parser-input parser) position)))) + +(defun ecss--parser-take (parser) + "Consume and return PARSER's current character." + (prog1 (ecss--parser-peek parser) + (cl-incf (ecss--selector-parser-position parser)))) + +(defun ecss--selector-space-p (character) + "Return non-nil when CHARACTER is CSS whitespace." + (memq character '(?\s ?\t ?\n ?\r ?\f))) + +(defun ecss--parser-skip-comment (parser) + "Skip one comment at PARSER and return non-nil when found." + (when (and (eq (ecss--parser-peek parser) ?/) + (eq (ecss--parser-peek parser 1) ?*)) + (cl-incf (ecss--selector-parser-position parser) 2) + (let ((end (string-match "\\*/" (ecss--selector-parser-input parser) + (ecss--selector-parser-position parser)))) + (unless end + (signal 'ecss-invalid-selector (list :unclosed-comment))) + (setf (ecss--selector-parser-position parser) (+ end 2))) + t)) + +(defun ecss--parser-skip-space (parser) + "Skip whitespace and comments at PARSER and report actual whitespace." + (let (space progress) + (while + (progn + (setq progress nil) + (while (ecss--selector-space-p (ecss--parser-peek parser)) + (setq progress t space t) + (ecss--parser-take parser)) + (when (ecss--parser-skip-comment parser) + (setq progress t)) + progress)) + space)) + +(defun ecss--parser-skip-comments (parser) + "Skip consecutive comments at PARSER without implying a combinator." + (while (ecss--parser-skip-comment parser))) + +(defun ecss--identifier-character-p (character) + "Return non-nil when CHARACTER may occur unescaped in an identifier." + (and character (not (memq character ecss--selector-delimiters)))) + +(defun ecss--parser-read-escape (parser) + "Read one escaped character from PARSER." + (ecss--parser-take parser) + (when (ecss--parser-end-p parser) + (signal 'ecss-invalid-selector (list :trailing-escape))) + (ecss--parser-take parser)) + +(defun ecss--parser-read-identifier (parser) + "Read and return one identifier from PARSER." + (let (characters) + (while (or (ecss--identifier-character-p (ecss--parser-peek parser)) + (eq (ecss--parser-peek parser) ?\\)) + (push (if (eq (ecss--parser-peek parser) ?\\) + (ecss--parser-read-escape parser) + (ecss--parser-take parser)) + characters)) + (unless characters + (signal 'ecss-invalid-selector + (list :expected-identifier + (ecss--selector-parser-position parser)))) + (apply #'string (nreverse characters)))) + +(defun ecss--parser-expect (parser character) + "Consume CHARACTER from PARSER or signal an invalid-selector error." + (unless (eq (ecss--parser-peek parser) character) + (signal 'ecss-invalid-selector + (list :expected character + :position (ecss--selector-parser-position parser)))) + (ecss--parser-take parser)) + +(defun ecss--parser-read-string (parser) + "Read one quoted string from PARSER." + (let ((quote (ecss--parser-take parser)) characters done) + (while (and (not done) (not (ecss--parser-end-p parser))) + (let ((character (ecss--parser-take parser))) + (cond ((eq character quote) (setq done t)) + ((eq character ?\\) + (when (ecss--parser-end-p parser) + (signal 'ecss-invalid-selector (list :trailing-escape))) + (push (ecss--parser-take parser) characters)) + (t (push character characters))))) + (unless done + (signal 'ecss-invalid-selector (list :unclosed-string))) + (apply #'string (nreverse characters)))) + +(defun ecss--parser-read-attribute-value (parser) + "Read one attribute value from PARSER." + (if (memq (ecss--parser-peek parser) '(?' ?\")) + (ecss--parser-read-string parser) + (ecss--parser-read-identifier parser))) + +(defun ecss--parser-attribute-operator (parser) + "Read an optional attribute operator from PARSER." + (let ((first (ecss--parser-peek parser)) + (second (ecss--parser-peek parser 1))) + (cond ((eq first ?=) (ecss--parser-take parser) "=") + ((and (memq first '(?~ ?| ?^ ?$ ?*)) (eq second ?=)) + (cl-incf (ecss--selector-parser-position parser) 2) + (string first second))))) + +(defun ecss--parser-read-attribute (parser) + "Read one attribute selector from PARSER." + (ecss--parser-expect parser ?\[) + (ecss--parser-skip-space parser) + (let ((name (ecss--parser-read-identifier parser)) operator value flag) + (ecss--parser-skip-space parser) + (setq operator (ecss--parser-attribute-operator parser)) + (when operator + (ecss--parser-skip-space parser) + (setq value (ecss--parser-read-attribute-value parser)) + (ecss--parser-skip-space parser) + (when (and (ecss--identifier-character-p (ecss--parser-peek parser)) + (not (eq (ecss--parser-peek parser) ?\]))) + (setq flag (downcase (ecss--parser-read-identifier parser))) + (unless (member flag '("i" "s")) + (signal 'ecss-invalid-selector (list :attribute-flag flag))) + (ecss--parser-skip-space parser))) + (ecss--parser-expect parser ?\]) + (if operator + (list :attr name operator value flag) + (list :attr name)))) + +(defun ecss--parser-read-raw-function (parser) + "Read an unknown pseudo function argument from PARSER." + (let ((start (ecss--selector-parser-position parser)) + (depth 1) quote escaped) + (while (and (> depth 0) (not (ecss--parser-end-p parser))) + (let ((character (ecss--parser-take parser))) + (cond (escaped (setq escaped nil)) + ((eq character ?\\) (setq escaped t)) + (quote (when (eq character quote) (setq quote nil))) + ((memq character '(?' ?\")) (setq quote character)) + ((eq character ?\() (cl-incf depth)) + ((eq character ?\)) (cl-decf depth))))) + (unless (zerop depth) + (signal 'ecss-invalid-selector (list :unclosed-pseudo))) + (string-trim + (substring (ecss--selector-parser-input parser) start + (1- (ecss--selector-parser-position parser)))))) + +(defun ecss--anchor-relative-selector (selector kind) + "Anchor relative SELECTOR with leading combinator KIND." + (if (memq (car-safe selector) '(:descendant :child :adjacent :sibling)) + (list (car selector) + (ecss--anchor-relative-selector (nth 1 selector) kind) + (nth 2 selector)) + (list kind '(:anchor) selector))) + +(defun ecss--parser-read-relative-list (parser) + "Read a relative selector list from PARSER through its closing parenthesis." + (ecss--parser-skip-space parser) + (let (selectors done) + (while (not done) + (let ((kind (or (ecss--combinator-kind (ecss--parser-peek parser)) + :descendant))) + (unless (eq kind :descendant) + (ecss--parser-take parser) + (ecss--parser-skip-space parser)) + (push (ecss--anchor-relative-selector + (ecss--parser-read-complex parser ?\)) kind) + selectors)) + (ecss--parser-skip-space parser) + (cond ((eq (ecss--parser-peek parser) ?,) + (ecss--parser-take parser) + (ecss--parser-skip-space parser)) + ((eq (ecss--parser-peek parser) ?\)) + (ecss--parser-take parser) + (setq done t)) + (t (signal 'ecss-invalid-selector (list :unterminated-relative))))) + (nreverse selectors))) + +(defun ecss--parser-read-pseudo (parser) + "Read one pseudo-class selector from PARSER." + (ecss--parser-expect parser ?:) + (when (eq (ecss--parser-peek parser) ?:) + (signal 'ecss-invalid-selector (list :pseudo-elements-unsupported))) + (let ((name (downcase (ecss--parser-read-identifier parser)))) + (if (not (eq (ecss--parser-peek parser) ?\()) + (list :state name) + (ecss--parser-take parser) + (cond + ((equal name "has") + (cons :has (ecss--parser-read-relative-list parser))) + ((member name '("is" "where" "not")) + (let ((selectors (ecss--parser-read-selector-list parser ?\)))) + (cons (intern (concat ":" name)) + (if (eq (car-safe selectors) :list) + (cdr selectors) + (list selectors))))) + (t (list :state + (list name (ecss--parser-read-raw-function parser)))))))) + +(defun ecss--compound-item-p (character) + "Return non-nil when CHARACTER can start a compound selector item." + (memq character '(?# ?. ?\[ ?:))) + +(defun ecss--parser-read-compound (parser) + "Read one compound selector from PARSER." + (let (items) + (cond ((eq (ecss--parser-peek parser) ?*) + (ecss--parser-take parser) + (push '(:universal) items)) + ((ecss--identifier-character-p (ecss--parser-peek parser)) + (push (list :type (ecss--parser-read-identifier parser)) items))) + (ecss--parser-skip-comments parser) + (while (ecss--compound-item-p (ecss--parser-peek parser)) + (pcase (ecss--parser-peek parser) + (?# (ecss--parser-take parser) + (push (list :id (ecss--parser-read-identifier parser)) items)) + (?. (ecss--parser-take parser) + (push (list :class (ecss--parser-read-identifier parser)) items)) + (?\[ (push (ecss--parser-read-attribute parser) items)) + (?: (push (ecss--parser-read-pseudo parser) items))) + (ecss--parser-skip-comments parser)) + (setq items (nreverse items)) + (cond ((null items) + (signal 'ecss-invalid-selector + (list :expected-compound + (ecss--selector-parser-position parser)))) + ((null (cdr items)) (car items)) + (t (cons :and items))))) + +(defun ecss--combinator-kind (character) + "Return AST combinator kind for CHARACTER." + (pcase character (?> :child) (?+ :adjacent) (?~ :sibling))) + +(defun ecss--selector-list-end-p (parser terminator) + "Return non-nil when PARSER is at a list boundary TERMINATOR." + (or (ecss--parser-end-p parser) + (eq (ecss--parser-peek parser) ?,) + (and terminator (eq (ecss--parser-peek parser) terminator)))) + +(defun ecss--parser-read-complex (parser terminator) + "Read one complex selector from PARSER up to TERMINATOR." + (let ((left (ecss--parser-read-compound parser)) done) + (while (not done) + (let ((space (ecss--parser-skip-space parser)) kind) + (cond ((ecss--selector-list-end-p parser terminator) + (setq done t)) + ((setq kind (ecss--combinator-kind (ecss--parser-peek parser))) + (ecss--parser-take parser) + (ecss--parser-skip-space parser) + (setq left (list kind left + (ecss--parser-read-compound parser)))) + (space + (setq left (list :descendant left + (ecss--parser-read-compound parser)))) + (t + (signal 'ecss-invalid-selector + (list :unexpected-character + (ecss--parser-peek parser))))))) + left)) + +(defun ecss--parser-read-selector-list (parser &optional terminator) + "Read a selector list from PARSER up to optional TERMINATOR." + (ecss--parser-skip-space parser) + (let (selectors done) + (while (not done) + (push (ecss--parser-read-complex parser terminator) selectors) + (ecss--parser-skip-space parser) + (cond ((eq (ecss--parser-peek parser) ?,) + (ecss--parser-take parser) + (ecss--parser-skip-space parser)) + ((and terminator (eq (ecss--parser-peek parser) terminator)) + (ecss--parser-take parser) + (setq done t)) + ((and (null terminator) (ecss--parser-end-p parser)) + (setq done t)) + (t (signal 'ecss-invalid-selector (list :unterminated-list))))) + (setq selectors (nreverse selectors)) + (if (null (cdr selectors)) (car selectors) (cons :list selectors)))) + +;;;###autoload +(defun ecss-selector-parse (selector) + "Parse CSS-like SELECTOR text into a structured selector AST." + (unless (and (stringp selector) (not (string-empty-p selector))) + (signal 'ecss-invalid-selector (list selector))) + (let ((parser (ecss--make-selector-parser + :input selector :position 0 :length (length selector)))) + (ecss--parser-read-selector-list parser))) + +(defun ecss--selector-form-p (selector kind arity) + "Return non-nil when SELECTOR is KIND with ARITY arguments." + (and (consp selector) (eq (car selector) kind) + (= (length (cdr selector)) arity))) + +(defun ecss--selector-list-valid-p (selectors) + "Return non-nil when SELECTORS is a nonempty valid selector list." + (and selectors (cl-every #'ecss-selector-valid-p selectors))) + +(defun ecss--attribute-selector-valid-p (selector) + "Return non-nil when attribute SELECTOR is valid." + (or (ecss--selector-form-p selector :attr 1) + (and (ecss--selector-form-p selector :attr 4) + (member (nth 2 selector) ecss--attribute-operators) + (or (null (nth 4 selector)) + (member (nth 4 selector) '("i" "s")))))) + +(defun ecss-selector-valid-p (selector) + "Return non-nil when structured SELECTOR is valid." + (pcase (car-safe selector) + ((or :type :id :class :state) + (and (ecss--selector-form-p selector (car selector) 1) + (nth 1 selector))) + (:attr (ecss--attribute-selector-valid-p selector)) + ((or :and :list :is :where :not :has) + (ecss--selector-list-valid-p (cdr selector))) + ((or :descendant :child :adjacent :sibling) + (and (ecss--selector-form-p selector (car selector) 2) + (ecss--selector-list-valid-p (cdr selector)))) + ((or :universal :anchor) (null (cdr selector))) + (_ nil))) + +(defun ecss--validate-selector (selector) + "Return SELECTOR or signal when it is invalid." + (unless (ecss-selector-valid-p selector) + (signal 'ecss-invalid-selector (list selector))) + selector) + +;;;###autoload +(defun ecss-selector-normalize (selector) + "Return a validated defensive AST for string or structured SELECTOR." + (let ((ast (if (stringp selector) (ecss-selector-parse selector) selector))) + (copy-tree (ecss--validate-selector ast)))) + +(defun ecss--subject-attribute-cell (subject adapter name) + "Return SUBJECT attribute NAME through ADAPTER." + (assoc name (ecss--adapter-call adapter 'attributes subject))) + +(defun ecss--subject-previous-siblings (subject adapter) + "Return SUBJECT's preceding siblings through ADAPTER." + (when-let ((parent (ecss--subject-parent subject adapter))) + (let ((siblings (ecss--subject-children parent adapter)) result) + (while (and siblings (not (eq (car siblings) subject))) + (push (pop siblings) result)) + (nreverse result)))) + +(defun ecss--attribute-token-member-p (needle value insensitive) + "Return whether NEEDLE occurs in whitespace-separated VALUE. +Compare without case when INSENSITIVE is non-nil." + (let ((tokens (split-string (format "%s" value) "[ \t\n\r\f]+" t))) + (cl-some (lambda (token) + (if insensitive + (string-equal (downcase needle) (downcase token)) + (string-equal needle token))) + tokens))) + +(defun ecss--attribute-string-match-p (operator expected actual insensitive) + "Match EXPECTED against ACTUAL with OPERATOR and case mode INSENSITIVE." + (let ((expected (format "%s" expected)) (actual (format "%s" actual))) + (when insensitive + (setq expected (downcase expected) actual (downcase actual))) + (cond ((equal operator "=") (string-equal actual expected)) + ((equal operator "~=") + (ecss--attribute-token-member-p expected actual insensitive)) + ((equal operator "|=") + (or (string-equal actual expected) + (string-prefix-p (concat expected "-") actual))) + ((equal operator "^=") (string-prefix-p expected actual)) + ((equal operator "$=") (string-suffix-p expected actual)) + ((equal operator "*=") + (string-match-p (regexp-quote expected) actual))))) + +(defun ecss--selector-match-attribute (selector subject adapter) + "Return whether attribute SELECTOR matches SUBJECT through ADAPTER." + (let ((cell (ecss--subject-attribute-cell subject adapter (nth 1 selector)))) + (and cell + (or (= (length selector) 2) + (ecss--attribute-string-match-p + (nth 2 selector) (nth 3 selector) (cdr cell) + (equal (nth 4 selector) "i")))))) + +(defun ecss--selector-match-descendant (selector subject adapter) + "Return whether descendant SELECTOR matches SUBJECT through ADAPTER." + (and (ecss-selector-match-p (nth 2 selector) subject adapter) + (cl-loop for parent = (ecss--subject-parent subject adapter) + then (ecss--subject-parent parent adapter) + while parent + thereis (ecss-selector-match-p + (nth 1 selector) parent adapter)))) + +(defun ecss--selector-match-adjacent (selector subject adapter) + "Return whether adjacent SELECTOR matches SUBJECT through ADAPTER." + (let ((siblings (ecss--subject-previous-siblings subject adapter))) + (and siblings + (ecss-selector-match-p (nth 1 selector) (car (last siblings)) adapter) + (ecss-selector-match-p (nth 2 selector) subject adapter)))) + +(defun ecss--selector-match-sibling (selector subject adapter) + "Return whether sibling SELECTOR matches SUBJECT through ADAPTER." + (and (ecss-selector-match-p (nth 2 selector) subject adapter) + (cl-some (lambda (sibling) + (ecss-selector-match-p (nth 1 selector) sibling adapter)) + (ecss--subject-previous-siblings subject adapter)))) + +(defun ecss--subject-descendants (subject adapter) + "Return all descendants of SUBJECT through ADAPTER." + (cl-loop for child in (ecss--subject-children subject adapter) + append (cons child (ecss--subject-descendants child adapter)))) + +(defun ecss--subject-following-siblings (subject adapter) + "Return siblings following SUBJECT through ADAPTER." + (when-let ((parent (ecss--subject-parent subject adapter))) + (let ((siblings (ecss--subject-children parent adapter))) + (while (and siblings (not (eq (pop siblings) subject)))) + siblings))) + +(defun ecss--relative-candidates (subject adapter) + "Return possible relative-selector targets from SUBJECT through ADAPTER." + (append + (ecss--subject-descendants subject adapter) + (cl-loop for sibling in (ecss--subject-following-siblings subject adapter) + append (cons sibling (ecss--subject-descendants sibling adapter))))) + +(defun ecss--selector-match-has (selectors subject adapter) + "Return whether SUBJECT has a relative target matching SELECTORS." + (let ((ecss--selector-anchor subject)) + (cl-some (lambda (candidate) + (cl-some (lambda (selector) + (ecss-selector-match-p selector candidate adapter)) + selectors)) + (ecss--relative-candidates subject adapter)))) + +(defun ecss--selector-match-valid (selector subject adapter) + "Match validated SELECTOR against SUBJECT through ADAPTER." + (pcase (car selector) + (:universal t) + (:anchor (eq subject ecss--selector-anchor)) + (:type (equal (nth 1 selector) (ecss--adapter-call adapter 'type subject))) + (:id (equal (nth 1 selector) (ecss--adapter-call adapter 'id subject))) + (:class (member (nth 1 selector) + (ecss--adapter-call adapter 'classes subject))) + (:state (member (nth 1 selector) + (ecss--adapter-call adapter 'states subject))) + (:attr (ecss--selector-match-attribute selector subject adapter)) + (:and (cl-every (lambda (item) + (ecss-selector-match-p item subject adapter)) + (cdr selector))) + ((or :list :is :where) + (cl-some (lambda (item) + (ecss-selector-match-p item subject adapter)) + (cdr selector))) + (:not (not (cl-some (lambda (item) + (ecss-selector-match-p item subject adapter)) + (cdr selector)))) + (:has (ecss--selector-match-has (cdr selector) subject adapter)) + (:descendant (ecss--selector-match-descendant selector subject adapter)) + (:child (and (ecss-selector-match-p (nth 2 selector) subject adapter) + (when-let ((parent (ecss--subject-parent subject adapter))) + (ecss-selector-match-p (nth 1 selector) parent adapter)))) + (:adjacent (ecss--selector-match-adjacent selector subject adapter)) + (:sibling (ecss--selector-match-sibling selector subject adapter)))) + +;;;###autoload +(defun ecss-selector-match-p + (selector subject &optional adapter) + "Return non-nil when SELECTOR matches SUBJECT through optional ADAPTER." + (let ((adapter (or adapter ecss-default-subject-adapter)) + (selector (if (stringp selector) + (ecss-selector-parse selector) + selector))) + (unless (ecss-subject-adapter-p adapter) + (signal 'wrong-type-argument (list 'ecss-subject-adapter-p adapter))) + (ecss--validate-selector selector) + (ecss--selector-match-valid selector subject adapter))) + +(defun ecss--specificity-add (left right) + "Add specificity triples LEFT and RIGHT." + (cl-mapcar #'+ left right)) + +(defun ecss--specificity-greater-p (left right) + "Return non-nil when specificity LEFT is greater than RIGHT." + (catch 'result + (cl-mapc (lambda (a b) + (cond ((> a b) (throw 'result t)) + ((< a b) (throw 'result nil)))) + left right) + nil)) + +(defun ecss--specificity-max (values) + "Return the lexicographically greatest specificity in VALUES." + (cl-reduce (lambda (left right) + (if (ecss--specificity-greater-p left right) left right)) + values :initial-value '(0 0 0))) + +(defun ecss--specificity-list-sum (selectors) + "Return the combined specificity of SELECTORS." + (cl-reduce #'ecss--specificity-add selectors + :key #'ecss-selector-specificity + :initial-value '(0 0 0))) + +;;;###autoload +(defun ecss-selector-specificity (selector) + "Return SELECTOR specificity as an (ID CLASS TYPE) list." + (setq selector (if (stringp selector) + (ecss-selector-parse selector) + selector)) + (ecss--validate-selector selector) + (pcase (car selector) + (:id '(1 0 0)) + ((or :class :attr :state) '(0 1 0)) + (:type '(0 0 1)) + ((or :universal :anchor :where) '(0 0 0)) + (:and (ecss--specificity-list-sum (cdr selector))) + ((or :list :is :not :has) + (ecss--specificity-max + (mapcar #'ecss-selector-specificity (cdr selector)))) + ((or :descendant :child :adjacent :sibling) + (ecss--specificity-list-sum (cdr selector))))) + +(defun ecss--selector-matched-specificity (selector subject adapter) + "Return matched specificity for SELECTOR, SUBJECT, and ADAPTER, or nil." + (when (ecss-selector-match-p selector subject adapter) + (if (eq (car selector) :list) + (ecss--specificity-max + (cl-loop for item in (cdr selector) + when (ecss-selector-match-p item subject adapter) + collect (ecss-selector-specificity item))) + (ecss-selector-specificity selector)))) + +(provide 'ecss-selector) +;;; ecss-selector.el ends here diff --git a/ecss.el b/ecss.el new file mode 100644 index 0000000..2ded085 --- /dev/null +++ b/ecss.el @@ -0,0 +1,27 @@ +;;; ecss.el --- Pure extensible CSS cascade engine -*- lexical-binding: t; -*- + +;; Copyright (C) 2026 Geekinney + +;; Author: Geekinney +;; URL: https://github.com/geekinney/ecss +;; Version: 0.1.0 +;; Package-Requires: ((emacs "28.1")) +;; Keywords: lisp, extensions +;; SPDX-License-Identifier: GPL-3.0-or-later +;; Assisted-by: Codex + +;;; Commentary: + +;; ECSS is a pure, consumer-independent selector and CSS cascade engine. +;; Consumers register their own property vocabulary, expose their own subject +;; values through adapters, and decide what computed values mean. ECSS never +;; mutates buffers and has no dependency on TP, Ebox, or the historical ECSS +;; repository. + +;;; Code: + +(require 'ecss-selector) +(require 'ecss-cascade) + +(provide 'ecss) +;;; ecss.el ends here diff --git a/tests/ecss-cascade-tests.el b/tests/ecss-cascade-tests.el new file mode 100644 index 0000000..287cbcf --- /dev/null +++ b/tests/ecss-cascade-tests.el @@ -0,0 +1,620 @@ +;;; ecss-cascade-tests.el --- Cascade tests -*- lexical-binding: t; -*- + +;; Copyright (C) 2026 Geekinney +;; SPDX-License-Identifier: GPL-3.0-or-later + +;;; Code: + +(require 'ert) +(require 'cl-lib) +(require 'ecss-cascade) + +(defun ecss-cascade-test--schemas () + "Return the standard test schema set." + (let ((schemas (ecss-schema-set-create))) + (ecss-schema-set-define + schemas 'app/color :initial "black" :inherits t + :validator #'stringp) + (ecss-schema-set-define + schemas 'app/width :initial 0 :validator #'integerp) + (ecss-schema-set-define schemas 'app/payload :initial nil :inherits t) + (dolist (property '(app/padding-top app/padding-right + app/padding-bottom app/padding-left)) + (ecss-schema-set-define + schemas property :initial 0 :validator #'integerp)) + (ecss-schema-set-define + schemas 'app/padding + :shorthand + (lambda (value) + (list 'app/padding-top value 'app/padding-right value + 'app/padding-bottom value 'app/padding-left value))) + schemas)) + +(defun ecss-cascade-test--subject (&rest options) + "Return a button subject using OPTIONS." + (apply #'ecss-subject-create :type "button" options)) + +(defun ecss-cascade-test--value (style property) + "Return PROPERTY from computed STYLE." + (ecss-computed-style-value style property :absent)) + +(ert-deftest ecss-cascade-test-schema-registration-is-atomic () + (let ((schemas (ecss-schema-set-create))) + (ecss-schema-set-define schemas 'app/width :initial 4 :validator #'integerp) + (should-error + (ecss-schema-set-define schemas 'app/width :initial "bad" + :validator #'integerp) + :type 'ecss-invalid-property-schema) + (should (= (ecss-property-schema-initial + (ecss-schema-set-property schemas 'app/width)) + 4)) + (should-error + (ecss-schema-set-define schemas 'not-namespaced :initial 1) + :type 'ecss-invalid-property-schema) + (should (equal (ecss-schema-set-property-ids schemas) '(app/width))))) + +(ert-deftest ecss-cascade-test-computed-defaults-are-not-renormalized () + (let ((schemas (ecss-schema-set-create)) + (subject (ecss-cascade-test--subject)) + (normalizations 0)) + (ecss-schema-set-define + schemas 'app/value :initial 2 :inherits t + :normalizer (lambda (value) (cl-incf normalizations) (* value 10)) + :validator #'integerp) + (let* ((initial (ecss-compute-style schemas subject)) + (declared (ecss-compute-style + schemas subject :declarations '(app/value 3))) + (inherited (ecss-compute-style + schemas subject :parent-style declared)) + (wide-initial + (ecss-compute-style + schemas subject :parent-style declared + :declarations + (list 'app/value (ecss-wide-value 'initial))))) + (should (= (ecss-cascade-test--value initial 'app/value) 20)) + (should (= (ecss-cascade-test--value declared 'app/value) 30)) + (should (= (ecss-cascade-test--value inherited 'app/value) 30)) + (should (= (ecss-cascade-test--value wide-initial 'app/value) 20)) + (should (= normalizations 2))))) + +(ert-deftest ecss-cascade-test-shorthand-expands-once-and-preserves-important () + (let* ((schemas (ecss-cascade-test--schemas)) + (expanded (ecss-expand-declarations + schemas (list 'app/padding (ecss-important 3))))) + (should (equal (cl-loop for (property _value) on expanded by #'cddr + collect property) + '(app/padding-top app/padding-right + app/padding-bottom app/padding-left))) + (cl-loop for (_property value) on expanded by #'cddr + do (should (ecss--important-p value)) + do (should (= (ecss--important-value value) 3))))) + +(ert-deftest ecss-cascade-test-shorthand-and-longhand-follow-declaration-order () + (let ((schemas (ecss-cascade-test--schemas)) + (subject (ecss-cascade-test--subject))) + (should (= (ecss-cascade-test--value + (ecss-compute-style + schemas subject + :declarations '(app/padding 1 app/padding-left 2)) + 'app/padding-left) + 2)) + (should (= (ecss-cascade-test--value + (ecss-compute-style + schemas subject + :declarations '(app/padding-left 2 app/padding 1)) + 'app/padding-left) + 1)))) + +(ert-deftest ecss-cascade-test-rule-addition-is-atomic () + (let ((schemas (ecss-cascade-test--schemas)) + (stylesheet (ecss-stylesheet-create))) + (ecss-stylesheet-add-rule + stylesheet schemas ".valid" '(app/color "blue") :layer 'base) + (should-error + (ecss-stylesheet-add-rule + stylesheet schemas ".broken" '(unknown/value 1) :layer 'broken) + :type 'ecss-invalid-declaration) + (should (equal (ecss-stylesheet-layers stylesheet) '(base))) + (should (= (length (ecss-stylesheet-rules stylesheet)) 1)))) + +(ert-deftest ecss-cascade-test-origin-importance-and-transition-order () + (let ((schemas (ecss-cascade-test--schemas)) + (stylesheet (ecss-stylesheet-create)) + (subject (ecss-cascade-test--subject :classes '("target")))) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" '(app/color "ua") :origin 'ua) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" '(app/color "user") :origin 'user) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" '(app/color "author") :origin 'author) + (should (equal (ecss-cascade-test--value + (ecss-compute-style schemas subject :stylesheet stylesheet) + 'app/color) + "author")) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" + (list 'app/color (ecss-important "author-important")) + :origin 'author) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" + (list 'app/color (ecss-important "user-important")) + :origin 'user) + (should (equal (ecss-cascade-test--value + (ecss-compute-style schemas subject :stylesheet stylesheet) + 'app/color) + "user-important")) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" '(app/color "transition") + :origin 'transition) + (should (equal (ecss-cascade-test--value + (ecss-compute-style schemas subject :stylesheet stylesheet) + 'app/color) + "transition")))) + +(ert-deftest ecss-cascade-test-standard-origin-levels-are-complete () + (let ((schemas (ecss-cascade-test--schemas)) + (stylesheet (ecss-stylesheet-create)) + (subject (ecss-cascade-test--subject :classes '("target")))) + (dolist (entry + (list (list 'author "author") + (list 'animation "animation") + (list 'author (ecss-important "author-important")) + (list 'user (ecss-important "user-important")) + (list 'ua (ecss-important "ua-important")))) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" (list 'app/color (cadr entry)) + :origin (car entry))) + (should (equal (ecss-cascade-test--value + (ecss-compute-style schemas subject :stylesheet stylesheet) + 'app/color) + "ua-important")))) + +(ert-deftest ecss-cascade-test-layer-order-reverses-for-important () + (let ((schemas (ecss-cascade-test--schemas)) + (normal (ecss-stylesheet-create)) + (important (ecss-stylesheet-create)) + (subject (ecss-cascade-test--subject :classes '("target")))) + (ecss-stylesheet-declare-layers normal '(base components)) + (ecss-stylesheet-add-rule + normal schemas ".target" '(app/color "base") :layer 'base) + (ecss-stylesheet-add-rule + normal schemas ".target" '(app/color "components") :layer 'components) + (ecss-stylesheet-add-rule normal schemas ".target" '(app/color "plain")) + (should (equal (ecss-cascade-test--value + (ecss-compute-style schemas subject :stylesheet normal) + 'app/color) + "plain")) + (ecss-stylesheet-declare-layers important '(base components)) + (dolist (entry '((base "base") (components "components") (nil "plain"))) + (ecss-stylesheet-add-rule + important schemas ".target" + (list 'app/color (ecss-important (cadr entry))) + :layer (car entry))) + (should (equal (ecss-cascade-test--value + (ecss-compute-style schemas subject :stylesheet important) + 'app/color) + "base")) + (should (equal (ecss-cascade-test--value + (ecss-compute-style + schemas subject :stylesheet important + :declarations + (list 'app/color (ecss-important "inline"))) + 'app/color) + "inline")))) + +(ert-deftest ecss-cascade-test-layer-order-is-independent-per-origin () + (let ((stylesheet (ecss-stylesheet-create))) + (ecss-stylesheet-declare-layers stylesheet '(base components) 'author) + (ecss-stylesheet-declare-layers stylesheet '(components base) 'user) + (should (equal (ecss-stylesheet-layers stylesheet 'author) + '(base components))) + (should (equal (ecss-stylesheet-layers stylesheet 'user) + '(components base))))) + +(ert-deftest ecss-cascade-test-specificity-source-order-and-selector-list () + (let ((schemas (ecss-cascade-test--schemas)) + (stylesheet (ecss-stylesheet-create)) + (subject (ecss-cascade-test--subject + :id "actual" :classes '("target")))) + (ecss-stylesheet-add-rule + stylesheet schemas "#other, .target" '(app/color "first")) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" '(app/color "later")) + (should (equal (ecss-cascade-test--value + (ecss-compute-style schemas subject :stylesheet stylesheet) + 'app/color) + "later")) + (ecss-stylesheet-add-rule + stylesheet schemas "button#actual" '(app/color "id")) + (should (equal (ecss-cascade-test--value + (ecss-compute-style schemas subject :stylesheet stylesheet) + 'app/color) + "id")))) + +(ert-deftest ecss-cascade-test-scope-proximity-follows-specificity () + (let* ((schemas (ecss-cascade-test--schemas)) + (stylesheet (ecss-stylesheet-create)) + (target (ecss-cascade-test--subject :classes '("target"))) + (inner (ecss-subject-create + :type "section" :classes '("inner") + :children (list target))) + (_outer (ecss-subject-create + :type "main" :classes '("outer") + :children (list inner)))) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" '(app/color "outer") :scope ".outer") + (ecss-stylesheet-add-rule + stylesheet schemas ".target" '(app/color "inner") :scope ".inner") + (ecss-stylesheet-add-rule + stylesheet schemas ".target" '(app/color "missing") :scope ".missing") + (should (equal (ecss-cascade-test--value + (ecss-compute-style schemas target :stylesheet stylesheet) + 'app/color) + "inner")))) + +(ert-deftest ecss-cascade-test-inheritance-distinguishes-nil-from-absence () + (let* ((schemas (ecss-cascade-test--schemas)) + (subject (ecss-cascade-test--subject)) + (parent (ecss-compute-style + schemas subject + :declarations '(app/color "red" app/payload nil))) + (child (ecss-compute-style schemas subject :parent-style parent)) + (initial (ecss-compute-style schemas subject))) + (should (equal (ecss-cascade-test--value child 'app/color) "red")) + (should (null (ecss-cascade-test--value child 'app/payload))) + (should (ecss-computed-style-present-p child 'app/payload)) + (should-not (ecss-computed-style-present-p initial 'app/payload)))) + +(ert-deftest ecss-cascade-test-css-wide-values-use-cascade-not-symbol-reservation () + (let* ((schemas (ecss-cascade-test--schemas)) + (subject (ecss-cascade-test--subject :classes '("target"))) + (parent (ecss-compute-style + schemas subject :declarations '(app/color "parent"))) + (inherit (ecss-compute-style + schemas subject :parent-style parent + :declarations + (list 'app/color (ecss-wide-value 'inherit)))) + (initial (ecss-compute-style + schemas subject :parent-style parent + :declarations + (list 'app/color (ecss-wide-value 'initial))))) + (should (equal (ecss-cascade-test--value inherit 'app/color) "parent")) + (should (equal (ecss-cascade-test--value initial 'app/color) "black")) + (should (equal (ecss-cascade-test--value + (ecss-compute-style + schemas subject :declarations '(app/payload inherit)) + 'app/payload) + 'inherit)))) + +(ert-deftest ecss-cascade-test-revert-and-revert-layer-select-lower-candidates () + (let ((schemas (ecss-cascade-test--schemas)) + (stylesheet (ecss-stylesheet-create)) + (subject (ecss-cascade-test--subject :classes '("target")))) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" '(app/color "ua") :origin 'ua) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" '(app/color "author") :origin 'author) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" + (list 'app/color (ecss-wide-value 'revert)) :origin 'author) + (should (equal (ecss-cascade-test--value + (ecss-compute-style schemas subject :stylesheet stylesheet) + 'app/color) + "ua")) + (ecss-stylesheet-clear stylesheet) + (ecss-stylesheet-declare-layers stylesheet '(base components)) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" '(app/color "base") :layer 'base) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" '(app/color "components") + :layer 'components) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" + (list 'app/color (ecss-wide-value 'revert-layer)) :layer 'components) + (should (equal (ecss-cascade-test--value + (ecss-compute-style schemas subject :stylesheet stylesheet) + 'app/color) + "base")))) + +(ert-deftest ecss-cascade-test-important-revert-removes-entire-origin () + (let ((schemas (ecss-cascade-test--schemas)) + (stylesheet (ecss-stylesheet-create)) + (subject (ecss-cascade-test--subject :classes '("target")))) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" '(app/color "user") :origin 'user) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" '(app/color "author-normal") + :origin 'author) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" + (list 'app/color (ecss-important (ecss-wide-value 'revert))) + :origin 'author) + (should (equal (ecss-cascade-test--value + (ecss-compute-style schemas subject :stylesheet stylesheet) + 'app/color) + "user")))) + +(ert-deftest ecss-cascade-test-important-revert-layer-removes-entire-layer () + (let ((schemas (ecss-cascade-test--schemas)) + (stylesheet (ecss-stylesheet-create)) + (subject (ecss-cascade-test--subject :classes '("target")))) + (ecss-stylesheet-declare-layers stylesheet '(base components)) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" '(app/color "base") :layer 'base) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" '(app/color "component-normal") + :layer 'components) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" + (list 'app/color (ecss-important (ecss-wide-value 'revert-layer))) + :layer 'components) + (should (equal (ecss-cascade-test--value + (ecss-compute-style schemas subject :stylesheet stylesheet) + 'app/color) + "base")))) + +(ert-deftest ecss-cascade-test-custom-property-revert-removes-entire-origin () + (let ((schemas (ecss-cascade-test--schemas)) + (stylesheet (ecss-stylesheet-create)) + (subject (ecss-cascade-test--subject :classes '("target")))) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" '(--theme 7) :origin 'user) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" '(--theme 8) :origin 'author) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" + (list '--theme (ecss-important (ecss-wide-value 'revert))) + :origin 'author) + (let ((style (ecss-compute-style + schemas subject :stylesheet stylesheet + :declarations (list 'app/width (ecss-var '--theme))))) + (should (= (ecss-cascade-test--value style 'app/width) 7))))) + +(ert-deftest ecss-cascade-test-custom-properties-resolve-nested-values () + (let* ((schemas (ecss-cascade-test--schemas)) + (subject (ecss-cascade-test--subject)) + (style (ecss-compute-style + schemas subject + :declarations + (list '--base 12 '--alias (ecss-var '--base) + 'app/width (ecss-var '--alias) + 'app/payload (list 'calc (ecss-var '--base)))))) + (should (= (ecss-cascade-test--value style 'app/width) 12)) + (should (equal (ecss-cascade-test--value style 'app/payload) + '(calc 12))) + (should (equal (ecss-computed-style-custom-properties style) + '(--alias 12 --base 12))))) + +(ert-deftest ecss-cascade-test-custom-properties-inherit-by-default () + (let* ((schemas (ecss-cascade-test--schemas)) + (subject (ecss-cascade-test--subject)) + (parent (ecss-compute-style + schemas subject :declarations '(--theme 17))) + (child (ecss-compute-style + schemas subject :parent-style parent + :declarations (list 'app/width (ecss-var '--theme))))) + (should (= (ecss-cascade-test--value child 'app/width) 17)) + (should (equal (ecss-computed-style-custom-properties child) + '(--theme 17))))) + +(ert-deftest ecss-cascade-test-variable-cycle-uses-outer-fallback () + (let* ((schemas (ecss-cascade-test--schemas)) + (style (ecss-compute-style + schemas (ecss-cascade-test--subject) + :declarations + (list '--a (ecss-var '--b) '--b (ecss-var '--a) + 'app/width (ecss-var '--a 9))))) + (should (= (ecss-cascade-test--value style 'app/width) 9)) + (should (equal (ecss-computed-style-diagnostics style) + '((:type variable-cycle :path (--a --b --a))))) + (should (null (ecss-computed-style-custom-properties style))))) + +(ert-deftest ecss-cascade-test-parent-plist-is-snapshotted () + (let* ((schemas (ecss-cascade-test--schemas)) + (payload (list 'original)) + (parent (list 'app/payload payload)) + (style (ecss-compute-style + schemas (ecss-cascade-test--subject) + :parent-style parent))) + (setcar payload 'damaged) + (should (equal (ecss-cascade-test--value style 'app/payload) + '(original))))) + +(ert-deftest ecss-cascade-test-invalid-winner-does-not-recascade () + (let ((schemas (ecss-cascade-test--schemas)) + (stylesheet (ecss-stylesheet-create)) + (subject (ecss-cascade-test--subject :classes '("target")))) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" '(app/width 10)) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" '(app/width "invalid")) + (let* ((style (ecss-compute-style + schemas subject :stylesheet stylesheet :provenance t)) + (facts (plist-get (ecss-computed-style-provenance style) + 'app/width))) + (should (= (ecss-cascade-test--value style 'app/width) 0)) + (should (eq (plist-get facts :valid) nil)) + (should (eq (plist-get facts :fallback) 'initial)) + (should-not (ecss-computed-style-present-p style 'app/width))))) + +(ert-deftest ecss-cascade-test-literal-functions-are-never-called () + (let ((schemas (ecss-cascade-test--schemas)) (calls 0)) + (let* ((literal (lambda () (cl-incf calls))) + (style (ecss-compute-style + schemas (ecss-cascade-test--subject) + :declarations (list 'app/payload literal)))) + (should (zerop calls)) + (should (functionp (ecss-cascade-test--value style 'app/payload)))))) + +(ert-deftest ecss-cascade-test-explicit-resolver-runs-once () + (let ((schemas (ecss-cascade-test--schemas)) (calls 0)) + (let* ((source (list :computed (lambda () (cl-incf calls) 42))) + (style + (ecss-compute-style + schemas (ecss-cascade-test--subject) + :declarations (list 'app/width source) + :value-resolver + (lambda (value _property _subject) + (if (eq (car-safe value) :computed) + (funcall (cadr value)) + value))))) + (should (= calls 1)) + (should (= (ecss-cascade-test--value style 'app/width) 42))))) + +(ert-deftest ecss-cascade-test-resolver-never-runs-for-losing-sources () + (let ((schemas (ecss-cascade-test--schemas)) + (stylesheet (ecss-stylesheet-create)) + (subject (ecss-cascade-test--subject :classes '("target"))) + (calls 0)) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" + (list 'app/width (list :computed (lambda () (error "loser ran"))))) + (ecss-stylesheet-add-rule + stylesheet schemas ".other" + (list 'app/width (list :computed (lambda () (error "unmatched ran"))))) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" '(app/width 8)) + (let ((style + (ecss-compute-style + schemas subject :stylesheet stylesheet + :value-resolver + (lambda (value _property _subject) + (cl-incf calls) + (if (eq (car-safe value) :computed) + (funcall (cadr value)) + value))))) + (should (= (ecss-cascade-test--value style 'app/width) 8)) + (should (= calls 1))))) + +(ert-deftest ecss-cascade-test-resolver-skips-reverted-origin-losers () + (let ((schemas (ecss-cascade-test--schemas)) + (stylesheet (ecss-stylesheet-create)) + (subject (ecss-cascade-test--subject :classes '("target"))) + (calls 0)) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" '(app/width 5) :origin 'ua) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" + (list 'app/width (list :computed (lambda () (error "reverted loser ran")))) + :origin 'author) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" + (list 'app/width (ecss-wide-value 'revert)) :origin 'author) + (let ((style + (ecss-compute-style + schemas subject :stylesheet stylesheet + :value-resolver + (lambda (value _property _subject) + (cl-incf calls) + (if (eq (car-safe value) :computed) + (funcall (cadr value)) + value))))) + (should (= (ecss-cascade-test--value style 'app/width) 5)) + (should (= calls 2))))) + +(ert-deftest ecss-cascade-test-selected-resolver-errors-propagate () + (let ((schemas (ecss-cascade-test--schemas))) + (should-error + (ecss-compute-style + schemas (ecss-cascade-test--subject) + :declarations '(app/width 1) + :value-resolver + (lambda (_value _property _subject) (error "resolver boom"))) + :type 'error))) + +(ert-deftest ecss-cascade-test-rule-list-is-an-independent-snapshot () + (let ((schemas (ecss-cascade-test--schemas)) + (stylesheet (ecss-stylesheet-create)) + (subject (ecss-cascade-test--subject :classes '("target")))) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" '(app/color "snapshot")) + (let ((rules (ecss-stylesheet-rules stylesheet))) + (ecss-stylesheet-clear stylesheet) + (should (equal (ecss-cascade-test--value + (ecss-compute-style schemas subject :rules rules) + 'app/color) + "snapshot")) + (should-error + (ecss-compute-style + schemas subject :stylesheet stylesheet :rules rules) + :type 'ecss-invalid-rule)))) + +(ert-deftest ecss-cascade-test-rule-snapshot-is-revalidated () + (let ((schemas (ecss-cascade-test--schemas)) + (stylesheet (ecss-stylesheet-create)) + (subject (ecss-cascade-test--subject :classes '("target")))) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" '(app/color "snapshot")) + (let ((rules (ecss-stylesheet-rules stylesheet))) + (setf (ecss-rule-declarations (car rules)) '(foreign/value 1)) + (should-error (ecss-compute-style schemas subject :rules rules) + :type 'ecss-invalid-declaration)))) + +(ert-deftest ecss-cascade-test-authoring-getters-are-defensive () + (let ((schemas (ecss-cascade-test--schemas)) + (stylesheet (ecss-stylesheet-create))) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" '(app/color "blue") :layer '(theme base)) + (let ((schema (ecss-schema-set-property schemas 'app/color)) + (rules (ecss-stylesheet-rules stylesheet)) + (layers (ecss-stylesheet-layers stylesheet))) + (setf (ecss-property-schema-initial schema) "damaged") + (setf (ecss-rule-declarations (car rules)) '(app/color "damaged")) + (setcar (car layers) 'damaged) + (should (equal (ecss-property-schema-initial + (ecss-schema-set-property schemas 'app/color)) + "black")) + (should (equal (ecss-rule-declarations + (car (ecss-stylesheet-rules stylesheet))) + '(app/color "blue"))) + (should (equal (ecss-stylesheet-layers stylesheet) + '((theme base))))))) + +(ert-deftest ecss-cascade-test-provenance-is-deterministic-and-defensive () + (let ((schemas (ecss-cascade-test--schemas)) + (stylesheet (ecss-stylesheet-create)) + (subject (ecss-cascade-test--subject :classes '("target")))) + (ecss-stylesheet-add-rule + stylesheet schemas ".target" '(--z 3 --a 1 app/color "blue")) + (let* ((first (ecss-compute-style + schemas subject :stylesheet stylesheet :provenance t)) + (second (ecss-compute-style + schemas subject :stylesheet stylesheet :provenance t)) + (values (ecss-computed-style-values first)) + (facts (ecss-computed-style-provenance first))) + (should (equal (ecss-computed-style-values first) + (ecss-computed-style-values second))) + (should (equal facts (ecss-computed-style-provenance second))) + (setcar values :damaged) + (setcar facts :damaged) + (should (equal (ecss-cascade-test--value first 'app/color) "blue")) + (should-not (eq (car (ecss-computed-style-provenance first)) + :damaged))))) + +(ert-deftest ecss-cascade-test-computation-never-mutates-a-buffer () + (let ((schemas (ecss-cascade-test--schemas)) + (subject (ecss-cascade-test--subject))) + (with-temp-buffer + (insert "sentinel") + (let ((before (buffer-string))) + (cl-letf (((symbol-function 'insert) + (lambda (&rest _args) (error "buffer write"))) + ((symbol-function 'delete-region) + (lambda (&rest _args) (error "buffer write"))) + ((symbol-function 'add-text-properties) + (lambda (&rest _args) (error "buffer write"))) + ((symbol-function 'put-text-property) + (lambda (&rest _args) (error "buffer write"))) + ((symbol-function 'erase-buffer) + (lambda (&rest _args) (error "buffer write"))) + ((symbol-function 'set-text-properties) + (lambda (&rest _args) (error "buffer write"))) + ((symbol-function 'remove-text-properties) + (lambda (&rest _args) (error "buffer write")))) + (should (ecss-computed-style-p + (ecss-compute-style + schemas subject :declarations '(app/color "blue"))))) + (should (equal (buffer-string) before)))))) + +(provide 'ecss-cascade-tests) +;;; ecss-cascade-tests.el ends here diff --git a/tests/ecss-package-tests.el b/tests/ecss-package-tests.el new file mode 100644 index 0000000..0b82db7 --- /dev/null +++ b/tests/ecss-package-tests.el @@ -0,0 +1,70 @@ +;;; ecss-package-tests.el --- Package boundary tests -*- lexical-binding: t; -*- + +;; Copyright (C) 2026 Geekinney +;; SPDX-License-Identifier: GPL-3.0-or-later + +;;; Code: + +(require 'ert) +(require 'package) +(require 'ecss) + +(defconst ecss-package-test--root + (file-name-directory + (directory-file-name + (file-name-directory (or load-file-name buffer-file-name)))) + "Absolute ecss repository root used by package tests.") + +(defun ecss-package-test--source (file) + "Return FILE contents below the repository root." + (with-temp-buffer + (insert-file-contents (expand-file-name file ecss-package-test--root)) + (buffer-string))) + +(ert-deftest ecss-package-test-facade-loads-public-features-only () + (should (featurep 'ecss)) + (should (featurep 'ecss-selector)) + (should (featurep 'ecss-cascade)) + (should-not (featurep 'tp)) + (should-not (featurep 'ebox))) + +(ert-deftest ecss-package-test-production-has-no-tp-or-ebox-dependency () + (dolist (file '("ecss.el" "ecss-selector.el" "ecss-cascade.el")) + (let ((source (ecss-package-test--source file))) + (should-not (string-match-p "(require[ \t\n]+['\"]tp" source)) + (should-not (string-match-p "(require[ \t\n]+['\"]ebox" source)) + (should-not (string-match-p "\\_ button#save.primary:hover > span.label" label)) + (should (ecss-selector-match-p "div .label" label)) + (should (ecss-selector-match-p "button + button#cancel" cancel)) + (should (ecss-selector-match-p "button ~ button#cancel" cancel)) + (should-not (ecss-selector-match-p "button#cancel" button)))) + +(ert-deftest ecss-selector-test-attribute-operators-and-flags () + (pcase-let ((`(,_root ,button ,_cancel ,label) + (ecss-selector-test--tree))) + (should (ecss-selector-match-p "[data-kind]" button)) + (should (ecss-selector-match-p "[data-kind=commit]" button)) + (should (ecss-selector-match-p "[data-tags~=safe]" button)) + (should (ecss-selector-match-p "[lang|=en]" label)) + (should (ecss-selector-match-p "[data-kind^=com]" button)) + (should (ecss-selector-match-p "[data-kind$=MIT i]" button)) + (should-not (ecss-selector-match-p "[data-kind$=MIT s]" button)) + (should (ecss-selector-match-p "[data-kind*=omm]" button)) + (should-not (ecss-selector-match-p "[data-kind=other]" button)))) + +(ert-deftest ecss-selector-test-functional-pseudos-and-specificity () + (pcase-let ((`(,root ,button ,_cancel ,_label) + (ecss-selector-test--tree))) + (should (ecss-selector-match-p "button:is(.primary, #other)" button)) + (should (ecss-selector-match-p "button:not(.disabled)" button)) + (should (ecss-selector-match-p "div:has(span.label)" root)) + (should (equal (ecss-selector-specificity + "button:is(.primary, #other)") + '(1 0 1))) + (should (equal (ecss-selector-specificity + "button:where(.primary, #other)") + '(0 0 1))))) + +(ert-deftest ecss-selector-test-has-supports-relative-combinators () + (let* ((direct (ecss-subject-create :type "button" :classes '("direct"))) + (nested (ecss-subject-create :type "span" :classes '("nested"))) + (wrapper (ecss-subject-create :type "section" :children (list nested))) + (root (ecss-subject-create + :type "div" :children (list direct wrapper))) + (adjacent (ecss-subject-create :type "button" :id "adjacent")) + (later (ecss-subject-create :type "button" :id "later")) + (_siblings (ecss-subject-create + :type "row" :children (list root adjacent later)))) + (should (ecss-selector-match-p "div:has(> button.direct)" root)) + (should (ecss-selector-match-p "div:has(> section .nested)" root)) + (should (ecss-selector-match-p "div:has(+ button#adjacent)" root)) + (should (ecss-selector-match-p "div:has(~ button#later)" root)) + (should-not (ecss-selector-match-p "div:has(> span.nested)" root)))) + +(ert-deftest ecss-selector-test-selector-lists-use-matching-branches () + (pcase-let ((`(,_root ,button ,_cancel ,_label) + (ecss-selector-test--tree))) + (let ((selector (ecss-selector-parse "#other, .primary"))) + (should (ecss-selector-match-p selector button)) + (should (equal (ecss--selector-matched-specificity + selector button ecss-default-subject-adapter) + '(0 1 0)))))) + +(ert-deftest ecss-selector-test-structured-tokens-use-value-equality () + (let ((subject (ecss-subject-create + :type (copy-sequence "button") + :classes (list (copy-sequence "primary")) + :states (list (copy-sequence "focus"))))) + (should (ecss-selector-match-p '(:type "button") subject)) + (should (ecss-selector-match-p '(:class "primary") subject)) + (should (ecss-selector-match-p '(:state "focus") subject)))) + +(ert-deftest ecss-selector-test-caller-owned-subject-adapter () + (let* ((root (vector "panel" "root" '("app") nil nil nil nil)) + (child (vector "button" "save" '("primary") + '(("role" . "submit")) '("active") root nil)) + (adapter + (ecss-subject-adapter-create + :type (lambda (node) (aref node 0)) + :id (lambda (node) (aref node 1)) + :classes (lambda (node) (aref node 2)) + :attributes (lambda (node) (aref node 3)) + :states (lambda (node) (aref node 4)) + :parent (lambda (node) (aref node 5)) + :children (lambda (node) (aref node 6))))) + (aset root 6 (list child)) + (should (ecss-selector-match-p + "panel.app > button#save[role=submit]:active" child adapter)) + (should (ecss-selector-match-p + "panel:has(button.primary)" root adapter)))) + +(ert-deftest ecss-selector-test-invalid-input-is-rejected () + (should-error (ecss-selector-parse "") :type 'ecss-invalid-selector) + (should-error (ecss-selector-parse "div >") :type 'ecss-invalid-selector) + (should-error (ecss-selector-parse "[name=value q]") + :type 'ecss-invalid-selector) + (should-error (ecss-selector-normalize '(:unknown value)) + :type 'ecss-invalid-selector)) + +(ert-deftest ecss-selector-test-comments-escapes-and-quoted-attributes () + (let ((subject (ecss-subject-create + :type "div" :classes '("card" "a:b") + :attributes '(("title" . "Save now"))))) + (should (ecss-selector-match-p "div/* comment */.card" subject)) + (should (ecss-selector-match-p ".a\\:b" subject)) + (should (ecss-selector-match-p "[title=\"Save now\"]" subject)))) + +(ert-deftest ecss-selector-test-subject-reparenting-detaches-old-parent () + (let* ((child (ecss-subject-create :type "button")) + (old-parent (ecss-subject-create + :type "old" :children (list child))) + (new-parent (ecss-subject-create :type "new"))) + (ecss-subject-set-children new-parent (list child)) + (should (eq (ecss-subject-parent child) new-parent)) + (should-not (memq child (ecss-subject-children old-parent))) + (should (memq child (ecss-subject-children new-parent))))) + +(ert-deftest ecss-selector-test-subject-parent-construction-is-bidirectional () + (let* ((parent (ecss-subject-create :type "panel")) + (child (ecss-subject-create :type "button" :parent parent))) + (should (eq (ecss-subject-parent child) parent)) + (should (equal (ecss-subject-children parent) (list child))) + (should (ecss-selector-match-p "panel:has(> button)" parent)))) + +(provide 'ecss-selector-tests) +;;; ecss-selector-tests.el ends here