0 | ||| Values for HTML elements and attributes.
   1 | module Text.Html.Values
   2 |
   3 | import Data.Either
   4 | import Language.Reflection
   5 | import Language.Reflection.Pretty
   6 | import Language.Reflection.Syntax
   7 | import Language.Reflection.Syntax.Ops
   8 | import Language.Reflection.Util
   9 | import Data.List1
  10 | import Data.String
  11 |
  12 | import Derive.Prelude
  13 | import Derive.Refined
  14 | import Data.Refined
  15 | import Data.Refined.Integer
  16 |
  17 | import Text.Html.Utils
  18 |
  19 | %default total
  20 | %language ElabReflection
  21 |
  22 | --------------------------------------------------------------------------------
  23 | -- LICENCE NOTICE
  24 | --
  25 | -- The below function is taken from the example provided in
  26 | -- `idris2-elab-util` package's documentation.
  27 | --
  28 | -- Copyright: (c) 2020, Stefan Höck
  29 | -- License: BSD 2-Clause License
  30 | -- Source: https://github.com/stefan-hoeck/idris2-elab-util/blob/main/src/Doc/Enum1.md
  31 | --------------------------------------------------------------------------------
  32 |
  33 | ||| Generates an enumeration data type.
  34 | |||
  35 | ||| The `name` argument is the name of the data type, and the `enum` argument
  36 | ||| is the list of data constructor names in lower case.
  37 | private
  38 | mkEnum : (name : String) -> (enum : List String) -> Elab ()
  39 | mkEnum name enum =
  40 |   declare [simpleDataPublic (UN $ Basic name) (map mkCon enum)]
  41 |   where
  42 |     mkCon : String -> ITy
  43 |     mkCon x = mkTy
  44 |                 (UN $ Basic $ upperFirstStr x)
  45 |                 (varStr name)
  46 |
  47 | --------------------------------------------------------------------------------
  48 | -- LICENCE NOTICE
  49 | --
  50 | -- The below function is derived from the example provided in
  51 | -- `idris2-elab-util` package's documentation.
  52 | --
  53 | -- Copyright: (c) 2020, Stefan Höck
  54 | -- License: BSD 2-Clause License
  55 | -- Source: https://github.com/stefan-hoeck/idris2-elab-util/blob/main/src/Doc/Enum2.md
  56 | --------------------------------------------------------------------------------
  57 |
  58 | ||| Generates a `Show` instance for an enumeration data type.
  59 | |||
  60 | ||| The `name` argument is the name of the data type, and the `enum` argument
  61 | ||| is the list of data constructor names with their name in lower case.
  62 | export
  63 | mkShowImpl : (name : String) -> (enum : List String) -> Elab ()
  64 | mkShowImpl enumName cons =
  65 |   let
  66 |     -- names
  67 |     mkShow       := UN $ Basic "MkShow"
  68 |     showName     := UN $ Basic "show"
  69 |     functionName := UN . Basic $ "implShow" ++ enumName
  70 |
  71 |     -- vars
  72 |     show     := var showName
  73 |     function := var functionName
  74 |     enum     := arg $ varStr $ enumName
  75 |     -- single pattern clause: `show X_Y = "x-y"`
  76 |     mkC := \x => show .$ (varStr $ upperFirstStr x)
  77 |                    .= primVal (Str $ replaceChar '_' '-' x)
  78 |
  79 |     showPrec := `(\_,v => show v)
  80 |
  81 |     impl =
  82 |       local
  83 |         [ private' showName $ enum .-> `(String)
  84 |         , def showName $ map mkC cons
  85 |         ] (var mkShow .$ show .$ showPrec)
  86 |
  87 |    in
  88 |    declare
  89 |      [ interfaceHint Public functionName (var "Show" .$ type enum)
  90 |      , def functionName [function .= impl]
  91 |      ]
  92 |
  93 | ||| Generates a function creating the data type from a `String`.
  94 | |||
  95 | ||| The generated function has the below format:
  96 | |||
  97 | ||| ```idris2
  98 | ||| public export
  99 | ||| <func name> : (str : String) -> Either String <Type name>
 100 | ||| <func name> <enum 1>  = Right <enum 1>
 101 | ||| <func name> <enum ..> = Right <enum ..>
 102 | ||| <func name> <enum n>  = Right <enum n>
 103 | ||| <func name> str       = Left "ERROR: [...]"
 104 | ||| ```
 105 | ||| Where:
 106 | |||
 107 | ||| - `<func name>` is the provided name.
 108 | ||| - `<Type name>` is the provided name with its first letter in upper case.
 109 | ||| - `<enum 1>` is the first element of the `enum` list.
 110 | mkValueFunc : (name : String) -> (enum : List String) -> Elab ()
 111 | mkValueFunc name enum =
 112 |   let
 113 |     argStr := arg $ primVal (PrT StringType)
 114 |     output := var "Either" .$ primVal (PrT StringType) .$ var (UN . Basic $ name)
 115 |   in
 116 |   declare
 117 |     [ public' functionName $ argStr .-> output
 118 |     , def functionName $ map mkCase enum ++ [errorCase]
 119 |     ]
 120 |   where
 121 |
 122 |     functionName : Name
 123 |     functionName = UN . Basic $ lowerFirstStr name
 124 |
 125 |     mkCase : String -> Clause
 126 |     mkCase c =
 127 |          var functionName
 128 |            .$ (var "fromString" .$ primVal (Str $ replaceChar '_' '-' c))
 129 |       .= var "Right" .$ var (UN . Basic $ upperFirstStr c)
 130 |
 131 |     -- TODO: improves error message by returning the provided value.
 132 |     msg : String
 133 |     msg =
 134 |       "ERROR: The accepted values for \{name} are: " ++ joinBy ", " enum ++ "."
 135 |
 136 |     errorCase : Clause
 137 |     errorCase =
 138 |          var functionName .$ var "str"
 139 |       .= var "Left" .$ (var "fromString" .$ primVal (Str msg))
 140 |
 141 | ||| Generates a `fromString` function for the data type.
 142 | |||
 143 | ||| The generated function has the below format:
 144 | |||
 145 | ||| ```idris2
 146 | ||| public export
 147 | ||| fromString : (str : String)
 148 | |||           -> {auto 0 prf : IsRight (<func name> str)}
 149 | |||           -> <Type name>
 150 | ||| from String str = fromRight (<func name> str)
 151 | ||| ```
 152 | ||| where `<func name>` is the provided name with its first letter in lower case
 153 | ||| while `<Type name>` is the provided name.
 154 | mkFromStringFunc : (name : String) -> Elab ()
 155 | mkFromStringFunc name =
 156 |   let
 157 |     functionName := "fromString"
 158 |     callName     := UN . Basic $ lowerFirstStr name
 159 |     strArg       := MkArg MW ExplicitArg (Just "str") `(String)
 160 |     prfArg       := MkArg
 161 |                       M0
 162 |                       AutoImplicit
 163 |                       (Just "prf")
 164 |                       (var "IsRight" .$ (var callName .$ bindVar "str"))
 165 |     output       := var (UN . Basic $ name)
 166 |   in
 167 |   declare
 168 |     [ public' functionName $ strArg .-> prfArg .-> output
 169 |     , def functionName
 170 |         [  var functionName .$ bindVar "str"
 171 |         .= var "fromRight" .$ (var callName .$ var "str")
 172 |         ]
 173 |     ]
 174 |
 175 | ||| Generates an enum data type and its related functions.
 176 | |||
 177 | ||| The functions are:
 178 | |||
 179 | ||| - a `Show` instance
 180 | ||| - a function using the name of the data type with the first letter in
 181 | |||   lower case for generating the data type from a `String` and returning
 182 | |||   a `Either String <Type>` value
 183 | ||| - a `fromString` function
 184 | private
 185 | mkValueFuncs : (name : String) -> (enum : List String) -> Elab ()
 186 | mkValueFuncs name enum = do
 187 |   mkEnum name enum
 188 |   mkShowImpl name enum
 189 |   mkValueFunc name enum
 190 |   mkFromStringFunc name
 191 |
 192 | namespace Identifier
 193 |
 194 |   ||| A CSS identifier.
 195 |   public export
 196 |   data Identifier = MkIdentifier String
 197 |
 198 |   public export
 199 |   Show Identifier where
 200 |     show (MkIdentifier x) = x
 201 |
 202 |   ||| Creates a valid CSS identifier.
 203 |   |||
 204 |   ||| The approach is restrictive, so such identifier is valid in Javascript.
 205 |   ||| Consequently, only the character set [A-Za-z0-9-_] is accepted.
 206 |   ||| On top of the above, an identifier cannot start with a digit nor with
 207 |   ||| an hyphen.
 208 |   ||| Also, an identifier cannot be empty.
 209 |   |||
 210 |   ||| Note that you can still create an identifier outside of the above
 211 |   ||| restrictions using the `MkIdentifier`.
 212 |   public export
 213 |   identifier : String -> Either String Identifier
 214 |   identifier str = case idHelper $ unpack str of
 215 |                      Right _ => Right (MkIdentifier str)
 216 |                      Left e  => Left e
 217 |     where
 218 |       idHelperTail : List Char -> Either String (List Char)
 219 |       idHelperTail []        = Right []
 220 |       idHelperTail (x :: xs) =
 221 |         if isAlphaNum x || x == '_' || x == '-'
 222 |         then idHelperTail xs
 223 |         else Left ("ERROR: \{show x} is not an authorised character for the "
 224 |                 ++ "start of an identifier.")
 225 |
 226 |       -- Check the head and pass the tail to `idHelperTail`.
 227 |       idHelper : List Char -> Either String (List Char)
 228 |       idHelper []        = Left "ERROR: an identifier cannot be empty."
 229 |       idHelper (x :: xs) =
 230 |         if isAlpha x || x == '_'
 231 |         then idHelperTail xs
 232 |         else Left ("ERROR: \{show x} is not an authorised character for the "
 233 |                 ++ "start of an identifier.")
 234 |
 235 |   %runElab mkFromStringFunc "Identifier"
 236 |
 237 | namespace Identifiers
 238 |
 239 |   ||| A list of CSS identifiers.
 240 |   public export
 241 |   data Identifiers = MkIdentifiers (List1 Identifier)
 242 |
 243 |   public export
 244 |   Show Identifiers where
 245 |     show (MkIdentifiers xs) = unwords $ map show $ toList xs
 246 |
 247 |   ||| Creates a list of valid CSS identifiers.
 248 |   |||
 249 |   ||| See the `identifier` function for more details.
 250 |   public export
 251 |   identifiers : String -> Either String Identifiers
 252 |   identifiers str =
 253 |     case !(mapM identifier $ words str) of
 254 |       []        => Left "ERROR: a list of identifiers cannot be empty."
 255 |       (x :: xs) => Right $ MkIdentifiers $ toList1 (x :: xs)
 256 |
 257 |   %runElab mkFromStringFunc "Identifiers"
 258 |
 259 | ||| The **as** attribute.
 260 | namespace As
 261 |
 262 |   %runElab mkValueFuncs
 263 |     "AsValue"
 264 |     [ "audioworklet"
 265 |     , "fetch"
 266 |     , "font"
 267 |     , "image"
 268 |     , "json"
 269 |     , "paintworklet"
 270 |     , "script"
 271 |     , "serviceworker"
 272 |     , "sharedworker"
 273 |     , "style"
 274 |     , "text"
 275 |     , "track"
 276 |     , "worker"
 277 |     ]
 278 |
 279 | ||| The **autocomplete** attribute.
 280 | namespace Autocomplete
 281 |
 282 |   public export
 283 |   data AutocompleteValue =
 284 |       On
 285 |     | Off
 286 |     | TokenList Identifiers
 287 |
 288 |   public export
 289 |   Show AutocompleteValue where
 290 |     show On             = "on"
 291 |     show Off            = "off"
 292 |     show (TokenList xs) = show xs
 293 |
 294 |   public export
 295 |   autocompleteValue : String -> Either String AutocompleteValue
 296 |   autocompleteValue "on"  = Right On
 297 |   autocompleteValue "off" = Right Off
 298 |   autocompleteValue str   = pure $ TokenList !(identifiers str)
 299 |
 300 |   %runElab mkFromStringFunc "AutocompleteValue"
 301 |
 302 | ||| The **autocorrect** attribute.
 303 | namespace Autocorrect
 304 |
 305 |   %runElab mkValueFuncs "AutocorrectValue" ["on" , "off"]
 306 |
 307 | namespace Base64
 308 |
 309 |   ||| Base64 encoding.
 310 |   public export
 311 |   data Base64 : Nat -> Type where
 312 |     MkBase64 : (n : Nat) -> (chars : Vect n Char) -> Base64 n
 313 |
 314 |   public export
 315 |   base64Digits : List Char -> Either String (List Char)
 316 |   base64Digits []          = Right []
 317 |   base64Digits ('=' :: xs) = pure ('=' :: !(b64tail xs))
 318 |     where
 319 |       b64tail : List Char -> Either String (List Char)
 320 |       b64tail []          = Right []
 321 |       b64tail ('=' :: xs) = pure ('=' :: !(b64tail xs))
 322 |       b64tail (x :: _)    =
 323 |         Left "ERROR: \{show x} is not a valid base64 padding character."
 324 |   base64Digits (x :: xs)  =
 325 |     if isAlphaNum x || x == '+' || x == '/'
 326 |     then pure (x :: !(base64Digits xs))
 327 |     else Left "ERROR: \{show x} is not a valid base64 character."
 328 |
 329 |   public export
 330 |   Show (Base64 n) where
 331 |     show (MkBase64 _ xs) = pack (toList xs)
 332 |
 333 |   public export
 334 |   base64Value' : (n : Nat) -> List Char -> Either String (Base64 n)
 335 |   base64Value' n xs =
 336 |     case toVect n !(base64Digits xs) of
 337 |       Nothing => Left "ERROR: \{pack xs} is not of length \{show n}."
 338 |       Just v  => Right (MkBase64 n v)
 339 |
 340 |   public export
 341 |   base64Value : (n : Nat) -> String -> Either String (Base64 n)
 342 |   base64Value n str = base64Value' n (unpack str)
 343 |
 344 |   public export
 345 |   fromString : (str : String)
 346 |             -> {auto 0 prf : IsRight (base64Value (length str) str)}
 347 |             -> Base64 (length str)
 348 |   fromString str = fromRight $ base64Value (length str) str
 349 |
 350 | ||| The **contenteditable** attribute.
 351 | namespace Contenteditable
 352 |
 353 |   %runElab mkValueFuncs
 354 |     "ContenteditableValue"
 355 |     [ "true"
 356 |     , "false"
 357 |     , "plaintext_only"
 358 |     ]
 359 |
 360 | namespace Coords
 361 |
 362 |   ||| Coordinates to be used within the **coords** attribute.
 363 |   public export
 364 |   data CoordsValue : Type where
 365 |     Rect : (x1 : Double)
 366 |         -> (y1 : Double)
 367 |         -> (x2 : Double)
 368 |         -> (y2 : Double)
 369 |         -> CoordsValue
 370 |     Circle : (x : Double)
 371 |           -> (y : Double)
 372 |           -> (r : Double)
 373 |           -> CoordsValue
 374 |     Poly : (x1 : Double)
 375 |         -> (y1 : Double)
 376 |         -> (x2 : Double)
 377 |         -> (y2 : Double)
 378 |         -> List (Double, Double)
 379 |         -> CoordsValue
 380 |
 381 |   public export
 382 |   Show CoordsValue where
 383 |     show (Rect x1 y1 x2 y2)    = "\{show x1},\{show y1},\{show x2},\{show y2}"
 384 |     show (Circle x y r)        = "\{show x},\{show y},\{show r}"
 385 |     show (Poly x1 y1 x2 y2 xs) =
 386 |       "\{show x1},\{show y1},\{show x2},\{show y2}" ++ showList xs
 387 |       where
 388 |         showList : List (Double, Double) -> String
 389 |         showList []               = ""
 390 |         showList ((xn, yn) :: xs) = ",\{show xn},\{show yn}" ++ showList xs
 391 |
 392 | ||| The **crossorigin** attribute.
 393 | namespace Crossorigin
 394 |
 395 |   %runElab mkValueFuncs "CrossoriginValue" ["anonymous", "use_credentials"]
 396 |
 397 | namespace Date
 398 |
 399 |   ||| Abbreviated symbolic month.
 400 |   public export
 401 |   data Month
 402 |     = Jan
 403 |     | Feb
 404 |     | Mar
 405 |     | Apr
 406 |     | May
 407 |     | Jun
 408 |     | Jul
 409 |     | Aug
 410 |     | Sep
 411 |     | Oct
 412 |     | Nov
 413 |     | Dec
 414 |
 415 |   public export
 416 |   Show Month where
 417 |     show Jan = "Jan"
 418 |     show Feb = "Feb"
 419 |     show Mar = "Mar"
 420 |     show Apr = "Apr"
 421 |     show May = "May"
 422 |     show Jun = "Jun"
 423 |     show Jul = "Jul"
 424 |     show Aug = "Aug"
 425 |     show Sep = "Sep"
 426 |     show Oct = "Oct"
 427 |     show Nov = "Nov"
 428 |     show Dec = "Dec"
 429 |
 430 |   public export
 431 |   Eq Month where
 432 |     Jan == Jan = True
 433 |     Feb == Feb = True
 434 |     Mar == Mar = True
 435 |     Apr == Apr = True
 436 |     May == May = True
 437 |     Jun == Jun = True
 438 |     Jul == Jul = True
 439 |     Aug == Aug = True
 440 |     Sep == Sep = True
 441 |     Oct == Oct = True
 442 |     Nov == Nov = True
 443 |     Dec == Dec = True
 444 |     _   == _   = False
 445 |
 446 |   public export
 447 |   fromMonth : Month -> Nat
 448 |   fromMonth Jan = 1
 449 |   fromMonth Feb = 2
 450 |   fromMonth Mar = 3
 451 |   fromMonth Apr = 4
 452 |   fromMonth May = 5
 453 |   fromMonth Jun = 6
 454 |   fromMonth Jul = 7
 455 |   fromMonth Aug = 8
 456 |   fromMonth Sep = 9
 457 |   fromMonth Oct = 10
 458 |   fromMonth Nov = 11
 459 |   fromMonth Dec = 12
 460 |
 461 |   public export
 462 |   toMonth : Integer -> Maybe Month
 463 |   toMonth 1  = Just Jan
 464 |   toMonth 2  = Just Feb
 465 |   toMonth 3  = Just Mar
 466 |   toMonth 4  = Just Apr
 467 |   toMonth 5  = Just May
 468 |   toMonth 6  = Just Jun
 469 |   toMonth 7  = Just Jul
 470 |   toMonth 8  = Just Aug
 471 |   toMonth 9  = Just Sep
 472 |   toMonth 10 = Just Oct
 473 |   toMonth 11 = Just Nov
 474 |   toMonth 12 = Just Dec
 475 |   toMonth _  = Nothing
 476 |
 477 |   public export
 478 |   Ord Month where
 479 |     x < y = fromMonth x < fromMonth y
 480 |
 481 |   ||| Returns `True` if the year is a leap year.
 482 |   |||
 483 |   ||| Year `0` is a considered as a leap year.
 484 |   ||| Negative years follow the same rules as positive year.
 485 |   ||| For example, `-4` is a leap year, but not `-100`.
 486 |   public export
 487 |   isLeap : (year : Integer) -> Bool
 488 |   isLeap year =
 489 |     let
 490 |       nthYear : Integer -> Bool
 491 |       nthYear n = mod year n == 0
 492 |     in
 493 |       (nthYear 4) && (not (nthYear 100) || (nthYear 400))
 494 |
 495 |   ||| Number of days in the given month and year.
 496 |   public export
 497 |   daysInMonth : (year : Integer) -> Month -> Integer
 498 |   daysInMonth year Feb = if isLeap year then 29 else 28
 499 |   daysInMonth _ Apr = 30
 500 |   daysInMonth _ Jun = 30
 501 |   daysInMonth _ Sep = 30
 502 |   daysInMonth _ Nov = 30
 503 |   daysInMonth _ _   = 31
 504 |
 505 |   ||| Returns `True` if the day is valid for the provided year and month.
 506 |   public export
 507 |   isValidDay : (year : Integer) -> Month -> (day : Integer) -> Bool
 508 |   isValidDay year month day = day > 0 && day <= daysInMonth year month
 509 |
 510 |   ||| Returns `True` if the year is valid (= within the -9999 to 9999 range).
 511 |   public export
 512 |   isValidYear : (year : Integer) -> Bool
 513 |   isValidYear year = year > -10000 && year < 10000
 514 |
 515 |   ||| Returns `True` if the date is valid.
 516 |   public export
 517 |   isValidDate : (year : Integer) -> Month -> (day : Integer) -> Bool
 518 |   isValidDate year month day = isValidYear year && isValidDay year month day
 519 |
 520 |   ||| A date in the format "yyyy-mm-dd".
 521 |   public export
 522 |   record Date where
 523 |     constructor MkDate
 524 |     year  : Integer
 525 |     month : Month
 526 |     day   : Integer
 527 |     {auto 0 prf : Holds (isValidDate year month) day}
 528 |
 529 |   ||| Shows a year in "yyyy" format.
 530 |   public export
 531 |   showYear : (year : Integer) -> String
 532 |   showYear year =
 533 |     let yStr := show year in
 534 |     replicate (minus 4 $ length yStr) '0' ++ yStr
 535 |
 536 |   ||| Shows a month in "mm" format.
 537 |   public export
 538 |   showMonth : Month -> String
 539 |   showMonth month =
 540 |     let mStr := show (fromMonth month) in
 541 |     replicate (minus 2 $ length mStr) '0' ++ mStr
 542 |
 543 |
 544 |   ||| Shows a number on two digits.
 545 |   public export
 546 |   show2Digits : Integer -> String
 547 |   show2Digits x =
 548 |     let str := show x in
 549 |     replicate (minus 2 $ length str) '0' ++ str
 550 |
 551 |   ||| Shows a date in the "yyyy-mm-dd" format.
 552 |   public export
 553 |   Show Date where
 554 |     show (MkDate year month day) =
 555 |       "\{showYear year}-\{showMonth month}-\{show2Digits day}"
 556 |
 557 |   %runElab derive "Date" [Eq, Ord]
 558 |
 559 |   ||| Returns a date or `Nothing` if the provided values are invalid.
 560 |   public export
 561 |   maybe_date : Integer -> Month -> Integer -> Maybe Date
 562 |   maybe_date year month day =
 563 |     case hdec0 {p = Holds (isValidDate year month)} day of
 564 |       Just0 _  => Just (MkDate year month day)
 565 |       Nothing0 => Nothing
 566 |
 567 |   private
 568 |   parseNeg : String -> Int
 569 |   parseNeg str = if strSubstr 0 1 str == "-" then 1 else 0
 570 |
 571 |   public export
 572 |   extractPart : (start : Int) -> (length : Int) -> String -> String
 573 |   extractPart start l str = strSubstr (start + parseNeg str) l str
 574 |
 575 |   public export
 576 |   parseYear : String -> Either String Integer
 577 |   parseYear str =
 578 |     let yyyy := extractPart 0 4 str in
 579 |     case parseInteger yyyy of
 580 |       Just x  => Right (if parseNeg str == 1 then -x else x)
 581 |       Nothing => Left "ERROR: '\{yyyy}' is not a valid year value."
 582 |
 583 |   public export
 584 |   parseMonth : String -> Either String Month
 585 |   parseMonth str =
 586 |     let mm := extractPart 5 2 str in
 587 |     case the (Maybe Integer) (parsePositive mm) >>= toMonth of
 588 |       Just x => Right x
 589 |       Nothing => Left "ERROR: '\{mm}' is not a valid month value."
 590 |
 591 |   public export
 592 |   parseDay : String -> Either String Integer
 593 |   parseDay str =
 594 |     let dd := extractPart 8 2 str in
 595 |     case parsePositive dd of
 596 |       Just x  => Right x
 597 |       Nothing => Left "ERROR: '\{dd}' is not a valid day value."
 598 |
 599 |   public export
 600 |   parseSep : (pos : Int) -> String -> Either String String
 601 |   parseSep pos str =
 602 |     let sep := extractPart pos 1 str in
 603 |     if sep == "-"
 604 |     then Right sep
 605 |     else Left "ERROR: '\{sep}' is not a valid date separator."
 606 |
 607 |   ||| Returns a date from a string.
 608 |   |||
 609 |   ||| An error is returned if the provided string isn't a valid date in
 610 |   ||| "yyyy-mm-dd" format.
 611 |   public export
 612 |   dateValue : String -> Either String Date
 613 |   dateValue str = do
 614 |     _ <- checkLength str
 615 |     _ <- parseSep 4 str
 616 |     _ <- parseSep 7 str
 617 |     case maybe_date !(parseYear str) !(parseMonth str) !(parseDay str) of
 618 |       Just x  => Right x
 619 |       Nothing => Left "ERROR: '\{str}' is not a valid date."
 620 |     where
 621 |       checkLength : String -> Either String String
 622 |       checkLength str =
 623 |         if length str == 10
 624 |         then Right str
 625 |         else Left "ERROR: \{str} has not a correct length for a date."
 626 |
 627 |   public export
 628 |   fromString : (str : String) -> {auto 0 prf : IsRight (dateValue str)} -> Date
 629 |   fromString str = fromRight (dateValue str)
 630 |
 631 | namespace YearMonth
 632 |
 633 |   ||| A month of a given year.
 634 |   public export
 635 |   record YearMonth where
 636 |     constructor MkYearMonth
 637 |     year  : Integer
 638 |     month : Month
 639 |     {auto 0 prf : Holds Date.isValidYear year}
 640 |
 641 |   public export
 642 |   Show YearMonth where
 643 |     show (MkYearMonth year month) = "\{showYear year}-\{showMonth month}"
 644 |
 645 |   ||| Returns a year-month in "yyyy-mm" format or `Nothing`.
 646 |   public export
 647 |   maybe_yearMonth : (year : Integer) -> Month -> Maybe YearMonth
 648 |   maybe_yearMonth year month =
 649 |     case hdec0 {p = Holds Date.isValidYear} year of
 650 |       Just0 _  => Just (MkYearMonth year month)
 651 |       Nothing0 => Nothing
 652 |
 653 |   public export
 654 |   yearMonthValue : String -> Either String YearMonth
 655 |   yearMonthValue str = do
 656 |     _ <- checkLength str
 657 |     _ <- parseSep 4 str
 658 |     case maybe_yearMonth !(parseYear str) !(parseMonth str) of
 659 |       Just x  => Right x
 660 |       Nothing => Left "ERROR: '\{str}' is not a valid year-month."
 661 |     where
 662 |       checkLength : String -> Either String String
 663 |       checkLength str =
 664 |         if length str == 7
 665 |         then Right str
 666 |         else Left "ERROR: \{str} has not a correct length for a year-month."
 667 |
 668 |   public export
 669 |   fromString : (str : String)
 670 |             -> {auto 0 prf : IsRight (yearMonthValue str)}
 671 |             -> YearMonth
 672 |   fromString str = fromRight (yearMonthValue str)
 673 |
 674 | namespace YearWeek
 675 |
 676 |   ||| Calculates the number of the day of the week on 31 december.
 677 |   |||
 678 |   ||| This is useful to later calculate the number of weeks for a given year.
 679 |   |||
 680 |   ||| Source of the algorithm: https://en.wikipedia.org/wiki/ISO_week_date
 681 |   private
 682 |   dayOn31Dec : (year : Integer) -> Integer
 683 |   dayOn31Dec year =
 684 |     let
 685 |       year' : Double
 686 |       year' = cast year
 687 |     in
 688 |     cast (year' + (year' / 4) - (year' / 100) + (year' / 400)) `mod` 7
 689 |
 690 |   ||| Calculates the number of ISO weeks for a given year.
 691 |   |||
 692 |   ||| The returned value can be `52` or `53` depending on the year.
 693 |   |||
 694 |   ||| Source of the algorithm: https://en.wikipedia.org/wiki/ISO_week_date
 695 |   public export
 696 |   nbWeeks : (year : Integer) -> Integer
 697 |   nbWeeks year =
 698 |     if dayOn31Dec year == 4 || dayOn31Dec (year - 1) == 3
 699 |     then 53
 700 |     else 52
 701 |
 702 |   ||| Returns `True` if the provided week is valid for the given year.
 703 |   public export
 704 |   isValidYearWeek : (year : Integer) -> (week : Integer) -> Bool
 705 |   isValidYearWeek year week =
 706 |     isValidYear year && week > 0 && week <= nbWeeks year
 707 |
 708 |   ||| A week of a given year.
 709 |   public export
 710 |   record YearWeek where
 711 |     constructor MkYearWeek
 712 |     year : Integer
 713 |     week : Integer
 714 |     {auto 0 prf : Holds (isValidYearWeek year) week}
 715 |
 716 |   public export
 717 |   Show YearWeek where
 718 |     show (MkYearWeek year week) = "\{showYear year}-W\{show2Digits week}"
 719 |
 720 |   ||| Returns a `YearWeek` if the provided week is valid for the given year.
 721 |   |||
 722 |   ||| Otherwise, returns `Nothing`.
 723 |   public export
 724 |   maybe_yearWeek : (year : Integer) -> (week : Integer) -> Maybe YearWeek
 725 |   maybe_yearWeek year week =
 726 |     case hdec0 {p = Holds (isValidYearWeek year)} week of
 727 |       Just0 _  => Just (MkYearWeek year week)
 728 |       Nothing0 => Nothing
 729 |
 730 |   public export
 731 |   yearWeekValue : String -> Either String YearWeek
 732 |   yearWeekValue str = do
 733 |     _ <- checkLength str
 734 |     _ <- parseSep 4 str
 735 |     _ <- parseW str
 736 |     case maybe_yearWeek !(parseYear str) !(parseWeek str) of
 737 |       Just x  => Right x
 738 |       Nothing => Left "ERROR: '\{str}' is not a valid year-week"
 739 |     where
 740 |       checkLength : String -> Either String String
 741 |       checkLength str =
 742 |         if length str == 8
 743 |         then Right str
 744 |         else Left "ERROR: \{str} has not a correct length for a year-week."
 745 |
 746 |       parseW : String -> Either String String
 747 |       parseW str =
 748 |         let w := extractPart 5 1 str in
 749 |         if w == "W"
 750 |         then Right w
 751 |         else Left ("ERROR: `\{w}' is not a valid week symbol. The only accepted "
 752 |                 ++ "symbol is 'W'.")
 753 |
 754 |       parseWeek : String -> Either String Integer
 755 |       parseWeek str =
 756 |         let w := extractPart 6 2 str in
 757 |         case parsePositive w of
 758 |           Just x  => Right x
 759 |           Nothing => Left "ERROR: `\{w} is not a valid week number."
 760 |
 761 |   public export
 762 |   fromString : (str : String)
 763 |             -> {auto 0 prf : IsRight (yearWeekValue str)}
 764 |             -> YearWeek
 765 |   fromString str = fromRight (yearWeekValue str)
 766 |
 767 | namespace Time
 768 |
 769 |   public export
 770 |   isValidTime : (hour : Int) -> (minute : Int) -> (second : Maybe Int) -> Bool
 771 |   isValidTime hour minute second =
 772 |        hour   >= 0 && hour   < 24
 773 |     && minute >= 0 && minute < 60
 774 |     && case second of
 775 |          Just s  => s >= 0 && s < 60
 776 |          Nothing => True
 777 |
 778 |   ||| A time with hours, minutes and optional seconds.
 779 |   public export
 780 |   record Time where
 781 |     constructor MkTime
 782 |     hour   : Int
 783 |     minute : Int
 784 |     second : Maybe Int
 785 |     {auto 0 prf : Holds (isValidTime hour minute) second}
 786 |
 787 |   ||| Shows a number on two digits.
 788 |   private
 789 |   show2Digits : Int -> String
 790 |   show2Digits x =
 791 |     let str := show x in
 792 |     replicate (minus 2 $ length str) '0' ++ str
 793 |
 794 |   public export
 795 |   Show Time where
 796 |     show (MkTime hour minute second) =
 797 |       "\{show2Digits hour}:\{show2Digits minute}"
 798 |       ++ case second of
 799 |            Just s  => ":\{show2Digits s}"
 800 |            Nothing => ""
 801 |
 802 |   ||| Returns a `Time` if the hour, minute and optional second are valid.
 803 |   |||
 804 |   ||| Otherwise, returns `Nothing`.
 805 |   public export
 806 |   maybe_time : (hour : Int)
 807 |             -> (minute : Int)
 808 |             -> (second : Maybe Int)
 809 |             -> Maybe Time
 810 |   maybe_time hour minute second =
 811 |     case hdec0 {p = Holds (isValidTime hour minute)} second of
 812 |       Just0 _  => Just (MkTime hour minute second)
 813 |       Nothing0 => Nothing
 814 |
 815 |   public export
 816 |   timeValue : String -> Either String Time
 817 |   timeValue str = do
 818 |     _ <- checkLength str
 819 |     _ <- parseTimeSep1 str
 820 |     _ <- parseTimeSep2 str
 821 |     case maybe_time !(parsePart 0 str) !(parsePart 3 str) !(parseSecond str) of
 822 |       Just x  => Right x
 823 |       Nothing => Left "ERROR: '\{str}' is not a valid time."
 824 |     where
 825 |       checkLength : String -> Either String String
 826 |       checkLength str =
 827 |         if length str == 5 || length str == 8
 828 |         then Right str
 829 |         else Left "ERROR: \{str} has not a correct length for a time."
 830 |
 831 |       parseTimeSep1 : String -> Either String String
 832 |       parseTimeSep1 str =
 833 |         let sep := extractPart 2 1 str in
 834 |         if sep == ":"
 835 |         then Right sep
 836 |         else Left ("ERROR: `\{sep}' is not a valid time separator. The only "
 837 |                    ++ "accepted one is ':'.")
 838 |
 839 |       parseTimeSep2 : String -> Either String String
 840 |       parseTimeSep2 str =
 841 |         let sep := extractPart 5 1 str in
 842 |         if sep == ":" || length str < 6
 843 |         then Right sep
 844 |         else Left ("ERROR: `\{sep}' is not a valid time separator. The only "
 845 |                    ++ "accepted one is ':'.")
 846 |
 847 |       parsePart : Int -> String -> Either String Int
 848 |       parsePart pos str =
 849 |         let
 850 |           part := extractPart pos 2 str
 851 |           text := if pos == 0 then "hour" else "minute"
 852 |         in
 853 |         case parsePositive part of
 854 |           Just x  => Right x
 855 |           Nothing => Left "ERROR: `\{part} is not a valid \{text}."
 856 |
 857 |       parseSecond : String -> Either String (Maybe Int)
 858 |       parseSecond str =
 859 |         let
 860 |           part := extractPart 6 2 str
 861 |         in
 862 |         if length str < 6
 863 |         then Right Nothing
 864 |         else case parsePositive part of
 865 |           Just x  => Right (Just x)
 866 |           Nothing => Left "ERROR: `\{part} is not a valid second."
 867 |
 868 |   public export
 869 |   fromString : (str : String)
 870 |             -> {auto 0 prf : IsRight (timeValue str)}
 871 |             -> Time
 872 |   fromString str = fromRight (timeValue str)
 873 |
 874 | namespace Datetime
 875 |
 876 |   ||| A Datetime.
 877 |   public export
 878 |   data Datetime : Type where
 879 |     -- TODO: use a datatime library.
 880 |     MkDatetime : (string : String) -> Datetime
 881 |
 882 |   public export
 883 |   Show Datetime where
 884 |     show (MkDatetime str) = str
 885 |
 886 |   ||| Naïve implementation accepting any `String` without validation.
 887 |   public export
 888 |   datetimeValue : String -> Either String Datetime
 889 |   datetimeValue = Right . MkDatetime
 890 |
 891 |   ||| Naïve implementation accepting any `String` without validation.
 892 |   public export
 893 |   fromString : (value : String) -> Datetime
 894 |   fromString = MkDatetime
 895 |
 896 | ||| The **decoding** attribute.
 897 | namespace Decoding
 898 |
 899 |   %runElab mkValueFuncs "DecodingValue" ["sync", "async", "auto"]
 900 |
 901 | ||| The **dir** attribute.
 902 | namespace Dir
 903 |
 904 |   %runElab mkValueFuncs "DirValue" ["ltr", "rtl", "auto"]
 905 |
 906 | ||| The **dirname** attribute.
 907 | namespace Dirname
 908 |
 909 |   %runElab mkValueFuncs "DirnameValue" ["ltr", "rtl"]
 910 |
 911 | namespace DocumentFragment
 912 |
 913 |   ||| A document fragment value.
 914 |   public export
 915 |   record DocumentFragment where
 916 |     constructor MkDocumentFragment
 917 |     value : String
 918 |
 919 |   ||| Returns a document fragment or an error if the string is not valid.
 920 |   |||
 921 |   ||| To be valid, the provided string must start with '#'.
 922 |   public export
 923 |   documentFragment : String -> Either String DocumentFragment
 924 |   documentFragment str =
 925 |     case unpack str of
 926 |       ('#' :: _) => Right (MkDocumentFragment str)
 927 |       v          => Left
 928 |         "ERROR: a document fragment must start with '#', **\{pack v}** provided"
 929 |
 930 |   public export
 931 |   FromString DocumentFragment where
 932 |     fromString str = MkDocumentFragment str
 933 |
 934 |   public export
 935 |   Show DocumentFragment where
 936 |     show (MkDocumentFragment str) = str
 937 |
 938 | namespace Enctype
 939 |
 940 |   %runElab mkEnum "EnctypeValue" ["urlencoded", "formData", "plain"]
 941 |
 942 |   %runElab mkShowImpl "EnctypeValue" ["urlencoded", "formData", "plain"]
 943 |
 944 |   enctypeValue : String -> Either String EnctypeValue
 945 |   enctypeValue "application/x-www-form-urlencoded" = Right Urlencoded
 946 |   enctypeValue "multipart/form-data"               = Right FormData
 947 |   enctypeValue "text/plain"                        = Right Plain
 948 |   enctypeValue str                                 = Left
 949 |     "ERROR: \{str} is not an allowed value for the **enctype** argument."
 950 |
 951 |   %runElab  mkFromStringFunc "EnctypeValue"
 952 |
 953 | ||| The **enterkeyhint** attribute.
 954 | namespace Enterkeyhint
 955 |
 956 |   %runElab mkValueFuncs
 957 |              "EnterkeyhintValue"
 958 |              [ "enter"
 959 |              , "done"
 960 |              , "go"
 961 |              , "next"
 962 |              , "previous"
 963 |              , "search"
 964 |              , "send"
 965 |              ]
 966 |
 967 | namespace Exportpart
 968 |
 969 |   ||| A single value for the **exportparts** attribute.
 970 |   public export
 971 |   data ExportpartValue : Type where
 972 |     Value    : Identifier -> ExportpartValue
 973 |     KeyValue : (key : Identifier) -> (value : Identifier) -> ExportpartValue
 974 |
 975 |   public export
 976 |   Show ExportpartValue where
 977 |     show (Value v)      = show v
 978 |     show (KeyValue k v) = "\{show k}:\{show v}"
 979 |
 980 |   public export
 981 |   exportpartValue : String -> Either String ExportpartValue
 982 |   exportpartValue str =
 983 |     let
 984 |       parts := break (== ':') str
 985 |     in
 986 |     if strLength (snd parts) == 0
 987 |     then map Value (identifier str)
 988 |     else pure
 989 |            $ KeyValue
 990 |                !(identifier $ fst parts)
 991 |                !(identifier $ strSubstr 1 (strLength $ snd parts) (snd parts))
 992 |
 993 |   %runElab  mkFromStringFunc "ExportpartValue"
 994 |
 995 | namespace Exportparts
 996 |
 997 |   ||| The **exportparts** attribute value.
 998 |   public export
 999 |   data ExportpartsValue = MkExportpartsValue (List1 ExportpartValue)
