Skip to content

Commit 55ece37

Browse files
Ensure components are initiated when a page uses Turbo
1 parent f5822c8 commit 55ece37

File tree

1 file changed

+67
-9
lines changed

1 file changed

+67
-9
lines changed
Lines changed: 67 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import "@hotwired/turbo-rails";
22
import {
33
createAll,
4+
isSupported,
45
Button,
56
Checkboxes,
67
ErrorSummary,
@@ -15,14 +16,71 @@ import { UpgradedRadios as Radios } from "./components/radios.js";
1516
// Configure Turbo
1617
Turbo.session.drive = false;
1718

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 initialiseComponents() {
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
1974
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+
initialiseComponents();
76+
});
77+
78+
// Reinitialize components when Turbo loads (and preloads) a page
79+
document.addEventListener("turbo:load", () => {
80+
initialiseComponents();
81+
});
82+
83+
// Reinitialize components when Turbo morphs a page
84+
document.addEventListener("turbo:morph", () => {
85+
initialiseComponents();
2886
});

0 commit comments

Comments
 (0)