From edcd4ebfde1d8b721fc75f744a0753773f46d203 Mon Sep 17 00:00:00 2001 From: "byte[]" Date: Sun, 6 Dec 2020 13:04:25 -0500 Subject: [PATCH] automatically apply system-wide theme preference for anonymous users (fixes philomena-dev/philomena#36) --- assets/js/theme.js | 13 +++++++++++++ assets/js/when-ready.js | 4 +++- lib/philomena_web/views/layout_view.ex | 14 ++++++++++++-- 3 files changed, 28 insertions(+), 3 deletions(-) create mode 100644 assets/js/theme.js diff --git a/assets/js/theme.js b/assets/js/theme.js new file mode 100644 index 00000000..5d7ad30a --- /dev/null +++ b/assets/js/theme.js @@ -0,0 +1,13 @@ +/** + * Theme setting + */ + +function setThemeCookie() { + if (window.matchMedia('(prefers-color-scheme: dark)').matches) { + document.cookie = `theme=dark; path=/; max-age=788923800; samesite=lax`; + } else { + document.cookie = `theme=light; path=/; max-age=788923800; samesite=lax`; + } +} + +export { setThemeCookie }; diff --git a/assets/js/when-ready.js b/assets/js/when-ready.js index 4f52a875..6bec6a1f 100644 --- a/assets/js/when-ready.js +++ b/assets/js/when-ready.js @@ -32,6 +32,7 @@ import { setupTimestamps } from './timeago'; import { setupImageUpload } from './upload'; import { setupSearch } from './search'; import { setupToolbar } from './textiletoolbar'; +import { setThemeCookie } from './theme'; import { hideStaffTools } from './staffhider'; import { pollOptionCreator } from './poll'; @@ -63,7 +64,8 @@ whenReady(() => { setupTimestamps(); setupImageUpload(); setupSearch(); - setupToolbar(); + setupToolbar() + setThemeCookie(); hideStaffTools(); pollOptionCreator(); diff --git a/lib/philomena_web/views/layout_view.ex b/lib/philomena_web/views/layout_view.ex index aec16af8..810028d6 100644 --- a/lib/philomena_web/views/layout_view.ex +++ b/lib/philomena_web/views/layout_view.ex @@ -64,14 +64,24 @@ defmodule PhilomenaWeb.LayoutView do Config.get(:footer) end + def stylesheet_path(conn, %{theme: "default"}), + do: Routes.static_path(conn, "/css/default.css") + def stylesheet_path(conn, %{theme: "dark"}), do: Routes.static_path(conn, "/css/dark.css") def stylesheet_path(conn, %{theme: "red"}), do: Routes.static_path(conn, "/css/red.css") - def stylesheet_path(conn, _user), - do: Routes.static_path(conn, "/css/default.css") + def stylesheet_path(conn, _user) do + case conn.cookies do + %{"theme" => "dark"} -> + Routes.static_path(conn, "/css/dark.css") + + _ -> + Routes.static_path(conn, "/css/default.css") + end + end def theme_name(%{theme: theme}), do: theme def theme_name(_user), do: "default"