packages feed

webcolor-labels (empty) → 0.1.0.0

raw patch · 6 files changed

+1099/−0 lines, 6 filesdep +basedep +tastydep +tasty-hunit

Dependencies added: base, tasty, tasty-hunit, webcolor-labels

Files

+ CHANGELOG.md view
@@ -0,0 +1,5 @@+# Revision history for webcolor-labels++## 0.1.0.0 -- 2025-09-20++* First version. Released on an unsuspecting world.
+ LICENSE view
@@ -0,0 +1,373 @@+Mozilla Public License Version 2.0+==================================++1. Definitions+--------------++1.1. "Contributor"+    means each individual or legal entity that creates, contributes to+    the creation of, or owns Covered Software.++1.2. "Contributor Version"+    means the combination of the Contributions of others (if any) used+    by a Contributor and that particular Contributor's Contribution.++1.3. "Contribution"+    means Covered Software of a particular Contributor.++1.4. "Covered Software"+    means Source Code Form to which the initial Contributor has attached+    the notice in Exhibit A, the Executable Form of such Source Code+    Form, and Modifications of such Source Code Form, in each case+    including portions thereof.++1.5. "Incompatible With Secondary Licenses"+    means++    (a) that the initial Contributor has attached the notice described+        in Exhibit B to the Covered Software; or++    (b) that the Covered Software was made available under the terms of+        version 1.1 or earlier of the License, but not also under the+        terms of a Secondary License.++1.6. "Executable Form"+    means any form of the work other than Source Code Form.++1.7. "Larger Work"+    means a work that combines Covered Software with other material, in+    a separate file or files, that is not Covered Software.++1.8. "License"+    means this document.++1.9. "Licensable"+    means having the right to grant, to the maximum extent possible,+    whether at the time of the initial grant or subsequently, any and+    all of the rights conveyed by this License.++1.10. "Modifications"+    means any of the following:++    (a) any file in Source Code Form that results from an addition to,+        deletion from, or modification of the contents of Covered+        Software; or++    (b) any new file in Source Code Form that contains any Covered+        Software.++1.11. "Patent Claims" of a Contributor+    means any patent claim(s), including without limitation, method,+    process, and apparatus claims, in any patent Licensable by such+    Contributor that would be infringed, but for the grant of the+    License, by the making, using, selling, offering for sale, having+    made, import, or transfer of either its Contributions or its+    Contributor Version.++1.12. "Secondary License"+    means either the GNU General Public License, Version 2.0, the GNU+    Lesser General Public License, Version 2.1, the GNU Affero General+    Public License, Version 3.0, or any later versions of those+    licenses.++1.13. "Source Code Form"+    means the form of the work preferred for making modifications.++1.14. "You" (or "Your")+    means an individual or a legal entity exercising rights under this+    License. For legal entities, "You" includes any entity that+    controls, is controlled by, or is under common control with You. For+    purposes of this definition, "control" means (a) the power, direct+    or indirect, to cause the direction or management of such entity,+    whether by contract or otherwise, or (b) ownership of more than+    fifty percent (50%) of the outstanding shares or beneficial+    ownership of such entity.++2. License Grants and Conditions+--------------------------------++2.1. Grants++Each Contributor hereby grants You a world-wide, royalty-free,+non-exclusive license:++(a) under intellectual property rights (other than patent or trademark)+    Licensable by such Contributor to use, reproduce, make available,+    modify, display, perform, distribute, and otherwise exploit its+    Contributions, either on an unmodified basis, with Modifications, or+    as part of a Larger Work; and++(b) under Patent Claims of such Contributor to make, use, sell, offer+    for sale, have made, import, and otherwise transfer either its+    Contributions or its Contributor Version.++2.2. Effective Date++The licenses granted in Section 2.1 with respect to any Contribution+become effective for each Contribution on the date the Contributor first+distributes such Contribution.++2.3. Limitations on Grant Scope++The licenses granted in this Section 2 are the only rights granted under+this License. No additional rights or licenses will be implied from the+distribution or licensing of Covered Software under this License.+Notwithstanding Section 2.1(b) above, no patent license is granted by a+Contributor:++(a) for any code that a Contributor has removed from Covered Software;+    or++(b) for infringements caused by: (i) Your and any other third party's+    modifications of Covered Software, or (ii) the combination of its+    Contributions with other software (except as part of its Contributor+    Version); or++(c) under Patent Claims infringed by Covered Software in the absence of+    its Contributions.++This License does not grant any rights in the trademarks, service marks,+or logos of any Contributor (except as may be necessary to comply with+the notice requirements in Section 3.4).++2.4. Subsequent Licenses++No Contributor makes additional grants as a result of Your choice to+distribute the Covered Software under a subsequent version of this+License (see Section 10.2) or under the terms of a Secondary License (if+permitted under the terms of Section 3.3).++2.5. Representation++Each Contributor represents that the Contributor believes its+Contributions are its original creation(s) or it has sufficient rights+to grant the rights to its Contributions conveyed by this License.++2.6. Fair Use++This License is not intended to limit any rights You have under+applicable copyright doctrines of fair use, fair dealing, or other+equivalents.++2.7. Conditions++Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted+in Section 2.1.++3. Responsibilities+-------------------++3.1. Distribution of Source Form++All distribution of Covered Software in Source Code Form, including any+Modifications that You create or to which You contribute, must be under+the terms of this License. You must inform recipients that the Source+Code Form of the Covered Software is governed by the terms of this+License, and how they can obtain a copy of this License. You may not+attempt to alter or restrict the recipients' rights in the Source Code+Form.++3.2. Distribution of Executable Form++If You distribute Covered Software in Executable Form then:++(a) such Covered Software must also be made available in Source Code+    Form, as described in Section 3.1, and You must inform recipients of+    the Executable Form how they can obtain a copy of such Source Code+    Form by reasonable means in a timely manner, at a charge no more+    than the cost of distribution to the recipient; and++(b) You may distribute such Executable Form under the terms of this+    License, or sublicense it under different terms, provided that the+    license for the Executable Form does not attempt to limit or alter+    the recipients' rights in the Source Code Form under this License.++3.3. Distribution of a Larger Work++You may create and distribute a Larger Work under terms of Your choice,+provided that You also comply with the requirements of this License for+the Covered Software. If the Larger Work is a combination of Covered+Software with a work governed by one or more Secondary Licenses, and the+Covered Software is not Incompatible With Secondary Licenses, this+License permits You to additionally distribute such Covered Software+under the terms of such Secondary License(s), so that the recipient of+the Larger Work may, at their option, further distribute the Covered+Software under the terms of either this License or such Secondary+License(s).++3.4. Notices++You may not remove or alter the substance of any license notices+(including copyright notices, patent notices, disclaimers of warranty,+or limitations of liability) contained within the Source Code Form of+the Covered Software, except that You may alter any license notices to+the extent required to remedy known factual inaccuracies.++3.5. Application of Additional Terms++You may choose to offer, and to charge a fee for, warranty, support,+indemnity or liability obligations to one or more recipients of Covered+Software. However, You may do so only on Your own behalf, and not on+behalf of any Contributor. You must make it absolutely clear that any+such warranty, support, indemnity, or liability obligation is offered by+You alone, and You hereby agree to indemnify every Contributor for any+liability incurred by such Contributor as a result of warranty, support,+indemnity or liability terms You offer. You may include additional+disclaimers of warranty and limitations of liability specific to any+jurisdiction.++4. Inability to Comply Due to Statute or Regulation+---------------------------------------------------++If it is impossible for You to comply with any of the terms of this+License with respect to some or all of the Covered Software due to+statute, judicial order, or regulation then You must: (a) comply with+the terms of this License to the maximum extent possible; and (b)+describe the limitations and the code they affect. Such description must+be placed in a text file included with all distributions of the Covered+Software under this License. Except to the extent prohibited by statute+or regulation, such description must be sufficiently detailed for a+recipient of ordinary skill to be able to understand it.++5. Termination+--------------++5.1. The rights granted under this License will terminate automatically+if You fail to comply with any of its terms. However, if You become+compliant, then the rights granted under this License from a particular+Contributor are reinstated (a) provisionally, unless and until such+Contributor explicitly and finally terminates Your grants, and (b) on an+ongoing basis, if such Contributor fails to notify You of the+non-compliance by some reasonable means prior to 60 days after You have+come back into compliance. Moreover, Your grants from a particular+Contributor are reinstated on an ongoing basis if such Contributor+notifies You of the non-compliance by some reasonable means, this is the+first time You have received notice of non-compliance with this License+from such Contributor, and You become compliant prior to 30 days after+Your receipt of the notice.++5.2. If You initiate litigation against any entity by asserting a patent+infringement claim (excluding declaratory judgment actions,+counter-claims, and cross-claims) alleging that a Contributor Version+directly or indirectly infringes any patent, then the rights granted to+You by any and all Contributors for the Covered Software under Section+2.1 of this License shall terminate.++5.3. In the event of termination under Sections 5.1 or 5.2 above, all+end user license agreements (excluding distributors and resellers) which+have been validly granted by You or Your distributors under this License+prior to termination shall survive termination.++************************************************************************+*                                                                      *+*  6. Disclaimer of Warranty                                           *+*  -------------------------                                           *+*                                                                      *+*  Covered Software is provided under this License on an "as is"       *+*  basis, without warranty of any kind, either expressed, implied, or  *+*  statutory, including, without limitation, warranties that the       *+*  Covered Software is free of defects, merchantable, fit for a        *+*  particular purpose or non-infringing. The entire risk as to the     *+*  quality and performance of the Covered Software is with You.        *+*  Should any Covered Software prove defective in any respect, You     *+*  (not any Contributor) assume the cost of any necessary servicing,   *+*  repair, or correction. This disclaimer of warranty constitutes an   *+*  essential part of this License. No use of any Covered Software is   *+*  authorized under this License except under this disclaimer.         *+*                                                                      *+************************************************************************++************************************************************************+*                                                                      *+*  7. Limitation of Liability                                          *+*  --------------------------                                          *+*                                                                      *+*  Under no circumstances and under no legal theory, whether tort      *+*  (including negligence), contract, or otherwise, shall any           *+*  Contributor, or anyone who distributes Covered Software as          *+*  permitted above, be liable to You for any direct, indirect,         *+*  special, incidental, or consequential damages of any character      *+*  including, without limitation, damages for lost profits, loss of    *+*  goodwill, work stoppage, computer failure or malfunction, or any    *+*  and all other commercial damages or losses, even if such party      *+*  shall have been informed of the possibility of such damages. This   *+*  limitation of liability shall not apply to liability for death or   *+*  personal injury resulting from such party's negligence to the       *+*  extent applicable law prohibits such limitation. Some               *+*  jurisdictions do not allow the exclusion or limitation of           *+*  incidental or consequential damages, so this exclusion and          *+*  limitation may not apply to You.                                    *+*                                                                      *+************************************************************************++8. Litigation+-------------++Any litigation relating to this License may be brought only in the+courts of a jurisdiction where the defendant maintains its principal+place of business and such litigation shall be governed by laws of that+jurisdiction, without reference to its conflict-of-law provisions.+Nothing in this Section shall prevent a party's ability to bring+cross-claims or counter-claims.++9. Miscellaneous+----------------++This License represents the complete agreement concerning the subject+matter hereof. If any provision of this License is held to be+unenforceable, such provision shall be reformed only to the extent+necessary to make it enforceable. Any law or regulation which provides+that the language of a contract shall be construed against the drafter+shall not be used to construe this License against a Contributor.++10. Versions of the License+---------------------------++10.1. New Versions++Mozilla Foundation is the license steward. Except as provided in Section+10.3, no one other than the license steward has the right to modify or+publish new versions of this License. Each version will be given a+distinguishing version number.++10.2. Effect of New Versions++You may distribute the Covered Software under the terms of the version+of the License under which You originally received the Covered Software,+or under the terms of any subsequent version published by the license+steward.++10.3. Modified Versions++If you create software not governed by this License, and you want to+create a new license for such software, you may create and use a+modified version of this License if you rename the license and remove+any references to the name of the license steward (except to note that+such modified license differs from this License).++10.4. Distributing Source Code Form that is Incompatible With Secondary+Licenses++If You choose to distribute Source Code Form that is Incompatible With+Secondary Licenses under the terms of this version of the License, the+notice described in Exhibit B of this License must be attached.++Exhibit A - Source Code Form License Notice+-------------------------------------------++  This Source Code Form is subject to the terms of the Mozilla Public+  License, v. 2.0. If a copy of the MPL was not distributed with this+  file, You can obtain one at http://mozilla.org/MPL/2.0/.++If it is not possible or desirable to put the notice in a particular+file, then You may include the notice in a location (such as a LICENSE+file in a relevant directory) where a recipient would be likely to look+for such a notice.++You may add additional accurate notices of copyright ownership.++Exhibit B - "Incompatible With Secondary Licenses" Notice+---------------------------------------------------------++  This Source Code Form is "Incompatible With Secondary Licenses", as+  defined by the Mozilla Public License, v. 2.0.
+ README.md view
@@ -0,0 +1,95 @@+# webcolor-labels++Zero-dependency, plug-and-play library that enables #hex-color syntax for your own types!++![Demo image](https://raw.githubusercontent.com/haskell-game/webcolor-labels/refs/heads/master/images/demo.png)++## Motivation++[Unrestricted OverloadedLabels syntax](https://github.com/ghc-proposals/ghc-proposals/blob/master/proposals/0170-unrestricted-overloadedlabels.rst) was implemented in GHC 9.6.1. It isn't hard to notice+that this syntax is a strict superset of hexadecimal CSS color syntax, a.k.a. [Web colors](https://en.wikipedia.org/wiki/Web_colors). It would be great if GUI libraries could take advantage of this+fact and allow their users to write `#f00` for the color "red," or even `#red`, right?++That's where `webcolor-labels` comes into play. This library implements type-level string parsing and validation+and provides you an easy-to-use interface for defining an `IsLabel` instance. In fact, it's as easy as counting+one, two, three:++```haskell+-- one+import WebColor.Labels+import GHC.OverloadedLabels++-- two+instance IsWebColorAlpha s => IsLabel s YourColor where+  fromLabel = webColorAlpha @s yourColorFromWord8++-- three+yourColorFromWord8 :: Word8 -> Word8 -> Word8 -> Word8 -> YourColor+yourColorFromWord8 red green blue alpha = ...+```++And that's all!++## Syntax++Allowed colors aim to follow the [Wikipedia Web Colors](https://en.wikipedia.org/wiki/Web_colors) page; here is a quick recap:++A color is written as a hex triplet, which is a six-digit (e.g., #fa12c7) or eight-digit (e.g., #fa12c7aa) hexadecimal number. The bytes represent the red, green, blue, and optional alpha channels of the color; hence we have #rrggbbaa.++It is possible to use the shorthand form with three and four digits: #f8c = #ff88cc and #f8c3 = #ff88cc33.++The syntax also supports 16 basic colors for convenience:++| Color name | Hex value |+| :--------- | :-------: |+| #white     | #FFFFFF |+| #silver    | #C0C0C0 |+| #gray      | #808080 |+| #black     | #000000 |+| #red       | #FF0000 |+| #maroon    | #800000 |+| #yellow    | #FFFF00 |+| #olive     | #808000 |+| #lime      | #00FF00 |+| #green     | #008000 |+| #aqua      | #00FFFF |+| #teal      | #008080 |+| #blue      | #0000FF |+| #navy      | #000080 |+| #fuchsia   | #FF00FF |+| #purple    | #800080 |++Hex triplet form is case-insensitive; therefore, #fff is the same as #FFF, but basic colors are case-sensitive.+That means #red is the same as #f00, but #RED and #Red result in a compile-time error.++## FAQ++### I want to use this syntax with _$LIBRARYNAME_, what should I do?++`webcolor-label`'s primary users are other library authors; therefore, you should go to the _$LIBRARYNAME_'s issue tracker and tell them that `webcolor-labels` will improve the lives of their users.++Alternatively, you may write an orphan instance, but it's a bad idea in general and you should avoid that as much as possible.++### `generic-lens` uses the same syntax. Does that mean it will conflict with an instance defined using `webcolor-labels`?++No, unless you define a highly polymorphic `IsLabel` instance or your color is a type alias for a function.++The `generic-lens` instance applies only if a function is expected in place of `#label`. Therefore, define instances with a concrete head, and everything will work smoothly.++### But what about instances for the color types from different libraries? Might they conflict?++No, if each instance is defined correctly.++### I have a type class to represent colors. How can I use `#` syntax with a function that accepts my type class?++Unfortunately, my library just doesn't fit this use case. It's the same problem as `show . read`; GHC just can't infer a type in the middle.++### I want to use different/custom values for named colors, but `webcolor-labels` provides pre-installed values. What should I do in that case?++You can still use type-level parsing from `webcolor-labels` and build custom routing on top of that, but you have to lower that into values yourself.++## Contact info and acknowledgements++If you have any questions, you can email me using `me@sandwitch.dev`. Alternatively, you can DM me on Matrix (`@root:sandwitch.dev`) or Telegram (`@sand_witch`).++Many thanks to the Russian Haskell gamedev community, who encouraged me to convert this code into a real library and assisted with shaping the API.
+ src/WebColor/Labels.hs view
@@ -0,0 +1,466 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE NoStarIsType #-}+{-# LANGUAGE UndecidableInstances #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE CPP #-}+{-# LANGUAGE AllowAmbiguousTypes #-}++-- We need this to have correct links inside haddocks+{-# OPTIONS_GHC -Wno-unused-imports #-}++-- Required to use `showType` inside haddock coments+{-# OPTIONS_GHC -Wno-unused-top-binds #-}++{- |+= Introduction and intended usage++This library contains a small number of helpers that primarily aim+to help users construct `IsLabel` instances to use @-XOverloadedLabels@+syntax to construct their color types using widely known web color syntax.++There are two ways to use this API:++1. Simple type-class-based API++2. Advanced manual type-family-based API++You should always prefer the simple API.++== Simple API++You should use the simple API to write an `IsLabel` instance for your own+type representing a color.++Depending on whether your type supports representing the alpha channel, you should+choose between `IsWebColor` and `IsWebColorAlpha` type classes.++Therefore, it's likely that you want to write an instance that looks like this:++@+data RGBA = MkRGBA { red :: `Word8`, green :: `Word8`, blue :: `Word8`, alpha :: `Word8` }++instance `IsWebColorAlpha` s => `IsLabel` s RGBA where+  `fromLabel` = `webColorAlpha` @s \r g b a ->+      MkRGBA { red = r, green = g, blue = b, alpha = a }+@++Or this in case your type doesn't have an alpha channel:++@+data RGB = MkRGB { red :: `Word8`, green :: `Word8`, blue :: `Word8` }++instance `IsWebColor` s => `IsLabel` s RGB where+  `fromLabel` = `webColor` @s \r g b ->+      MkRGB { red = r, green = g, blue = b }+@++Please do not try to use `IsWebColor` if your type can represent either+RGB or RGBA colors; use `IsWebColorAlpha` and alternate data construction+depending on the value of the alpha channel:++@+data Color+  = MkRGB { red :: `Word8`, green :: `Word8`, blue :: `Word8` }+  | MkRGBA { red :: `Word8`, green :: `Word8`, blue :: `Word8`, alpha :: `Word8` }++instance `IsWebColorAlpha` s => `IsLabel` s RGBA where+  `fromLabel` = `webColorAlpha` @s \r g b a ->+      if a `==` 255+        then MkRGB { red = r, green = g, blue = b }+        else MkRGBA { red = r, green = g, blue = b, alpha = a }+@++== Advanced API++It's always recommended to use the simple API unless you want to drop+named colors for some reason or want to work with raw `KnownNat`s.++There are four main type families:++* `ParseWebColor`+* `ParseWebColorAlpha`+* `ParseWebColorMaybeAlpha`+* `ParseHexadecimalColor`++The first two correspond to the output of `IsWebColor` and `IsWebColorAlpha` type+classes listed in the previous section.++`ParseWebColorMaybeAlpha` allows you to alternate behavior between presence and+absence of the alpha channel in the input. Please let me know if you have a use case+for this and why you can't simply consider 255 alpha as an RGB color.++`ParseHexadecimalColor` converts hexadecimal strings of length 3, 4, 6, and 8 into+correct color channels but doesn't accept named colors.++In general, you give a parsing function a symbol argument and match results using the equality+operator:++@+f :: `ParseWebColorAlpha` s ~ '(r,g,b,a) => ...+@++After that, you can set various constraints on the results. For example, this is how you can+convert given values into a 32-bit number without any runtime computations:++@+{-# LANGUAGE DataKinds, NoStarIsType, AllowAmbiguousTypes #-}++f ::  forall s r g b a w32.+      `ParseWebColorAlpha` s ~ '(r,g,b,a) =>+      ((r * 0x100 + g) * 0x100 + b) * 0x100 + a ~ w32 =>+      `KnownNat` w32 => `Word32`+f = `fromInteger` `$` `natVal` (`Proxy` @w32)+@++== To advanced end users++If you're an advanced Haskell user. If you think that rules are just "recommendations."+If you're ready to face possible breakages just for slight usability improvements.+Then I present you a footgun.++It is possible to write orphan instances for `IsWebColor` and `IsWebColorAlpha` type classes+to extend #-syntax with custom named colors, just like this:++@+instance `IsWebColor` "gold" where+  `webColor` k = k 255 215 0++instance `IsWebColorAlpha` "gold" where+  `webColorAlpha` k = k 255 215 0 255+@++I'm not going to guarantee you anything. Enjoy!+-}++module WebColor.Labels+  ( -- * Primary API+    IsWebColor(..),+    IsWebColorAlpha(..),+    -- * Advanced type-level API+    WebColor,+    WebColorAlpha,+    ParseWebColor,+    ParseWebColorAlpha,+    WebColorParsed,+    ParseWebColorMaybeAlpha,+    ParseHexadecimalColor,+    -- * Utility type families+    --+    -- | These type families aren't required to use+    -- the library, but may be useful for defining your+    -- own parse routing on top of web colors+    ParseHexadecimalChar,+  ) where++import Data.Proxy (Proxy (..))+#if __GLASGOW_HASKELL__ >= 906+import Data.Type.Equality (type (~))+#endif+import Data.Word (Word8, Word32)+import GHC.TypeLits+  (ErrorMessage (..), KnownNat, Nat, Symbol, TypeError, UnconsSymbol, natVal, type (*), type (+))+import Prelude (Char, Maybe (..), fromInteger, ($!), ($), (==))+import Data.Kind (Constraint)++-- Imports for haddocks+import GHC.OverloadedLabels (IsLabel(..))++#if __GLASGOW_HASKELL__ >= 908+import GHC.TypeError (Unsatisfiable)++showType :: forall a. (Unsatisfiable (ShowType a)) => ()+showType = ()+#endif++-- | Red, green, blue, and optional alpha color channels in range from 0 to 255+type WebColorParsed = (Nat, Nat, Nat, Maybe Nat)++-- | Parse a string containing a named color from a basic+-- palette or hexadecimal representation with an optional+-- alpha channel.+--+-- * Named colors are always considered RGB-only:+--+-- >>> showType @(`ParseWebColorMaybeAlpha` "red")+-- '(255, 0, 0, 'Nothing)+--+-- >>> showType @(`ParseWebColorMaybeAlpha` "silver")+-- '(192, 192, 192, 'Nothing)+--+-- `ParseWebColorMaybeAlpha` inherits many properties from `ParseHexadecimalColor`:+--+-- * The difference between a `Nothing` alpha channel and @`Just` 255@+--   is purely syntactical, and you have to tackle the difference yourself+-- * This family automatically handles shortened syntax+-- * This family throws a compile-time error when the wrong number+--   of hex characters is supplied+--+-- Please refer to `ParseHexadecimalColor` for the examples.+type ParseWebColorMaybeAlpha :: Symbol -> WebColorParsed+type family ParseWebColorMaybeAlpha s where+  ParseWebColorMaybeAlpha "white"   = '(255, 255, 255, Nothing)+  ParseWebColorMaybeAlpha "silver"  = '(192, 192, 192, Nothing)+  ParseWebColorMaybeAlpha "gray"    = '(128, 128, 128, Nothing)+  ParseWebColorMaybeAlpha "black"   = '(0,   0,   0,   Nothing)+  ParseWebColorMaybeAlpha "red"     = '(255, 0,   0,   Nothing)+  ParseWebColorMaybeAlpha "maroon"  = '(128, 0,   0,   Nothing)+  ParseWebColorMaybeAlpha "yellow"  = '(255, 255, 0,   Nothing)+  ParseWebColorMaybeAlpha "olive"   = '(128, 128, 0,   Nothing)+  ParseWebColorMaybeAlpha "lime"    = '(0,   255, 0,   Nothing)+  ParseWebColorMaybeAlpha "green"   = '(0,   128, 0,   Nothing)+  ParseWebColorMaybeAlpha "aqua"    = '(0,   255, 255, Nothing)+  ParseWebColorMaybeAlpha "teal"    = '(0,   128, 128, Nothing)+  ParseWebColorMaybeAlpha "blue"    = '(0,   0,   255, Nothing)+  ParseWebColorMaybeAlpha "navy"    = '(0,   0,   128, Nothing)+  ParseWebColorMaybeAlpha "fuchsia" = '(255, 0,   255, Nothing)+  ParseWebColorMaybeAlpha "purple"  = '(128, 0,   128, Nothing)+  ParseWebColorMaybeAlpha s = ParseHexadecimalColor s++-- | Parse a string containing hexadecimal representation of a+-- color with an optional alpha channel.+--+-- * This family doesn't handle named colors.+-- * The difference between a `Nothing` alpha channel and @`Just` 255@+--   is purely syntactical, and you have to tackle the difference yourself:+--+-- >>> showType @(`ParseHexadecimalColor` "fafefb")+-- '(250, 254, 251, 'Nothing)+--+-- >>> showType @(`ParseHexadecimalColor` "fafefbff")+-- '(250, 254, 251, 'Just 255)+--+-- * This family automatically handles shortened syntax:+--+-- E.g. #123 is the same as #112233:+--+-- >>> showType @(`ParseHexadecimalColor` "123")+-- '(17, 34, 51, 'Nothing)+--+-- >>> showType @(`ParseHexadecimalColor` "112233")+-- '(17, 34, 51, 'Nothing)+--+-- The same applies to #1234 and #11223344:+--+-- >>> showType @(`ParseHexadecimalColor` "1234")+-- '(17, 34, 51, 'Just 68)+--+-- >>> showType @(`ParseHexadecimalColor` "11223344")+-- '(17, 34, 51, 'Just 68)+--+-- * This family throws a compile-time error when the wrong number+-- of hex characters is supplied:+--+-- >>> showType @(`ParseHexadecimalColor` "1")+-- Unexpected number of hex codes+-- expected 3, 4, 6 or 8+--+-- >>> showType @(`ParseHexadecimalColor` "1122334455")+-- Unexpected number of hex codes+-- expected 3, 4, 6 or 8+type ParseHexadecimalColor :: Symbol -> WebColorParsed+type family ParseHexadecimalColor s where+  ParseHexadecimalColor s = ParseColorRec '[] (UnconsSymbol s)++type ParseColorRec :: [Nat] -> Maybe (Char, Symbol) -> WebColorParsed+type family ParseColorRec color str where+  ParseColorRec colors Nothing = UpgradeColor colors+  ParseColorRec colors (Just '(ch, t)) = ParseColorRec (ParseHexadecimalChar ch : colors) (UnconsSymbol t)++-- | Red, green, and blue color channels in range from 0 to 255+type WebColor = (Nat, Nat, Nat)++-- | Parse a string containing a named color from a basic+-- palette or hexadecimal representation without an alpha channel.+--+-- * For convenience, a 255 alpha channel is interpreted+--   as a solid color without an alpha channel:+--+-- >>> showType @(`ParseWebColor` "123")+-- '(17, 34, 51)+--+-- >>> showType @(`ParseWebColor` "123f")+-- '(17, 34, 51)+--+-- * Other alpha channel values result in a compile-time error:+--+-- >>> showType @(`ParseWebColor` "123d")+-- Unexpected alpha channel! RGB color expected+--+-- This family inherits many properties from `ParseWebColorMaybeAlpha`:+--+-- * Named colors are always considered RGB-only:+--+-- >>> showType @(`ParseWebColor` "red")+-- '(255, 0, 0)+--+-- * This family automatically handles shortened syntax.+-- * This family throws a compile-time error when the wrong number+--   of hex characters is supplied+type ParseWebColor :: Symbol -> WebColor+type family ParseWebColor s where+  ParseWebColor s = ParseRGBColorWorker (ParseWebColorMaybeAlpha s)++type ParseRGBColorWorker :: WebColorParsed -> WebColor+type family ParseRGBColorWorker color where+  ParseRGBColorWorker '(r, g, b, Nothing)  = '(r, g, b)+  ParseRGBColorWorker '(r, g, b, Just 255) = '(r, g, b)+  ParseRGBColorWorker '(_, _, _, Just _) = TypeError (Text "Unexpected alpha channel! RGB color expected")++-- | Red, green, blue, and alpha color channels in range from 0 to 255+type WebColorAlpha = (Nat, Nat, Nat, Nat)++-- | Parse a string containing a named color from a basic+-- palette or a hexadecimal representation with an optional+-- alpha channel.+--+-- * This family converts an absence of an alpha channel into+--   the 255 value.+--+-- >>> showType @(`ParseWebColorAlpha` "123")+-- '(17, 34, 51, 255)+--+-- This family inherits many properties from `ParseWebColorMaybeAlpha`:+--+-- * Named colors are always considered RGB-only and are handled the same way:+--+-- >>> showType @(`ParseWebColorAlpha` "red")+-- '(255, 0, 0, 255)+--+-- * This family automatically handles shortened syntax.+-- * This family throws a compile-time error when the wrong number+--   of hex characters is supplied+type ParseWebColorAlpha :: Symbol -> WebColorAlpha+type family ParseWebColorAlpha s where+  ParseWebColorAlpha s = ParseRGBAColorWorker (ParseWebColorMaybeAlpha s)++type ParseRGBAColorWorker :: WebColorParsed -> WebColorAlpha+type family ParseRGBAColorWorker color where+  ParseRGBAColorWorker '(r, g, b, Nothing) = '(r, g, b, 0xFF)+  ParseRGBAColorWorker '(r, g, b, Just a)  = '(r, g, b, a)++type a & b = a++-- | Parse a type-level string containing a named color from a basic+-- palette or a hexadecimal representation and convert it into three+-- bytes representing red, green, and blue channels+--+--+-- * For convenience, a 255 alpha channel is interpreted+--   as a solid color without an alpha channel:+--+-- >>> webColor @"123" (,,)+-- (17,34,51)+--+-- >>> webColor @"123f" (,,)+-- (17,34,51)+--+-- * Other alpha channel values result in a compile-time error:+--+-- >>> webColor @"123d" (,,)+-- Unexpected alpha channel! RGB color expected+--+-- * Named colors are always considered RGB-only:+--+-- >>> webColor @"red" (,,)+-- (255,0,0)+type IsWebColor :: Symbol -> Constraint+class IsWebColor s where+  -- | Parse a type-level string and give you bytes representing+  -- red, green, and blue colors.+  --+  -- NB: @&@ is just a type alias that should help to keep with order.+  webColor ::+    (Word8 & "red" -> Word8 & "green" -> Word8 & "blue" -> r) -> r++-- | Hacky instance to avoid a warning from GHC+instance {-# OVERLAPPING #-} IsWebColor "red" where+  webColor k = k 255 0 0++-- | Main instance where all the magic happens+instance {-# OVERLAPPABLE #-}+  ( ParseWebColor s ~ '(r, g, b),+    KnownNat r, KnownNat g, KnownNat b+  ) => IsWebColor s where+  webColor k =+      k `color` Proxy @r `color` Proxy @g `color` Proxy @b++-- | Parse a type-level string containing a named color from a basic+-- palette or a hexadecimal representation and convert it into four+-- bytes representing red, green, blue, and alpha channels+--+--+-- * An absent alpha channel  get converted into the 255 value:+--+-- >>> webColorAlpha @"123" (,,,)+-- (17,34,51,255)+--+-- >>> webColorAlpha @"123f" (,,,)+-- (17,34,51,255)+--+-- * Named colors are always considered RGB-only:+--+-- >>> webColorAlpha @"red" (,,,)+-- (255,0,0,255)+type IsWebColorAlpha :: Symbol -> Constraint+class IsWebColorAlpha s where+  -- | Parse a type-level string and give you bytes representing+  -- red, green, blue, and alpha colors.+  --+  -- NB: @&@ is just a type alias that should help to keep with order.+  webColorAlpha ::+    (Word8 & "red" -> Word8 & "green" -> Word8 & "blue" -> Word8 & "alpha" -> r) -> r++-- | Hacky instance to avoid a warning from GHC+instance {-# OVERLAPPING #-} IsWebColorAlpha "red" where+  webColorAlpha k = k 255 0 0 255++-- | Main instance where all the magic happens+instance {-# OVERLAPPABLE #-}+  ( ParseWebColorAlpha s ~ '(r, g, b, a),+    KnownNat r, KnownNat g, KnownNat b, KnownNat a+  ) => IsWebColorAlpha s where+  webColorAlpha k =+      k `color` Proxy @r `color` Proxy @g `color` Proxy @b `color` Proxy @a++color :: KnownNat n => (Word8 -> r) -> Proxy n -> r+color k p = k $! fromInteger (natVal p)++type UpgradeColor :: [Nat] -> WebColorParsed+type family UpgradeColor nats where+  UpgradeColor [        b,      g,      r     ] = UpgradeColor [      b,  b,  g,  g,  r,  r]+  UpgradeColor [a,      b,      g,      r     ] = UpgradeColor [a, a, b,  b,  g,  g,  r,  r]+  UpgradeColor [        b1, b2, g1, g2, r1, r2] = '(MakeByte r2 r1, MakeByte g2 g1, MakeByte b2 b1, Nothing)+  UpgradeColor [a1, a2, b1, b2, g1, g2, r1, r2] = '(MakeByte r2 r1, MakeByte g2 g1, MakeByte b2 b1, Just (MakeByte a2 a1))+  UpgradeColor _ = TypeError (Text "Unexpected number of hex codes" :$$: Text "expected 3, 4, 6 or 8")++-- | Convert a hexadecimal character (0 .. F) into a corresponging+-- number. Case insensitive.+type ParseHexadecimalChar :: Char -> Nat+type family ParseHexadecimalChar ch where+  ParseHexadecimalChar '0' = 0x0+  ParseHexadecimalChar '1' = 0x1+  ParseHexadecimalChar '2' = 0x2+  ParseHexadecimalChar '3' = 0x3+  ParseHexadecimalChar '4' = 0x4+  ParseHexadecimalChar '5' = 0x5+  ParseHexadecimalChar '6' = 0x6+  ParseHexadecimalChar '7' = 0x7+  ParseHexadecimalChar '8' = 0x8+  ParseHexadecimalChar '9' = 0x9+  ParseHexadecimalChar 'a' = 0xa+  ParseHexadecimalChar 'b' = 0xb+  ParseHexadecimalChar 'c' = 0xc+  ParseHexadecimalChar 'd' = 0xd+  ParseHexadecimalChar 'e' = 0xe+  ParseHexadecimalChar 'f' = 0xf+  ParseHexadecimalChar 'A' = 0xA+  ParseHexadecimalChar 'B' = 0xB+  ParseHexadecimalChar 'C' = 0xC+  ParseHexadecimalChar 'D' = 0xD+  ParseHexadecimalChar 'E' = 0xE+  ParseHexadecimalChar 'F' = 0xF+  ParseHexadecimalChar ch  = TypeError (Text "Unable to recognize a character: " :$$: ShowType ch)++type MakeByte :: Nat -> Nat -> Nat+type family MakeByte x y where+  MakeByte x y = x * 0x10 + y
+ test/Main.hs view
@@ -0,0 +1,92 @@+{-# LANGUAGE OverloadedLabels #-}+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE BlockArguments #-}++{-# OPTIONS_GHC -Wno-orphans #-}++module Main (main) where++import WebColor.Labels+import Data.Word (Word8)+import GHC.OverloadedLabels++import Test.Tasty+import Test.Tasty.HUnit++instance IsWebColor "gold" where+  webColor k = k 255 215 0++instance IsWebColorAlpha "gold" where+  webColorAlpha k = k 255 215 0 255++data RGB = MkRGB Word8 Word8 Word8+  deriving (Show, Eq)++instance IsWebColor s => IsLabel s RGB where+  fromLabel = webColor @s MkRGB++data RGBA = MkRGBA Word8 Word8 Word8 Word8+  deriving (Show, Eq)++instance IsWebColorAlpha s => IsLabel s RGBA where+  fromLabel = webColorAlpha @s MkRGBA++main :: IO ()+main = defaultMain $ testGroup "Tests"+  [ testGroup "Named colors RGB" [+      testCase "white" do #white @?= MkRGB 255 255 255; #FFFFFF @?= MkRGB 255 255 255,+      testCase "silver" do #silver @?= MkRGB 192 192 192; #C0C0C0 @?= MkRGB 192 192 192,+      testCase "gray" do #gray @?= MkRGB 128 128 128; #808080 @?= MkRGB 128 128 128,+      testCase "black" do #black @?= MkRGB 0 0 0; #000000 @?= MkRGB 0 0 0,+      testCase "red" do #red @?= MkRGB 255 0 0; #FF0000 @?= MkRGB 255 0 0,+      testCase "maroon" do #maroon @?= MkRGB 128 0 0; #800000 @?= MkRGB 128 0 0,+      testCase "yellow" do #yellow @?= MkRGB 255 255 0; #FFFF00 @?= MkRGB 255 255 0,+      testCase "olive" do #olive @?= MkRGB 128 128 0; #808000 @?= MkRGB 128 128 0,+      testCase "lime" do #lime @?= MkRGB 0 255 0; #00FF00 @?= MkRGB 0 255 0,+      testCase "green" do #green @?= MkRGB 0 128 0; #008000 @?= MkRGB 0 128 0,+      testCase "aqua" do #aqua @?= MkRGB 0 255 255; #00FFFF @?= MkRGB 0 255 255,+      testCase "teal" do #teal @?= MkRGB 0 128 128; #008080 @?= MkRGB 0 128 128,+      testCase "blue" do #blue @?= MkRGB 0 0 255; #0000FF @?= MkRGB 0 0 255,+      testCase "navy" do #navy @?= MkRGB 0 0 128; #000080 @?= MkRGB 0 0 128,+      testCase "fuchsia" do #fuchsia @?= MkRGB 255 0 255; #FF00FF @?= MkRGB 255 0 255,+      testCase "purple" do #purple @?= MkRGB 128 0 128; #800080 @?= MkRGB 128 0 128+    ]+    , testGroup "Named colors RGBA" [+      testCase "white" do #white @?= MkRGBA 255 255 255 255; #FFFFFF @?= MkRGBA 255 255 255 255,+      testCase "silver" do #silver @?= MkRGBA 192 192 192 255; #C0C0C0 @?= MkRGBA 192 192 192 255,+      testCase "gray" do #gray @?= MkRGBA 128 128 128 255; #808080 @?= MkRGBA 128 128 128 255,+      testCase "black" do #black @?= MkRGBA 0 0 0 255; #000000 @?= MkRGBA 0 0 0 255,+      testCase "red" do #red @?= MkRGBA 255 0 0 255; #FF0000 @?= MkRGBA 255 0 0 255,+      testCase "maroon" do #maroon @?= MkRGBA 128 0 0 255; #800000 @?= MkRGBA 128 0 0 255,+      testCase "yellow" do #yellow @?= MkRGBA 255 255 0 255; #FFFF00 @?= MkRGBA 255 255 0 255,+      testCase "olive" do #olive @?= MkRGBA 128 128 0 255; #808000 @?= MkRGBA 128 128 0 255,+      testCase "lime" do #lime @?= MkRGBA 0 255 0 255; #00FF00 @?= MkRGBA 0 255 0 255,+      testCase "green" do #green @?= MkRGBA 0 128 0 255; #008000 @?= MkRGBA 0 128 0 255,+      testCase "aqua" do #aqua @?= MkRGBA 0 255 255 255; #00FFFF @?= MkRGBA 0 255 255 255,+      testCase "teal" do #teal @?= MkRGBA 0 128 128 255; #008080 @?= MkRGBA 0 128 128 255,+      testCase "blue" do #blue @?= MkRGBA 0 0 255 255; #0000FF @?= MkRGBA 0 0 255 255,+      testCase "navy" do #navy @?= MkRGBA 0 0 128 255; #000080 @?= MkRGBA 0 0 128 255,+      testCase "fuchsia" do #fuchsia @?= MkRGBA 255 0 255 255; #FF00FF @?= MkRGBA 255 0 255 255,+      testCase "purple" do #purple @?= MkRGBA 128 0 128 255; #800080 @?= MkRGBA 128 0 128 255+    ]+  , testGroup "Custom colors" [+      testCase "rgb gold" do #gold @?= MkRGB 255 215 0; #FFD700 @?= MkRGB 255 215 0,+      testCase "rgba gold" do #gold @?= MkRGBA 255 215 0 255; #FFD700 @?= MkRGBA 255 215 0 255+    ]+  , testGroup "hex syntax" [+      testCase "rgb 3 == 6 chars"  $ #fad    `rgb`  #ffaadd,+      testCase "rgb 3 == 8 chars"  $ #fad    `rgb`  #ffaaddff,+      testCase "rgb 4 == 8 chars"  $ #eadf   `rgb`  #eeaaddff,+      testCase "rgb 6 == 8 chars"  $ #fade12 `rgb`  #fade12ff,+      testCase "rgba 3 == 6 chars" $ #fad    `rgba` #ffaadd,+      testCase "rgba 3 == 8 chars" $ #fad    `rgba` #ffaaddff,+      testCase "rgba 4 == 8 chars" $ #fade   `rgba` #ffaaddee,+      testCase "rgba 6 == 8 chars" $ #fade12 `rgba` #fade12ff+    ]+  ]+  where+    rgb :: RGB -> RGB -> Assertion+    rgb = (@?=)++    rgba :: RGBA -> RGBA -> Assertion+    rgba = (@?=)
+ webcolor-labels.cabal view
@@ -0,0 +1,68 @@+cabal-version:   3.0++-- Initial package description 'webcolor-labels' generated by+-- 'cabal init'. For further documentation, see:+--   http://haskell.org/cabal/users-guide/+--+-- The name of the package.+name:            webcolor-labels++-- PVP summary:  +-+------- breaking API changes+--               | | +----- non-breaking API additions+--               | | | +--- code changes with no API change+version:         0.1.0.0++-- A short (one-line) description of the package.+synopsis:        Plug-n-play #hex-syntax for your colors++-- A longer description of the package.+description:+  This library contains a small number of helpers that primarily aim+  to help users construct `IsLabel` instances to use @-XOverloadedLabels@+  syntax to construct their color types using widely known web color syntax.++  Plug this library into your code, enable OverloadedLabels and use+  #fff, #1212bc44, and even #fuchsia to create colors.++license:         MPL-2.0+license-file:    LICENSE+author:          Andrei Borzenkov <me@sandwitch.dev>+maintainer:      me@sandwitch.dev+homepage:        https://github.com/haskell-game/webcolor-labels+bug-reports:     https://github.com/haskell-game/webcolor-labels/issues++-- A copyright notice.+-- copyright:+category:        Graphics+build-type:      Simple+extra-doc-files:+  CHANGELOG.md+  README.md++tested-with:     GHC ==9.8.4 || ==9.10.2 || ==9.12.2++source-repository head+  type:     git+  location: https://github.com/haskell-game/webcolor-labels/++common warnings+  ghc-options: -Wall++library+  import:           warnings+  exposed-modules:  WebColor.Labels+  build-depends:    base >=4.16.0.0 && <5.0.0.0+  hs-source-dirs:   src+  default-language: GHC2021++test-suite webcolor-labels-test+  import:           warnings+  default-language: GHC2021+  type:             exitcode-stdio-1.0+  hs-source-dirs:   test+  main-is:          Main.hs+  build-depends:+    , base             >=4.18.2.1+    , tasty+    , tasty-hunit+    , webcolor-labels