1
1
import "@hotwired/turbo-rails" ;
2
2
import {
3
3
createAll ,
4
+ isSupported ,
4
5
Button ,
5
6
Checkboxes ,
6
7
ErrorSummary ,
@@ -15,14 +16,71 @@ import { UpgradedRadios as Radios } from "./components/radios.js";
15
16
// Configure Turbo
16
17
Turbo . session . drive = false ;
17
18
18
- // Initiate NHS.UK frontend components on page load
19
+ /**
20
+ * Check if component has been initialised
21
+ *
22
+ * @param {string } moduleName - Name of component module
23
+ * @returns {boolean } Whether component is already initialised
24
+ */
25
+ function isInitialised ( moduleName ) {
26
+ return document . querySelector ( `[data-${ moduleName } -init]` ) !== null ;
27
+ }
28
+
29
+ /**
30
+ * Initialise components
31
+ *
32
+ * We need to check if components have already been initialised because Turbo
33
+ * may have initialised them on a previous page (pre-)load.
34
+ */
35
+ function initializeComponents ( ) {
36
+ if ( ! isSupported ( ) ) {
37
+ document . body . classList . add ( "nhsuk-frontend-supported" ) ;
38
+ }
39
+
40
+ if ( ! isInitialised ( "app-autocomplete" ) ) {
41
+ createAll ( Autocomplete ) ;
42
+ }
43
+
44
+ if ( ! isInitialised ( "nhsuk-button" ) ) {
45
+ createAll ( Button , { preventDoubleClick : true } ) ;
46
+ }
47
+
48
+ if ( ! isInitialised ( "nhsuk-checkboxes" ) ) {
49
+ createAll ( Checkboxes ) ;
50
+ }
51
+
52
+ if ( ! isInitialised ( "nhsuk-error-summary" ) ) {
53
+ createAll ( ErrorSummary ) ;
54
+ }
55
+
56
+ if ( ! isInitialised ( "nhsuk-header" ) ) {
57
+ createAll ( Header ) ;
58
+ }
59
+
60
+ if ( ! isInitialised ( "nhsuk-radios" ) ) {
61
+ createAll ( Radios ) ;
62
+ }
63
+
64
+ if ( ! isInitialised ( "nhsuk-notification-banner" ) ) {
65
+ createAll ( NotificationBanner ) ;
66
+ }
67
+
68
+ if ( ! isInitialised ( "nhsuk-skip-link" ) ) {
69
+ createAll ( SkipLink ) ;
70
+ }
71
+ }
72
+
73
+ // Initiate components once page has loaded
19
74
document . addEventListener ( "DOMContentLoaded" , ( ) => {
20
- createAll ( Autocomplete ) ;
21
- createAll ( Button , { preventDoubleClick : true } ) ;
22
- createAll ( Checkboxes ) ;
23
- createAll ( ErrorSummary ) ;
24
- createAll ( Header ) ;
25
- createAll ( Radios ) ;
26
- createAll ( NotificationBanner ) ;
27
- createAll ( SkipLink ) ;
75
+ initializeComponents ( ) ;
76
+ } ) ;
77
+
78
+ // Reinitialize components when Turbo loads (and preloads) a page
79
+ document . addEventListener ( "turbo:load" , ( ) => {
80
+ initializeComponents ( ) ;
81
+ } ) ;
82
+
83
+ // Reinitialize components when Turbo morphs a page
84
+ document . addEventListener ( "turbo:morph" , ( ) => {
85
+ initializeComponents ( ) ;
28
86
} ) ;
0 commit comments