analytics/lib/plausible_web/components/layout.ex
hq1 9f2f894421
Fix flashing on reapplying theme (#3760)
* Fix flashing on reapplying theme

This seem to be making a difference on staging

* Add `blocking="rendering"` attribute
2024-02-07 09:32:30 +01:00

43 lines
1.3 KiB
Elixir

defmodule PlausibleWeb.Components.Layout do
@moduledoc false
use Phoenix.Component
def theme_script(assigns) do
~H"""
<script blocking="rendering">
(function(){
var themePref = '<%= theme_preference(assigns) %>';
function reapplyTheme() {
var darkMediaPref = window.matchMedia('(prefers-color-scheme: dark)').matches;
var htmlRef = document.querySelector('html');
var hcaptchaRefs = Array.from(document.getElementsByClassName('h-captcha'));
var isDark = themePref === 'dark' || (themePref === 'system' && darkMediaPref);
if (isDark) {
htmlRef.classList.add('dark')
hcaptchaRefs.forEach(function(ref) { ref.dataset.theme = "dark"; });
} else {
htmlRef.classList.remove('dark');
hcaptchaRefs.forEach(function(ref) { ref.dataset.theme = "light"; });
}
}
reapplyTheme();
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', reapplyTheme);
})()
</script>
"""
end
defp theme_preference(%{theme: theme}) when not is_nil(theme), do: theme
defp theme_preference(%{current_user: %Plausible.Auth.User{theme: theme}})
when not is_nil(theme) do
theme
end
defp theme_preference(_assigns), do: "system"
end