~alcinnz/bureaucromancy

ref: 1030d237866bf99999711515fa46dd9fdf729324 bureaucromancy/src/Text/HTML/Form.hs -rw-r--r-- 19.7 KiB
1030d237 — Adrian Cochrane Internationalize form validation. 11 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
{-# LANGUAGE OverloadedStrings, TypeSynonymInstances, FlexibleInstances #-}
-- | Parse webforms out of webpages
module Text.HTML.Form (Form(..), Input(..), OptionGroup(..), Option(..),
    FileSelector(..), defaultFileData, ImageData(..), defaultImageData,
    TextArea(..), defaultTextArea, parseElement, parseDocument, ensureButtons) where

import Data.Text (Text)
import qualified Data.Text as Txt
import Text.XML.Cursor
import Text.XML (Document, Name(..), Node(..))

import Data.Maybe (fromMaybe, listToMaybe, mapMaybe)
import Data.List (singleton)
import Text.Read (readMaybe)
import Data.Function (on)

import Network.URI (parseURIReference, URI, nullURI)
import Text.Regex.TDFA (Regex, defaultCompOpt, defaultExecOpt)
import Text.Regex.TDFA.Text (compile)

-- | A collection of controls intended to be handle by a particular URL endpoint.
data Form = Form {
    -- | The URL which should receive valid input from this form.
    action :: URI,
    -- | How to encode the data to be received by the URL.
    enctype :: Text,
    -- | Which HTTP method to use.
    method :: Text,
    -- | Whether to validate the form data before submitting it to the endpoint.
    validate :: Bool,
    -- | Where to display the response.
    target :: Text,
    -- | Which character sets to encode the data in.
    acceptCharset :: [Text],
    -- | Whether to offer autocompletions for all controls.
    autocomplete :: Bool,
    -- | The name of this form.
    formName :: Text,
    -- | The purpose of this form, typically using an external vocabulary.
    rel :: Text,
    -- | What data should be sent to the endpoint.
    inputs :: [Input],
    -- | Which human language the form is written? To which additional messages should be localized?
    lang :: String
}

-- | Individual piece of data to send to a webservice.
data Input = Input {
    -- Core attributes
    -- | Human-legible yet brief description of this input.
    label :: Text,
    -- | Human-legible longer-form description of this input.
    description :: Node,
    -- | How this control should be presented to the user, supporting all the HTML5 input types.
    -- Support for more types may be added in the future, with any unsupported types
    -- fallingback to text entry.
    inputType :: Text,
    -- | In which query parameter should we store the text direction?
    dirname :: Text,
    -- | In which query parameter should we store this value?
    inputName :: Text,
    -- State
    -- | The user-provided value or caller-provided default to upload to the server.
    value :: Text,
    -- | Whether to autocomplete this input, if its enabled on the form.
    inputAutocomplete :: Text,
    -- | Whether this input has initial focus.
    autofocus :: Bool,
    -- | Whether (for certain types) to upload the data for this input.
    checked :: Bool,
    -- | Whether to temporarily-disallow users from editting this value.
    disabled :: Bool,
    -- | Whether to permanantly-disallow users from editting this value.
    readonly :: Bool,
    -- Input behaviour
    -- | Whether to allow entering multiple values.
    multiple :: Bool,
    -- | If this control is used to submit the form, where to upload it.
    formAction :: Maybe URI,
    -- | If this control is used to submit the form, which text encoding to use in the upload.
    formEnctype :: Maybe Text,
    -- | If this control is used to submit the form, which HTTP method to use.
    formMethod :: Maybe Text,
    -- | If this control is used to submit the form, whether to enforce validation.
    formValidate :: Bool,
    -- | If this control is used to submit the form, where to render the response.
    formTarget :: Maybe Text,
    -- | Suggests which keyboard to use for the input.
    inputMode :: Text,
    -- | Autocompletion values provided by caller.
    list :: [OptionGroup],
    -- Validation
    -- | The minimum & maximum values for the value of this input.
    range :: (Maybe Text, Maybe Text),
    -- | In which period from start do valid values occur?
    step :: Maybe Text,
    -- | The minimum & maximum lengths for the value of this input.
    lengthRange :: (Maybe Int, Maybe Int),
    -- | Optional regex to enforce on the value of this input.
    pattern :: Maybe Regex,
    -- | Whether this control must have a value for it to be considered valid.
    required :: Bool,
    -- Presentation
    -- | Sample value, often visual clarity of its role incurs inaccessibility.
    -- Make sure to communicate what's implied here elsewhere.
    placeholder :: Text,
    -- sort by tabindex?
    -- | Longform clarifications.
    title :: Text,
    -- | How wide the control should be.
    size :: Maybe Int,
    -- | Additional data for inputs of type "file".
    fileData :: FileSelector,
    -- | Additional data for inputs of type "image".
    imageData :: ImageData,
    -- | Additional data for inputs of type "textarea".
    textArea :: TextArea
}
-- | A labelled-group of options, that can be collectively disabled.
data OptionGroup = OptGroup {
    -- | A brief human-legible description of the options on this group.
    optsLabel :: Text,
    -- | Whether these options can be selected.
    optsDisabled :: Bool,
    -- | The options in this group.
    subopts :: [Option]
}
-- | A possible value for an input.
data Option = Option {
    -- | Human-legible text identifying this option.
    optLabel :: Text,
    -- | Machine-legible text identifying this option.
    optValue :: Text,
    -- | Whether the option is selected.
    optSelected :: Bool,
    -- | Whether the option can be selected.
    optDisabled :: Bool
}
-- | Data specific to "file" inputs.
data FileSelector = FileSelector {
    -- | The MIMEtypes of the files which can be validly entered into this control.
    fileAccept :: [Text],
    -- | Whether options for capturing from a camera should be offered.
    fileCapture :: Text
}
-- | Empty values for file data.
defaultFileData :: FileSelector
defaultFileData = FileSelector [] ""
-- | Data specific to "image" inputs.
data ImageData = ImageData {
    -- | Text describing the image, in case the reader can't view it.
    imgAlt :: Maybe Text,
    -- | How much screenspace the image takes up.
    imgSize :: (Maybe Int, Maybe Int),
    -- | The link to the image.
    imgSrc :: Maybe URI
}
-- | Empty values for image data.
defaultImageData :: ImageData
defaultImageData = ImageData Nothing (Nothing, Nothing) Nothing
-- | Data specific to textarea inputs.
data TextArea = TextArea {
    -- | Whether to enable autocorrect.
    autocorrect :: Bool,
    -- | Number of rows to display.
    rows :: Maybe Int,
    -- | Whether to enable spellcheck.
    spellcheck :: Maybe Bool,
    -- | Whether to enable text-wrap.
    textwrap :: Maybe Bool
}
-- | Empty values for textarea data.
defaultTextArea :: TextArea
defaultTextArea = TextArea True Nothing Nothing Nothing

-- | Helper for looking up attributes on a selected element, with fallback.
attr :: Text -> Cursor -> Text -> Text
attr n el def | [ret] <- n `laxAttribute` el = ret
    | otherwise = def
-- | Helper for looking up attributes on a selected element, with fallback & callback.
attr' :: Text -> Cursor -> (Text -> a) -> Text -> a
attr' n el cb def = cb $ attr n el def
-- | Variant of `attr'` which passes which unpacks the callback's argument to a string.
attr'' :: Text -> Cursor -> (String -> a) -> Text -> a
attr'' n el cb def = attr' n el (cb . Txt.unpack) def
-- | Helper for checking whether an attribute is present.
hasAttr :: Name -> Cursor -> Bool
hasAttr n = not . null . hasAttribute n
-- | Helper for looking up an attribute on a selected element if present.
mAttr :: Text -> Cursor -> Maybe Text
mAttr n = listToMaybe . laxAttribute n
-- | Parse a form from the selected HTML element.
parseElement :: Cursor -> Maybe Form
parseElement el | _:_ <- laxElement "form" el = Just Form {
        action = attr'' "action" el (fromMaybe nullURI . parseURIReference) ".",
        enctype = attr "enctype" el "",
        method = attr "method" el "GET",
        validate = null $ hasAttribute "novalidate" el,
        target = attr "target" el "_self",
        acceptCharset = attr' "accept-charset" el Txt.words "utf-8",
        autocomplete = hasAttr "autocomplete" el,
        formName = attr "name" el "",
        rel = attr "rel" el "",
        inputs = mapMaybe parseInput $ queryInputs el,
        lang = Txt.unpack $ attr "lang" el "en"
      }
    | otherwise = Nothing

-- | Helper to retrieve the root node of a document.
root :: Axis
root = singleton . last . orSelf ancestor
-- | Case-insensitive element selection.
laxElements :: [Text] -> Axis
laxElements ns = checkName (\x -> or [
    on (==) Txt.toCaseFold n $ nameLocalName x | n <- ns])
-- | Retrieve all the inputs associated with a form element.
queryInputs :: Cursor -> [Cursor]
queryInputs form = (allInputs >=> inForm) form
  where
    allInputs = root >=> descendant >=> laxElements [
        "input", "textarea", "button", "select"]
    inForm = check (\x ->
        laxAttribute "form" x == laxAttribute "id" form ||
        nestedInForm x)
    nestedInForm x = listToMaybe ((ancestor >=> laxElement "form") x) == Just form
-- | Parse an input from the selected element.
parseInput :: Cursor -> Maybe Input
parseInput el | _:_ <- laxElement "input" el = Just Input {
        label = fromMaybe
                -- Additional fallbacks are primarily for buttons
                (attr "name" el $ attr "value" el $ attr "alt" el $
                attr "type" el "text") $ fmap text label',
        description = fromMaybe (mkEl $ attr "title" el "") $ fmap node $
            elByID (attr "aria-describedby" el "") `orElse` label',
        inputType = attr "type" el "text",
        value = attr "value" el "",
        inputAutocomplete = attr "autocomplete" el "on",
        autofocus = hasAttr "autofocus" el,
        checked = hasAttr "checked" el,
        -- NOTE: No remaining harm in displaying hidden inputs,
        -- might be informative...
        disabled = hasAttr "disabled" el || attr "type" el "" == "hidden",
        readonly = hasAttr "readonly" el || attr "type" el "" == "hidden",
        multiple = hasAttr "multiple" el,
        dirname = attr "dirname" el "",
        inputName = attr "name" el "",
        formAction = if hasAttr "formaction" el
            then attr' "formaction" el (parseURIReference . Txt.unpack) ""
            else Nothing,
        formEnctype = mAttr "formenctype" el,
        formMethod = mAttr "formmethod" el,
        formValidate = not $ hasAttr "formnovalidate" el,
        formTarget = mAttr "formtarget" el,
        inputMode = attr "inputmode" el "text",
        list = fromMaybe [] $ fmap parseOptions (elByID =<< mAttr "list" el),
        range = (mAttr "min" el, mAttr "max" el),
        step = mAttr "step" el,
        lengthRange = (attr'' "minlength" el readMaybe "",
            attr'' "maxLength" el readMaybe ""),
        pattern = attr' "pattern" el
            (rightToMaybe . compile defaultCompOpt defaultExecOpt) ".*",
        required = hasAttr "required" el,
        placeholder = attr "placeholder" el "",
        title = attr "title" el "",
        size = attr'' "size" el readMaybe "",
        fileData = FileSelector {
            fileAccept = attr' "accept" el Txt.words "*",
            fileCapture = attr "capture" el ""
        },
        imageData = ImageData {
            imgAlt = mAttr "alt" el,
            imgSize = (attr'' "width" el readMaybe "",
                attr'' "height" el readMaybe ""),
            imgSrc = attr'' "src" el (parseURIReference) ""
        },
        textArea = defaultTextArea
      }
    | _:_ <- laxElement "textarea" el = Just Input {
        inputType = "<textarea>",
        label = fromMaybe (attr "name" el "") $ fmap text label',
        description = fromMaybe (mkEl $ attr "title" el "") $ fmap node $
            elByID (attr "aria-describedby" el "") `orElse` label',
        value = text el,

        inputAutocomplete = attr "autocomplete" el "on",
        autofocus = hasAttr "autofocus" el,
        size = attr'' "cols" el readMaybe "",
        dirname = attr "dirname" el "",
        disabled = hasAttr "disabled" el,
        lengthRange = (attr'' "minLength" el readMaybe "",
            attr'' "maxLength" el readMaybe ""),
        inputName = attr "name" el "",
        placeholder = attr "placeholder" el "",
        readonly = hasAttr "readonly" el,
        required = hasAttr "required" el,
        title = attr "title" el "",
        inputMode = attr "inputMode" el "text",
        textArea = TextArea {
            autocorrect = attr "autocorrect" el "on" /= "off",
            rows = attr'' "rows" el readMaybe "",
            spellcheck = attr' "spellcheck" el (\x -> case x of
                "true" -> Just True
                "false" -> Just False
                "default" -> Nothing
                _ -> Nothing) "default",
            textwrap = attr' "wrap" el (\x -> case x of
                "hard" -> Just True
                "soft" -> Just False
                "off" -> Nothing
                _ -> Just False) "soft"
        },

        checked = False,
        multiple = True,
        formAction = Nothing,
        formEnctype = Nothing,
        formMethod = Nothing,
        formValidate = False,
        formTarget = Nothing,
        list = [],
        range = (Nothing, Nothing),
        step = Nothing,
        pattern = Nothing,
        fileData = defaultFileData,
        imageData = defaultImageData
    }
    | _:_ <- laxElement "button" el = Just Input {
        -- Fallingback to the input itself as its label allow for
        -- the full richness of its children to be rendered!
        label = fromMaybe (text el) $ fmap text label',
        description = fromMaybe (node el) $ fmap node $
            elByID $ attr "aria-describedby" el "",

        autofocus = hasAttr "autofocus" el,
        disabled = hasAttr "disabled" el,
        formAction = if hasAttr "formaction" el
            then attr' "formaction" el (parseURIReference . Txt.unpack) ""
            else Nothing,
        formEnctype = mAttr "formenctype" el,
        formMethod = mAttr "formmethod" el,
        formValidate = not $ hasAttr "formnovalidate" el,
        formTarget = mAttr "formtarget" el,
        inputName = attr "name" el "",
        -- Popover buttons should be handled by HTML engine, not form engine.
        inputType = attr "type" el "submit",
        value = attr "value" el "",
        title = attr "title" el "",
        -- Placeholder makes sense as a place to put the label...
        placeholder = Txt.concat $ (descendant >=> content) el,

        dirname = "",
        inputAutocomplete = "",
        checked = False, -- Switch to true for the activated button!
        readonly = False,
        multiple = False,
        inputMode = "",
        list = [],
        range = (Nothing, Nothing),
        step = Nothing,
        lengthRange = (Nothing, Nothing),
        pattern = Nothing,
        required = False,
        size = Nothing,
        fileData = defaultFileData,
        imageData = defaultImageData,
        textArea = defaultTextArea
    }
    | _:_ <- laxElement "select" el = Just Input {
        inputType = "<select>",
        label = fromMaybe (attr "name" el "") $ fmap Txt.concat $
            fmap filterSelect label',
        description = fromMaybe (mkEl $ attr "title" el "") $ fmap node $
            elByID $ attr "aria-describedby" el "",

        inputAutocomplete = attr "autocomplete" el "on",
        autofocus = hasAttr "autofocus" el,
        disabled = hasAttr "disabled" el,
        multiple = hasAttr "multiple" el,
        inputName = attr "name" el "",
        required = hasAttr "required" el,
        size = attr'' "size" el readMaybe "",
        list = parseOptions el,
        title = attr "title" el "",

        dirname = "",
        value = "", -- Sourced from list...
        checked = False,
        readonly = False,
        formAction = Nothing,
        formEnctype = Nothing,
        formMethod = Nothing,
        formValidate = False,
        formTarget = Nothing,
        inputMode = "",
        range = (Nothing, Nothing),
        step = Nothing,
        lengthRange = (Nothing, Nothing),
        pattern = Nothing,
        placeholder = "",
        fileData = defaultFileData,
        imageData = defaultImageData,
        textArea = defaultTextArea
      }
    | otherwise = Nothing
  where
    elByAttr k v = listToMaybe $ (root >=> descendant >=> attributeIs k v) el
    elByID = elByAttr "id"
    label' = elByAttr "for" (attr "id" el "") `orElse`
            listToMaybe $ (ancestor >=> laxElement "label") el
    filterSelect = descendant >=>
        checkNot (orSelf ancestor >=> laxElement "select") >=>
        content
