Accessibility: keyboard move entry and screen reader support (#72) (#115)

* commented out lesson and learning strip until lessons are established

* reword the hero section

* change layout and working on puzzle section - remove top div as it was
redundant

* amend flash message on replay

* switch cancel session for return home

* remove system theme toggle since this is the default, leaving only light
and dark toggles

* add keyboard and screen reader support for play (#72)

First draft covering the accessibility work in #72:\n\n- labelled SAN/UCI move input, validated against the tablebase and applied\n  by the board hook, plus an accessible promotion picker\n- live-region announcements for moves, checks, checkmates and solve/fail,\n  and a hidden text summary of the position\n- accessible labels, focus ring, skip link, keyboard-friendly review table\n  and non-colour grade cues\n- WCAG AA text contrast roles and a responsive play surface\n- regression tests for move entry, announcements and link-style CTAs
This commit is contained in:
2026-11-09 12:09:07 +01:00
committed by GitHub
parent 8df7ac982c
commit 805c2f1150
31 changed files with 812 additions and 136 deletions
+4
View File
@@ -16,6 +16,10 @@
} }
button, a { -webkit-tap-highlight-color: transparent; } button, a { -webkit-tap-highlight-color: transparent; }
button { cursor: pointer; } button { cursor: pointer; }
/* A consistent focus ring for links, buttons and native controls. Components
that provide their own ring (form inputs) override this through utilities. */
:focus-visible { outline: 2px solid var(--color-coral-text); outline-offset: 2px; }
} }
main { overflow: hidden; flex: 1 0 auto; } main { overflow: hidden; flex: 1 0 auto; }
+8 -2
View File
@@ -10,8 +10,11 @@
--color-coral: var(--coral); --color-coral: var(--coral);
--color-coral-control: var(--coral); --color-coral-control: var(--coral);
--color-coral-control-hover: var(--coral-dark); --color-coral-control-hover: var(--coral-dark);
--color-coral-text: var(--coral-dark); --color-coral-text: #b8432c;
--color-success-text: var(--mint-deep); --color-success-text: #3f6d5a;
--color-warning-text: #8a5a00;
--color-primary-text: #b8432c;
--color-error-text: #b8432c;
--color-mint-chip: var(--mint); --color-mint-chip: var(--mint);
--color-on-accent-muted: #5f2c23; --color-on-accent-muted: #5f2c23;
@@ -71,6 +74,9 @@ html[data-theme="dark"] {
--color-coral-control-hover: #b8432c; --color-coral-control-hover: #b8432c;
--color-coral-text: #ff9c85; --color-coral-text: #ff9c85;
--color-success-text: #8fd3b5; --color-success-text: #8fd3b5;
--color-warning-text: #f0b35a;
--color-primary-text: #f2816b;
--color-error-text: #f2816b;
--color-mint-chip: #24403a; --color-mint-chip: #24403a;
--color-on-accent-muted: rgba(255, 255, 255, 0.97); --color-on-accent-muted: rgba(255, 255, 255, 0.97);
--color-promotion-surface: #1b2822; --color-promotion-surface: #1b2822;
+7
View File
@@ -39,3 +39,10 @@
/* Admin Chessboard */ /* Admin Chessboard */
.bg-boardwhite { background-color: #f2f5f3; /* light square */ } .bg-boardwhite { background-color: #f2f5f3; /* light square */ }
.bg-boardblack { background-color: #71828f; /* dark square */ } .bg-boardblack { background-color: #71828f; /* dark square */ }
/* Play board */
#endgame-board { position: relative; }
/* Chessground's wrapper has no intrinsic height; let it fill the sized
aspect-ratio container so the board scales with the viewport. */
#endgame-board .cg-wrap { width: 100%; height: 100%; }
+77 -4
View File
@@ -22,7 +22,20 @@ export const ChessBoard = {
this.applyBestLineMove({ from, to, promotion, san }); this.applyBestLineMove({ from, to, promotion, san });
}); });
this.handleEvent("apply_move", ({ from, to, promotion }) => {
if (this.reviewing) return;
this.executeMove(from, to, promotion);
});
this.handleKeyDown = (event) => { this.handleKeyDown = (event) => {
if (this.pendingPromotion) {
if (event.key === "Escape") {
event.preventDefault();
this.cancelPromotion();
}
return;
}
if (!this.reviewing) return; if (!this.reviewing) return;
if (event.key === "ArrowLeft") { if (event.key === "ArrowLeft") {
@@ -31,6 +44,12 @@ export const ChessBoard = {
} else if (event.key === "ArrowRight") { } else if (event.key === "ArrowRight") {
event.preventDefault(); event.preventDefault();
this.pushEvent("review_next", {}); this.pushEvent("review_next", {});
} else if (event.key === "Home") {
event.preventDefault();
this.pushEvent("review_start", {});
} else if (event.key === "End") {
event.preventDefault();
this.pushEvent("review_end", {});
} }
}; };
@@ -185,9 +204,13 @@ export const ChessBoard = {
showPromotionDialog(orig, dest) { showPromotionDialog(orig, dest) {
this.pendingPromotion = { orig, dest }; this.pendingPromotion = { orig, dest };
this.previousFocus = document.activeElement;
const color = this.chess.turn() === "w" ? "white" : "black"; const color = this.chess.turn() === "w" ? "white" : "black";
const overlay = document.createElement("div"); const overlay = document.createElement("div");
overlay.className = "promotion-overlay"; overlay.className = "promotion-overlay";
overlay.setAttribute("role", "dialog");
overlay.setAttribute("aria-modal", "true");
overlay.setAttribute("aria-label", "Choose a promotion piece");
const picker = document.createElement("div"); const picker = document.createElement("div");
picker.className = "promotion-picker"; picker.className = "promotion-picker";
const pieces = [ const pieces = [
@@ -198,22 +221,64 @@ export const ChessBoard = {
]; ];
pieces.forEach(({ type, code }) => { pieces.forEach(({ type, code }) => {
const btn = document.createElement("button"); const btn = document.createElement("button");
btn.type = "button";
btn.className = `promotion-piece ${type} ${color}`; btn.className = `promotion-piece ${type} ${color}`;
btn.setAttribute("aria-label", `Promote to ${type}`);
btn.addEventListener("click", () => this.completePromotion(code)); btn.addEventListener("click", () => this.completePromotion(code));
picker.appendChild(btn); picker.appendChild(btn);
}); });
overlay.addEventListener("keydown", (event) => {
if (event.key === "Escape") {
event.preventDefault();
this.cancelPromotion();
return;
}
if (event.key !== "Tab") return;
const buttons = Array.from(picker.querySelectorAll("button"));
const first = buttons[0];
const last = buttons[buttons.length - 1];
if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
});
overlay.appendChild(picker); overlay.appendChild(picker);
const boardContainer = this.el.closest(".shadow-inner"); const container = this.el.parentElement;
boardContainer.style.position = "relative"; container.style.position = "relative";
boardContainer.appendChild(overlay); container.appendChild(overlay);
picker.querySelector("button")?.focus();
},
cancelPromotion() {
this.pendingPromotion = null;
const overlay = this.el.parentElement?.querySelector(".promotion-overlay");
if (overlay) overlay.remove();
this.restoreFocus();
},
restoreFocus() {
if (this.previousFocus instanceof HTMLElement) {
this.previousFocus.focus();
} else {
document.getElementById("move-input")?.focus();
}
this.previousFocus = null;
}, },
completePromotion(pieceType) { completePromotion(pieceType) {
const { orig, dest } = this.pendingPromotion; const { orig, dest } = this.pendingPromotion;
this.pendingPromotion = null; this.pendingPromotion = null;
const picker = this.el.closest(".shadow-inner")?.querySelector(".promotion-overlay"); const picker = this.el.parentElement?.querySelector(".promotion-overlay");
if (picker) picker.remove(); if (picker) picker.remove();
this.executeMove(orig, dest, pieceType); this.executeMove(orig, dest, pieceType);
document.getElementById("move-input")?.focus();
}, },
executeMove(orig, dest, promotion) { executeMove(orig, dest, promotion) {
@@ -234,6 +299,7 @@ export const ChessBoard = {
san: move.san, san: move.san,
promotion: promotion || null, promotion: promotion || null,
draw: this.chess.isDraw(), draw: this.chess.isDraw(),
check: this.chess.isCheck(),
checkmate: this.chess.isCheckmate(), checkmate: this.chess.isCheckmate(),
}; };
@@ -252,8 +318,14 @@ export const ChessBoard = {
? { color: null, dests: new Map() } ? { color: null, dests: new Map() }
: { color: nextTurnColor, dests: this.getValidDests() }, : { color: nextTurnColor, dests: this.getValidDests() },
}); });
return true;
} else { } else {
this.ground.set({ fen: this.chess.fen() }); this.ground.set({ fen: this.chess.fen() });
this.pushEvent("move_input_error", {
message: "That move is not legal in this position.",
});
return false;
} }
}, },
@@ -279,6 +351,7 @@ export const ChessBoard = {
fen: this.chess.fen(), fen: this.chess.fen(),
san: move.san, san: move.san,
draw: this.chess.isDraw(), draw: this.chess.isDraw(),
check: this.chess.isCheck(),
checkmate: this.chess.isCheckmate(), checkmate: this.chess.isCheckmate(),
}); });
}, },
@@ -6,6 +6,8 @@ defmodule ChesstrainerWeb.Board.BoardComponent do
use Phoenix.Component use Phoenix.Component
import ChesstrainerWeb.Board.SquareComponent import ChesstrainerWeb.Board.SquareComponent
alias ChesstrainerWeb.Board.PositionText
attr :game, :map, required: true attr :game, :map, required: true
attr :myself, :any, default: nil attr :myself, :any, default: nil
@@ -41,7 +43,11 @@ defmodule ChesstrainerWeb.Board.BoardComponent do
~H""" ~H"""
<div class={["m-auto left-0 right-0", @class]}> <div class={["m-auto left-0 right-0", @class]}>
<div class="border border-2 border-zinc-700 grid grid-rows-8 grid-cols-8"> <div
class="border border-2 border-zinc-700 grid grid-rows-8 grid-cols-8"
role="img"
aria-label={"Chess position. #{PositionText.summary(Map.get(@game, :fen))}"}
>
<%= for rank <- @ranks do %> <%= for rank <- @ranks do %>
<%= for file <- @files do %> <%= for file <- @files do %>
<% square = {file, rank} %> <% square = {file, rank} %>
@@ -12,7 +12,7 @@ defmodule ChesstrainerWeb.Board.PieceComponent do
~H""" ~H"""
<%= if @path do %> <%= if @path do %>
<img src={@path} class={@class} /> <img src={@path} class={@class} alt="" aria-hidden="true" />
<% end %> <% end %>
""" """
end end
@@ -0,0 +1,93 @@
defmodule ChesstrainerWeb.Board.PositionText do
@moduledoc """
Plain-language descriptions of a chess position for assistive technology.
A chessground board is a picture to a screen reader, so the play surface and
the static boards use this text as their accessible name or description.
"""
alias Chesstrainer.FEN
@files ~w(a b c d e f g h)
@names %{
"k" => "king",
"q" => "queen",
"r" => "rook",
"b" => "bishop",
"n" => "knight",
"p" => "pawn"
}
@doc """
Describes whose turn it is and where every piece stands.
Returns a generic description when the FEN cannot be read.
## Examples
iex> ChesstrainerWeb.Board.PositionText.summary("8/8/3k4/8/8/3K1R2/8/8 w - - 0 1")
"White to move. White: king on d3, rook on f3. Black: king on d6."
"""
@spec summary(String.t() | nil) :: String.t()
def summary(fen) when is_binary(fen) do
case FEN.board(fen) do
nil ->
"Chess position."
rows ->
["#{turn(fen)}." | piece_groups(rows)]
|> Enum.join(" ")
end
end
def summary(_fen), do: "Chess position."
defp turn(fen) do
case FEN.color_from_fen(fen) do
:white -> "White to move"
:black -> "Black to move"
_ -> "Side to move unknown"
end
end
defp piece_groups(rows) do
["White", "Black"]
|> Enum.map(fn label -> group(label, rows) end)
|> Enum.reject(&is_nil/1)
end
defp group(label, rows) do
colour = if label == "White", do: :white, else: :black
case pieces(rows, colour) do
[] -> nil
pieces -> "#{label}: #{Enum.join(pieces, ", ")}."
end
end
defp pieces(rows, colour) do
rows
|> Enum.with_index()
|> Enum.flat_map(fn {row, rank_index} ->
row
|> Enum.with_index()
|> Enum.flat_map(fn
{nil, _file_index} ->
[]
{piece, file_index} ->
if piece_colour(piece) == colour do
square = "#{Enum.at(@files, file_index)}#{8 - rank_index}"
["#{Map.fetch!(@names, String.downcase(piece))} on #{square}"]
else
[]
end
end)
end)
end
defp piece_colour(piece) do
if piece == String.upcase(piece), do: :white, else: :black
end
end
@@ -112,7 +112,7 @@ defmodule ChesstrainerWeb.CoreComponents do
<.button phx-click="go" variant="primary">Send!</.button> <.button phx-click="go" variant="primary">Send!</.button>
<.button navigate={~p"/"}>Home</.button> <.button navigate={~p"/"}>Home</.button>
""" """
attr :rest, :global, include: ~w(href navigate patch method download name value disabled) attr :rest, :global, include: ~w(href navigate patch method download name value disabled type)
attr :class, :any attr :class, :any
attr :variant, :string, values: ~w(primary secondary ghost danger) attr :variant, :string, values: ~w(primary secondary ghost danger)
slot :inner_block, required: true slot :inner_block, required: true
@@ -123,7 +123,7 @@ defmodule ChesstrainerWeb.CoreComponents do
"secondary" => "border border-base-300 bg-base-100 text-base-content hover:bg-base-200", "secondary" => "border border-base-300 bg-base-100 text-base-content hover:bg-base-200",
"ghost" => "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", "danger" => "bg-error text-error-content hover:bg-error/90",
nil => "bg-primary/15 text-primary hover:bg-primary/25" nil => "bg-primary/15 text-primary-text hover:bg-primary/25"
} }
assigns = assigns =
@@ -338,7 +338,7 @@ defmodule ChesstrainerWeb.CoreComponents do
# Helper used by inputs to generate form errors # Helper used by inputs to generate form errors
defp error(assigns) do defp error(assigns) do
~H""" ~H"""
<p class="mt-1.5 flex gap-2 items-center text-sm text-error"> <p class="mt-1.5 flex gap-2 items-center text-sm text-error-text">
<.icon name="hero-exclamation-circle" class="size-5" /> <.icon name="hero-exclamation-circle" class="size-5" />
{render_slot(@inner_block)} {render_slot(@inner_block)}
</p> </p>
@@ -479,8 +479,8 @@ defmodule ChesstrainerWeb.CoreComponents do
"inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium", "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]", @size == "sm" && "px-1.5 text-[0.7rem]",
@color == "neutral" && "bg-base-200 text-base-content", @color == "neutral" && "bg-base-200 text-base-content",
@color == "primary" && "bg-primary/15 text-primary", @color == "primary" && "bg-primary/15 text-primary-text",
@color == "warning" && "bg-warning/15 text-warning", @color == "warning" && "bg-warning/15 text-warning-text",
@class @class
]} ]}
{@rest} {@rest}
@@ -136,6 +136,7 @@ defmodule ChesstrainerWeb.EndgameList do
phx-click="remove_theme" phx-click="remove_theme"
phx-value-id={theme.id} phx-value-id={theme.id}
aria-label={"Remove #{theme.name}"} aria-label={"Remove #{theme.name}"}
class="px-1"
> >
× ×
</button> </button>
@@ -12,6 +12,7 @@ defmodule ChesstrainerWeb.LandingComponents do
alias Chesstrainer.FEN alias Chesstrainer.FEN
alias Chesstrainer.Themes alias Chesstrainer.Themes
alias ChesstrainerWeb.Board.PositionText
@button_variants %{ @button_variants %{
nav: "nav-cta", nav: "nav-cta",
@@ -84,9 +85,9 @@ defmodule ChesstrainerWeb.LandingComponents do
<section class="mailing-list" id="mailing-list"> <section class="mailing-list" id="mailing-list">
<div class="mailing-list-copy"> <div class="mailing-list-copy">
<span class="section-kicker">Mailing list</span> <span class="section-kicker">Mailing list</span>
<h2>One good endgame idea, now and then.</h2> <h2>Stay in the loop.</h2>
<p> <p>
Occasional emails about new puzzles and features. We'll ask you to confirm your address first. Get occasional endgame ideas, new puzzles, and feature updates delivered to your inbox. (Please confirm your email after signing up.)
</p> </p>
</div> </div>
@@ -180,14 +181,21 @@ defmodule ChesstrainerWeb.LandingComponents do
assigns = assign(assigns, :squares, squares) assigns = assign(assigns, :squares, squares)
~H""" ~H"""
<div class="chessboard" aria-label="Chess position"> <div
class="chessboard"
role="img"
aria-label={"Chess position. #{PositionText.summary(assigns.fen)}"}
>
<%= for square <- @squares do %> <%= for square <- @squares do %>
<div class={[ <div
class={[
"square", "square",
if(square.light, do: "light", else: "dark"), if(square.light, do: "light", else: "dark"),
square.selected? && "selected", square.selected? && "selected",
square.target? && "target" square.target? && "target"
]}> ]}
aria-hidden="true"
>
<span :if={square.label_rank} class="rank">{square.rank}</span> <span :if={square.label_rank} class="rank">{square.rank}</span>
<span :if={square.label_file} class="file">{square.file}</span> <span :if={square.label_file} class="file">{square.file}</span>
<span <span
+11 -17
View File
@@ -42,7 +42,7 @@ defmodule ChesstrainerWeb.Layouts do
def app(assigns) do def app(assigns) do
~H""" ~H"""
<main class="px-4 py-20 sm:px-6 lg:px-8"> <main id="main-content" tabindex="-1" class="px-4 py-20 sm:px-6 lg:px-8">
<div class={["mx-auto space-y-4", if(@wide, do: "max-w-7xl", else: "max-w-2xl")]}> <div class={["mx-auto space-y-4", if(@wide, do: "max-w-7xl", else: "max-w-2xl")]}>
{render_slot(@inner_block)} {render_slot(@inner_block)}
</div> </div>
@@ -235,7 +235,10 @@ defmodule ChesstrainerWeb.Layouts do
end end
@doc """ @doc """
Provides the system / light / dark colour-mode switch. Provides the light / dark colour-mode switch.
With no saved preference the page follows the OS setting; only the explicit
light and dark modes are selectable here.
The click handling and `aria-checked` syncing live in `theme_script.html.heex`, 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 which runs before paint and also on pages without LiveView (the landing page
@@ -250,40 +253,31 @@ defmodule ChesstrainerWeb.Layouts do
aria-label="Colour mode" aria-label="Colour mode"
> >
<div <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]" class="absolute w-1/2 h-full rounded-full border border-base-200 bg-base-100 brightness-200 left-0 [[data-theme=dark]_&]:left-1/2 transition-[left]"
aria-hidden="true" aria-hidden="true"
> >
</div> </div>
<button <button
type="button" 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" class="flex p-2 cursor-pointer w-1/2 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
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" data-phx-theme="light"
role="radio" role="radio"
aria-checked="false" aria-checked="true"
aria-label="Light colour mode" aria-label="Light colour mode"
tabindex="0"
> >
<.icon name="hero-sun-micro" class="size-4 opacity-75 hover:opacity-100" /> <.icon name="hero-sun-micro" class="size-4 opacity-75 hover:opacity-100" />
</button> </button>
<button <button
type="button" 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" class="flex p-2 cursor-pointer w-1/2 justify-center rounded-full focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary"
data-phx-theme="dark" data-phx-theme="dark"
role="radio" role="radio"
aria-checked="false" aria-checked="false"
aria-label="Dark colour mode" aria-label="Dark colour mode"
tabindex="-1"
> >
<.icon name="hero-moon-micro" class="size-4 opacity-75 hover:opacity-100" /> <.icon name="hero-moon-micro" class="size-4 opacity-75 hover:opacity-100" />
</button> </button>
@@ -67,6 +67,12 @@
<Layouts.theme_script /> <Layouts.theme_script />
</head> </head>
<body> <body>
<a
href="#main-content"
class="sr-only focus:not-sr-only focus:fixed focus:left-4 focus:top-4 focus:z-50 focus:rounded-md focus:bg-base-100 focus:px-4 focus:py-2 focus:text-base-content focus:shadow-lg"
>
Skip to main content
</a>
<Layouts.navbar current_scope={@current_scope} /> <Layouts.navbar current_scope={@current_scope} />
{@inner_content} {@inner_content}
<Layouts.footer /> <Layouts.footer />
@@ -16,14 +16,15 @@
} }
}; };
const selectedMode = () => { // There is no system button, so report the effective theme. This keeps the
const source = document.documentElement.getAttribute("data-theme-source"); // visible light/dark control in sync when the page is following the OS.
return source === "system" ? "system" : document.documentElement.getAttribute("data-theme"); const selectedMode = () => document.documentElement.getAttribute("data-theme");
};
const syncChecked = () => { const syncChecked = () => {
document.querySelectorAll("[data-phx-theme]").forEach((button) => { document.querySelectorAll("[data-phx-theme]").forEach((button) => {
button.setAttribute("aria-checked", String(button.dataset.phxTheme === selectedMode())); const checked = button.dataset.phxTheme === selectedMode();
button.setAttribute("aria-checked", String(checked));
button.tabIndex = checked ? 0 : -1;
}); });
}; };
@@ -56,6 +57,25 @@
if (button) setMode(button.dataset.phxTheme); if (button) setMode(button.dataset.phxTheme);
}); });
// Arrow keys move between the radio options, as a radiogroup should.
document.addEventListener("keydown", (event) => {
const button = event.target instanceof Element && event.target.closest("[data-phx-theme]");
if (!button) return;
if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;
event.preventDefault();
const buttons = Array.from(document.querySelectorAll("[data-phx-theme]"));
const offset = event.key === "ArrowRight" ? 1 : -1;
const index = (buttons.indexOf(button) + offset + buttons.length) % buttons.length;
const next = buttons[index];
if (next) {
setMode(next.dataset.phxTheme);
next.focus();
}
});
window.addEventListener("storage", (event) => { window.addEventListener("storage", (event) => {
if (event.key === "phx:theme") setMode(event.newValue || "system"); if (event.key === "phx:theme") setMode(event.newValue || "system");
}); });
@@ -8,9 +8,11 @@ defmodule ChesstrainerWeb.PlayComponents do
use ChesstrainerWeb, :html use ChesstrainerWeb, :html
alias ChesstrainerWeb.Board.PositionText
alias ChesstrainerWeb.EndgameLive.PlayCore alias ChesstrainerWeb.EndgameLive.PlayCore
attr :endgame, :any, required: true attr :endgame, :any, required: true
attr :fen, :string, default: nil
attr :status, :atom, required: true attr :status, :atom, required: true
attr :blocked_reason, :string, default: nil attr :blocked_reason, :string, default: nil
attr :best_move, :string, default: nil attr :best_move, :string, default: nil
@@ -24,26 +26,98 @@ defmodule ChesstrainerWeb.PlayComponents do
attr :last_grade, :atom, default: nil attr :last_grade, :atom, default: nil
attr :awaiting_best_line, :boolean, default: false attr :awaiting_best_line, :boolean, default: false
attr :session, :boolean, default: false attr :session, :boolean, default: false
attr :move_input, :string, default: ""
attr :move_input_error, :string, default: nil
attr :last_check, :boolean, default: false
attr :last_checkmate, :boolean, default: false
def play_surface(assigns) do def play_surface(assigns) do
assigns =
assigns
|> assign(
:can_input,
assigns.status == :playing and not assigns.awaiting_reply and not assigns.reviewing
)
|> assign(:move_hint, move_hint(assigns.status, assigns.awaiting_reply))
~H""" ~H"""
<div class="flex gap-2 bg-base-200 p-4 rounded-xl shadow-inner"> <div class="flex flex-col gap-2 rounded-xl bg-base-200 p-4 shadow-inner sm:flex-row">
<div class="w-100 flex flex-col gap-2"> <div class="flex w-full flex-col gap-2 sm:w-100">
<div class="relative">
<div <div
id="endgame-board" id="endgame-board"
phx-hook="ChessBoard" phx-hook="ChessBoard"
phx-update="ignore" phx-update="ignore"
data-endgame-id={@endgame.id} data-endgame-id={@endgame.id}
class="w-100 h-100" class="aspect-square w-full"
aria-hidden="true"
> >
</div> </div>
</div>
<div :if={@reviewing} id="review-controls" class="flex items-center gap-2"> <div
id="board-announcer"
role="status"
aria-live="polite"
aria-atomic="true"
class="sr-only"
>
{board_announcement(assigns)}
</div>
<div id="position-summary" class="sr-only">
{PositionText.summary(position_fen(assigns))}
</div>
<form
:if={not @reviewing}
id="move-input-form"
phx-submit="submit_move"
phx-change="move_input"
phx-debounce="200"
class="flex items-start gap-2"
>
<div class="min-w-0 flex-1">
<.input
id="move-input"
name="move"
value={@move_input}
label="Your move"
placeholder="Nf3 or g1f3"
autocomplete="off"
aria-describedby="move-input-help"
disabled={not @can_input}
class="font-mono"
/>
<p id="move-input-help" class="mt-1 text-xs text-muted">
SAN or UCI, e.g. <span class="font-mono">Nf3</span>
or <span class="font-mono">g1f3</span>.
</p>
<p :if={@move_hint} class="mt-1 text-xs text-muted" role="status">{@move_hint}</p>
<p
:if={@move_input_error}
id="move-input-error"
role="alert"
class="mt-1 text-sm text-error-text"
>
{@move_input_error}
</p>
</div>
<.button type="submit" class="mt-6" disabled={not @can_input}>Play move</.button>
</form>
<div
:if={@reviewing}
id="review-controls"
class="flex items-center gap-2"
role="group"
aria-label="Review navigation"
>
<.button <.button
id="review-start" id="review-start"
phx-click="review_start" phx-click="review_start"
disabled={@review_index <= 0} disabled={@review_index <= 0}
title="Back to start" title="Back to start"
aria-label="Back to start"
> >
{"<<"} {"<<"}
</.button> </.button>
@@ -52,6 +126,7 @@ defmodule ChesstrainerWeb.PlayComponents do
phx-click="review_prev" phx-click="review_prev"
disabled={@review_index <= 0} disabled={@review_index <= 0}
title="Previous position" title="Previous position"
aria-label="Previous position"
> >
← ←
</.button> </.button>
@@ -60,6 +135,7 @@ defmodule ChesstrainerWeb.PlayComponents do
phx-click="review_next" phx-click="review_next"
disabled={@review_index >= length(@line)} disabled={@review_index >= length(@line)}
title="Next position" title="Next position"
aria-label="Next position"
> >
→ →
</.button> </.button>
@@ -68,12 +144,13 @@ defmodule ChesstrainerWeb.PlayComponents do
phx-click="review_end" phx-click="review_end"
disabled={@review_index >= length(@line)} disabled={@review_index >= length(@line)}
title="Go to end" title="Go to end"
aria-label="Go to end"
> >
{">>"} {">>"}
</.button> </.button>
</div> </div>
<div class="flex flex-wrap gap-2"> <div class="flex flex-wrap gap-2" role="group" aria-label="Puzzle actions">
<.button <.button
:if={(@reviewing and @review_tablebase) && PlayCore.best_move_text(@review_tablebase)} :if={(@reviewing and @review_tablebase) && PlayCore.best_move_text(@review_tablebase)}
phx-click="play_best_line" phx-click="play_best_line"
@@ -105,8 +182,8 @@ defmodule ChesstrainerWeb.PlayComponents do
</div> </div>
</div> </div>
<div class="relative w-48"> <div class="relative w-full sm:w-48">
<div class="absolute inset-0 flex flex-col gap-3"> <div class="flex flex-col gap-3 sm:absolute sm:inset-0">
<%= if @reviewing do %> <%= if @reviewing do %>
<div <div
id="best-move-panel" id="best-move-panel"
@@ -128,29 +205,20 @@ defmodule ChesstrainerWeb.PlayComponents do
<% end %> <% end %>
</div> </div>
<% else %> <% else %>
<div class="rounded-lg bg-canvas-raised p-3 text-sm">
<p class="flex items-center justify-between gap-2 font-semibold">
<span>{turn_label(@status, @awaiting_reply)}</span>
<span class="text-xs font-normal text-muted">
You play {colour_name(@endgame.color)}
</span>
</p>
</div>
<div class="rounded-lg bg-canvas-raised p-3 text-sm"> <div class="rounded-lg bg-canvas-raised p-3 text-sm">
<%= cond do %> <%= cond do %>
<% @status == :loading -> %> <% @status == :loading -> %>
<p class="text-muted">Loading tablebase…</p> <p class="text-muted">Loading tablebase…</p>
<% @status == :blocked -> %> <% @status == :blocked -> %>
<p class="font-semibold text-error">Tablebase unavailable</p> <p class="font-semibold text-error-text">Tablebase unavailable</p>
<p class="text-error">{@blocked_reason}</p> <p class="text-error-text">{@blocked_reason}</p>
<% @status == :solved -> %> <% @status == :solved -> %>
<p class="font-semibold text-success-text"> <p class="font-semibold text-success-text">
{if @endgame.result == :draw, do: "Draw held!", else: "Solved!"} {if @endgame.result == :draw, do: "Draw held!", else: "Solved!"}
</p> </p>
<% @status == :failed -> %> <% @status == :failed -> %>
<p class="font-semibold text-error">Failed</p> <p class="font-semibold text-error-text">Failed</p>
<p class="text-error"> <p class="text-error-text">
{if @endgame.result == :draw, {if @endgame.result == :draw,
do: "That move loses the draw.", do: "That move loses the draw.",
else: "That move throws away the win."} else: "That move throws away the win."}
@@ -161,17 +229,17 @@ defmodule ChesstrainerWeb.PlayComponents do
</p> </p>
<% end %> <% end %>
<% @awaiting_reply -> %> <% @awaiting_reply -> %>
<p class="text-muted">Opponent is replying…</p> <p class="text-muted">Thinkin...</p>
<% @last_grade == :optimal -> %> <% @last_grade == :optimal -> %>
<p class="font-semibold text-success-text">Optimal move</p> <p class="font-semibold text-success-text">Optimal move</p>
<% @last_grade == :winning -> %> <% @last_grade == :winning -> %>
<p class="font-semibold text-warning"> <p class="font-semibold text-warning-text">
{if @endgame.result == :draw, {if @endgame.result == :draw,
do: "Keeps the draw — but not the sharpest", do: "Keeps the draw — but not the sharpest",
else: "Winning — but not the sharpest"} else: "Winning — but not the sharpest"}
</p> </p>
<% @last_grade == :losing -> %> <% @last_grade == :losing -> %>
<p class="font-semibold text-error"> <p class="font-semibold text-error-text">
{if @endgame.result == :draw, {if @endgame.result == :draw,
do: "Losing move — this loses the draw", do: "Losing move — this loses the draw",
else: "Losing move — this throws away the win"} else: "Losing move — this throws away the win"}
@@ -179,7 +247,8 @@ defmodule ChesstrainerWeb.PlayComponents do
<% @last_grade == :unknown -> %> <% @last_grade == :unknown -> %>
<p class="font-semibold text-muted">Could not grade that move</p> <p class="font-semibold text-muted">Could not grade that move</p>
<% true -> %> <% true -> %>
<p class="text-muted">Make a move to have it graded.</p> <p class="text-muted font-bold">Make a move.</p>
<p class="text-muted">You play {colour_name(@endgame.color)}</p>
<% end %> <% end %>
<p :if={@status in [:solved, :failed]} class="mt-1 text-xs text-muted"> <p :if={@status in [:solved, :failed]} class="mt-1 text-xs text-muted">
Puzzle rating: {round(@endgame.rating)} Puzzle rating: {round(@endgame.rating)}
@@ -188,6 +257,8 @@ defmodule ChesstrainerWeb.PlayComponents do
<div <div
id="move-list" id="move-list"
role="region"
aria-label="Moves"
class="flex-1 min-h-0 flex flex-col bg-canvas-raised rounded-lg p-3" class="flex-1 min-h-0 flex flex-col bg-canvas-raised rounded-lg p-3"
> >
<% plies = display_plies(@reviewing, @line, @plies) %> <% plies = display_plies(@reviewing, @line, @plies) %>
@@ -243,14 +314,19 @@ defmodule ChesstrainerWeb.PlayComponents do
<p class={["text-xs font-semibold", class]}>{label}</p> <p class={["text-xs font-semibold", class]}>{label}</p>
<table class="w-full text-left text-xs font-mono"> <table class="w-full text-left text-xs font-mono">
<tbody> <tbody>
<tr <tr :for={move <- moves}>
:for={move <- moves} <td class={["py-0.5 pr-2", class]}>
<button
type="button"
phx-click="review_move" phx-click="review_move"
phx-value-uci={move.uci} phx-value-uci={move.uci}
class="cursor-pointer hover:bg-base-200" class="text-left hover:underline"
title={"Play #{move.san}"} title={"Play #{move.san}"}
aria-label={"Play #{move.san}"}
> >
<td class={["py-0.5 pr-2", class]}>{move.san}</td> {move.san}
</button>
</td>
<td class="py-0.5 text-right text-muted" title="Distance to zeroing (DTZ)"> <td class="py-0.5 text-right text-muted" title="Distance to zeroing (DTZ)">
{dtz_text(move)} {dtz_text(move)}
</td> </td>
@@ -266,7 +342,7 @@ defmodule ChesstrainerWeb.PlayComponents do
[ [
{"Winning", "text-success-text", :win}, {"Winning", "text-success-text", :win},
{"Drawn", "text-muted", :draw}, {"Drawn", "text-muted", :draw},
{"Losing", "text-error", :loss}, {"Losing", "text-error-text", :loss},
{"Unknown", "text-muted", :unknown} {"Unknown", "text-muted", :unknown}
] ]
|> Enum.flat_map(fn {label, class, outcome} -> |> Enum.flat_map(fn {label, class, outcome} ->
@@ -308,9 +384,11 @@ defmodule ChesstrainerWeb.PlayComponents do
current_ply?(@ply, @review_index) && "underline" current_ply?(@ply, @review_index) && "underline"
]} ]}
title={ply_title(@ply, @result)} title={ply_title(@ply, @result)}
aria-current={current_ply?(@ply, @review_index) && "step"}
data-grade={@ply.grade} data-grade={@ply.grade}
> >
{@ply.san} {@ply.san}
<span :if={ply_title(@ply, @result)} class="sr-only"> — {ply_title(@ply, @result)}</span>
</button> </button>
<% else %> <% else %>
<span <span
@@ -319,6 +397,7 @@ defmodule ChesstrainerWeb.PlayComponents do
data-grade={@ply.grade} data-grade={@ply.grade}
> >
{@ply.san} {@ply.san}
<span :if={ply_title(@ply, @result)} class="sr-only"> — {ply_title(@ply, @result)}</span>
</span> </span>
<% end %> <% end %>
""" """
@@ -335,13 +414,6 @@ defmodule ChesstrainerWeb.PlayComponents do
defp display_plies(true, line, _plies), do: line defp display_plies(true, line, _plies), do: line
defp display_plies(false, _line, plies), do: plies defp display_plies(false, _line, plies), do: plies
defp turn_label(:playing, false), do: "Your move"
defp turn_label(:playing, true), do: "Opponent's move"
defp turn_label(:solved, _awaiting_reply), do: "Solved"
defp turn_label(:failed, _awaiting_reply), do: "Finished"
defp turn_label(:blocked, _awaiting_reply), do: "Unavailable"
defp turn_label(_status, _awaiting_reply), do: "Loading…"
defp colour_name(:white), do: "White" defp colour_name(:white), do: "White"
defp colour_name(:black), do: "Black" defp colour_name(:black), do: "Black"
defp colour_name(colour), do: colour |> to_string() |> String.capitalize() defp colour_name(colour), do: colour |> to_string() |> String.capitalize()
@@ -364,8 +436,8 @@ defmodule ChesstrainerWeb.PlayComponents do
defp ply_title(ply, result), do: grade_label(ply.grade, result) defp ply_title(ply, result), do: grade_label(ply.grade, result)
defp grade_class(:optimal), do: "text-success-text" defp grade_class(:optimal), do: "text-success-text"
defp grade_class(:winning), do: "text-warning" defp grade_class(:winning), do: "text-warning-text"
defp grade_class(:losing), do: "text-error" defp grade_class(:losing), do: "text-error-text"
defp grade_class(_), do: "text-body" defp grade_class(_), do: "text-body"
defp grade_label(nil, _result), do: nil defp grade_label(nil, _result), do: nil
@@ -375,4 +447,128 @@ defmodule ChesstrainerWeb.PlayComponents do
defp grade_label(:losing, :draw), do: "Loses the draw" defp grade_label(:losing, :draw), do: "Loses the draw"
defp grade_label(:losing, _result), do: "Throws away the win" defp grade_label(:losing, _result), do: "Throws away the win"
defp grade_label(:unknown, _result), do: "Not graded" defp grade_label(:unknown, _result), do: "Not graded"
defp move_hint(:loading, _awaiting), do: "Loading the tablebase…"
defp move_hint(:blocked, _awaiting),
do: "The tablebase is unavailable, so moves cannot be entered."
defp move_hint(status, _awaiting) when status in [:solved, :failed],
do: "This puzzle is finished. Reset or try again."
defp move_hint(_status, true), do: "Waiting for the opponent's reply."
defp move_hint(_status, _awaiting), do: nil
# While the opponent's move is in flight the server's `fen` still points at
# the position before it, so describe the move the player just made instead.
defp position_fen(%{awaiting_reply: true, plies: plies}) do
case List.last(plies) do
%{fen_after: fen} -> fen
_ -> nil
end
end
defp position_fen(%{fen: fen}) when is_binary(fen), do: fen
defp position_fen(%{endgame: %{fen: fen}}), do: fen
defp board_announcement(assigns) do
cond do
assigns.status == :loading ->
"Loading the tablebase."
assigns.status == :blocked ->
"Tablebase unavailable. #{assigns.blocked_reason || "Moves cannot be graded."}"
assigns.reviewing ->
review_announcement(assigns)
assigns.status == :solved ->
join_sentences([solved_sentence(assigns), check_sentence(assigns)])
assigns.status == :failed ->
join_sentences(["Failed.", failure_sentence(assigns), best_move_sentence(assigns)])
assigns.awaiting_reply ->
join_sentences([
"Move #{length(assigns.plies)}: you played #{last_san(assigns.plies)}.",
grade_sentence(assigns),
check_sentence(assigns),
"Waiting for the opponent's reply."
])
assigns.plies == [] ->
"You play #{colour_name(assigns.endgame.color)}. #{colour_name(assigns.endgame.color)} to move."
true ->
case List.last(assigns.plies) do
%{grade: nil} ->
join_sentences([
"Move #{length(assigns.plies)}: opponent played #{last_san(assigns.plies)}.",
check_sentence(assigns),
"Your move."
])
_ ->
join_sentences([
"Move #{length(assigns.plies)}: you played #{last_san(assigns.plies)}.",
grade_sentence(assigns),
check_sentence(assigns),
"Your move."
])
end
end
end
defp review_announcement(assigns) do
previous = Enum.at(assigns.line, assigns.review_index - 1)
position =
cond do
assigns.review_index <= 0 -> "Starting position."
previous -> "After #{previous.san}."
true -> "Final position."
end
"Reviewing position #{assigns.review_index} of #{length(assigns.line)}. #{position}"
end
defp failure_sentence(%{endgame: %{result: :draw}}), do: "That move loses the draw."
defp failure_sentence(_assigns), do: "That move throws away the win."
defp solved_sentence(%{endgame: %{result: :draw}}), do: "Draw held!"
defp solved_sentence(_assigns), do: "Solved!"
defp best_move_sentence(%{best_move: nil}), do: ""
defp best_move_sentence(%{best_move: best}), do: "Best was #{best}."
defp grade_sentence(%{plies: plies, endgame: endgame}) do
case List.last(plies) do
%{grade: grade} ->
case grade_label(grade, endgame.result) do
nil -> ""
label -> "#{label}."
end
_ ->
""
end
end
defp check_sentence(%{last_checkmate: true}), do: "Checkmate."
defp check_sentence(%{last_check: true}), do: "Check."
defp check_sentence(_assigns), do: ""
defp last_san(plies) do
case List.last(plies) do
%{san: san} when is_binary(san) -> san
_ -> "a move"
end
end
defp join_sentences(sentences) do
sentences
|> Enum.reject(&(&1 in [nil, ""]))
|> Enum.join(" ")
end
end end
@@ -1,16 +1,15 @@
<Layouts.flash_group flash={@flash} /> <Layouts.flash_group flash={@flash} />
<main> <main id="main-content" tabindex="-1">
<section class="hero"> <section class="hero">
<div class="hero-copy"> <div class="hero-copy">
<div class="eyebrow"> <div class="eyebrow">
<.icon_spark /> Endgames, made clear <.icon_spark /> Endgames, simplified
</div> </div>
<h1> <h1>
Learn to see the <em>winning move.</em> Master the <em>endgame.</em>
</h1> </h1>
<p> <p>
Short, focused endgame sessions that build the instincts you need Train your intuition to find the winning moves under pressure. Puzzle sessions focused purely on technical execution.
when every move matters.
</p> </p>
<div class="hero-actions"> <div class="hero-actions">
<.pill_button variant={:primary} navigate={play_path(@active_endgame)}> <.pill_button variant={:primary} navigate={play_path(@active_endgame)}>
@@ -35,7 +34,7 @@
</div> </div>
</section> </section>
<section class="learning-strip" id="method"> <%!-- <section class="learning-strip" id="method">
<p>Built for the part of chess that decides everything.</p> <p>Built for the part of chess that decides everything.</p>
<div class="stat"> <div class="stat">
<strong>{count_label(@puzzle_count)}</strong> <strong>{count_label(@puzzle_count)}</strong>
@@ -45,19 +44,19 @@
<strong>{@user_count}</strong> <strong>{@user_count}</strong>
<span>Players improving their endgame</span> <span>Players improving their endgame</span>
</div> </div>
</section> </section> --%>
<section class="puzzle-section" id="puzzles"> <%!-- <section class="puzzle-section" id="puzzles">
<div class="section-heading"> <div class="section-heading">
<div> <div>
<span class="section-kicker">Choose your challenge</span> <span class="section-kicker">Choose your lesson</span>
<h2> <h2>
One position. <br /> One clear idea. One position. <br /> One idea.
</h2> </h2>
</div> </div>
<p> <p>
No noise, no endless variations. Each exercise teaches a pattern Each exercise teaches a pattern
you’ll recognize over the board. that you’ll recognise over the board.
</p> </p>
</div> </div>
<div class="puzzle-grid"> <div class="puzzle-grid">
@@ -69,7 +68,7 @@
/> />
<% end %> <% end %>
</div> </div>
</section> </section> --%>
<.mailing_list_signup /> <.mailing_list_signup />
@@ -72,6 +72,7 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
:if={@endgame} :if={@endgame}
session={is_nil(@limit_reached)} session={is_nil(@limit_reached)}
endgame={@endgame} endgame={@endgame}
fen={@fen}
status={@status} status={@status}
blocked_reason={@blocked_reason} blocked_reason={@blocked_reason}
best_move={@best_move} best_move={@best_move}
@@ -84,6 +85,10 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
awaiting_reply={@awaiting_reply} awaiting_reply={@awaiting_reply}
last_grade={@last_grade} last_grade={@last_grade}
awaiting_best_line={@awaiting_best_line} awaiting_best_line={@awaiting_best_line}
move_input={@move_input}
move_input_error={@move_input_error}
last_check={@last_check}
last_checkmate={@last_checkmate}
/> />
<p :if={@loading} class="text-base-content/70">Picking a random puzzle…</p> <p :if={@loading} class="text-base-content/70">Picking a random puzzle…</p>
@@ -150,6 +155,13 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
def handle_event("endgame_move_played", params, socket), def handle_event("endgame_move_played", params, socket),
do: PlayCore.move_played(socket, params) do: PlayCore.move_played(socket, params)
def handle_event("submit_move", params, socket), do: PlayCore.submit_move(socket, params)
def handle_event("move_input", params, socket), do: PlayCore.move_input_changed(socket, params)
def handle_event("move_input_error", params, socket),
do: PlayCore.move_input_error(socket, params)
def handle_event("opponent_reply_applied", params, socket), def handle_event("opponent_reply_applied", params, socket),
do: PlayCore.opponent_reply_applied(socket, params) do: PlayCore.opponent_reply_applied(socket, params)
@@ -43,7 +43,7 @@ defmodule ChesstrainerWeb.EndgameLive.Index do
type="button" type="button"
id="clear-endgame-search" id="clear-endgame-search"
phx-click="clear_search" phx-click="clear_search"
class="text-sm text-primary underline underline-offset-4 hover:text-primary/80" class="text-sm text-primary-text underline underline-offset-4 hover:text-primary-text/80"
> >
Clear Clear
</button> </button>
+15 -1
View File
@@ -23,10 +23,12 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
<span>FEN: {@endgame.fen}</span> <span>FEN: {@endgame.fen}</span>
<button <button
id="copy-fen-btn" id="copy-fen-btn"
type="button"
phx-hook="CopyFen" phx-hook="CopyFen"
data-fen={@endgame.fen} data-fen={@endgame.fen}
class="inline-flex items-center cursor-pointer" class="inline-flex items-center justify-center rounded p-1.5 cursor-pointer"
title="Copy FEN to clipboard" title="Copy FEN to clipboard"
aria-label="Copy FEN to clipboard"
> >
<.icon name="hero-document-duplicate" class="w-3.5 h-3.5" /> <.icon name="hero-document-duplicate" class="w-3.5 h-3.5" />
</button> </button>
@@ -44,6 +46,7 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
<PlayComponents.play_surface <PlayComponents.play_surface
endgame={@endgame} endgame={@endgame}
fen={@fen}
status={@status} status={@status}
blocked_reason={@blocked_reason} blocked_reason={@blocked_reason}
best_move={@best_move} best_move={@best_move}
@@ -56,6 +59,10 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
awaiting_reply={@awaiting_reply} awaiting_reply={@awaiting_reply}
last_grade={@last_grade} last_grade={@last_grade}
awaiting_best_line={@awaiting_best_line} awaiting_best_line={@awaiting_best_line}
move_input={@move_input}
move_input_error={@move_input_error}
last_check={@last_check}
last_checkmate={@last_checkmate}
/> />
<div :if={@user_rating} class="mb-4"> <div :if={@user_rating} class="mb-4">
@@ -76,6 +83,13 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
def handle_event("endgame_move_played", params, socket), def handle_event("endgame_move_played", params, socket),
do: PlayCore.move_played(socket, params) do: PlayCore.move_played(socket, params)
def handle_event("submit_move", params, socket), do: PlayCore.submit_move(socket, params)
def handle_event("move_input", params, socket), do: PlayCore.move_input_changed(socket, params)
def handle_event("move_input_error", params, socket),
do: PlayCore.move_input_error(socket, params)
def handle_event("opponent_reply_applied", params, socket), def handle_event("opponent_reply_applied", params, socket),
do: PlayCore.opponent_reply_applied(socket, params) do: PlayCore.opponent_reply_applied(socket, params)
@@ -20,6 +20,8 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
alias Chesstrainer.Endgames.Tablebase alias Chesstrainer.Endgames.Tablebase
alias Chesstrainer.Ratings alias Chesstrainer.Ratings
@uci_pattern ~r/^[a-h][1-8][a-h][1-8][qrbn]?$/
@doc """ @doc """
Loads `endgame` and starts an attempt on it. Loads `endgame` and starts an attempt on it.
@@ -53,6 +55,10 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|> assign(:last_grade, nil) |> assign(:last_grade, nil)
|> assign(:awaiting_reply, false) |> assign(:awaiting_reply, false)
|> assign(:last_rating_delta, nil) |> assign(:last_rating_delta, nil)
|> assign(:last_check, false)
|> assign(:last_checkmate, false)
|> assign(:move_input, "")
|> assign(:move_input_error, nil)
|> load_attempt() |> load_attempt()
end end
@@ -60,6 +66,8 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
%{"from" => from, "to" => to, "san" => san} = params %{"from" => from, "to" => to, "san" => san} = params
promotion = params["promotion"] promotion = params["promotion"]
draw = params["draw"] || false draw = params["draw"] || false
check = params["check"] || false
checkmate = params["checkmate"] || false
prev_fen = params["prev_fen"] || socket.assigns.fen prev_fen = params["prev_fen"] || socket.assigns.fen
fen_after = params["fen"] || socket.assigns.fen fen_after = params["fen"] || socket.assigns.fen
@@ -76,16 +84,72 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
put_flash(socket, :error, "That move is out of sequence. Press Reset to try again.")} put_flash(socket, :error, "That move is out of sequence. Press Reset to try again.")}
true -> true ->
grade_and_record(socket, from, to, promotion, san, fen_after, draw) grade_and_record(socket, from, to, promotion, san, fen_after, draw, check, checkmate)
end end
end end
@doc """
Plays the move typed into the keyboard move input.
The tablebase already knows every legal move in the position, so matching SAN
or UCI against it validates the input without a chess engine on the server.
The board hook applies the move and reports it through the normal move events.
"""
def submit_move(socket, %{"move" => input}) do
cond do
socket.assigns.reviewing ->
move_input_rejected(socket, "Leave review to make a move.")
socket.assigns.status != :playing ->
move_input_rejected(socket, "This puzzle is not open for moves right now.")
socket.assigns.awaiting_reply ->
move_input_rejected(socket, "Wait for the opponent's reply.")
true ->
case parse_move_input(socket.assigns.tablebase, input) do
%Tablebase.Move{} = move ->
{:noreply,
socket
|> assign(:move_input, "")
|> assign(:move_input_error, nil)
|> push_event("apply_move", reply_payload(move))}
_ ->
move_input_rejected(
socket,
"Not a legal move here. Try SAN like Nf3, or squares like g1f3."
)
end
end
end
def submit_move(socket, _params), do: {:noreply, socket}
def move_input_changed(socket, %{"move" => value}) when is_binary(value) do
{:noreply, socket |> assign(:move_input, value) |> assign(:move_input_error, nil)}
end
def move_input_changed(socket, _params), do: {:noreply, socket}
def move_input_error(socket, %{"message" => message}) when is_binary(message) do
{:noreply, assign(socket, :move_input_error, message)}
end
def move_input_error(socket, _params), do: {:noreply, socket}
def opponent_reply_applied(socket, params) do def opponent_reply_applied(socket, params) do
%{"fen" => fen} = params %{"fen" => fen} = params
draw = params["draw"] || false draw = params["draw"] || false
check = params["check"] || false
checkmate = params["checkmate"] || false
if socket.assigns.awaiting_reply do if socket.assigns.awaiting_reply do
socket = record_opponent_ply(socket, fen, params["san"]) socket =
socket
|> record_opponent_ply(fen, params["san"])
|> assign(:last_check, check)
|> assign(:last_checkmate, checkmate)
if draw and socket.assigns.endgame.result == :draw do if draw and socket.assigns.endgame.result == :draw do
solve_attempt(socket) solve_attempt(socket)
@@ -100,6 +164,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|> assign(:awaiting_reply, false) |> assign(:awaiting_reply, false)
|> assign(:status, :playing) |> assign(:status, :playing)
|> assign(:blocked_reason, nil) |> assign(:blocked_reason, nil)
|> assign(:move_input_error, nil)
|> push_event("resume_board", %{})} |> push_event("resume_board", %{})}
other -> other ->
@@ -141,6 +206,10 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|> assign(:last_from_to, "None yet") |> assign(:last_from_to, "None yet")
|> assign(:last_grade, nil) |> assign(:last_grade, nil)
|> assign(:last_rating_delta, nil) |> assign(:last_rating_delta, nil)
|> assign(:last_check, false)
|> assign(:last_checkmate, false)
|> assign(:move_input, "")
|> assign(:move_input_error, nil)
{:noreply, load_attempt(socket)} {:noreply, load_attempt(socket)}
end end
@@ -334,7 +403,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
"The tablebase is unavailable (#{inspect(reason)})." "The tablebase is unavailable (#{inspect(reason)})."
end end
defp grade_and_record(socket, from, to, promotion, san, fen_after, draw) do defp grade_and_record(socket, from, to, promotion, san, fen_after, draw, check, checkmate) do
case find_move(socket.assigns.tablebase, from, to, promotion) do case find_move(socket.assigns.tablebase, from, to, promotion) do
nil -> nil ->
{:noreply, put_flash(socket, :error, "Could not identify that move in the tablebase.")} {:noreply, put_flash(socket, :error, "Could not identify that move in the tablebase.")}
@@ -354,6 +423,10 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|> assign(:last_from_to, "#{from} ➔ #{to}") |> assign(:last_from_to, "#{from} ➔ #{to}")
|> assign(:last_san, san) |> assign(:last_san, san)
|> assign(:last_grade, grade) |> assign(:last_grade, grade)
|> assign(:last_check, check)
|> assign(:last_checkmate, checkmate)
|> assign(:move_input, "")
|> assign(:move_input_error, nil)
|> assign(:plies, socket.assigns.plies ++ [ply]) |> assign(:plies, socket.assigns.plies ++ [ply])
cond do cond do
@@ -450,7 +523,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|> assign(:last_rating_delta, nil) |> assign(:last_rating_delta, nil)
|> put_flash( |> put_flash(
:info, :info,
"Replay recorded. Your rating is unchanged because you played this recently." "Your rating is unchanged because you played this puzzle recently."
) )
end end
@@ -525,6 +598,38 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
defp find_move_by_uci(_tablebase, _uci), do: nil defp find_move_by_uci(_tablebase, _uci), do: nil
defp parse_move_input(%Tablebase{} = tablebase, input) when is_binary(input) do
normalized = input |> String.trim() |> String.downcase() |> String.replace(" ", "")
uci = String.replace(normalized, "-", "")
cond do
normalized == "" -> nil
Regex.match?(@uci_pattern, uci) -> find_move_by_uci(tablebase, uci)
true -> find_move_by_san(tablebase, normalize_san(normalized))
end
end
defp parse_move_input(_tablebase, _input), do: nil
defp find_move_by_san(%Tablebase{moves: moves}, san) when is_list(moves) and is_binary(san) do
Enum.find(moves, &(normalize_san(&1.san) == san))
end
defp find_move_by_san(_tablebase, _san), do: nil
defp normalize_san(san) when is_binary(san) do
san
|> String.downcase()
|> String.replace("=", "")
|> String.replace(~r/[+#!?]/, "")
end
defp normalize_san(_san), do: nil
defp move_input_rejected(socket, message) do
{:noreply, assign(socket, :move_input_error, message)}
end
# Compare only the board and side to move: chess.js may normalise the rest # Compare only the board and side to move: chess.js may normalise the rest
# (castling/en-passant/halfmove/fullmove) differently from the stored FEN. # (castling/en-passant/halfmove/fullmove) differently from the stored FEN.
defp same_position?(fen_a, fen_b), do: position_key(fen_a) == position_key(fen_b) defp same_position?(fen_a, fen_b), do: position_key(fen_a) == position_key(fen_b)
@@ -42,7 +42,7 @@ defmodule ChesstrainerWeb.EndgameLive.Show do
</:actions> </:actions>
</.header> </.header>
<.board game={@game} myself="board" /> <.board game={@game} myself="board" interactive={false} />
<.list> <.list>
<:item title="Fen">{@endgame.fen}</:item> <:item title="Fen">{@endgame.fen}</:item>
@@ -54,8 +54,9 @@ defmodule ChesstrainerWeb.EndgameLive.Show do
type="button" type="button"
phx-hook=".CopyPublicCode" phx-hook=".CopyPublicCode"
data-code={@endgame.public_code} data-code={@endgame.public_code}
class="ml-2 inline-flex cursor-pointer items-center" class="ml-2 inline-flex cursor-pointer items-center justify-center rounded p-1.5"
title="Copy public code" title="Copy public code"
aria-label="Copy public code to clipboard"
> >
<.icon name="hero-document-duplicate" class="w-3.5 h-3.5" /> <.icon name="hero-document-duplicate" class="w-3.5 h-3.5" />
</button> </button>
@@ -82,6 +82,7 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
<PlayComponents.play_surface <PlayComponents.play_surface
session={true} session={true}
endgame={@endgame} endgame={@endgame}
fen={@fen}
status={@status} status={@status}
blocked_reason={@blocked_reason} blocked_reason={@blocked_reason}
best_move={@best_move} best_move={@best_move}
@@ -94,6 +95,10 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
awaiting_reply={@awaiting_reply} awaiting_reply={@awaiting_reply}
last_grade={@last_grade} last_grade={@last_grade}
awaiting_best_line={@awaiting_best_line} awaiting_best_line={@awaiting_best_line}
move_input={@move_input}
move_input_error={@move_input_error}
last_check={@last_check}
last_checkmate={@last_checkmate}
/> />
<% else %> <% else %>
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4"> <div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
@@ -164,7 +169,7 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
<% end %> <% end %>
</div> </div>
<.button navigate={~p"/"} variant="ghost" class="mt-2 w-full justify-center"> <.button navigate={~p"/"} variant="ghost" class="mt-2 w-full justify-center">
Cancel <.icon name="hero-arrow-left" />Return Home
</.button> </.button>
</div> </div>
</div> </div>
@@ -255,6 +260,13 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
{:noreply, account_completion(socket)} {:noreply, account_completion(socket)}
end end
def handle_event("submit_move", params, socket), do: PlayCore.submit_move(socket, params)
def handle_event("move_input", params, socket), do: PlayCore.move_input_changed(socket, params)
def handle_event("move_input_error", params, socket),
do: PlayCore.move_input_error(socket, params)
def handle_event("opponent_reply_applied", params, socket) do def handle_event("opponent_reply_applied", params, socket) do
{:noreply, socket} = PlayCore.opponent_reply_applied(socket, params) {:noreply, socket} = PlayCore.opponent_reply_applied(socket, params)
{:noreply, account_completion(socket)} {:noreply, account_completion(socket)}
@@ -374,6 +386,6 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
end end
defp gain_class(delta) when is_number(delta) and delta > 0, do: "text-success-text" defp gain_class(delta) when is_number(delta) and delta > 0, do: "text-success-text"
defp gain_class(delta) when is_number(delta) and delta < 0, do: "text-error" defp gain_class(delta) when is_number(delta) and delta < 0, do: "text-error-text"
defp gain_class(_delta), do: "text-muted" defp gain_class(_delta), do: "text-muted"
end end
+2 -2
View File
@@ -14,7 +14,7 @@ defmodule ChesstrainerWeb.UserLive.Login do
<p class="settings-subtitle my-4"> <p class="settings-subtitle my-4">
Don't have an account? <.link Don't have an account? <.link
navigate={~p"/users/register"} navigate={~p"/users/register"}
class="font-semibold text-primary hover:underline" class="font-semibold text-primary-text hover:underline"
phx-no-format phx-no-format
>Sign up</.link> for an account now. >Sign up</.link> for an account now.
</p> </p>
@@ -56,7 +56,7 @@ defmodule ChesstrainerWeb.UserLive.Login do
<p class="text-center text-sm"> <p class="text-center text-sm">
<.link <.link
navigate={~p"/users/reset-password"} navigate={~p"/users/reset-password"}
class="font-semibold text-primary hover:underline" class="font-semibold text-primary-text hover:underline"
> >
Forgot your password? Forgot your password?
</.link> </.link>
@@ -30,7 +30,7 @@ defmodule ChesstrainerWeb.UserLive.Profile do
class={[ class={[
"border-b-2 -mb-px px-3 py-2 text-sm font-semibold", "border-b-2 -mb-px px-3 py-2 text-sm font-semibold",
if(@live_action == tab.id, if(@live_action == tab.id,
do: "border-primary text-primary", do: "border-primary text-primary-text",
else: "border-transparent text-base-content/60 hover:text-base-content" else: "border-transparent text-base-content/60 hover:text-base-content"
) )
]} ]}
@@ -14,7 +14,10 @@ defmodule ChesstrainerWeb.UserLive.Registration do
<h1 class="settings-header">Register for an account</h1> <h1 class="settings-header">Register for an account</h1>
<p class="settings-subtitle my-4"> <p class="settings-subtitle my-4">
Already registered? Already registered?
<.link navigate={~p"/users/log-in"} class="font-semibold text-primary hover:underline"> <.link
navigate={~p"/users/log-in"}
class="font-semibold text-primary-text hover:underline"
>
Log in Log in
</.link> </.link>
to your account now to your account now
@@ -51,7 +51,7 @@ defmodule ChesstrainerWeb.UserLive.ResetPassword do
<p class="text-center text-sm"> <p class="text-center text-sm">
<.link <.link
navigate={~p"/users/log-in"} navigate={~p"/users/log-in"}
class="font-semibold text-primary hover:underline" class="font-semibold text-primary-text hover:underline"
> >
Back to log in Back to log in
</.link> </.link>
@@ -25,6 +25,14 @@ defmodule ChesstrainerWeb.LandingComponentsTest do
assert html =~ "Today’s position" assert html =~ "Today’s position"
end end
test "describes the board as an image for assistive technology" do
html = render_component(&LandingComponents.board_preview/1, %{endgame: @endgame})
assert html =~ ~s(role="img")
assert html =~ "Chess position. White to move"
assert html =~ "rook on f3"
end
test "falls back to a neutral position without an endgame" do test "falls back to a neutral position without an endgame" do
html = render_component(&LandingComponents.board_preview/1, %{endgame: nil}) html = render_component(&LandingComponents.board_preview/1, %{endgame: nil})
@@ -31,14 +31,13 @@ defmodule ChesstrainerWeb.LayoutsTest do
end end
describe "colour_mode_toggle/1" do describe "colour_mode_toggle/1" do
test "renders all three modes as a labelled radiogroup" do test "renders light and dark modes as a labelled radiogroup" do
html = render_component(&Layouts.colour_mode_toggle/1, %{}) html = render_component(&Layouts.colour_mode_toggle/1, %{})
assert html =~ ~s(role="radiogroup") assert html =~ ~s(role="radiogroup")
assert html =~ ~s(aria-label="Colour mode") assert html =~ ~s(aria-label="Colour mode")
for {mode, label} <- [ for {mode, label} <- [
{"system", "System colour mode"},
{"light", "Light colour mode"}, {"light", "Light colour mode"},
{"dark", "Dark colour mode"} {"dark", "Dark colour mode"}
] do ] do
@@ -47,6 +46,7 @@ defmodule ChesstrainerWeb.LayoutsTest do
assert html =~ ~s(role="radio") assert html =~ ~s(role="radio")
end end
refute html =~ ~s(data-phx-theme="system")
assert html =~ ~s(aria-checked="true") assert html =~ ~s(aria-checked="true")
end end
@@ -57,4 +57,13 @@ defmodule ChesstrainerWeb.LayoutsTest do
assert html =~ ~s(class="nav-right") assert html =~ ~s(class="nav-right")
end end
end end
describe "pill button" do
test "renders the navigation call to action as a link" do
html = render_component(&Layouts.navbar/1, %{current_scope: nil})
assert html =~ ~r/<a[^>]*class="nav-cta"/
refute html =~ ~r/<button[^>]*class="nav-cta"/
end
end
end end
@@ -0,0 +1,27 @@
defmodule ChesstrainerWeb.Board.PositionTextTest do
use ExUnit.Case, async: true
alias ChesstrainerWeb.Board.PositionText
test "names the side to move and every piece" do
assert PositionText.summary("8/8/3k4/8/8/3K1R2/8/8 w - - 0 1") ==
"White to move. White: king on d3, rook on f3. Black: king on d6."
end
test "describes black to move" do
assert PositionText.summary("8/8/3k4/8/8/3K1R2/8/8 b - - 0 1") =~
"Black to move."
end
test "includes pawns and both colours" do
summary = PositionText.summary("8/8/3k4/8/8/3K1R2/4P3/8 w - - 0 1")
assert summary =~ "White: king on d3, rook on f3, pawn on e2."
assert summary =~ "Black: king on d6."
end
test "falls back when the FEN cannot be read" do
assert PositionText.summary("not a fen") == "Chess position."
assert PositionText.summary(nil) == "Chess position."
end
end
@@ -69,7 +69,7 @@ defmodule ChesstrainerWeb.PageControllerTest do
refute html =~ "Phoenix Framework" refute html =~ "Phoenix Framework"
eyebrow = LazyHTML.query(document, ".eyebrow") eyebrow = LazyHTML.query(document, ".eyebrow")
assert LazyHTML.text(eyebrow) =~ "Endgames, made clear" assert LazyHTML.text(eyebrow) =~ "Endgames, simplified"
assert LazyHTML.attribute(LazyHTML.query(eyebrow, "svg"), "aria-hidden") == ["true"] assert LazyHTML.attribute(LazyHTML.query(eyebrow, "svg"), "aria-hidden") == ["true"]
assert LazyHTML.attribute(LazyHTML.query(document, ~s(meta[name="description"])), "content") == assert LazyHTML.attribute(LazyHTML.query(document, ~s(meta[name="description"])), "content") ==
@@ -216,19 +216,13 @@ defmodule ChesstrainerWeb.PageControllerTest do
refute html =~ ~p"/users/register" refute html =~ ~p"/users/register"
end end
test "renders curated cards and the daily board", %{conn: conn} do test "renders the daily board", %{conn: conn} do
{beginner, intermediate, advanced} = curated!() curated!()
daily = DailyPuzzles.today() daily = DailyPuzzles.today()
html = conn |> get(~p"/") |> html_response(200) html = conn |> get(~p"/") |> html_response(200)
document = LazyHTML.from_document(html) document = LazyHTML.from_document(html)
assert LazyHTML.attribute(LazyHTML.query(document, ".puzzle-card"), "href") == [
"/endgames/#{beginner.public_code}/play",
"/endgames/#{intermediate.public_code}/play",
"/endgames/#{advanced.public_code}/play"
]
board = LazyHTML.text(LazyHTML.query(document, ".board-caption")) board = LazyHTML.text(LazyHTML.query(document, ".board-caption"))
assert board =~ daily.key assert board =~ daily.key
@@ -238,7 +232,6 @@ defmodule ChesstrainerWeb.PageControllerTest do
assert LazyHTML.text(LazyHTML.query(document, ".board-topline")) =~ "White" assert LazyHTML.text(LazyHTML.query(document, ".board-topline")) =~ "White"
assert html =~ "Try today's puzzle" assert html =~ "Try today's puzzle"
assert html =~ "<span>puzzles</span>"
end end
test "hero CTA links to the daily puzzle", %{conn: conn} do test "hero CTA links to the daily puzzle", %{conn: conn} do
@@ -274,7 +267,6 @@ defmodule ChesstrainerWeb.PageControllerTest do
document = LazyHTML.from_document(html) document = LazyHTML.from_document(html)
assert html =~ "Featured position" assert html =~ "Featured position"
assert html =~ "<span>puzzles</span>"
refute html =~ "puzzle-card" refute html =~ "puzzle-card"
assert LazyHTML.attribute(LazyHTML.query(document, ".hero-actions a"), "href") == [ assert LazyHTML.attribute(LazyHTML.query(document, ".hero-actions a"), "href") == [
@@ -961,7 +961,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
assert_receive {^ref, {:push_event, "review_position", _}}, 100 assert_receive {^ref, {:push_event, "review_position", _}}, 100
assert_receive {^ref, {:push_event, "review_position", _}}, 100 assert_receive {^ref, {:push_event, "review_position", _}}, 100
view |> element("#best-move-panel tr[phx-value-uci='d1d5']") |> render_click() view |> element("#best-move-panel button[phx-value-uci='d1d5']") |> render_click()
assert_receive {^ref, {:push_event, "best_line_move", %{from: "d1", to: "d5"}}}, 100 assert_receive {^ref, {:push_event, "best_line_move", %{from: "d1", to: "d5"}}}, 100
@@ -1044,4 +1044,84 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
assert panel =~ "Qd7+" assert panel =~ "Qd7+"
end end
end end
describe "keyboard move input" do
defp open_with_moves(conn) do
endgame = endgame_fixture()
seed_tablebase(endgame.fen, moves: grading_moves())
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
view
end
test "accepts SAN and asks the board to apply it", %{conn: conn} do
view = open_with_moves(conn)
%{proxy: {ref, _topic, _}} = view
view |> form("#move-input-form", move: "Qd7+") |> render_submit()
assert_receive {^ref, {:push_event, "apply_move", %{from: "d1", to: "d7", san: "Qd7+"}}},
100
end
test "accepts UCI", %{conn: conn} do
view = open_with_moves(conn)
%{proxy: {ref, _topic, _}} = view
view |> form("#move-input-form", move: "d1d5") |> render_submit()
assert_receive {^ref, {:push_event, "apply_move", %{from: "d1", to: "d5"}}}, 100
end
test "reports an illegal move without asking the board to play it", %{conn: conn} do
view = open_with_moves(conn)
%{proxy: {ref, _topic, _}} = view
html = view |> form("#move-input-form", move: "Qh8") |> render_submit()
assert html =~ "Not a legal move here"
refute_receive {^ref, {:push_event, "apply_move", _}}, 100
end
test "labels the input and explains both move formats", %{conn: conn} do
view = open_with_moves(conn)
assert has_element?(view, "label[for='move-input']", "Your move")
assert has_element?(view, "#move-input-help", "SAN or UCI")
assert has_element?(view, "#move-input[aria-describedby='move-input-help']")
end
end
describe "screen reader announcements" do
test "announces the opening position and whose move it is", %{conn: conn} do
endgame = endgame_fixture()
seed_tablebase(endgame.fen)
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
announcer = view |> element("#board-announcer") |> render()
assert announcer =~ "You play White."
assert announcer =~ "White to move."
summary = view |> element("#position-summary") |> render()
assert summary =~ "king on"
end
test "announces a failed puzzle and the best move", %{conn: conn} do
{view, _fens} = seeded_attempt(conn)
announcer = view |> element("#board-announcer") |> render()
assert announcer =~ "Failed."
assert announcer =~ "Best was"
end
test "announces the reviewed position", %{conn: conn} do
{view, _fens} = seeded_attempt(conn)
view |> element("button", "Review") |> render_click()
announcer = view |> element("#board-announcer") |> render()
assert announcer =~ "Reviewing position"
assert announcer =~ "After Qd4"
end
end
end end
@@ -87,7 +87,7 @@ defmodule ChesstrainerWeb.EndgameLive.TrainTest do
assert has_element?(view, "#difficulty-medium") assert has_element?(view, "#difficulty-medium")
assert has_element?(view, "#difficulty-hard") assert has_element?(view, "#difficulty-hard")
assert has_element?(view, "#close-difficulty[href='/']") assert has_element?(view, "#close-difficulty[href='/']")
assert has_element?(view, "a", "Cancel") assert has_element?(view, "a", "Return Home")
refute has_element?(view, "#puzzle-search") refute has_element?(view, "#puzzle-search")
assert has_element?(view, "#rating-guide") assert has_element?(view, "#rating-guide")
assert render(view) =~ "Choose a difficulty" assert render(view) =~ "Choose a difficulty"