404 and 500 drafts

This commit is contained in:
2026-11-06 15:42:52 +01:00
parent b17f346b25
commit 785e403370
14 changed files with 335 additions and 95 deletions
+4 -3
View File
@@ -239,9 +239,10 @@ defmodule ChesstrainerWeb.Layouts do
@doc """
Provides the system / light / dark colour-mode switch.
The click handling and `aria-checked` syncing live in the script in
`root.html.heex`, which runs before paint and also on pages without LiveView
(the landing page uses the marketing bundle).
The click handling and `aria-checked` syncing live in `theme_script.html.heex`,
which runs before paint and also on pages without LiveView (the landing page
uses the marketing bundle). Error pages include it explicitly because they do
not render through the root layout.
"""
def colour_mode_toggle(assigns) do
~H"""
@@ -3,6 +3,7 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta :if={assigns[:noindex]} name="robots" content="noindex" />
<meta name="csrf-token" content={get_csrf_token()} />
<.live_title
@@ -63,79 +64,7 @@
src={assigns[:js_entry] || ~p"/assets/js/app.js"}
>
</script>
<script>
(() => {
const systemMode = () => matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
const storedMode = () => {
try { return localStorage.getItem("phx:theme"); } catch (_) { return null; }
};
const persistMode = (mode) => {
try {
if (mode === "system") localStorage.removeItem("phx:theme");
else localStorage.setItem("phx:theme", mode);
} catch (_) {
// Storage can be blocked (private modes, embedded browsers); the
// mode still applies for this page load.
}
};
const selectedMode = () => {
const source = document.documentElement.getAttribute("data-theme-source");
return source === "system" ? "system" : document.documentElement.getAttribute("data-theme");
};
const syncChecked = () => {
document.querySelectorAll("[data-phx-theme]").forEach((button) => {
button.setAttribute("aria-checked", String(button.dataset.phxTheme === selectedMode()));
});
};
const setMode = (mode) => {
if (mode !== "system" && mode !== "light" && mode !== "dark") return;
if (mode === "system") {
persistMode("system");
document.documentElement.setAttribute("data-theme", systemMode());
document.documentElement.setAttribute("data-theme-source", "system");
} else {
persistMode(mode);
document.documentElement.setAttribute("data-theme", mode);
document.documentElement.setAttribute("data-theme-source", "user");
}
syncChecked();
};
if (!document.documentElement.hasAttribute("data-theme")) {
setMode(storedMode() || "system");
}
document.addEventListener("DOMContentLoaded", syncChecked);
// Plain DOM so the switch also works on controller-rendered pages
// (the landing page ships no LiveView runtime).
document.addEventListener("click", (event) => {
const button = event.target instanceof Element && event.target.closest("[data-phx-theme]");
if (button) setMode(button.dataset.phxTheme);
});
window.addEventListener("storage", (event) => {
if (event.key === "phx:theme") setMode(event.newValue || "system");
});
window.addEventListener("phx:set-theme", (event) => {
setMode(event.target?.dataset?.phxTheme);
});
matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => {
if (document.documentElement.getAttribute("data-theme-source") === "system") {
document.documentElement.setAttribute("data-theme", systemMode());
}
});
})();
</script>
<Layouts.theme_script />
</head>
<body>
<Layouts.navbar current_scope={@current_scope} />
@@ -0,0 +1,73 @@
<script>
(() => {
const systemMode = () => matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
const storedMode = () => {
try { return localStorage.getItem("phx:theme"); } catch (_) { return null; }
};
const persistMode = (mode) => {
try {
if (mode === "system") localStorage.removeItem("phx:theme");
else localStorage.setItem("phx:theme", mode);
} catch (_) {
// Storage can be blocked (private modes, embedded browsers); the
// mode still applies for this page load.
}
};
const selectedMode = () => {
const source = document.documentElement.getAttribute("data-theme-source");
return source === "system" ? "system" : document.documentElement.getAttribute("data-theme");
};
const syncChecked = () => {
document.querySelectorAll("[data-phx-theme]").forEach((button) => {
button.setAttribute("aria-checked", String(button.dataset.phxTheme === selectedMode()));
});
};
const setMode = (mode) => {
if (mode !== "system" && mode !== "light" && mode !== "dark") return;
if (mode === "system") {
persistMode("system");
document.documentElement.setAttribute("data-theme", systemMode());
document.documentElement.setAttribute("data-theme-source", "system");
} else {
persistMode(mode);
document.documentElement.setAttribute("data-theme", mode);
document.documentElement.setAttribute("data-theme-source", "user");
}
syncChecked();
};
if (!document.documentElement.hasAttribute("data-theme")) {
setMode(storedMode() || "system");
}
document.addEventListener("DOMContentLoaded", syncChecked);
// Plain DOM so the switch also works on controller-rendered pages
// (the landing page ships no LiveView runtime).
document.addEventListener("click", (event) => {
const button = event.target instanceof Element && event.target.closest("[data-phx-theme]");
if (button) setMode(button.dataset.phxTheme);
});
window.addEventListener("storage", (event) => {
if (event.key === "phx:theme") setMode(event.newValue || "system");
});
window.addEventListener("phx:set-theme", (event) => {
setMode(event.target?.dataset?.phxTheme);
});
matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => {
if (document.documentElement.getAttribute("data-theme-source") === "system") {
document.documentElement.setAttribute("data-theme", systemMode());
}
});
})();
</script>
+38 -11
View File
@@ -3,21 +3,48 @@ defmodule ChesstrainerWeb.ErrorHTML do
This module is invoked by your endpoint in case of errors on HTML requests.
See config/config.exs.
Error templates are rendered outside the root layout, so `404.html.heex` and
`500.html.heex` each render a complete document. They share the body markup
through `error_page/1`, which the catch-all 404 route also uses.
"""
use ChesstrainerWeb, :html
# If you want to customize your error pages,
# uncomment the embed_templates/1 call below
# and add pages to the error directory:
#
# * lib/chesstrainer_web/controllers/error_html/404.html.heex
# * lib/chesstrainer_web/controllers/error_html/500.html.heex
#
# embed_templates "error_html/*"
embed_templates "error_html/*"
# The default is to render a plain text page based on
# the template name. For example, "404.html" becomes
# "Not Found".
@doc """
The body shared by the standalone error pages and the catch-all 404 route.
Rendered inside the root layout by `PageController.not_found/2`, and directly
by the `ErrorHTML` templates, which bypass layouts.
"""
attr :status, :integer, required: true
attr :title, :string, required: true
attr :message, :string, required: true
attr :hint, :string, default: nil
attr :puzzles, :boolean, default: true
def error_page(assigns) do
~H"""
<main class="error-page">
<span class="error-code">{@status}</span>
<h1>{@title}</h1>
<p>{@message}</p>
<p :if={@hint} class="error-hint">{@hint}</p>
<div class="error-actions">
<.pill_button variant={:primary} href={~p"/"}>
Back to home <.icon_arrow />
</.pill_button>
<.pill_button :if={@puzzles} variant={:light} href={~p"/endgames"}>
Browse puzzles
</.pill_button>
</div>
</main>
"""
end
# Statuses without a template keep the previous plain-text behaviour.
def render(template, _assigns) do
Phoenix.Controller.status_message_from_template(template)
end
@@ -0,0 +1,40 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="robots" content="noindex" />
<title>{Branding.title("Page not found")}</title>
<link phx-track-static rel="stylesheet" href={~p"/assets/css/app.css"} />
<link
rel="preload"
href="/fonts/dm-sans-variable.woff2"
as="font"
type="font/woff2"
crossorigin
/>
<link
rel="preload"
href="/fonts/dm-serif-display.woff2"
as="font"
type="font/woff2"
crossorigin
/>
<script defer phx-track-static type="text/javascript" src={~p"/assets/js/marketing.js"}>
</script>
<Layouts.theme_script />
</head>
<body>
<Layouts.navbar current_scope={assigns[:current_scope]} />
<.error_page
status={404}
title="This page isn't on the board"
message="The page you were looking for moved, or never existed. Check the address, or head back to the trainer."
/>
<Layouts.footer />
</body>
</html>
@@ -0,0 +1,41 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="robots" content="noindex" />
<title>{Branding.title("Something went wrong")}</title>
<link phx-track-static rel="stylesheet" href={~p"/assets/css/app.css"} />
<link
rel="preload"
href="/fonts/dm-sans-variable.woff2"
as="font"
type="font/woff2"
crossorigin
/>
<link
rel="preload"
href="/fonts/dm-serif-display.woff2"
as="font"
type="font/woff2"
crossorigin
/>
<script defer phx-track-static type="text/javascript" src={~p"/assets/js/marketing.js"}>
</script>
<Layouts.theme_script />
</head>
<body>
<Layouts.navbar current_scope={assigns[:current_scope]} />
<.error_page
status={500}
title="Something went wrong"
message="An unexpected error stopped this page from loading. It's on us, not you — please try again in a moment."
hint={"If it keeps happening, email #{Branding.support_email()}."}
/>
<Layouts.footer />
</body>
</html>
@@ -12,6 +12,14 @@ defmodule ChesstrainerWeb.ErrorJSON do
# %{errors: %{detail: "Internal Server Error"}}
# end
def render("404.json", _assigns) do
%{errors: %{detail: "Not Found"}}
end
def render("500.json", _assigns) do
%{errors: %{detail: "Internal Server Error"}}
end
# By default, Phoenix returns the status message from
# the template name. For example, "404.json" becomes
# "Not Found".
@@ -49,4 +49,14 @@ defmodule ChesstrainerWeb.PageController do
|> assign(:canonical_url, current_url(conn))
|> render(:terms_conditions)
end
def not_found(conn, _params) do
conn
|> put_status(:not_found)
|> assign(:js_entry, ~p"/assets/js/marketing.js")
|> assign(:page_title, Branding.title("Page not found"))
|> assign(:title_suffix, "")
|> assign(:noindex, true)
|> render(:not_found)
end
end
@@ -0,0 +1,7 @@
<Layouts.flash_group flash={@flash} />
<ChesstrainerWeb.ErrorHTML.error_page
status={404}
title="This page isn't on the board"
message="The page you were looking for moved, or never existed. Check the address, or head back to the trainer."
/>
+8
View File
@@ -93,4 +93,12 @@ defmodule ChesstrainerWeb.Router do
post "/users/log-in", UserSessionController, :create
delete "/users/log-out", UserSessionController, :delete
end
# Keep this last: routes match in definition order. It gives unmatched paths a
# branded 404 page with the site chrome instead of Phoenix's bare status page.
scope "/", ChesstrainerWeb do
pipe_through :browser
match :*, "/*path", PageController, :not_found
end
end