-- | Parse the options beneath a selected element.
parseOptions :: Cursor -> [OptionGroup]
parseOptions el = [parseGroup opt
    | opt <- (descendant >=> laxElements ["option", "optgroup"] >=>
        checkNot (parent >=> laxElement "optgroup")) el]
  where
    parseGroup opt
        | _:_ <- laxElement "option" opt =
            OptGroup "" False [parseOption opt False]
        | _:_ <- laxElement "optgroup" opt = OptGroup {
            optsLabel = attr "label" opt "",
            optsDisabled = hasAttr "disabled" opt,
            subopts = [parseOption o $ hasAttr "disabled" opt | o <- child opt]
          }
        | otherwise = OptGroup "" True [] -- Shouldn't happen!
    parseOption opt disabledOverride = Option {
        optLabel = attr "label" opt $ text opt,
        optValue = attr "value" opt $ text opt,
        optSelected = hasAttr "selected" opt,
        optDisabled = hasAttr "disabled" opt || disabledOverride
      }

-- | Parse a named or numerically-indexed form from an HTML document.
parseDocument :: Document -> Text -> Maybe Form
parseDocument doc n
    | Just n' <- readMaybe $ Txt.unpack n, n' < length (forms doc') =
        parseElement (forms doc' !! n')
    | el:_ <- (forms >=> attributeIs "name" n) doc' = parseElement el
    | otherwise = Nothing
  where
    forms = orSelf descendant >=> laxElement "form"
    doc' = fromDocument doc

-- | Helper to select elements which fail a test.
checkNot :: Boolean b => (Cursor -> b) -> Axis
checkNot test = check (not . bool . test)
-- | Helper to maybe-get the right side of an either.
rightToMaybe :: Either a b -> Maybe b
rightToMaybe (Left _)  = Nothing
rightToMaybe (Right x) = Just x
instance Eq Cursor where
    a == b = node a == node b
-- | Helper to return the 1st Just from its 2 arguments.
orElse :: Maybe a -> Maybe a -> Maybe a
orElse ret@(Just _) _ = ret
orElse _ ret = ret
infixr 0 `orElse`
-- | Helper to retrieve the concatenated text under a selected element.
text :: Cursor -> Text
text = Txt.concat . (descendant >=> content)
-- | Concise synonym for an XML text node.
mkEl :: Text -> Node
mkEl = NodeContent

-- | Add submit & reset buttons to a form if they were missing!
ensureButtons :: Form -> Form
ensureButtons = ensureButton "submit" "Submit" . ensureButton "reset" "Reset"
  where
    ensureButton typ label' form
        | any (\x -> inputType x == typ) $ inputs form = form
        | otherwise = form { inputs = inputs form ++ [button typ label'] }
    button typ label' = Input {
        label = label',
        description = mkEl "",
        autofocus = False,
        disabled = False,
        formAction = Nothing,
        formMethod = Nothing,
        formEnctype = Nothing,
        formValidate = True,
        formTarget = Nothing,
        inputName = "",
        inputType = typ,
        value = "",
        title = "",
        placeholder = "",
        dirname = "",
        inputAutocomplete = "",
        checked = False, -- Switch to true for the activated button!
        readonly = False,
        multiple = False,
        inputMode = "",
        list = [],
        range = (Nothing, Nothing),
        step = Nothing,
        lengthRange = (Nothing, Nothing),
        pattern = Nothing,
        required = False,
        size = Nothing,
        fileData = defaultFileData,
        imageData = defaultImageData,
        textArea = defaultTextArea
      }