1+ import { Component , ElementError } from 'nhsuk-frontend'
2+
13import setSubmit from './set-submit.js'
24
35/**
46 * Enhance an HTML form to intercept submit events and instead fetch the form action URL.
57 * If successful, show child elements with data-show-on-submit, and hide those with data-hide-on-submit.
68 * If unsuccessful, or the fetch times out, force a page refresh.
79 */
8- class CheckIn {
10+ export class CheckIn extends Component {
911 /**
10- * @param {Element | null } [ $root] - HTML element to use for component
12+ * @param {Element | null } $root - HTML element to use for component
1113 */
1214 constructor ( $root ) {
13- if ( ! $root || ! ( $root instanceof HTMLElement ) ) {
14- throw new Error ( 'CheckIn initialised without a root element' )
15- }
15+ super ( $root )
1616
17- const $form = $root . querySelector ( 'form' )
17+ const $form = this . $root . querySelector ( 'form' )
1818 if ( ! $form ) {
19- throw new Error ( 'CheckIn initialised without a form element' )
19+ throw new ElementError ( {
20+ element : $root ,
21+ component : CheckIn ,
22+ identifier : 'Form element (`$form`)'
23+ } )
2024 }
2125
22- this . $root = $root
2326 this . $form = $form
24- this . $showOnSubmit = $root . querySelectorAll ( '[data-show-on-submit]' )
25- this . $hideOnSubmit = $root . querySelectorAll ( '[data-hide-on-submit]' )
27+ this . $showOnSubmit = this . $root . querySelectorAll ( '[data-show-on-submit]' )
28+ this . $hideOnSubmit = this . $root . querySelectorAll ( '[data-hide-on-submit]' )
2629
2730 const showResult = this . showResult . bind ( this )
2831
@@ -44,19 +47,9 @@ class CheckIn {
4447 this . $hideOnSubmit . forEach ( ( $elem ) => $elem . setAttribute ( 'hidden' , '' ) )
4548 this . $showOnSubmit . forEach ( ( $elem ) => $elem . removeAttribute ( 'hidden' ) )
4649 }
47- }
48-
49- /**
50- * Initialise check in component
51- *
52- * @param {object } [options]
53- * @param {Element | Document | null } [options.scope] - Scope of the document to search within
54- */
55- export function initCheckIn ( options = { } ) {
56- const $scope = options . scope || document
57- const $elements = $scope . querySelectorAll ( '[data-module="app-check-in"]' )
5850
59- $elements . forEach ( ( $root ) => {
60- new CheckIn ( $root )
61- } )
51+ /**
52+ * Name for the component used when initialising using data-module attributes
53+ */
54+ static moduleName = 'app-check-in'
6255}
0 commit comments