Module: Daisy::ThemeHelper
- Defined in:
- app/helpers/daisy/theme_helper.rb
Instance Method Summary collapse
-
#theme_preload_script ⇒ String
Returns an inline script that preloads the saved theme from localStorage to prevent a flash of content when the page loads.
Instance Method Details
#theme_preload_script ⇒ String
Returns an inline script that preloads the saved theme from localStorage to prevent a flash of content when the page loads.
This script runs synchronously in the head section before the page
renders. It resolves the saved theme mode (light / dark pin that
scheme; system follows the OS preference) and the matching per-scheme
theme preference, then sets the data-theme, data-color-scheme, and
data-theme-mode attributes on the html element. The legacy single
savedTheme key is still honored until the ThemeController migrates
it.
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 |
# File 'app/helpers/daisy/theme_helper.rb', line 27 def theme_preload_script " <script>\n (function() {\n try {\n var mode = localStorage.getItem('savedThemeMode');\n var theme = null;\n var slot = null;\n var colorScheme = null;\n\n if (mode) {\n slot = mode === 'system'\n ? (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')\n : mode;\n theme = localStorage.getItem(slot === 'dark' ? 'savedDarkTheme' : 'savedLightTheme') || slot;\n\n // A slot may hold a theme of the OTHER scheme (a dark theme\n // as the daytime choice); its actual scheme was cached at\n // save time since CSS isn't loaded yet to compute it.\n colorScheme = localStorage.getItem(slot === 'dark' ? 'savedDarkScheme' : 'savedLightScheme') || slot;\n } else {\n // Legacy single-theme key; the ThemeController migrates it to\n // the per-slot model on connect.\n theme = localStorage.getItem('savedTheme');\n }\n\n if (theme) {\n document.documentElement.setAttribute('data-theme', theme);\n }\n if (colorScheme) {\n document.documentElement.setAttribute('data-color-scheme', colorScheme);\n }\n if (mode) {\n document.documentElement.setAttribute('data-theme-mode', mode);\n }\n } catch (e) {\n // localStorage not available (e.g., private browsing mode)\n }\n })();\n </script>\n SCRIPT\nend\n".html_safe |