1000 |
1001 |   public export
1002 |   Show ExportpartsValue where
1003 |     show (MkExportpartsValue xs) = joinBy ", " $ map show $ toList xs
1004 |
1005 |   public export
1006 |   exportpartsValue : String -> Either String ExportpartsValue
1007 |   exportpartsValue str =
1008 |     case !(mapM exportpartValue $ map trim $ toList $ split (== ',') str) of
1009 |       []        => Left "ERROR: **exportparts** attribute cannot be empty."
1010 |       (x :: xs) => Right $ MkExportpartsValue $ toList1 (x :: xs)
1011 |
1012 |   %runElab mkFromStringFunc "ExportpartsValue"
1013 |
1014 | ||| The **fetchpriority** attribute.
1015 | namespace Fetchpriority
1016 |
1017 |   %runElab mkValueFuncs "FetchpriorityValue" ["high" , "low" , "auto"]
1018 |
1019 | namespace Filename
1020 |
1021 |   ||| A filename value.
1022 |   public export
1023 |   data Filename = MkFilename String
1024 |
1025 |   public export
1026 |   Show Filename where
1027 |     show (MkFilename name) = name
1028 |
1029 |   ||| Naïve implementation accepting any `String` as a filename.
1030 |   public export
1031 |   filename : String -> Either String Filename
1032 |   filename name = Right (MkFilename name)
1033 |
1034 |   ||| Naïve implementation accepting any `String` as a filename.
1035 |   public export
1036 |   fromString : (str : String) -> Filename
1037 |   fromString name = MkFilename name
1038 |
1039 | ||| The **formmethod** attribute.
1040 | namespace Formmethod
1041 |
1042 |   %runElab mkValueFuncs "FormmethodValue" ["post" , "get" , "dialog"]
1043 |
1044 | ||| The **formtarget** attribute.
1045 | namespace Formtarget
1046 |
1047 |   %runElab mkEnum "FormtargetValue" ["self", "blank", "parent", "top"]
1048 |
1049 |   %runElab mkShowImpl "FormtargetValue" ["self", "blank", "parent", "top"]
1050 |
1051 |   public export
1052 |   formtargetValue : String -> Either String FormtargetValue
1053 |   formtargetValue "_self"   = Right Self
1054 |   formtargetValue "_blank"  = Right Blank
1055 |   formtargetValue "_parent" = Right Parent
1056 |   formtargetValue "_top"    = Right Top
1057 |   formtargetValue str       =
1058 |     Left ("ERROR: \{str} provided. For the **formtarget** attribute, "
1059 |       ++ "the allowed values are: _self, _blank, _parent or _top.")
1060 |
1061 |   %runElab mkFromStringFunc "FormtargetValue"
1062 |
1063 | namespace Hidden
1064 |
1065 |   %runElab mkEnum "HiddenValue" ["hidden" , "untilFound" , "empty"]
1066 |
1067 |   %runElab mkShowImpl "HiddenValue" ["hidden" , "untilFound" , "empty"]
1068 |
1069 |   public export
1070 |   hiddenValue : String -> Either String HiddenValue
1071 |   hiddenValue "hidden"      = Right Hidden
1072 |   hiddenValue "until-found" = Right UntilFound
1073 |   hiddenValue ""            = Right Empty
1074 |   hiddenValue str           =
1075 |     Left ("ERROR: \{str} provided. For the **hidden** attribute, "
1076 |       ++ "the allowed values are: hidden, until-found or an empty string.")
1077 |
1078 |   %runElab mkFromStringFunc "HiddenValue"
1079 |
1080 | ||| The **http-equiv** attribute.
1081 | namespace HttpEquiv
1082 |
1083 |   %runElab mkEnum
1084 |              "HttpEquivValue"
1085 |              [ "contentType"
1086 |              , "contentSecurityPolicy"
1087 |              , "defaultStyle"
1088 |              , "refresh"
1089 |              ]
1090 |
1091 |   %runElab mkShowImpl
1092 |              "HttpEquivValue"
1093 |              [ "contentType"
1094 |              , "contentSecurityPolicy"
1095 |              , "defaultStyle"
1096 |              , "refresh"
1097 |              ]
1098 |
1099 |   httpEquivValue : String -> Either String HttpEquivValue
1100 |   httpEquivValue "content-type"            = Right ContentType
1101 |   httpEquivValue "content-security-policy" = Right ContentSecurityPolicy
1102 |   httpEquivValue "default-style"           = Right DefaultStyle
1103 |   httpEquivValue "refresh"                 = Right Refresh
1104 |   httpEquivValue str                       =
1105 |     Left ("ERROR: \{str} provided. For the **http-equiv** attribute, "
1106 |       ++ "the allowed values are: content-type, content-security-policy, "
1107 |       ++ "default-style or refresh.")
1108 |
1109 |   %runElab mkFromStringFunc "HttpEquivValue"
1110 |
1111 | namespace Integrity
1112 |
1113 |   ||| An **integrity** attribute value.
1114 |   public export
1115 |   data IntegrityValue : Type where
1116 |     Sha256 : Base64 44 -> IntegrityValue
1117 |     Sha384 : Base64 64 -> IntegrityValue
1118 |     Sha512 : Base64 88 -> IntegrityValue
1119 |
1120 |   public export
1121 |   Show IntegrityValue where
1122 |     show (Sha256 b64) = "sha256-" ++ show b64
1123 |     show (Sha384 b64) = "sha384-" ++ show b64
1124 |     show (Sha512 b64) = "sha512-" ++ show b64
1125 |
1126 |   public export
1127 |   integrityValue' : List Char -> Either String IntegrityValue
1128 |   integrityValue' ('s' :: 'h' :: 'a' :: '2' :: '5' :: '6' :: '-' :: xs)
1129 |     with (length xs)
1130 |     _ | 43 = pure $ Sha256 !(base64Value' 44 $ snoc xs '=')
1131 |     _ | 44 = pure $ Sha256 !(base64Value' 44 xs)
1132 |     _ | n  = Left "ERROR: \{show n} isn't a valid length for sha256 in base64."
1133 |   integrityValue' ('s' :: 'h' :: 'a' :: '3' :: '8' :: '4' :: '-' :: xs)
1134 |     with (length xs)
1135 |     _ | 64 = pure $ Sha384 !(base64Value' 64 xs)
1136 |     _ | n  = Left "ERROR: \{show n} isn't a valid length for sha384 in base64."
1137 |   integrityValue' ('s' :: 'h' :: 'a' :: '5' :: '1' :: '2' :: '-' :: xs)
1138 |     with (length xs)
1139 |     _ | 86 = pure $ Sha512 !(base64Value' 88 $ xs ++ ['=', '='])
1140 |     _ | 87 = pure $ Sha512 !(base64Value' 88 $ snoc xs '=')
1141 |     _ | 88 = pure $ Sha512 !(base64Value' 88 xs)
1142 |     _ | n  = Left "ERROR: \{show n} isn't a valid length for sha512 in base64."
1143 |   integrityValue' xs =
1144 |     Left "Error: \{pack xs} is not a valid **integrity** attribute value."
1145 |
1146 |   public export
1147 |   integrityValue : String -> Either String IntegrityValue
1148 |   integrityValue = integrityValue' . unpack
1149 |
1150 |   %runElab mkFromStringFunc "IntegrityValue"
1151 |
1152 | ||| The **inputmode** attribute value.
1153 | namespace Inputmode
1154 |
1155 |   %runElab mkValueFuncs "InputmodeValue"
1156 |     [ "none"
1157 |     , "text"
1158 |     , "decimal"
1159 |     , "numeric"
1160 |     , "tel"
1161 |     , "search"
1162 |     , "email"
1163 |     , "url"
1164 |     ]
1165 |
1166 | ||| The **kind** attribute value.
1167 | namespace Kind
1168 |
1169 |   %runElab mkValueFuncs "KindValue"
1170 |     [ "subtitles"
1171 |     , "captions"
1172 |     , "descriptions"
1173 |     , "chapters"
1174 |     , "metadata"
1175 |     ]
1176 |
1177 | ||| The **loading** attribute value.
1178 | namespace Loading
1179 |
1180 |   %runElab mkValueFuncs "LoadingValue" ["eager" , "lazy"]
1181 |
1182 | namespace MediaQuery
1183 |
1184 |   ||| A media query.
1185 |   |||
1186 |   ||| Note: this is a simplification with no checks.
1187 |   public export
1188 |   data MediaQuery = MkMediaQuery String
1189 |
1190 |   public export
1191 |   Show MediaQuery where
1192 |     show (MkMediaQuery str) = str
1193 |
1194 |   public export
1195 |   mediaQueryValue : String -> Either String MediaQuery
1196 |   mediaQueryValue = Right . MkMediaQuery
1197 |
1198 |   public export
1199 |   fromString : String -> MediaQuery
1200 |   fromString = MkMediaQuery
1201 |
1202 | ||| The **method** attribute value.
1203 | namespace Method
1204 |
1205 |   %runElab mkValueFuncs "MethodValue" ["post" , "get", "dialog"]
1206 |
1207 | ||| The **popover** attribute value.
1208 | namespace Popover
1209 |
1210 |   %runElab mkValueFuncs "PopoverValue" ["auto" , "hint", "manual"]
1211 |
1212 | namespace Referrerpolicy
1213 |
1214 |   %runElab mkValueFuncs "ReferrerpolicyValue"
1215 |     [ "no_referrer"
1216 |     , "no_referrer_when-downgrade"
1217 |     , "origin"
1218 |     , "origin_when_cross_origin"
1219 |     , "same_origin"
1220 |     , "strict_origin"
1221 |     , "strict_origin_when_cross_origin"
1222 |     , "unsafe_url"
1223 |     ]
1224 |
1225 | namespace RegExp
1226 |
1227 |   ||| A regular expression.
1228 |   |||
1229 |   ||| Note: this is a simplification with no checks.
1230 |   public export
1231 |   data RegExp = MkRegExp String
1232 |
1233 |   public export
1234 |   Show RegExp where
1235 |     show (MkRegExp str) = str
1236 |
1237 |   public export
1238 |   regExpValue : String -> Either String RegExp
1239 |   regExpValue = Right . MkRegExp
1240 |
1241 |   public export
1242 |   fromString : String -> RegExp
1243 |   fromString = MkRegExp
1244 |
1245 | ||| The **sandbox** attribute value.
1246 | namespace Sandbox
1247 |
1248 |   %runElab mkValueFuncs "SandboxValue"
1249 |     [ "allow_downloads"
1250 |     , "allow_forms"
1251 |     , "allow_modals"
1252 |     , "allow_orientation_lock"
1253 |     , "allow_pointer_lock"
1254 |     , "allow_popups"
1255 |     , "allow_popups_to_escape_sandbox"
1256 |     , "allow_presentation"
1257 |     , "allow_same_origin"
1258 |     , "allow_scripts"
1259 |     , "allow_top_navigation"
1260 |     , "allow_top_navigation_by_user_activation"
1261 |     , "allow_top_navigation_to_custom_protocols"
1262 |     ]
1263 |
1264 | ||| The **scope** attribute value.
1265 | namespace Scope
1266 |
1267 |   %runElab mkValueFuncs "ScopeValue" ["row" , "col" , "rowgroup" , "colgroup"]
1268 |
1269 | ||| The **shape** attribute value.
1270 | namespace Shape
1271 |
1272 |   %runElab mkValueFuncs "ShapeValue" ["rect" , "circle" , "poly" , "default"]
1273 |
1274 | ||| The **sizes** attribute value.
1275 | namespace Sizes
1276 |
1277 |   public export
1278 |   record SizeValue where
1279 |     constructor MkSize
1280 |     width : Nat
1281 |     height : Nat
1282 |
1283 |   public export
1284 |   Show SizeValue where
1285 |     show size = "\{show size.width}x\{show size.height}"
1286 |
1287 |   public export
1288 |   sizeValue : String -> Either String SizeValue
1289 |   sizeValue str =
1290 |     let
1291 |       parts := break (== 'x') $ toLower str
1292 |       width := fst parts
1293 |       height := strSubstr 1 (strLength $ snd parts) (snd parts)
1294 |     in do
1295 |     x <- case parsePositive width of
1296 |            Nothing => Left $
1297 |              "ERROR: '\{width}' in '\{str}' is not a valid positive integer."
1298 |            Just w => Right w
1299 |     y <- case parsePositive height of
1300 |            Nothing => Left $
1301 |              "ERROR: '\{height}' in '\{str}' is not a valid positive integer."
1302 |            Just h => Right h
1303 |     Right (MkSize x y)
1304 |
1305 |   public export
1306 |   data SizesValue : Type where
1307 |     Any       : SizesValue
1308 |     ListSizes : List1 SizeValue -> SizesValue
1309 |
1310 |   public export
1311 |   Show SizesValue where
1312 |     show Any            = "any"
1313 |     show (ListSizes xs) = unwords $ map show $ toList xs
1314 |
1315 |   public export
1316 |   sizesValue : String -> Either String SizesValue
1317 |   sizesValue "any" = Right Any
1318 |   sizesValue str   =
1319 |     case !(mapM sizeValue $ words str) of
1320 |       []        => Left "ERROR: a list of sizes cannot be empty."
1321 |       (x :: xs) => Right $ ListSizes $ toList1 (x :: xs)
1322 |
1323 |   %runElab mkFromStringFunc "SizesValue"
1324 |
1325 | ||| The **type** attribute value for inputs.
1326 | namespace Type
1327 |
1328 |   %runElab mkValueFuncs "TypeValue"
1329 |     [ "button"
1330 |     , "checkbox"
1331 |     , "color"
1332 |     , "date"
1333 |     , "datetime_local"
1334 |     , "email"
1335 |     , "file"
1336 |     , "hidden"
1337 |     , "image"
1338 |     , "month"
1339 |     , "number"
1340 |     , "password"
1341 |     , "radio"
1342 |     , "range"
1343 |     , "reset"
1344 |     , "search"
1345 |     , "submit"
1346 |     , "tel"
1347 |     , "text"
1348 |     , "time"
1349 |     , "url"
1350 |     , "week"
1351 |     ]
1352 |
1353 | ||| A MIME type value.
1354 | namespace MimeType
1355 |
1356 |   public export
1357 |   record MimeTypeValue where
1358 |     constructor MkMimeTypeValue
1359 |     content : String
1360 |     fileType : String
1361 |
1362 |   public export
1363 |   Show MimeTypeValue where
1364 |     show mimeType = "\{mimeType.content}/\{mimeType.fileType}"
1365 |
1366 |   public export
1367 |   mimeTypeValue : String -> Either String MimeTypeValue
1368 |   mimeTypeValue str =
1369 |     let
1370 |       parts    := break (== '/') $ str
1371 |       content  := fst parts
1372 |       fileType := strSubstr 1 (strLength $ snd parts) (snd parts)
1373 |     in
1374 |     if length fileType > 0
1375 |     then Right (MkMimeTypeValue content fileType)
1376 |     else Left "ERROR: '\{str}' is not a valid MIME type."
1377 |
1378 |   %runElab mkFromStringFunc "MimeTypeValue"
1379 |
1380 | ||| The **type** attribute value for lists.
1381 | namespace NumberingType
1382 |
1383 |   public export
1384 |   data NumberingTypeValue = ALower | AUpper | ILower | IUpper | One
1385 |
1386 |   public export
1387 |   Show NumberingTypeValue where
1388 |     show ALower = "a"
1389 |     show AUpper = "A"
1390 |     show ILower = "i"
1391 |     show IUpper = "I"
1392 |     show One    = "1"
1393 |
1394 |   public export
1395 |   numberingTypeValue : String -> Either String NumberingTypeValue
1396 |   numberingTypeValue "a" = Right ALower
1397 |   numberingTypeValue "A" = Right AUpper
1398 |   numberingTypeValue "i" = Right ILower
1399 |   numberingTypeValue "I" = Right IUpper
1400 |   numberingTypeValue "1" = Right One
1401 |   numberingTypeValue str =
1402 |     Left $ "ERROR: '\{str}' is not a valid numbering type value. "
1403 |         ++ "The possible values are 'a', 'A', 'i', 'I' or '1'."
1404 |
1405 |   %runElab mkFromStringFunc "NumberingTypeValue"
1406 |
1407 | ||| The **type** attribute value for the **script** attribute.
1408 | namespace ScriptType
1409 |
1410 |   public export
1411 |   data ScriptTypeValue = Importmap | Module | Other MimeTypeValue
1412 |
1413 |   public export
1414 |   Show ScriptTypeValue where
1415 |     show Importmap    = "importmap"
1416 |     show Module       = "module"
1417 |     show (Other mime) = show mime
1418 |
1419 |   public export
1420 |   scriptTypeValue : String -> Either String ScriptTypeValue
1421 |   scriptTypeValue "importmap" = Right Importmap
1422 |   scriptTypeValue "module"    = Right Module
1423 |   scriptTypeValue str         = pure $ Other !(mimeTypeValue str)
1424 |
1425 |   %runElab mkFromStringFunc "ScriptTypeValue"
1426 |
1427 | ||| The **wrap** attribute value.
1428 | namespace Wrap
1429 |
1430 |   %runElab mkValueFuncs "WrapValue" ["hard" , "soft"]
1431 |
1432 | namespace Uri
1433 |
1434 |   ||| An URI value.
1435 |   public export
1436 |   record Uri where
1437 |     constructor MkUri
1438 |     value : String
1439 |
1440 |   ||| Naïve implementation accepting any `String` without validation.
1441 |   public export
1442 |   uriValue : String -> Either String Uri
1443 |   uriValue = Right . MkUri
1444 |
1445 |   public export
1446 |   fromString :
1447 |     (str : String)
1448 |     -> {auto 0 prf : IsRight (uriValue str)}
1449 |     -> Uri
1450 |   fromString str = MkUri str
1451 |
1452 |   public export
1453 |   Show Uri where
1454 |     show (MkUri str) = str
1455 |
1456 | namespace Url
1457 |
1458 |   ||| An URL value.
1459 |   public export
1460 |   record Url where
1461 |     constructor MkUrl
1462 |     value : String
1463 |
1464 |   ||| Naïve implementation accepting any `String` without validation.
1465 |   public export
1466 |   urlValue : String -> Either String Url
1467 |   urlValue = Right . MkUrl
1468 |
1469 |   public export
1470 |   fromString :
1471 |     (str : String)
1472 |     -> {auto 0 prf : IsRight (urlValue str)}
1473 |     -> Url
1474 |   fromString str = MkUrl str
1475 |
1476 |   public export
1477 |   Show Url where
1478 |     show (MkUrl str) = str
1479 |
1480 | namespace Urls
1481 |
1482 |   ||| A list of URLs.
1483 |   |||
1484 |   ||| Note: this is a naïve implementation without validation.
1485 |   public export
1486 |   data Urls = MkUrls (List1 Url)
1487 |
1488 |   public export
1489 |   Show Urls where
1490 |     show (MkUrls xs) = unwords $ map show $ toList xs
1491 |
1492 |   ||| Creates a list of URLs.
1493 |   public export
1494 |   urls : String -> Either String Urls
1495 |   urls str =
1496 |     case !(mapM urlValue $ words str) of
1497 |       []        => Left "ERROR: a list of URLs cannot be empty."
1498 |       (x :: xs) => Right $ MkUrls $ toList1 (x :: xs)
1499 |
1500 |   %runElab mkFromStringFunc "Urls"
1501 |
1502 | namespace Urn
1503 |
1504 |   ||| An URN value.
1505 |   public export
1506 |   data Urn = MkUrn String
1507 |
1508 |   public export
1509 |   Show Urn where
1510 |     show (MkUrn str) = str
1511 |
1512 |   ||| Naïve implementation accepting any `String` without validation.
1513 |   public export
1514 |   urnValue : String -> Either String Urn
1515 |   urnValue = Right . MkUrn
1516 |
1517 |   public export
1518 |   fromString :
1519 |     (str : String)
1520 |     -> {auto 0 prf : IsRight (urnValue str)}
1521 |     -> Urn
1522 |   fromString str = MkUrn str
1523 |
1524 | namespace PartialUrl
1525 |
1526 |   ||| A partial URL value starting with `#`.
1527 |   public export
1528 |   data PartialUrl = MkPartialUrl String
1529 |
1530 |   public export
1531 |   Show PartialUrl where
1532 |     show (MkPartialUrl str) = str
1533 |
1534 |   ||| Naïve implementation accepting any `String` starting with `#`.
1535 |   public export
1536 |   partialUrl : String -> Either String PartialUrl
1537 |   partialUrl str =
1538 |     case strSubstr 0 1 str of
1539 |       "#" => Right (MkPartialUrl str)
1540 |       _   => Left
1541 |                $ "ERROR: \{str} is not a valid partial URL, "
1542 |               ++ "which must start with `#`."
1543 |
1544 |   %runElab mkFromStringFunc "PartialUrl"
1545 |
1546 | ||| The **preload** attribute value.
1547 | namespace Preload
1548 |
1549 |   %runElab mkValueFuncs "PreloadValue" ["none" , "metadata", "auto"]
1550 |
1551 | -- Must come after URN and URL.
1552 | namespace Itemid
1553 |
1554 |   ||| An **itemvalue** attribute value.
1555 |   public export
1556 |   data ItemidValue = UrlValue Url | UrnValue Urn
1557 |
1558 |   public export
1559 |   Show ItemidValue where
1560 |     show (UrlValue url) = show url
1561 |     show (UrnValue urn) = show urn
1562 |
1563 |   ||| Naïve implementation accepting any string and always returning an URL.
1564 |   public export
1565 |   itemidValue : String -> Either String ItemidValue
1566 |   itemidValue str = pure $ UrlValue !(urlValue str)
1567 |
1568 |   %runElab mkFromStringFunc "ItemidValue"
1569 |
1570 | ||| The **role** attribute value.
1571 | |||
1572 | ||| Note: only roles considered as useful/relevant are included as per MDN
1573 | ||| documentation[1].
1574 | |||
1575 | ||| [1] : https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Reference/Roles
1576 | namespace Role
1577 |
1578 |   %runElab mkValueFuncs "RoleValue"
1579 |     [
1580 |     -- Document structure roles
1581 |       "toolbar"
1582 |     , "tooltip"
1583 |     , "feed"
1584 |     , "math"
1585 |     , "presentation"
1586 |     , "none"
1587 |     , "note"
1588 |     -- Widget roles
1589 |     , "scrollbar"
1590 |     , "searchbox"
1591 |     , "separator"
1592 |     , "slider"
1593 |     , "spinbutton"
1594 |     , "switch"
1595 |     , "tab"
1596 |     , "tabpanel"
1597 |     , "treeitem"
1598 |     , "combobox"
1599 |     , "menu"
1600 |     , "menubar"
1601 |     , "tablist"
1602 |     , "tree"
1603 |     , "treegrid"
1604 |     -- Landmark roles
1605 |     , "banner"
1606 |     , "complementary"
1607 |     , "contentinfo"
1608 |     , "form"
1609 |     , "main"
1610 |     , "navigation "
1611 |     , "region "
1612 |     , "search"
1613 |     -- Live region roles
1614 |     , "alert"
1615 |     , "log"
1616 |     , "marquee"
1617 |     , "status"
1618 |     , "timer"
1619 |     -- Window roles
1620 |     , "alertdialog"
1621 |     ]
1622 |
1623 | ||| The **srcdoc** attribute value.
1624 | namespace Srcdoc
1625 |
1626 |   ||| This is a naïve implementation without any checks.
1627 |   public export
1628 |   data SrcdocValue = MkSrcdocValue String
1629 |
1630 |   public export
1631 |   Show SrcdocValue where
1632 |     show (MkSrcdocValue str) = str
1633 |
1634 |   public export
1635 |   fromString : String -> SrcdocValue
1636 |   fromString = MkSrcdocValue
1637 |
1638 | namespace Tabindex
1639 |
1640 |   ||| The **tabindex** attribute value.
1641 |   public export
1642 |   data TabindexValue = MinusOne | Zero
1643 |
1644 |   public export
1645 |   Show TabindexValue where
1646 |     show MinusOne = "-1"
1647 |     show Zero     = "0"
1648 |
1649 |   ||| Builds a **tabindex** attribute value from a `String`.
1650 |   |||
1651 |   ||| Only `-1` or `0` are accepted as per [MDN recommendations][1].
1652 |   |||
1653 |   ||| [1]: https://developer.mozilla.org/docs/Web/HTML/Reference/Global_attributes/tabindex
1654 |   public export
1655 |   tabindexValue : String -> Either String TabindexValue
1656 |   tabindexValue "-1" = Right MinusOne
1657 |   tabindexValue "0"  = Right Zero
1658 |   tabindexValue str  = Left $
1659 |        "ERROR: `\{str}` isn't a valid **tabindex** attribute value. "
1660 |     ++ "Only `-1` or `0` should be used."
1661 |
1662 |   %runElab mkFromStringFunc "TabindexValue"
1663 |
1664 | namespace Css
1665 |
1666 |   ||| A CSS styling declaration value for the **style** attribute.
1667 |   |||
1668 |   ||| This is a naïve implementation without any checks.
1669 |   public export
1670 |   data CssValue = MkCssValue String
1671 |
1672 |   public export
1673 |   Show CssValue where
1674 |     show (MkCssValue str) = str
1675 |
1676 |   public export
1677 |   fromString : String -> CssValue
1678 |   fromString = MkCssValue
1679 |
1680 | namespace Href
1681 |
1682 |   ||| A value accepted by the **href** attribute.
1683 |   |||
1684 |   ||| Currently accepted values are:
1685 |   |||
1686 |   ||| - An URL
1687 |   ||| - A document fragment
1688 |   public export
1689 |   data Href : Type where
1690 |     HrefUrl : Url -> Href
1691 |     HrefDocumentFragment : DocumentFragment -> Href
1692 |
1693 |   ||| Returns a **href** value or an error if the provided string isn't valid.
1694 |   |||
1695 |   ||| To be valid, the string must be a valid document fragment or a valid URL.
1696 |   |||
1697 |   ||| > [!WARNING]
1698 |   ||| > No checks are currently implemented for URLs.
1699 |   public export
1700 |   hrefValue : String -> Either String Href
1701 |   hrefValue str =
1702 |     case documentFragment str of
1703 |       Right docF => Right $ HrefDocumentFragment docF
1704 |       Left _     => Right $ HrefUrl (MkUrl str)
1705 |
1706 |   public export
1707 |   fromString :
1708 |        (value : String)
1709 |     -> {auto prf : IsRight (hrefValue value)}
1710 |     -> Href
1711 |   fromString str = fromRight (hrefValue str)
1712 |
1713 |   public export
1714 |   Show Href where
1715 |     show (HrefUrl url) = show url
1716 |     show (HrefDocumentFragment fragment) = show fragment
1717 |
1718 | ||| A **charset** attribute value.
1719 | |||
1720 | ||| The only constructor is `Utf8`, because UTF-8 is the only valid encoding
1721 | ||| for HTML5 documents, see [MDN documentation][1].
1722 | |||
1723 | ||| [1]: https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/meta#charset
1724 | namespace Charset
1725 |
1726 |   %runElab mkValueFuncs "Charset" ["utf_8"]
1727 |
1728 | namespace FileTypes
1729 |
1730 |   ||| List of values for an **accept** attribute.
1731 |   public export
1732 |   record FileTypes where
1733 |     constructor MkFileTypes
1734 |     values : List1 String
1735 |
1736 |   public export
1737 |   FromString FileTypes where
1738 |     fromString = MkFileTypes . split (== ',') . trim
1739 |
1740 | namespace Key
1741 |
1742 |   ||| A single printable character.
1743 |   public export
1744 |   record Key where
1745 |     constructor MkKey
1746 |     char : Char
1747 |
1748 | namespace NonWhitespace
1749 |
1750 |   ||| A non-empty string not only formed by white space characters.
1751 |   public export
1752 |   data NonWhitespace : Type where
1753 |     MkNonWhitespace : (string : String) -> NonWhitespace
1754 |
1755 |   public export
1756 |   nonWhiteSpace : String -> Either String NonWhitespace
1757 |   nonWhiteSpace str =
1758 |     if trim str == ""
1759 |     then Left "ERROR: this string cannot be empty or formed of spaces only."
1760 |     else Right (MkNonWhitespace str)
1761 |
1762 |   public export
1763 |   fromString :
1764 |        (value : String)
1765 |     -> {auto 0 prf : IsRight (nonWhiteSpace value)}
1766 |     -> NonWhitespace
1767 |   fromString str = MkNonWhitespace str
1768 |
1769 |   public export
1770 |   Show NonWhitespace where
1771 |     show (MkNonWhitespace str) = str
1772 |
1773 | ||| A link relation value for the **rel** attribute.
1774 | |||
1775 | ||| Currently, only `Icon` and `Stylesheet` are supported.
1776 | namespace Rel
1777 |
1778 |   %runElab mkValueFuncs "RelValue" ["icon", "stylesheet"]
1779 |
1780 | namespace Language
1781 |
1782 |   ||| A BCP 47 language tag.
1783 |   public export
1784 |   record LanguageTag where
1785 |     constructor MkLanguageTag
1786 |     language : String
1787 |     script: Maybe String
1788 |     region : Maybe String
1789 |
1790 |   public export
1791 |   Show LanguageTag where
1792 |     show (MkLanguageTag language Nothing Nothing) = language
1793 |     show (MkLanguageTag language Nothing (Just region)) =
1794 |       language <+> "-" <+> region
1795 |     show (MkLanguageTag language (Just script) Nothing) =
1796 |       language <+> "-" <+> script
1797 |     show (MkLanguageTag language (Just script) (Just region)) =
1798 |       language <+> "-" <+> script <+> "-" <+> region
1799 |
1800 |   ||| Re-implement split for `List` to return a `List` rather than a `List1`
1801 |   |||
1802 |   ||| This is necessary to avoid name clashes between `List` and `List1`.
1803 |   public export
1804 |   splitList : (a -> Bool) -> List a -> List (List a)
1805 |   splitList p xs =
1806 |     case break p xs of
1807 |       ([], [])             => []
1808 |       (chunk, [])          => singleton chunk
1809 |       (chunk, (c :: rest)) => chunk :: splitList p (assert_smaller xs rest)
1810 |
1811 |   ||| Re-implement split for `String` to return a `List` rather than a `List1`
1812 |   |||
1813 |   ||| This is necessary to avoid name clashes between `List` and `List1`.
1814 |   public export
1815 |   splitStr : (Char -> Bool) -> String -> List String
1816 |   splitStr p xs = map pack (splitList p (unpack xs))
1817 |
1818 |   ||| Check a BCP 47 language tag value.
1819 |   |||
1820 |   ||| At the moment, it only ensures that the provided string has the correct
1821 |   ||| number of parts (1, 2 or 3, separated by a '-').
1822 |   public export
1823 |   bcpValue : String -> Either String LanguageTag
1824 |   bcpValue str =
1825 |     let parts = splitStr (== '-') str in
1826 |     case parts of
1827 |       (x :: [])           => Right (MkLanguageTag x Nothing Nothing)
1828 |       (x :: y :: [])      => if String.length y == 4
1829 |                              then Right $ MkLanguageTag x Nothing (Just y)
1830 |                              else Right $ MkLanguageTag x (Just y) Nothing
1831 |       (x :: y :: z :: []) => Right $ MkLanguageTag x (Just y) (Just z)
1832 |       _                   => Left
1833 |                                ( "ERROR: **\{str}** is not a valid BCP 47 "
1834 |                               ++ "language tag"
1835 |                                )
1836 |
1837 |   public export
1838 |   fromString :
1839 |        (str : String)
1840 |     -> {auto 0 prf : IsRight (bcpValue str)}
1841 |     -> LanguageTag
1842 |   fromString str = fromRight (bcpValue str)
1843 |
1844 | namespace Srcset
1845 |
1846 |   public export
1847 |   data Descriptor = Width Nat | Density Double
1848 |
1849 |   public export
1850 |   Show Descriptor where
1851 |     show (Width n)   = show n ++ "w"
1852 |     show (Density d) = show d ++ "x"
1853 |
1854 |   public export
1855 |   descriptorValue : String -> Either String Descriptor
1856 |   descriptorValue val =
1857 |     let
1858 |       len   = strLength val
1859 |       start = strSubstr 0 (len - 1) val
1860 |       end   = strSubstr (len - 1) len val
1861 |     in
1862 |     case end of
1863 |       "w" => case parsePositive start of
1864 |                Just 0  => Left (eMsgW "0")
1865 |                Just w  => Right $ Width w
1866 |                Nothing => Left (eMsgW start)
1867 |       "x" => case parseDouble start of
1868 |                Just 0  => Left (eMsgX "0")
1869 |                Just x  => if x > 0
1870 |                           then Right $ Density x
1871 |                           else Left $ eMsgX $ show x
1872 |                Nothing => Left (eMsgX start)
1873 |       e   => Left
1874 |                "ERROR: a descriptor must end with 'w' or 'x'.\"\{e}\" provided."
1875 |     where
1876 |       eMsgW : String -> String
1877 |       eMsgW w = "ERROR: width descriptor must be a positive integer; "
1878 |              ++ "\"\{w}\" provided."
1879 |
1880 |       eMsgX : String -> String
1881 |       eMsgX x = "ERROR: pixel density descriptor must be a positive double; "
1882 |              ++ "\"\{x}\" provided."
1883 |
1884 |   ||| A srcset value.
1885 |   public export
1886 |   record SrcsetValue where
1887 |     constructor MkSrcset
1888 |     url        : Url
1889 |     descriptor : Maybe Descriptor
1890 |
1891 |   public export
1892 |   Show SrcsetValue where
1893 |     show (MkSrcset url (Just descriptor)) = show url ++ " " ++ show descriptor
1894 |     show (MkSrcset url Nothing)           = show url
1895 |
1896 |   public export
1897 |   srcsetValue : String -> Either String SrcsetValue
1898 |   srcsetValue val =
1899 |     let srcset = words val in
1900 |     case srcset of
1901 |       (url :: [])               => pure $ MkSrcset !(urlValue url) Nothing
1902 |       (url :: descriptor :: []) => pure $ MkSrcset
1903 |                                      !(urlValue url) (Just $
1904 |                                      !(descriptorValue descriptor))
1905 |       _                         =>
1906 |         Left "ERROR: \"\{val}\" is not a valid **srcset** value."
1907 |
1908 |   public export
1909 |   srcsetValues : String -> Either String (List1 SrcsetValue)
1910 |   srcsetValues val =
1911 |     let vals = map trim $ split (== ',') val in
1912 |     mapM1 srcsetValue vals
1913 |
1914 |   public export
1915 |   fromString :
1916 |        (str : String)
1917 |     -> {auto 0 prf : IsRight (srcsetValues str)}
1918 |     -> List1 SrcsetValue
1919 |   fromString str = fromRight (srcsetValues str)
1920 |
1921 |   public export
1922 |   toString : (List1 SrcsetValue) -> String
1923 |   toString (x ::: []) = show x
1924 |   toString (x ::: xs) = show x ++ ", " ++ toString' xs
1925 |     where
1926 |       toString' : List SrcsetValue -> String
1927 |       toString' [] = ""
1928 |       toString' (x :: []) = show x
1929 |       toString' (x :: xs) = show x ++ ", " ++ toString' xs
1930 |
1931 | namespace Target
1932 |
1933 |   public export
1934 |   data TargetValue =
1935 |       Self
1936 |     | Parent
1937 |     | Top
1938 |     | Blank
1939 |     | XmlName String
1940 |
1941 |   public export
1942 |   Show TargetValue where
1943 |     show Self = "_self"
1944 |     show Parent = "_parent"
1945 |     show Top = "_top"
1946 |     show Blank = "_blank"
1947 |     show (XmlName str) = str
1948 |
1949 |   public export
1950 |   targetValue : String -> Either String TargetValue
1951 |   targetValue "_self"   = Right Self
1952 |   targetValue "_parent" = Right Parent
1953 |   targetValue "_top"    = Right Top
1954 |   targetValue "_blank"  = Right Blank
1955 |   -- TODO: implement proper XML name validation.
1956 |   targetValue str       = if strSubstr 0 0 str /= "_"
1957 |                           then Right (XmlName str)
1958 |                           else Left $
1959 |                                "ERROR: \"\{str}\" provided. The accepted "
1960 |                             <+> "values for the **target** attribute are "
1961 |                             <+> "\"_self\", \"_parent\", \"_top\", \"_blank\", "
1962 |                             <+> "or a valid XML name not starting with \"_\"."
1963 |
1964 |   %runElab mkFromStringFunc "TargetValue"
1965 |
1966 | -- Note: this namespace is on purpose at the end of the module, to prevent
1967 | -- all numbers to become polymorphic.
1968 | namespace PositiveFloat
1969 |
1970 |   public export
1971 |   PositiveDouble : Double -> Bool
1972 |   PositiveDouble x = x > 0
1973 |
1974 |   ||| A positive float number
1975 |   public export
1976 |   record PositiveFloat where
1977 |     constructor MkPositiveFloat
1978 |     -- It's easier to store it as a `Double` as there's the builtin `fromDouble`
1979 |     -- function.
1980 |     value : Double
1981 |     {auto 0 prf : Holds PositiveDouble value}
1982 |
1983 |   public export
1984 |   Show PositiveFloat where
1985 |     show (MkPositiveFloat value) = show value
1986 |
1987 |   ||| Returns a positive value if the provided float is greater than `0`.
1988 |   public export
1989 |   maybe_positiveFloat : Double -> Maybe PositiveFloat
1990 |   maybe_positiveFloat x =
1991 |     case hdec0 {p = Holds PositiveDouble} x of
1992 |       Just0 _  => Just (MkPositiveFloat x)
1993 |       Nothing0 => Nothing
1994 |
1995 |   public export
1996 |   Num PositiveFloat where
1997 |     x + y = case maybe_positiveFloat (x.value + y.value) of
1998 |               Just z  => z
1999 |               Nothing => MkPositiveFloat 1.0
2000 |
2001 |     x * y = case maybe_positiveFloat (x.value * y.value) of
2002 |               Just z  => z
2003 |               Nothing => MkPositiveFloat 1.0
2004 |
2005 |     fromInteger x = case maybe_positiveFloat (fromInteger x) of
2006 |                       Just z  => z
2007 |                       Nothing => MkPositiveFloat 1.0
2008 |
2009 |   public export
2010 |   positiveFloatValue : Double -> Either String PositiveFloat
2011 |   positiveFloatValue x =
2012 |     case maybe_positiveFloat x of
2013 |       Just x  => Right x
2014 |       Nothing => Left "ERROR: \{show x} is not a positive value."
2015 |
2016 |   public export
2017 |   fromDouble : (x : Double)
2018 |              -> {auto 0 prf : IsRight (positiveFloatValue x)}
2019 |              -> PositiveFloat
2020 |   fromDouble x = fromRight (positiveFloatValue x)
2021 |
2022 | -- Note: this namespace is on purpose at the very end of the module, to prevent
2023 | -- all numbers to become polymorphic.
2024 | namespace Positive
2025 |
2026 |   ||| A positive number
2027 |   public export
2028 |   record Positive where
2029 |     constructor MkPositive
2030 |     value : Integer
2031 |     {auto 0 prf : GreaterThan 0 value}
2032 |
2033 |   public export
2034 |   Show Positive where
2035 |     show (MkPositive value) = show value
2036 |
2037 |   ||| Returns a positive value if the provided integer is greater than `0`.
2038 |   public export
2039 |   maybe_positive : Integer -> Maybe Positive
2040 |   maybe_positive x =
2041 |     case hdec0 {p = GreaterThan 0} x of
2042 |       Just0 _  => Just (MkPositive x)
2043 |       Nothing0 => Nothing
2044 |
2045 |   public export
2046 |   positiveValue : Integer -> Either String Positive
2047 |   positiveValue x =
2048 |     case maybe_positive x of
2049 |       Just x  => Right x
2050 |       Nothing => Left "ERROR: \{show x} is not a positive value."
2051 |
2052 |   public export
2053 |   fromInteger : (x : Integer)
2054 |              -> {auto 0 prf : IsRight (positiveValue x)}
2055 |              -> Positive
2056 |   fromInteger x = fromRight (positiveValue x)
2057 |