landing page (#63)

* remove daisyui and rebuild styles

* very basic setup of new design - missing components etc

* basic navbar with reusable landing components

* basic puzzle of the day

* update todos

* update todos

* add curated landing puzzle cards with selectable board (#55)

* update with footer

* add button to solve today's puzzle

* Make landing page a dead view

Render the home page from PageController with a static board preview, link puzzle cards and CTAs to public-code play routes, count puzzles from the DB, and add a global footer.

* Serve a marketing-only JS bundle on the landing page

Build a small marketing entry point with phoenix_html and the plain-DOM navbar, select it on controller-rendered pages, and keep the full LiveView bundle for LiveView pages.

* Add landing page SEO metadata

Replace the Phoenix default title with a descriptive Lucid Chess title, and add description, canonical, Open Graph, and Twitter card tags to the landing page.

* Complete the hero copy block

Add the spark icon primitive and the Endgames, made clear eyebrow. The primary CTA keeps linking to the active puzzle rather than scrolling to the board.

* Add a persisted global daily puzzle

Assign one endgame per UTC day in a daily_puzzles table with a unique date, preferring endgames unused in the last 30 days and falling back to any. Concurrent first requests insert with on-conflict-ignore and read the winning row. The landing board now shows the daily puzzle.

* remove unused CSS, nav links, time pill

* allow devices to connect to dev server by changing IP address to 0.0.0.0

* Restore the colour-mode switch and add a dark palette

* Use brand colour tokens on the play page

* self host fonts  - closes issue #62

* begin splitting CSS into modules

* remove hover on hero chessboard, split more css modules

* remove interactivity from hero chessboard

* update todo
This commit is contained in:
2026-11-05 13:52:14 +01:00
committed by GitHub
parent fd6277ef92
commit 93806b9ab2
60 changed files with 2253 additions and 11028 deletions
@@ -8,12 +8,10 @@ defmodule ChesstrainerWeb.CoreComponents do
with doc strings and declarative assigns. You may customize and style
them in any way you want, based on your application growth and needs.
The foundation for styling is Tailwind CSS, a utility-first CSS framework,
augmented with daisyUI, a Tailwind CSS plugin that provides UI components
and themes. Here are useful references:
* [daisyUI](https://daisyui.com/docs/intro/) - a good place to get
started and see the available components.
The foundation for styling is Tailwind CSS, a utility-first CSS framework.
Semantic colors such as `base-100`, `base-content` and `primary` are defined
in `assets/css/app.css` and switch with the `data-theme` attribute. Here are
useful references:
* [Tailwind CSS](https://tailwindcss.com) - the foundational framework
we build on. You will use it for layout, sizing, flexbox, grid, and
@@ -31,6 +29,24 @@ defmodule ChesstrainerWeb.CoreComponents do
alias Phoenix.LiveView.JS
@input_class "w-full rounded-md border border-base-300 bg-base-100 px-3 py-2 text-sm text-base-content placeholder:text-base-content/50 focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/30"
@input_error_class "border-error focus:border-error focus:ring-error/30"
@label_class "mb-1 block text-sm font-medium text-base-content"
@checkbox_class "size-4 rounded border-base-300 accent-primary"
defp input_class, do: @input_class
defp input_error_class, do: @input_error_class
defp label_class, do: @label_class
defp checkbox_class, do: @checkbox_class
@table_class "w-full border-collapse text-left text-sm [&_th]:border-b [&_th]:border-base-200 [&_th]:px-4 [&_th]:py-3 [&_th]:font-semibold [&_td]:border-b [&_td]:border-base-200 [&_td]:px-4 [&_td]:py-3 [&_tbody_tr:nth-child(odd)]:bg-base-200/50"
@doc """
Returns the shared data-table classes, for tables that render their own
`<thead>`/`<tbody>` markup.
"""
def table_class, do: @table_class
@doc """
Renders flash notices.
@@ -63,13 +79,13 @@ defmodule ChesstrainerWeb.CoreComponents do
id={@id}
phx-click={JS.push("lv:clear-flash", value: %{key: @kind}) |> hide("##{@id}")}
role="alert"
class="toast toast-top toast-end z-50"
class="fixed right-4 top-4 z-50 flex flex-col gap-2"
{@rest}
>
<div class={[
"alert w-80 sm:w-96 max-w-80 sm:max-w-96 text-wrap",
@kind == :info && "alert-info",
@kind == :error && "alert-error"
"flex w-80 max-w-80 items-start gap-3 rounded-lg border px-4 py-3 text-sm text-wrap shadow-lg sm:w-96 sm:max-w-96",
@kind == :info && "border-info bg-info text-info-content",
@kind == :error && "border-error bg-error text-error-content"
]}>
<.icon :if={@kind == :info} name="hero-information-circle" class="size-5 shrink-0" />
<.icon :if={@kind == :error} name="hero-exclamation-circle" class="size-5 shrink-0" />
@@ -97,16 +113,24 @@ defmodule ChesstrainerWeb.CoreComponents do
"""
attr :rest, :global, include: ~w(href navigate patch method download name value disabled)
attr :class, :any
attr :variant, :string, values: ~w(primary)
attr :variant, :string, values: ~w(primary secondary ghost danger)
slot :inner_block, required: true
def button(%{rest: rest} = assigns) do
variants = %{"primary" => "btn-primary", nil => "btn-primary btn-soft"}
variants = %{
"primary" => "bg-primary text-primary-content hover:bg-primary/90",
"secondary" => "border border-base-300 bg-base-100 text-base-content hover:bg-base-200",
"ghost" => "text-base-content hover:bg-base-200",
"danger" => "bg-error text-error-content hover:bg-error/90",
nil => "bg-primary/15 text-primary hover:bg-primary/25"
}
assigns =
assign_new(assigns, :class, fn ->
["btn", Map.fetch!(variants, assigns[:variant])]
end)
assign(assigns, :class, [
"inline-flex items-center justify-center gap-2 rounded-md px-4 py-2 text-sm font-semibold transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed disabled:opacity-60",
Map.fetch!(variants, assigns[:variant]),
assigns[:class]
])
if rest[:href] || rest[:navigate] || rest[:patch] do
~H"""
@@ -181,8 +205,11 @@ defmodule ChesstrainerWeb.CoreComponents do
attr :prompt, :string, default: nil, doc: "the prompt for select inputs"
attr :options, :list, doc: "the options to pass to Phoenix.HTML.Form.options_for_select/2"
attr :multiple, :boolean, default: false, doc: "the multiple flag for select inputs"
attr :class, :any, default: nil, doc: "the input class to use over defaults"
attr :error_class, :any, default: nil, doc: "the input error class to use over defaults"
attr :class, :any, default: nil, doc: "extra classes merged with the default input classes"
attr :error_class, :any,
default: nil,
doc: "extra classes merged with the default error classes"
attr :rest, :global,
include: ~w(accept autocomplete capture cols disabled form list max maxlength min minlength
@@ -212,8 +239,8 @@ defmodule ChesstrainerWeb.CoreComponents do
end)
~H"""
<div class="fieldset mb-2">
<label for={@id}>
<div class="mb-3">
<label for={@id} class="flex items-center gap-2">
<input
type="hidden"
name={@name}
@@ -221,17 +248,16 @@ defmodule ChesstrainerWeb.CoreComponents do
disabled={@rest[:disabled]}
form={@rest[:form]}
/>
<span class="label">
<input
type="checkbox"
id={@id}
name={@name}
value="true"
checked={@checked}
class={@class || "checkbox checkbox-sm"}
{@rest}
/>{@label}
</span>
<input
type="checkbox"
id={@id}
name={@name}
value="true"
checked={@checked}
class={[checkbox_class(), @class]}
{@rest}
/>
<span class="text-sm text-base-content">{@label}</span>
</label>
<.error :for={msg <- @errors}>{msg}</.error>
</div>
@@ -240,13 +266,17 @@ defmodule ChesstrainerWeb.CoreComponents do
def input(%{type: "select"} = assigns) do
~H"""
<div class="fieldset mb-2">
<div class="mb-3">
<label for={@id}>
<span :if={@label} class="label mb-1">{@label}</span>
<span :if={@label} class={label_class()}>{@label}</span>
<select
id={@id}
name={@name}
class={[@class || "w-full select", @errors != [] && (@error_class || "select-error")]}
class={[
input_class(),
@errors != [] && (@error_class || input_error_class()),
@class
]}
multiple={@multiple}
{@rest}
>
@@ -261,15 +291,16 @@ defmodule ChesstrainerWeb.CoreComponents do
def input(%{type: "textarea"} = assigns) do
~H"""
<div class="fieldset mb-2">
<div class="mb-3">
<label for={@id}>
<span :if={@label} class="label mb-1">{@label}</span>
<span :if={@label} class={label_class()}>{@label}</span>
<textarea
id={@id}
name={@name}
class={[
@class || "w-full textarea",
@errors != [] && (@error_class || "textarea-error")
input_class(),
@errors != [] && (@error_class || input_error_class()),
@class
]}
{@rest}
>{Phoenix.HTML.Form.normalize_value("textarea", @value)}</textarea>
@@ -282,17 +313,18 @@ defmodule ChesstrainerWeb.CoreComponents do
# All other inputs text, datetime-local, url, password, etc. are handled here...
def input(assigns) do
~H"""
<div class="fieldset mb-2">
<div class="mb-3">
<label for={@id}>
<span :if={@label} class="label mb-1">{@label}</span>
<span :if={@label} class={label_class()}>{@label}</span>
<input
type={@type}
name={@name}
id={@id}
value={Phoenix.HTML.Form.normalize_value(@type, @value)}
class={[
@class || "w-full input",
@errors != [] && (@error_class || "input-error")
input_class(),
@errors != [] && (@error_class || input_error_class()),
@class
]}
{@rest}
/>
@@ -367,7 +399,7 @@ defmodule ChesstrainerWeb.CoreComponents do
end
~H"""
<table class="table table-zebra">
<table class={table_class()}>
<thead>
<tr>
<th :for={col <- @col}>{col[:label]}</th>
@@ -414,17 +446,49 @@ defmodule ChesstrainerWeb.CoreComponents do
def list(assigns) do
~H"""
<ul class="list">
<li :for={item <- @item} class="list-row">
<div class="list-col-grow">
<div class="font-bold">{item.title}</div>
<div>{render_slot(item)}</div>
<ul class="divide-y divide-base-200">
<li :for={item <- @item} class="flex gap-3 py-3">
<div class="flex-1 space-y-1">
<div class="font-semibold">{item.title}</div>
<div class="text-sm text-base-content/70">{render_slot(item)}</div>
</div>
</li>
</ul>
"""
end
@doc """
Renders a small pill label.
## Examples
<.badge>Lucena</.badge>
<.badge color="primary" size="sm">KR v K</.badge>
"""
attr :color, :string, default: "neutral", values: ~w(neutral primary warning)
attr :size, :string, default: "md", values: ~w(sm md)
attr :class, :any, default: nil
attr :rest, :global
slot :inner_block, required: true
def badge(assigns) do
~H"""
<span
class={[
"inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium",
@size == "sm" && "px-1.5 text-[0.7rem]",
@color == "neutral" && "bg-base-200 text-base-content",
@color == "primary" && "bg-primary/15 text-primary",
@color == "warning" && "bg-warning/15 text-warning",
@class
]}
{@rest}
>
{render_slot(@inner_block)}
</span>
"""
end
@doc """
Renders a [Heroicon](https://heroicons.com).
+24 -15
View File
@@ -129,7 +129,7 @@ defmodule ChesstrainerWeb.EndgameList do
~H"""
<div class="mb-6 space-y-3">
<div :if={@selected_themes != []} class="flex flex-wrap gap-2">
<span :for={theme <- @selected_themes} class="badge badge-primary gap-1">
<.badge :for={theme <- @selected_themes} color="primary">
{theme.name}
<button
type="button"
@@ -139,24 +139,30 @@ defmodule ChesstrainerWeb.EndgameList do
>
×
</button>
</span>
</.badge>
</div>
<div class="flex flex-col gap-3 sm:flex-row">
<form id="theme-filter-form" phx-change="search_themes" class="flex-1">
<input
type="text"
<.input
name="theme_search"
value={@theme_query}
phx-debounce="200"
autocomplete="off"
placeholder="Filter by theme…"
class="input input-bordered w-full"
/>
<ul :if={@theme_results != []} class="menu bg-base-100 rounded-box mt-2">
<ul
:if={@theme_results != []}
class="mt-2 w-full rounded-md border border-base-300 bg-base-100 p-1 shadow-sm"
>
<li :for={theme <- @theme_results}>
<button type="button" phx-click="add_theme" phx-value-id={theme.id}>
<button
type="button"
phx-click="add_theme"
phx-value-id={theme.id}
class="block w-full rounded px-3 py-2 text-left text-sm hover:bg-base-200"
>
{theme.name}
</button>
</li>
@@ -164,12 +170,13 @@ defmodule ChesstrainerWeb.EndgameList do
</form>
<form id="key-filter-form" phx-change="filter_key" class="flex-1">
<select name="key" class="select w-full">
<option value="" selected={is_nil(@selected_key)}>All keys</option>
<option :for={key <- @keys} value={key} selected={key == @selected_key}>
{key}
</option>
</select>
<.input
type="select"
name="key"
prompt="All keys"
options={@keys}
value={@selected_key}
/>
</form>
</div>
@@ -202,7 +209,9 @@ defmodule ChesstrainerWeb.EndgameList do
>
<span class="font-semibold">{group.key}</span>
<span class="flex items-center gap-2 text-sm">
<span class="badge">{group.count}</span>
<.badge id={"key-group-count-" <> String.replace(group.key, " ", "-")}>
{group.count}
</.badge>
<.icon
name={if group.expanded, do: "hero-chevron-down", else: "hero-chevron-right"}
class="size-4"
@@ -210,7 +219,7 @@ defmodule ChesstrainerWeb.EndgameList do
</span>
</button>
<table :if={group.expanded} class="table table-zebra">
<table :if={group.expanded} class={table_class()}>
<thead>
{render_slot(@header)}
</thead>
@@ -0,0 +1,328 @@
defmodule ChesstrainerWeb.LandingComponents do
@moduledoc """
Presentational primitives for the marketing landing page.
Kept separate from `ChesstrainerWeb.CoreComponents`: the landing page uses a
distinct pill-button language, while CoreComponents provides the compact
admin and auth UI.
"""
use Phoenix.Component
alias Chesstrainer.FEN
alias Chesstrainer.Themes
@button_variants %{
nav: "nav-cta",
primary: "primary-button",
light: "light-button"
}
@files ~w(a b c d e f g h)
@piece_glyphs %{
"K" => "♔",
"Q" => "♕",
"R" => "♖",
"B" => "♗",
"N" => "♘",
"P" => "♙",
"k" => "♚",
"q" => "♛",
"r" => "♜",
"b" => "♝",
"n" => "♞",
"p" => "♟"
}
@fallback_fen "8/5k2/8/3K4/8/6R1/8/8 w - - 0 1"
@doc """
Renders a landing-page pill button.
Renders a link when given `href`, `navigate`, or `patch`; otherwise a button.
## Examples
<.pill_button variant={:nav} href="/#trainer">Start training</.pill_button>
<.pill_button variant={:primary} phx-click="go">Go</.pill_button>
"""
attr :rest, :global, include: ~w(href navigate patch method type disabled)
attr :variant, :atom, values: [:nav, :primary, :light], default: :nav
attr :class, :any, default: nil
slot :inner_block, required: true
def pill_button(%{rest: rest} = assigns) do
assigns =
assign(assigns, :class, [Map.fetch!(@button_variants, assigns.variant), assigns.class])
if rest[:href] || rest[:navigate] || rest[:patch] do
~H"""
<.link class={@class} {@rest}>
{render_slot(@inner_block)}
</.link>
"""
else
~H"""
<button class={@class} {@rest}>
{render_slot(@inner_block)}
</button>
"""
end
end
@doc """
Renders a static board preview for the landing page.
Accepts an endgame map with `:fen`, `:color` and `:key`; falls back to a
neutral position when no endgame is given. For an interactive board inside a
LiveView, use `board_grid/1` directly.
"""
attr :endgame, :map, default: nil
def board_preview(assigns) do
endgame = assigns.endgame
assigns =
assign(assigns,
fen: fen_for(endgame),
turn: turn_label(endgame),
title: title(endgame),
themes: theme_names(endgame),
orientation: orientation(endgame)
)
~H"""
<div class="board-shell">
<div class="board-topline">
<div class="player">
<span class="player-piece dark-piece">♚</span>
<span>
<small>To move</small>
<strong>{@turn}</strong>
</span>
</div>
</div>
<.board_grid fen={@fen} orientation={@orientation} />
<div class="board-caption">
<div>
<span>Today’s position</span>
<strong>{@title}</strong>
<small :if={@themes != []} class="board-themes">{Enum.join(@themes, " · ")}</small>
</div>
</div>
</div>
"""
end
@doc """
Renders the squares of a chess position.
Set `interactive` inside a LiveView to emit `phx-click="square"` events with
`phx-value-square` (for example `"e4"`). `selected` and `targets` are square
keys in algebraic notation.
"""
attr :fen, :string, required: true
attr :orientation, :atom, values: [:white, :black], default: :white
attr :selected, :string, default: nil
attr :targets, :list, default: []
attr :interactive, :boolean, default: false
attr :disabled, :boolean, default: false
attr :target, :any, default: nil
def board_grid(assigns) do
rows = FEN.board(assigns.fen) || FEN.board(@fallback_fen)
squares = board_squares(rows, assigns.orientation, assigns.selected, assigns.targets)
assigns = assign(assigns, :squares, squares)
~H"""
<div class="chessboard" aria-label="Chess position">
<%= for square <- @squares do %>
<div class={[
"square",
if(square.light, do: "light", else: "dark"),
square.selected? && "selected",
square.target? && "target"
]}>
<span :if={square.label_rank} class="rank">{square.rank}</span>
<span :if={square.label_file} class="file">{square.file}</span>
<span
:if={square.piece}
class={["piece", if(square.white, do: "white-piece", else: "black-piece")]}
>
{square.glyph}
</span>
</div>
<% end %>
</div>
"""
end
@doc """
Renders a curated endgame card for the landing-page grid.
The card links straight to the puzzle's player-facing play route.
"""
attr :endgame, :map, required: true
attr :index, :integer, required: true
attr :active, :boolean, default: false
def puzzle_card(assigns) do
~H"""
<.link
navigate={"/endgames/#{@endgame.public_code}/play"}
class={["puzzle-card", @active && "active"]}
>
<span class="card-number">{card_number(@index)}</span>
<span class="mini-piece">{mini_piece(@endgame)}</span>
<span class="difficulty">{difficulty(@endgame.rating)}</span>
<strong>{title(@endgame)}</strong>
<small>{meta(@endgame)}</small>
<span class="card-arrow"><.icon_arrow /></span>
</.link>
"""
end
@doc """
Formats the puzzle count for the landing-page stat.
Counts below 100 are shown exactly. Larger counts are floored to the nearest
hundred or thousand and suffixed with `+`, so the claim is never overstated.
"""
def puzzle_count_label(count) when is_integer(count) and count < 100 do
Integer.to_string(count)
end
def puzzle_count_label(count) when is_integer(count) and count < 1000 do
"#{div(count, 100) * 100}+"
end
def puzzle_count_label(count) when is_integer(count) do
"#{div(count, 1000) * 1000}+"
end
@doc "The spark used by the landing-page eyebrow."
def icon_spark(assigns) do
~H"""
<svg aria-hidden="true" viewBox="0 0 20 20" fill="none">
<path
d="M10 1.75c.33 3.25 1.85 4.77 5.1 5.1-3.25.33-4.77 1.85-5.1 5.1-.33-3.25-1.85-4.77-5.1-5.1 3.25-.33 4.77-1.85 5.1-5.1Z"
fill="currentColor"
/>
<path
d="M15.25 11.5c.18 1.8.95 2.57 2.75 2.75-1.8.18-2.57.95-2.75 2.75-.18-1.8-.95-2.57-2.75-2.75 1.8-.18 2.57-.95 2.75-2.75Z"
fill="currentColor"
/>
</svg>
"""
end
@doc "The arrow used by landing-page CTAs."
def icon_arrow(assigns) do
~H"""
<svg aria-hidden="true" viewBox="0 0 20 20" fill="none">
<path
d="M4 10h11m-4.5-4.5L15 10l-4.5 4.5"
stroke="currentColor"
stroke-width="1.7"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
"""
end
defp board_squares(rows, orientation, selected, targets) do
rows
|> Enum.with_index()
|> Enum.flat_map(fn {row, r} ->
row
|> Enum.with_index()
|> Enum.map(fn {piece, c} ->
rank = 8 - r
file = Enum.at(@files, c)
key = "#{file}#{rank}"
%{
key: key,
rank: rank,
file: file,
file_index: c,
light: rem(c + rank, 2) == 0,
piece: piece,
glyph: piece_glyph(piece),
white: piece != nil and piece == String.upcase(piece),
selected?: selected == key,
target?: key in targets,
label_rank: (orientation == :black and c == 7) or (orientation != :black and c == 0),
label_file:
(orientation == :black and rank == 8) or (orientation != :black and rank == 1)
}
end)
end)
|> Enum.sort_by(&display_key(&1, orientation))
end
defp display_key(square, :black), do: {square.rank - 1, 7 - square.file_index}
defp display_key(square, _orientation), do: {8 - square.rank, square.file_index}
defp piece_glyph(nil), do: nil
defp piece_glyph(piece), do: Map.get(@piece_glyphs, piece)
defp square_label(%{piece: piece} = square) when is_binary(piece) do
"#{square.key}, #{square.glyph}"
end
defp square_label(square), do: square.key
defp fen_for(%{fen: fen}) when is_binary(fen), do: fen
defp fen_for(_endgame), do: @fallback_fen
defp turn_label(:black), do: "Black"
defp turn_label(:white), do: "White"
defp turn_label(%{color: color}), do: turn_label(color)
defp turn_label(%{fen: fen}) when is_binary(fen), do: turn_label(FEN.color_from_fen(fen))
defp turn_label(_endgame), do: "White"
defp title(%{key: key}) when is_binary(key) and key != "", do: key
defp title(%{message: message}) when is_binary(message) and message != "", do: message
defp title(_endgame), do: "Featured position"
defp theme_names(%{themes: themes}) when is_list(themes), do: Themes.names(themes)
defp theme_names(_endgame), do: []
defp orientation(%{color: color}) when color in [:white, :black], do: color
defp orientation(_endgame), do: :white
defp card_number(index), do: (index + 1) |> Integer.to_string() |> String.pad_leading(2, "0")
defp mini_piece(%{key: key}) when is_binary(key) do
cond do
String.contains?(key, "Q") -> "♛"
String.contains?(key, "R") -> "♖"
String.contains?(key, "B") -> "♗"
String.contains?(key, "N") -> "♘"
true -> "♙"
end
end
defp mini_piece(_endgame), do: "♙"
defp difficulty(rating) when is_number(rating) and rating < 1600, do: "Beginner"
defp difficulty(rating) when is_number(rating) and rating < 1900, do: "Intermediate"
defp difficulty(_rating), do: "Advanced"
defp meta(%{themes: themes, rating: rating}) when is_list(themes) do
case Themes.names(themes) do
[] -> rating_label(rating)
names -> Enum.join(names, " · ")
end
end
defp meta(%{rating: rating}), do: rating_label(rating)
defp rating_label(nil), do: "Unrated"
defp rating_label(rating), do: "Rating #{round(rating)}"
end
+137 -50
View File
@@ -52,57 +52,125 @@ defmodule ChesstrainerWeb.Layouts do
@doc """
Renders the application navbar.
The marketing and account links are defined once in `nav_links/1` and rendered
in both the desktop bar and the mobile menu. Edit that list to change what
appears in either place.
"""
attr :current_scope, :map,
default: nil,
doc: "the current [scope](https://phoenix.hexdocs.pm/scopes.html)"
def navbar(assigns) do
assigns = assign(assigns, :nav_links, nav_links(assigns.current_scope))
~H"""
<header class="navbar px-4 sm:px-6 lg:px-8">
<div class="flex-1">
<a href="/" class="flex-1 flex w-fit items-center gap-2">
<img src={~p"/images/logo.svg"} width="36" />
<span class="text-sm font-semibold">v{Application.spec(:phoenix, :vsn)}</span>
<header>
<nav class="nav-wrap" aria-label="Main navigation">
<a class="brand" href="/" aria-label="Lucid Chess home">
<span class="brand-mark">♞</span>
<span>LUCID</span>
</a>
</div>
<div class="flex-none">
<ul class="flex flex-column px-1 space-x-4 items-center">
<li>
<a href="/endgames" class="btn btn-ghost">Endgames</a>
</li>
<li :if={@current_scope && Role.admin?(@current_scope.user.role)}>
<a href="/admin/endgames" class="btn btn-ghost">Admin</a>
</li>
<li>
<.theme_toggle />
</li>
<%= if @current_scope do %>
<li>
<span class="text-sm">{@current_scope.user.username}</span>
</li>
<li>
<.link navigate={~p"/users/settings"} class="btn btn-ghost">Settings</.link>
</li>
<li>
<.link href={~p"/users/log-out"} method="delete" class="btn btn-ghost">
Log out
</.link>
</li>
<% else %>
<li>
<.link navigate={~p"/users/register"} class="btn btn-ghost">Register</.link>
</li>
<li>
<.link navigate={~p"/users/log-in"} class="btn btn-primary">Log in</.link>
</li>
<% end %>
</ul>
</div>
<div class="nav-right">
<.colour_mode_toggle />
<button
class="menu-button"
type="button"
aria-expanded="false"
aria-controls="nav-links"
aria-label="Toggle menu"
>
<span></span>
<span></span>
</button>
<div class="nav-links" id="nav-links">
<%= for link <- @nav_links do %>
<%= if link[:kind] == :text do %>
<span class="nav-user">{link.label}</span>
<% else %>
<.link href={link.href} method={link[:method]}>{link.label}</.link>
<% end %>
<% end %>
<.pill_button variant={:nav} href="/endgames">
Start training <.icon_arrow />
</.pill_button>
</div>
</div>
</nav>
</header>
"""
end
defp nav_links(scope) do
marketing = [
%{label: "Puzzle Search", href: "/#puzzles"}
]
admin =
if admin?(scope) do
[%{label: "Admin", href: ~p"/admin/endgames"}]
else
[]
end
account =
case scope do
%{user: %{username: username}} ->
[
%{label: username, kind: :text},
%{label: "Settings", href: ~p"/users/settings"},
%{label: "Log out", href: ~p"/users/log-out", method: "delete"}
]
_ ->
[
%{label: "Log in", href: ~p"/users/log-in"},
%{label: "Register", href: ~p"/users/register"}
]
end
marketing ++ admin ++ account
end
defp admin?(%{user: %{role: role}}), do: Role.admin?(role)
defp admin?(_scope), do: false
@doc """
Renders the site-wide footer.
Rendered once from the root layout so it appears on every page, matching the
navbar. Links to the landing-page anchors keep working from other pages
because they point at `/` first.
"""
def footer(assigns) do
assigns = assign(assigns, :year, DateTime.utc_now().year)
~H"""
<footer class="site-footer">
<div class="footer-brand">
<a class="brand" href="/" aria-label="Lucid Chess home">
<span class="brand-mark">♞</span>
<span>LUCID</span>
</a>
<p>Short, focused endgame training.</p>
</div>
<nav class="footer-links" aria-label="Footer">
<a href="/#method">Method</a>
<a href="/#puzzles">Puzzles</a>
<a href="/#progress">Progress</a>
<a href={~p"/endgames"}>Endgames</a>
</nav>
<small>© {@year} Lucid Chess</small>
</footer>
"""
end
@doc """
Shows the flash group with standard titles and content.
@@ -153,35 +221,54 @@ defmodule ChesstrainerWeb.Layouts do
end
@doc """
Provides dark vs light theme toggle based on themes defined in app.css.
Provides the system / light / dark colour-mode switch.
See <head> in root.html.heex which applies the theme before page load.
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).
"""
def theme_toggle(assigns) do
def colour_mode_toggle(assigns) do
~H"""
<div class="card relative flex flex-row items-center border-2 border-base-300 bg-base-300 rounded-full">
<div class="absolute w-1/3 h-full rounded-full border-1 border-base-200 bg-base-100 brightness-200 left-0 [[data-theme=light]_&]:left-1/3 [[data-theme=dark]_&]:left-2/3 [[data-theme-source=system]_&]:!left-0 transition-[left]" />
<div
class="relative flex flex-row items-center rounded-full border-2 border-base-300 bg-base-300"
role="radiogroup"
aria-label="Colour mode"
>
<div
class="absolute w-1/3 h-full rounded-full border border-base-200 bg-base-100 brightness-200 left-0 [[data-theme=light]_&]:left-1/3 [[data-theme=dark]_&]:left-2/3 [[data-theme-source=system]_&]:!left-0 transition-[left]"
aria-hidden="true"
>
</div>
<button
class="flex p-2 cursor-pointer w-1/3"
phx-click={JS.dispatch("phx:set-theme")}
type="button"
class="flex p-2 cursor-pointer w-1/3 justify-center rounded-full focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary"
data-phx-theme="system"
role="radio"
aria-checked="true"
aria-label="System colour mode"
>
<.icon name="hero-computer-desktop-micro" class="size-4 opacity-75 hover:opacity-100" />
</button>
<button
class="flex p-2 cursor-pointer w-1/3"
phx-click={JS.dispatch("phx:set-theme")}
type="button"
class="flex p-2 cursor-pointer w-1/3 justify-center rounded-full focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary"
data-phx-theme="light"
role="radio"
aria-checked="false"
aria-label="Light colour mode"
>
<.icon name="hero-sun-micro" class="size-4 opacity-75 hover:opacity-100" />
</button>
<button
class="flex p-2 cursor-pointer w-1/3"
phx-click={JS.dispatch("phx:set-theme")}
type="button"
class="flex p-2 cursor-pointer w-1/3 justify-center rounded-full focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary"
data-phx-theme="dark"
role="radio"
aria-checked="false"
aria-label="Dark colour mode"
>
<.icon name="hero-moon-micro" class="size-4 opacity-75 hover:opacity-100" />
</button>
@@ -3,37 +3,135 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="csrf-token" content={get_csrf_token()} />
<.live_title default="Chesstrainer" suffix=" · Phoenix Framework" phx-no-format>{assigns[:page_title]}</.live_title>
<link phx-track-static rel="stylesheet" href={~p"/assets/css/app.css"} />
<script defer phx-track-static type="text/javascript" src={~p"/assets/js/app.js"}>
<meta name="csrf-token" content={get_csrf_token()} />
<.live_title
default="Lucid Chess — Endgame Trainer"
suffix={assigns[:title_suffix] || " · Lucid Chess"}
phx-no-format
>{assigns[:page_title]}</.live_title>
<meta
:if={assigns[:meta_description]}
name="description"
content={assigns[:meta_description]}
/>
<link :if={assigns[:canonical_url]} rel="canonical" href={assigns[:canonical_url]} />
<meta :if={assigns[:meta_description]} property="og:type" content="website" />
<meta :if={assigns[:meta_description]} property="og:site_name" content="Lucid Chess" />
<meta
:if={assigns[:meta_description]}
property="og:title"
content={assigns[:page_title] || "Lucid Chess — Endgame Trainer"}
/>
<meta
:if={assigns[:meta_description]}
property="og:description"
content={assigns[:meta_description]}
/>
<meta :if={assigns[:canonical_url]} property="og:url" content={assigns[:canonical_url]} />
<meta :if={assigns[:meta_description]} name="twitter:card" content="summary" />
<meta
:if={assigns[:meta_description]}
name="twitter:title"
content={assigns[:page_title] || "Lucid Chess — Endgame Trainer"}
/>
<meta
:if={assigns[:meta_description]}
name="twitter:description"
content={assigns[:meta_description]}
/>
<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={assigns[:js_entry] || ~p"/assets/js/app.js"}
>
</script>
<script>
(() => {
const systemTheme = () => matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
const systemMode = () => matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
const setTheme = (theme) => {
if (theme === "system") {
localStorage.removeItem("phx:theme");
document.documentElement.setAttribute("data-theme", systemTheme());
document.documentElement.setAttribute("data-theme-source", "system");
} else {
localStorage.setItem("phx:theme", theme);
document.documentElement.setAttribute("data-theme", theme);
document.documentElement.setAttribute("data-theme-source", "user");
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.
}
};
if (!document.documentElement.hasAttribute("data-theme")) {
setTheme(localStorage.getItem("phx:theme") || "system");
}
window.addEventListener("storage", (e) => e.key === "phx:theme" && setTheme(e.newValue || "system"));
window.addEventListener("phx:set-theme", (e) => setTheme(e.target.dataset.phxTheme));
matchMedia("(prefers-color-scheme: dark)").addEventListener("change", (e) => {
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", systemTheme());
document.documentElement.setAttribute("data-theme", systemMode());
}
});
})();
@@ -42,5 +140,6 @@
<body>
<Layouts.navbar current_scope={@current_scope} />
{@inner_content}
<Layouts.footer />
</body>
</html>