|
| 1 | +/* |
| 2 | + * Lighthouse only runs the theme checking function on load if a user is using |
| 3 | + * a dark theme. This change modifies the check to _always_ pass regardless of |
| 4 | + * theme preference. |
| 5 | + * |
| 6 | + * This ensures we always run the function on load, where we add additional |
| 7 | + * custom logic to test if a preferred theme was set as a querystring parameter, |
| 8 | + * falling back to a standard dark theme check. |
| 9 | + */ |
| 10 | +const forceThemeChecking = { |
| 11 | + source: `(prefers-color-scheme: dark)`, |
| 12 | + replacement: `(prefers-color-scheme)`, |
| 13 | +}; |
| 14 | + |
| 15 | +/* |
| 16 | + * Relative line numbers of the replacements: |
| 17 | + * 1. Ensure original source line is retained |
| 18 | + * 2-3. We only want to trigger this on first run. This function is also run |
| 19 | + * each time the theme is manually toggled using the dropdown menu and |
| 20 | + * we don't want to interfere. |
| 21 | + * 4. Check the URL querystring for a light/dark theme preference. |
| 22 | + * 5-7. If we recognise the value, use it to set/remove the theme class. |
| 23 | + * 8-9. We made a change to the Lighthouse-supplied matchMedia check which |
| 24 | + * runs on page load, to always trigger this function regardless of theme. |
| 25 | + * This means we can't rely on the second parameter being passed to this |
| 26 | + * function being accurate. If we make it this far, we need to run our own |
| 27 | + * check to replicate that original functionality. |
| 28 | + */ |
| 29 | +const enableQuerystringThemeCheck = { |
| 30 | + source: `const n=e.rootEl;`, |
| 31 | + replacement: `const n=e.rootEl; |
| 32 | + if (!window.qsThemeChecked) { |
| 33 | + window.qsThemeChecked = true; |
| 34 | + const qsTheme = new URLSearchParams(window.location.search).get('theme'); |
| 35 | + if (qsTheme === 'dark' || qsTheme === 'light') { |
| 36 | + return n.classList.toggle('lh-dark', qsTheme === 'dark'); |
| 37 | + } |
| 38 | + const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches; |
| 39 | + return n.classList.toggle('lh-dark', prefersDark); |
| 40 | + }`, |
| 41 | +}; |
| 42 | + |
| 43 | +const replacements = [forceThemeChecking, enableQuerystringThemeCheck]; |
| 44 | + |
| 45 | +const makeReplacements = (str) => { |
| 46 | + return replacements.reduce((acc, { source, replacement }) => { |
| 47 | + return acc.replace(source, replacement); |
| 48 | + }, str); |
| 49 | +}; |
| 50 | + |
| 51 | +module.exports = { makeReplacements }; |
0 commit comments