Compare commits

...
5 Commits
Author SHA1 Message Date
owenrees 7209923de7 Align board file labels with their squares 2026-11-17 15:13:47 +01:00
owenrees f4ff1e00fb Move colour mode and Discord controls into the mobile menu 2026-11-17 15:05:02 +01:00
owenrees 514c6ac924 Add Discord invite link to navbar and footer 2026-11-17 15:00:38 +01:00
owenrees e0b446bbfb Weight puzzle selection and stop repeats inside a session (#183)
Selection took a hard rating band (medium = user rating ± 100), removed
everything attempted in the last 30 days, and drew uniformly from what was
left. Because the bulk importer gives every endgame in a batch the same
rating, the band held either the whole library or — once a user's rating
drifted past it — only the endgames that user had already played. With
`fresh` empty, the fallback re-drew from the same band ignoring recency, so
recently played puzzles came straight back. An empty band used a
deterministic nearest-match, alternating between the same two puzzles.

Difficulty is now a bias rather than a filter: candidates are weighted by
`exp(-|rating - target| / spread)` and drawn with an exponential race, so
the whole library stays reachable and a thin region around the user's rating
can never empty the pool. `easy` and `hard` keep one-sided guards so the
labels stay honest. When every candidate is excluded, selection serves the
least recently attempted endgame instead of a random recent one.

Sessions now carry the ids they have served, which fixes the observed
in-session repeat (only the current puzzle used to be excluded), and guest
training gets the same treatment. The 30-day window is configurable as the
repeat window and is now named in GLOSSARY.md, distinct from the rating
window and from the tablebase cooldown.

Difficulty copy is qualitative, since the band numbers no longer describe
how selection works.
2026-11-17 14:28:24 +01:00
owenrees fa1fef7b62 Launch amendments: one login, crawler policy, and asset caching (#180)
* lesson library shown as com,ing soon. re-enable learngin strip

* replace learning strip text with a lasker quote

* remove admin login endpoint

* fix crawler directives and prelaunch login

- noindex the authenticated scope and the 404 catch-all, and cover the
  mailing-list confirmation redirect
- emit noindex, nofollow from the robots meta and /health, and assert
  public pages stay indexable and followable
- stop inventing lastmod values in the sitemap
- log in through /users/log-in during prelaunch now that the admin login
  endpoint is gone; drop create_admin/2 and its orphaned tests

* update caching length to 1 year - name change will invalidate cache

* remove logger

* fix tablebase path breaking tests

* test: check cache headers without requiring built assets

CI's test job does not run mix assets.build, so /assets/css/app.css is a
404 there. Committed piece art is already content-hashed and takes the same
Plug.Static cache option, so the test no longer needs a build step and
passes on a fresh checkout.
2026-11-17 12:55:47 +01:00
37 changed files with 544 additions and 213 deletions
+2
View File
@@ -11,6 +11,8 @@ SES_CONFIGURATION_SET=my-first-configuration-set
# Optional: override the sender or send everything to one address while testing. # Optional: override the sender or send everything to one address while testing.
# MAIL_FROM=no-reply@mail.innersquare.app # MAIL_FROM=no-reply@mail.innersquare.app
# MAIL_REDIRECT_TO=you@example.com # MAIL_REDIRECT_TO=you@example.com
# Optional: directory of local Syzygy .rtbw/.rtbz files. Ignored by the test
# suite, which always uses the committed 3-piece fixtures.
TABLEBASE_PATH= TABLEBASE_PATH=
MATOMO_URL=https://analytics.owenrees.eu/ MATOMO_URL=https://analytics.owenrees.eu/
+15 -5
View File
@@ -105,6 +105,14 @@ carries a start time and a rating baseline for the timer and rating-gain
monitor. Ephemeral — it lives only in the running LiveView, never persisted. monitor. Ephemeral — it lives only in the running LiveView, never persisted.
_Avoid_: Run, game, attempt _Avoid_: Run, game, attempt
**Repeat window**:
The minimum interval before the same endgame may be served to the same user
again. Selection skips endgames attempted inside the window; only when nothing
else is available does the least recently attempted endgame come back. It is
independent of the rating window, which decides whether a replay may move a
rating.
_Avoid_: Cooldown (reserved for tablebase rate-limiting), due date
## Ratings ## Ratings
**Rating**: **Rating**:
@@ -128,11 +136,13 @@ systems; the trainer deliberately does not track it.
_Avoid_: Variance, inconsistency _Avoid_: Variance, inconsistency
**Difficulty**: **Difficulty**:
A choice — `easy`, `medium` or `hard` — that selects which puzzles to serve A choice — `easy`, `medium` or `hard` — that biases which puzzles are served
relative to the current user's rating: `medium` is near the user's rating, relative to the current user's rating: `medium` centres on the user's rating,
`easy` below it, `hard` above it. The band width is a configured constant. It is `easy` below it, `hard` above it. Candidates are weighted by how close their
a property of a session, not of an endgame — the same endgame is easy for one rating is to that centre, so a session draws mostly from near the target but the
user and hard for another. whole library stays reachable. The spread is a configured constant. It is a
property of a session, not of an endgame — the same endgame is easy for one user
and hard for another.
_Avoid_: Level, rank, tier _Avoid_: Level, rank, tier
## Infrastructure ## Infrastructure
+5
View File
@@ -43,6 +43,10 @@
.avatar-stack i:last-child { background: var(--color-deep); color: var(--color-on-deep); } .avatar-stack i:last-child { background: var(--color-deep); color: var(--color-on-deep); }
.puzzle-section { width: min(1180px, calc(100% - 48px)); margin: 0 auto; padding: 110px 0 125px; } .puzzle-section { width: min(1180px, calc(100% - 48px)); margin: 0 auto; padding: 110px 0 125px; }
.puzzle-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; } .puzzle-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; }
.puzzle-coming-soon { min-height: 285px; display: grid; place-content: center; justify-items: center; gap: 10px; padding: 46px 28px; text-align: center; border: 1px dashed var(--color-hairline); border-radius: 12px; background: var(--color-canvas-raised); }
.puzzle-coming-soon .eyebrow { margin-bottom: 6px; }
.puzzle-coming-soon strong { font-family: 'DM Serif Display', serif; font-size: 30px; font-weight: 400; }
.puzzle-coming-soon p { max-width: 420px; margin: 0; color: var(--color-muted); font-size: 14px; line-height: 1.7; }
.puzzle-card { display: block; position: relative; min-height: 285px; padding: 25px; text-align: left; text-decoration: none; color: inherit; cursor: pointer; border: 1px solid var(--color-hairline); border-radius: 12px; background: rgba(255,255,255,.28); overflow: hidden; transition: transform .25s, background .25s, box-shadow .25s; } .puzzle-card { display: block; position: relative; min-height: 285px; padding: 25px; text-align: left; text-decoration: none; color: inherit; cursor: pointer; border: 1px solid var(--color-hairline); border-radius: 12px; background: rgba(255,255,255,.28); overflow: hidden; transition: transform .25s, background .25s, box-shadow .25s; }
.puzzle-card:hover, .puzzle-card.active { transform: translateY(-5px); background: var(--color-canvas-raised); box-shadow: 0 18px 36px rgba(23,53,45,.08); } .puzzle-card:hover, .puzzle-card.active { transform: translateY(-5px); background: var(--color-canvas-raised); box-shadow: 0 18px 36px rgba(23,53,45,.08); }
.puzzle-card.active { border-color: var(--color-success-text); } .puzzle-card.active { border-color: var(--color-success-text); }
@@ -69,6 +73,7 @@ html[data-theme="dark"] .learning-strip { box-shadow: inset 0 1px 0 var(--color-
@media (max-width: 650px) { @media (max-width: 650px) {
.puzzle-section { width: calc(100% - 36px); padding: 80px 0; } .puzzle-section { width: calc(100% - 36px); padding: 80px 0; }
.puzzle-grid { grid-template-columns: 1fr; } .puzzle-grid { grid-template-columns: 1fr; }
.puzzle-coming-soon { min-height: 255px; padding: 38px 22px; }
.puzzle-card { min-height: 255px; } .puzzle-card { min-height: 255px; }
.progress-banner { width: calc(100% - 36px); padding: 48px 28px; flex-direction: column; align-items: flex-start; gap: 34px; } .progress-banner { width: calc(100% - 36px); padding: 48px 28px; flex-direction: column; align-items: flex-start; gap: 34px; }
} }
+7
View File
@@ -43,6 +43,13 @@
/* Play board */ /* Play board */
#endgame-board { position: relative; } #endgame-board { position: relative; }
/* Chessground's stock stylesheet shifts the file labels 24px right of the
board, assuming a gutter we don't have, so they land on square boundaries
instead of under each file. Place the row on the board and right-justify
each label within its square; the row's width already matches the board
because the container is sized to whole squares. */
#endgame-board coords.files { left: 0; text-align: right; }
/* Chessground's wrapper has no intrinsic height; let it fill the sized /* Chessground's wrapper has no intrinsic height; let it fill the sized
aspect-ratio container so the board scales with the viewport. */ aspect-ratio container so the board scales with the viewport. */
#endgame-board .cg-wrap { width: 100%; height: 100%; } #endgame-board .cg-wrap { width: 100%; height: 100%; }
+8 -1
View File
@@ -1,2 +1,9 @@
.eyebrow { display: flex; align-items: center; gap: 9px; margin-bottom: 27px; color: var(--color-coral-text); text-transform: uppercase; letter-spacing: .13em; font-size: 12px; font-weight: 700; } .eyebrow { display: flex; align-items: center; gap: 9px; margin-bottom: 27px; color: var(--color-coral-text); text-transform: uppercase; letter-spacing: .13em; font-size: 12px; font-weight: 700; }
.eyebrow svg { width: 20px; height: 20px; } .eyebrow svg { width: 20px; height: 20px; }
/* Icon-only external links, e.g. the Discord invite in the navbar and footer.
Colour is inherited so the glyph matches the surrounding link row. */
.discord-link { display: inline-flex; align-items: center; color: inherit; transition: opacity .2s; }
.discord-link:hover { opacity: .55; }
.discord-link:focus-visible { outline: 2px solid var(--color-coral-control); outline-offset: 3px; border-radius: 4px; }
.discord-link svg { width: 20px; height: 20px; }
+4 -2
View File
@@ -3,7 +3,9 @@
display: grid; grid-template-columns: 1.5fr repeat(3, 1fr); align-items: center; background: var(--color-deep); color: var(--color-on-deep); display: grid; grid-template-columns: 1.5fr repeat(3, 1fr); align-items: center; background: var(--color-deep); color: var(--color-on-deep);
} }
.learning-strip > p { max-width: 260px; color: var(--color-on-deep-muted); font-family: 'DM Serif Display', serif; font-size: 19px; line-height: 1.25; } .learning-quote { margin: 0; max-width: 300px; }
.learning-quote blockquote { margin: 0; color: var(--color-on-deep); font-family: 'DM Serif Display', serif; font-size: 19px; line-height: 1.25; }
.learning-quote figcaption { margin-top: 10px; color: var(--color-on-deep-faint); font-size: 10px; text-transform: uppercase; letter-spacing: .09em; }
.stat { padding-left: 34px; border-left: 1px solid rgba(255,255,255,.17); } .stat { padding-left: 34px; border-left: 1px solid rgba(255,255,255,.17); }
.stat strong { display: block; font-family: 'DM Serif Display', serif; font-size: 28px; font-weight: 400; } .stat strong { display: block; font-family: 'DM Serif Display', serif; font-size: 28px; font-weight: 400; }
@@ -15,7 +17,7 @@
@media (max-width: 650px) { @media (max-width: 650px) {
.learning-strip { padding: 38px 24px; grid-template-columns: 1fr 1fr; gap: 30px 10px; } .learning-strip { padding: 38px 24px; grid-template-columns: 1fr 1fr; gap: 30px 10px; }
.learning-strip > p { grid-column: 1 / -1; } .learning-quote { grid-column: 1 / -1; }
.stat { padding-left: 18px; } .stat { padding-left: 18px; }
.stat:last-child { grid-column: 1 / -1; } .stat:last-child { grid-column: 1 / -1; }
} }
+8
View File
@@ -14,6 +14,9 @@
.nav-links a { transition: opacity .2s; } .nav-links a { transition: opacity .2s; }
.nav-links a:hover { opacity: .55; } .nav-links a:hover { opacity: .55; }
.nav-links a.nav-cta:hover { opacity: 1; } .nav-links a.nav-cta:hover { opacity: 1; }
/* Utilities (colour mode, Discord) sit in the bar on desktop and in the
collapsible menu on small screens. */
.nav-menu-tools { display: none; }
.nav-user-menu { position: relative; } .nav-user-menu { position: relative; }
.nav-user-menu summary { display: flex; align-items: center; gap: 6px; list-style: none; cursor: pointer; color: var(--color-muted); font-weight: 500; } .nav-user-menu summary { display: flex; align-items: center; gap: 6px; list-style: none; cursor: pointer; color: var(--color-muted); font-weight: 500; }
.nav-user-menu summary::-webkit-details-marker { display: none; } .nav-user-menu summary::-webkit-details-marker { display: none; }
@@ -42,6 +45,11 @@ html[data-theme="dark"] .nav-user-menu-panel { box-shadow: 0 18px 40px rgba(0, 0
.nav-links.open { display: flex; } .nav-links.open { display: flex; }
.nav-cta { width: 100%; } .nav-cta { width: 100%; }
.nav-links { display: none; position: absolute; top: 65px; left: 0; right: 0; padding: 24px; flex-direction: column; align-items: stretch; gap: 22px; border-radius: 10px; background: var(--color-canvas-raised); box-shadow: 0 18px 40px rgba(23,53,45,.15); } .nav-links { display: none; position: absolute; top: 65px; left: 0; right: 0; padding: 24px; flex-direction: column; align-items: stretch; gap: 22px; border-radius: 10px; background: var(--color-canvas-raised); box-shadow: 0 18px 40px rgba(23,53,45,.15); }
.nav-menu-tools { display: flex; align-items: center; justify-content: space-between; gap: 18px; width: 100%; }
/* The menu owns these on small screens; keep them in the bar only when no
menu is rendered (prelaunch with no links). */
.nav-wrap:has(#nav-links) .nav-right > [role="radiogroup"],
.nav-wrap:has(#nav-links) .nav-right > .discord-link { display: none; }
.nav-user-menu-panel { position: static; min-width: 0; padding: 12px 0 0; background: transparent; box-shadow: none; } .nav-user-menu-panel { position: static; min-width: 0; padding: 12px 0 0; background: transparent; box-shadow: none; }
html[data-theme="dark"] .nav-links { box-shadow: 0 18px 40px rgba(0, 0, 0, .45); } html[data-theme="dark"] .nav-links { box-shadow: 0 18px 40px rgba(0, 0, 0, .45); }
} }
+12 -6
View File
@@ -15,7 +15,8 @@ config :chesstrainer, :branding,
wordmark: "INNERSQUARE", wordmark: "INNERSQUARE",
tagline: "Endgame Trainer", tagline: "Endgame Trainer",
support_email: "support@innersquare.app", support_email: "support@innersquare.app",
mail_from: "no-reply@mail.innersquare.app" mail_from: "no-reply@mail.innersquare.app",
discord_invite: "https://discord.gg/Z2NfkG7thV"
# Prelaunch gating. Production sets these from PRELAUNCH and # Prelaunch gating. Production sets these from PRELAUNCH and
# MAILING_LIST_ENABLED; dev and test use these defaults. # MAILING_LIST_ENABLED; dev and test use these defaults.
@@ -61,11 +62,16 @@ config :chesstrainer, :ratings,
window_days: 7, window_days: 7,
rd_inflation_c: 10.0 rd_inflation_c: 10.0
# Difficulty bands for puzzle sessions. An endgame is "medium" when its rating # Puzzle selection. Difficulty is a weighted bias towards a target rating —
# falls within `band_width` of the user's rating, "easy" below that band and # `medium` targets the user's rating, `easy` 200 below it and `hard` 200 above
# "hard" above it. Tweak to widen or narrow the served difficulty (e.g. 150 or # it — and `spread` is how many rating points it takes for a puzzle's chance to
# 200). # fall off by a factor of e. `repeat_window_days` is how long an attempted
config :chesstrainer, :puzzles, band_width: 100 # puzzle stays out of the pool. Tweak `spread` to widen or narrow the served
# difficulty (e.g. 100 or 250).
config :chesstrainer, :puzzles,
spread: 150,
repeat_window_days: 30,
targets: [easy: -200, medium: 0, hard: 200]
# Public codes of the endgames pinned to the landing-page puzzle grid, in # Public codes of the endgames pinned to the landing-page puzzle grid, in
# display order. When empty (or short) the grid is topped up with a date-seeded # display order. When empty (or short) the grid is topped up with a date-seeded
+7 -3
View File
@@ -48,9 +48,13 @@ config :chesstrainer, :mail_redirect_to, System.get_env("MAIL_REDIRECT_TO")
# Local Syzygy tablebases: set TABLEBASE_PATH to the directory holding the # Local Syzygy tablebases: set TABLEBASE_PATH to the directory holding the
# .rtbw/.rtbz files. When unset, the local backend stays disabled and lookups # .rtbw/.rtbz files. When unset, the local backend stays disabled and lookups
# fall back to Lichess. # fall back to Lichess. Tests are always pinned to the committed 3-piece
if tablebase_path = System.get_env("TABLEBASE_PATH") do # fixtures by config/test.exs, so an exported TABLEBASE_PATH cannot make them
config :chesstrainer, :tablebase_path, tablebase_path # depend on whatever tables the developer happens to have downloaded.
if config_env() != :test do
if tablebase_path = System.get_env("TABLEBASE_PATH") do
config :chesstrainer, :tablebase_path, tablebase_path
end
end end
# Tablebase cache: size and the UTC time of the daily backup. Environment # Tablebase cache: size and the UTC time of the daily backup. Environment
+2 -2
View File
@@ -106,8 +106,8 @@ defmodule Chesstrainer.Attempts do
@doc """ @doc """
The distinct endgame ids `user_id` has attempted in the last `days` days. The distinct endgame ids `user_id` has attempted in the last `days` days.
Used by puzzle selection to prefer fresh puzzles; a retry still counts as an Used by puzzle selection to skip puzzles inside the repeat window; a retry
attempt, even though the rating window leaves it unrated. still counts as an attempt, even though the rating window leaves it unrated.
""" """
def recent_endgame_ids(user_id, days \\ 30) do def recent_endgame_ids(user_id, days \\ 30) do
cutoff = DateTime.add(DateTime.utc_now(), -days, :day) cutoff = DateTime.add(DateTime.utc_now(), -days, :day)
+22 -1
View File
@@ -12,7 +12,8 @@ defmodule Chesstrainer.Branding do
wordmark: "INNERSQUARE", wordmark: "INNERSQUARE",
tagline: "Endgame Trainer", tagline: "Endgame Trainer",
support_email: "support@innersquare.app", support_email: "support@innersquare.app",
mail_from: "no-reply@mail.innersquare.app" mail_from: "no-reply@mail.innersquare.app",
discord_invite: "https://discord.gg/Z2NfkG7thV"
] ]
@doc "The display name, e.g. `\"Lucid Chess\"`." @doc "The display name, e.g. `\"Lucid Chess\"`."
@@ -30,6 +31,26 @@ defmodule Chesstrainer.Branding do
@doc "The From address used for outgoing mail." @doc "The From address used for outgoing mail."
def mail_from, do: get(:mail_from) def mail_from, do: get(:mail_from)
@doc """
The Discord invite URL, or `nil` when no invite is configured.
Accepts either a bare invite code (`"abc123"`) or a full URL; a bare code is
expanded to `https://discord.gg/<code>`.
"""
def discord_invite_url do
case get(:discord_invite) do
value when is_binary(value) ->
case String.trim(value) do
"" -> nil
"http" <> _ = url -> url
code -> "https://discord.gg/#{code}"
end
_ ->
nil
end
end
@doc "The home-page title, e.g. `\"Lucid Chess — Endgame Trainer\"`." @doc "The home-page title, e.g. `\"Lucid Chess — Endgame Trainer\"`."
def home_title, do: "#{name()} — #{tagline()}" def home_title, do: "#{name()} — #{tagline()}"
+85 -58
View File
@@ -2,14 +2,21 @@ defmodule Chesstrainer.Puzzles do
@moduledoc """ @moduledoc """
Selects endgames to serve as puzzles. Selects endgames to serve as puzzles.
A puzzle is played at one of three difficulties — `:easy`, `:medium` or Difficulty is a bias, not a filter. Every endgame is weighted by how close its
`:hard` — defined relative to the current user's rating: `:medium` is within rating is to a target derived from the user's rating — the user's own rating
a configurable band of the user's rating, `:easy` below it and `:hard` above for `:medium`, below it for `:easy` and above it for `:hard` — and one
it. The same endgame is therefore easy for one player and hard for another. candidate is drawn from that weighted distribution. Nearby endgames are much
more likely, but the whole library stays reachable, so a thin region around
the user's rating can never leave the pool empty.
Selection prefers endgames the user has not attempted in the last 30 days. Endgames the user has attempted inside the repeat window are skipped, as is
When that pool is empty it falls back to any endgame in the band; the rating anything passed in `:exclude_ids` (the puzzles already served in a session).
window keeps a recent replay unrated until it expires. Only when every candidate is excluded does selection fall back to the least
recently attempted endgame, so the repeat is the most overdue one rather than
an arbitrary one.
The same endgame is therefore easy for one player and hard for another: a
rating is what makes the two comparable.
""" """
import Ecto.Query, warn: false import Ecto.Query, warn: false
@@ -17,95 +24,115 @@ defmodule Chesstrainer.Puzzles do
alias Chesstrainer.Repo alias Chesstrainer.Repo
alias Chesstrainer.Accounts.User alias Chesstrainer.Accounts.User
alias Chesstrainer.Attempts alias Chesstrainer.Attempts
alias Chesstrainer.Attempts.Attempt
alias Chesstrainer.Endgames.Endgame alias Chesstrainer.Endgames.Endgame
@default_band_width 100 @default_spread 150
@default_repeat_window_days 30
@default_targets [easy: -200, medium: 0, hard: 200]
@difficulties [:easy, :medium, :hard] @difficulties [:easy, :medium, :hard]
@doc "The difficulties a session can be played at." @doc "The difficulties a session can be played at."
def difficulties, do: @difficulties def difficulties, do: @difficulties
@doc """ @doc """
The half-width of the medium band, in rating points. How far, in rating points, a puzzle's likelihood falls off from the target.
Configured under `:chesstrainer, :puzzles, :band_width`. A larger spread draws more widely around the target. Configured under
`:chesstrainer, :puzzles, :spread`.
""" """
def band_width do def spread, do: setting(:spread, @default_spread)
:chesstrainer
|> Application.get_env(:puzzles, [])
|> Keyword.get(:band_width, @default_band_width)
end
@doc """ @doc """
The `{min, max}` rating range for `difficulty` relative to `rating`. The minimum gap, in days, before the same endgame may be served again.
A `nil` bound is open-ended. Configured under `:chesstrainer, :puzzles, :repeat_window_days`.
""" """
def difficulty_range(rating, difficulty) when difficulty in @difficulties do def repeat_window_days, do: setting(:repeat_window_days, @default_repeat_window_days)
width = band_width()
case difficulty do @doc """
:easy -> {nil, rating - width} The rating `difficulty` aims at, given the player's `rating`.
:medium -> {rating - width, rating + width}
:hard -> {rating + width, nil} The offsets are configured under `:chesstrainer, :puzzles, :targets`.
end """
def difficulty_target(rating, difficulty) when difficulty in @difficulties do
rating + Keyword.fetch!(setting(:targets, @default_targets), difficulty)
end end
@doc """ @doc """
Picks the next puzzle for `user` at `difficulty`, using `user.rating` as the Picks the next puzzle for `user` at `difficulty`, using `user.rating` as the
baseline. baseline.
`:exclude_ids` (default `[]`) skips endgames by id — used to avoid repeating `:exclude_ids` (default `[]`) skips endgames by id — used for the puzzles
the puzzle just played. Returns `nil` when no endgame exists at all. already served in this session. Returns `nil` when no endgame exists at all.
""" """
def next_endgame(%User{} = user, difficulty, opts \\ []) def next_endgame(%User{} = user, difficulty, opts \\ [])
when difficulty in @difficulties do when difficulty in @difficulties do
exclude_ids = Keyword.get(opts, :exclude_ids, []) exclude_ids = Keyword.get(opts, :exclude_ids, [])
band = difficulty_range(user.rating, difficulty) recent_ids = Attempts.recent_endgame_ids(user.id, repeat_window_days())
recent_ids = Attempts.recent_endgame_ids(user.id) target = difficulty_target(user.rating, difficulty)
fresh =
Endgame
|> in_band(band)
|> skip_ids(exclude_ids)
|> skip_ids(recent_ids)
|> random_one()
fresh || fallback(user.rating, band, exclude_ids)
end
defp fallback(rating, band, exclude_ids) do
Endgame Endgame
|> in_band(band) |> on_side_of(user.rating, difficulty)
|> skip_ids(exclude_ids) |> skip_ids(exclude_ids ++ recent_ids)
|> random_one() |> weighted_one(target)
|> case do |> case do
nil -> nearest(rating, exclude_ids) nil -> least_recently_attempted(user.id, exclude_ids)
endgame -> endgame endgame -> endgame
end end
end end
defp nearest(rating, exclude_ids) do # Keep the labels honest: "easy" never serves above the user's rating plus the
# spread, and "hard" never below it minus the spread. "medium" is open, which
# is what lets it reach the rest of the library.
defp on_side_of(query, _rating, :medium), do: query
defp on_side_of(query, rating, :easy),
do: where(query, [e], e.rating <= ^(rating + spread()))
defp on_side_of(query, rating, :hard),
do: where(query, [e], e.rating >= ^(rating - spread()))
# Draw one row with probability proportional to
# `exp(-|rating - target| / spread)`: an exponential race, where the row with
# the smallest `-ln(U) / weight` wins.
defp weighted_one(query, target) do
spread = spread() * 1.0
target = target * 1.0
query
|> order_by(
[e],
fragment("-ln(1 - random()) * exp(abs(? - ?) / ?)", e.rating, ^target, ^spread)
)
|> limit(1)
|> Repo.one()
end
# Every candidate is excluded, so the repeat window is overruled: serve
# whatever the user has waited longest to see again.
defp least_recently_attempted(user_id, exclude_ids) do
attempted =
Attempt
|> where([a], a.user_id == ^user_id)
|> group_by([a], a.endgame_id)
|> select([a], %{endgame_id: a.endgame_id, last_at: max(a.inserted_at)})
Endgame Endgame
|> skip_ids(exclude_ids) |> skip_ids(exclude_ids)
|> order_by([e], asc: fragment("ABS(? - ?)", e.rating, ^rating)) |> join(:left, [e], a in subquery(attempted), on: a.endgame_id == e.id)
|> order_by([_e, a], asc_nulls_first: a.last_at)
|> order_by([e], fragment("random()"))
|> limit(1) |> limit(1)
|> Repo.one() |> Repo.one()
end end
defp random_one(query) do
query
|> order_by([e], fragment("RANDOM()"))
|> limit(1)
|> Repo.one()
end
defp in_band(query, {nil, max}), do: where(query, [e], e.rating <= ^max)
defp in_band(query, {min, nil}), do: where(query, [e], e.rating >= ^min)
defp in_band(query, {min, max}),
do: where(query, [e], e.rating >= ^min and e.rating <= ^max)
defp skip_ids(query, []), do: query defp skip_ids(query, []), do: query
defp skip_ids(query, ids), do: where(query, [e], e.id not in ^ids) defp skip_ids(query, ids), do: where(query, [e], e.id not in ^ids)
defp setting(key, default) do
:chesstrainer
|> Application.get_env(:puzzles, [])
|> Keyword.get(key, default)
end
end end
@@ -126,8 +126,15 @@ defmodule ChesstrainerWeb.Layouts do
Start training <.icon_arrow /> Start training <.icon_arrow />
</.pill_button> </.pill_button>
<% end %> <% end %>
<div class="nav-menu-tools">
<.colour_mode_toggle />
<.discord_link />
</div>
</div> </div>
<% end %> <% end %>
<.discord_link />
</div> </div>
</nav> </nav>
</header> </header>
@@ -225,6 +232,7 @@ defmodule ChesstrainerWeb.Layouts do
<a href="/terms-conditions">Terms & Conditions</a> <a href="/terms-conditions">Terms & Conditions</a>
<a href="/mentions-legales">Mentions légales</a> <a href="/mentions-legales">Mentions légales</a>
<a href="/sitemap.xml">Sitemap</a> <a href="/sitemap.xml">Sitemap</a>
<.discord_link />
</nav> </nav>
<small>© {@year} {Branding.name()}</small> <small>© {@year} {Branding.name()}</small>
@@ -232,6 +240,35 @@ defmodule ChesstrainerWeb.Layouts do
""" """
end end
@doc """
Renders the Discord invite as an icon-only link.
The glyph is decorative; the `aria-label` carries the link's purpose for
screen readers. Renders nothing when no invite is configured, so environments
without one never show a dead link.
"""
def discord_link(assigns) do
assigns = assign(assigns, :href, Branding.discord_invite_url())
~H"""
<a
:if={@href}
class="discord-link"
href={@href}
target="_blank"
rel="noopener noreferrer"
aria-label={"Join the #{Branding.name()} Discord"}
>
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<path
fill="currentColor"
d="M20.317 4.3698a19.7913 19.7913 0 0 0-4.8851-1.5152.0741.0741 0 0 0-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 0 0-.0785-.037 19.7363 19.7363 0 0 0-4.8852 1.515.0699.0699 0 0 0-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 0 0 .0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 0 0 .0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 0 0-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 0 1-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 0 1 .0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 0 1 .0785.0105c.1202.0991.246.1971.3728.2914a.077.077 0 0 1-.0066.1277c-.5986.3428-1.2201.6447-1.8739.8923a.0766.0766 0 0 0-.0407.1057c.36.699.7715 1.3647 1.225 1.9942a.076.076 0 0 0 .0843.0276c1.9608-.6066 3.9493-1.5218 6.0021-3.0294a.077.077 0 0 0 .0322-.0561c.5008-5.1763-.8398-9.6746-3.5543-13.6607a.061.061 0 0 0-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.946 2.4189-2.1568 2.4189Z"
/>
</svg>
</a>
"""
end
@doc """ @doc """
Shows the flash group with standard titles and content. Shows the flash group with standard titles and content.
@@ -3,7 +3,7 @@
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<meta :if={assigns[:noindex]} name="robots" content="noindex" /> <meta :if={assigns[:noindex]} name="robots" content="noindex, nofollow" />
<meta name="csrf-token" content={get_csrf_token()} /> <meta name="csrf-token" content={get_csrf_token()} />
<.live_title <.live_title
@@ -65,7 +65,10 @@
if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return; if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;
event.preventDefault(); event.preventDefault();
const buttons = Array.from(document.querySelectorAll("[data-phx-theme]")); // Each breakpoint renders its own copy of the switch, so only the visible
// group takes part in arrow-key navigation.
const buttons = Array.from(document.querySelectorAll("[data-phx-theme]"))
.filter((button) => button.offsetParent !== null);
const offset = event.key === "ArrowRight" ? 1 : -1; const offset = event.key === "ArrowRight" ? 1 : -1;
const index = (buttons.indexOf(button) + offset + buttons.length) % buttons.length; const index = (buttons.indexOf(button) + offset + buttons.length) % buttons.length;
const next = buttons[index]; const next = buttons[index];
@@ -10,7 +10,7 @@ defmodule ChesstrainerWeb.HealthController do
status = if health.status == "down", do: :service_unavailable, else: :ok status = if health.status == "down", do: :service_unavailable, else: :ok
conn conn
|> put_resp_header("x-robots-tag", "noindex") |> put_resp_header("x-robots-tag", "noindex, nofollow")
|> put_status(status) |> put_status(status)
|> json(health) |> json(health)
end end
@@ -40,8 +40,11 @@
</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> <figure class="learning-quote">
<blockquote>“The hardest game to win is a won game.”</blockquote>
<figcaption>— Emmanuel Lasker</figcaption>
</figure>
<div class="stat"> <div class="stat">
<strong>{count_label(@puzzle_count)}</strong> <strong>{count_label(@puzzle_count)}</strong>
<span>puzzles</span> <span>puzzles</span>
@@ -50,9 +53,9 @@
<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 lesson</span> <span class="section-kicker">Choose your lesson</span>
@@ -65,16 +68,16 @@
that you’ll recognise over the board. that you’ll recognise over the board.
</p> </p>
</div> </div>
<div class="puzzle-grid"> <div class="puzzle-coming-soon">
<%= for {endgame, index} <- Enum.with_index(@endgames) do %> <div class="eyebrow">
<.puzzle_card <.icon_spark /> Coming soon
endgame={endgame} </div>
index={index} <strong>The lesson library is on its way.</strong>
active={@active_endgame && endgame.id == @active_endgame.id} <p>
/> A growing set of positions, each teaching one idea. Today’s puzzle is already live.
<% end %> </p>
</div> </div>
</section> --%> </section>
<.mailing_list_signup :if={@mailing_list_enabled} /> <.mailing_list_signup :if={@mailing_list_enabled} />
@@ -6,19 +6,20 @@ defmodule ChesstrainerWeb.SitemapController do
them and they render the same interactive surface with only the position them and they render the same interactive surface with only the position
differing, so listing them all would be index bloat. Revisit that if public differing, so listing them all would be index bloat. Revisit that if public
browse pages (by Key or theme) exist and are worth ranking. browse pages (by Key or theme) exist and are worth ranking.
No `<lastmod>` is emitted: none of these pages has a stored modification time,
and an invented date (such as "today" on every request) teaches crawlers to
distrust the sitemap.
""" """
use ChesstrainerWeb, :controller use ChesstrainerWeb, :controller
def index(conn, _params) do def index(conn, _params) do
# The landing page changes every day (daily puzzle, counts), so its
# lastmod is honest. The legal pages have no stored modification time, and
# an invented lastmod is worse than none.
entries = [ entries = [
{url(conn, ~p"/"), Date.utc_today()}, url(conn, ~p"/"),
{url(conn, ~p"/privacy"), nil}, url(conn, ~p"/privacy"),
{url(conn, ~p"/terms-conditions"), nil}, url(conn, ~p"/terms-conditions"),
{url(conn, ~p"/mentions-legales"), nil} url(conn, ~p"/mentions-legales")
] ]
conn conn
@@ -28,8 +29,8 @@ defmodule ChesstrainerWeb.SitemapController do
defp render_sitemap(entries) do defp render_sitemap(entries) do
urls = urls =
Enum.map_join(entries, fn {loc, lastmod} -> Enum.map_join(entries, fn loc ->
" <url><loc>#{escape(loc)}</loc>#{lastmod_entry(lastmod)}</url>\n" " <url><loc>#{escape(loc)}</loc></url>\n"
end) end)
""" """
@@ -39,9 +40,6 @@ defmodule ChesstrainerWeb.SitemapController do
""" """
end end
defp lastmod_entry(nil), do: ""
defp lastmod_entry(%Date{} = date), do: "<lastmod>#{Date.to_iso8601(date)}</lastmod>"
# Templates escape automatically; this response is built as a plain string, # Templates escape automatically; this response is built as a plain string,
# so XML-significant characters must be escaped here. # so XML-significant characters must be escaped here.
defp escape(value) do defp escape(value) do
@@ -12,14 +12,6 @@ defmodule ChesstrainerWeb.UserSessionController do
authenticate(conn, user_params, ~p"/users/log-in", nil) authenticate(conn, user_params, ~p"/users/log-in", nil)
end end
def create_admin(conn, %{"user" => user_params}) do
if ChesstrainerWeb.prelaunch?() do
authenticate(conn, user_params, ~p"/admin/log-in", ~p"/admin/endgames")
else
authenticate(conn, user_params, ~p"/users/log-in", nil)
end
end
defp authenticate(conn, user_params, failure_path, success_path) do defp authenticate(conn, user_params, failure_path, success_path) do
%{"email" => login} = user_params %{"email" => login} = user_params
address = ClientAddress.from_conn(conn) address = ClientAddress.from_conn(conn)
+7 -1
View File
@@ -19,12 +19,18 @@ defmodule ChesstrainerWeb.Endpoint do
# #
# When code reloading is disabled (e.g., in production), # When code reloading is disabled (e.g., in production),
# the `gzip` option is enabled to serve compressed # the `gzip` option is enabled to serve compressed
# static files generated by running `phx.digest`. # static files generated by running `phx.digest`, and the cache headers promise
# a year. Build output is digested, and the stable-name assets (fonts, piece
# art, icons) only change when the file is renamed, so a long max-age is safe
# and keeps browsers and the CDN off the origin. Dev keeps plain `public` so
# edits show up immediately.
plug Plug.Static, plug Plug.Static,
at: "/", at: "/",
from: :chesstrainer, from: :chesstrainer,
gzip: not code_reloading?, gzip: not code_reloading?,
only: ChesstrainerWeb.static_paths(), only: ChesstrainerWeb.static_paths(),
cache_control_for_etags:
if(code_reloading?, do: "public", else: "public, max-age=31536000, immutable"),
raise_on_missing_only: code_reloading? raise_on_missing_only: code_reloading?
# Code reloading can be explicitly enabled under the # Code reloading can be explicitly enabled under the
@@ -135,7 +135,10 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
@impl true @impl true
def mount(_params, _session, socket) do def mount(_params, _session, socket) do
socket = assign(socket, :limit, GuestLimits.limit()) socket =
socket
|> assign(:limit, GuestLimits.limit())
|> assign(:served_ids, [])
cond do cond do
signed_in?(socket) -> signed_in?(socket) ->
@@ -217,11 +220,7 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
|> assign(:limit_reached, retry_ms) |> assign(:limit_reached, retry_ms)
{:ok, _remaining} -> {:ok, _remaining} ->
endgame = case random_unserved(socket) do
Endgames.random_endgame(exclude_ids: [socket.assigns.endgame.id]) ||
Endgames.random_endgame()
case endgame do
nil -> assign(socket, :empty, :exhausted) nil -> assign(socket, :empty, :exhausted)
endgame -> start_guest_puzzle(socket, socket.assigns.guest_address, endgame) endgame -> start_guest_puzzle(socket, socket.assigns.guest_address, endgame)
end end
@@ -234,13 +233,21 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
{:ok, limit_wall(socket, address, retry_ms)} {:ok, limit_wall(socket, address, retry_ms)}
{:ok, _remaining} -> {:ok, _remaining} ->
case Endgames.random_endgame() do case random_unserved(socket) do
nil -> {:ok, empty_pool(socket, address)} nil -> {:ok, empty_pool(socket, address)}
endgame -> {:ok, start_guest_puzzle(socket, address, endgame)} endgame -> {:ok, start_guest_puzzle(socket, address, endgame)}
end end
end end
end end
# Prefer an endgame this visitor has not seen in this session. Once the whole
# pool is served — only possible on a very long guest session — start over
# rather than dead-end.
defp random_unserved(socket) do
Endgames.random_endgame(exclude_ids: socket.assigns.served_ids) ||
Endgames.random_endgame()
end
defp start_guest_puzzle(socket, address, endgame) do defp start_guest_puzzle(socket, address, endgame) do
case GuestLimits.take(address) do case GuestLimits.take(address) do
{:ok, remaining} -> {:ok, remaining} ->
@@ -250,6 +257,7 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
|> assign(:guest_remaining, remaining) |> assign(:guest_remaining, remaining)
|> assign(:limit_reached, nil) |> assign(:limit_reached, nil)
|> assign(:empty, nil) |> assign(:empty, nil)
|> assign(:served_ids, [endgame.id | socket.assigns.served_ids])
|> PlayCore.init(endgame, page_title: "Train") |> PlayCore.init(endgame, page_title: "Train")
{:limit_reached, retry_ms} -> {:limit_reached, retry_ms} ->
+13 -11
View File
@@ -106,7 +106,7 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
id="pool-exhausted" id="pool-exhausted"
class="rounded-xl border border-hairline bg-canvas-raised p-6" class="rounded-xl border border-hairline bg-canvas-raised p-6"
> >
<h2 class="text-lg font-semibold">You've finished every puzzle at this difficulty</h2> <h2 class="text-lg font-semibold">You've played every puzzle available right now</h2>
<p class="mt-1 text-sm text-muted"> <p class="mt-1 text-sm text-muted">
There are no more {difficulty_label(@session.difficulty)} puzzles right now. There are no more {difficulty_label(@session.difficulty)} puzzles right now.
Try again, or pick another difficulty. Try again, or pick another difficulty.
@@ -161,7 +161,7 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
<div> <div>
<h2 class="text-lg font-semibold">Choose a difficulty</h2> <h2 class="text-lg font-semibold">Choose a difficulty</h2>
<p class="mt-1 text-sm text-muted"> <p class="mt-1 text-sm text-muted">
Difficulty bands are ±{Puzzles.band_width()} around your rating. Easy draws easier endgames, hard draws harder ones — your rating sets the centre.
</p> </p>
</div> </div>
<.link <.link
@@ -190,7 +190,7 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
</.button> </.button>
</div> </div>
<div class="mt-4 grid gap-2"> <div class="mt-4 grid gap-2">
<%= for {difficulty, label, description} <- difficulty_options(@user_rating) do %> <%= for {difficulty, label, description} <- difficulty_options() do %>
<.button <.button
id={"difficulty-#{difficulty}"} id={"difficulty-#{difficulty}"}
phx-click="start_session" phx-click="start_session"
@@ -315,7 +315,8 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
started_at_ms: System.system_time(:millisecond), started_at_ms: System.system_time(:millisecond),
baseline: socket.assigns.user_rating, baseline: socket.assigns.user_rating,
count: 0, count: 0,
sum_ms: 0 sum_ms: 0,
served_ids: [endgame.id]
} }
socket socket
@@ -333,13 +334,16 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
if session do if session do
case Puzzles.next_endgame(selection_user(socket), session.difficulty, case Puzzles.next_endgame(selection_user(socket), session.difficulty,
exclude_ids: [socket.assigns.endgame.id] exclude_ids: session.served_ids
) do ) do
nil -> nil ->
assign(socket, :pool, %{difficulty: session.difficulty}) assign(socket, :pool, %{difficulty: session.difficulty})
endgame -> endgame ->
session = %{session | served_ids: [endgame.id | session.served_ids]}
socket socket
|> assign(:session, session)
|> assign(:pool, nil) |> assign(:pool, nil)
|> assign(:puzzle_started_mono, System.monotonic_time(:millisecond)) |> assign(:puzzle_started_mono, System.monotonic_time(:millisecond))
|> assign(:puzzle_counted, false) |> assign(:puzzle_counted, false)
@@ -395,13 +399,11 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
defp parse_difficulty(_value), do: :medium defp parse_difficulty(_value), do: :medium
defp difficulty_options(rating) do defp difficulty_options do
width = Puzzles.band_width()
[ [
{:easy, "Easy", "below #{round(rating - width)}"}, {:easy, "Easy", "easier than your rating"},
{:medium, "Medium", "#{round(rating - width)}–#{round(rating + width)}"}, {:medium, "Medium", "around your rating"},
{:hard, "Hard", "above #{round(rating + width)}"} {:hard, "Hard", "harder than your rating"}
] ]
end end
+2 -7
View File
@@ -27,7 +27,7 @@ defmodule ChesstrainerWeb.UserLive.Login do
:let={f} :let={f}
for={@form} for={@form}
id="login_form_password" id="login_form_password"
action={@login_action} action={~p"/users/log-in"}
phx-submit="submit_password" phx-submit="submit_password"
phx-trigger-action={@trigger_submit} phx-trigger-action={@trigger_submit}
> >
@@ -75,17 +75,12 @@ defmodule ChesstrainerWeb.UserLive.Login do
get_in(socket.assigns, [:current_scope, Access.key(:user), Access.key(:email)]) get_in(socket.assigns, [:current_scope, Access.key(:user), Access.key(:email)])
form = to_form(%{"email" => email}, as: "user") form = to_form(%{"email" => email}, as: "user")
prelaunch = ChesstrainerWeb.prelaunch?()
login_action =
if prelaunch, do: ~p"/admin/log-in", else: ~p"/users/log-in"
{:ok, {:ok,
assign(socket, assign(socket,
form: form, form: form,
trigger_submit: false, trigger_submit: false,
prelaunch: prelaunch, prelaunch: ChesstrainerWeb.prelaunch?()
login_action: login_action
)} )}
end end
+1 -1
View File
@@ -19,6 +19,7 @@ defmodule ChesstrainerWeb.Plugs.Prelaunch do
/health /health
/robots.txt /robots.txt
/sitemap.xml /sitemap.xml
/users/log-in
/favicon.ico /favicon.ico
/favicon.svg /favicon.svg
/favicon-16x16.png /favicon-16x16.png
@@ -40,7 +41,6 @@ defmodule ChesstrainerWeb.Plugs.Prelaunch do
/assets /assets
/fonts /fonts
/images /images
/dev
) )
def init(opts), do: opts def init(opts), do: opts
+3 -5
View File
@@ -36,8 +36,6 @@ defmodule ChesstrainerWeb.Router do
get "/terms-conditions", PageController, :terms_conditions get "/terms-conditions", PageController, :terms_conditions
get "/mentions-legales", PageController, :mentions_legales get "/mentions-legales", PageController, :mentions_legales
post "/mailing-list", MailingListController, :create post "/mailing-list", MailingListController, :create
get "/mailing-list/confirm/:token", MailingListController, :confirm
post "/admin/log-in", UserSessionController, :create_admin
end end
scope "/admin", ChesstrainerWeb do scope "/admin", ChesstrainerWeb do
@@ -89,7 +87,7 @@ defmodule ChesstrainerWeb.Router do
## Authentication routes ## Authentication routes
scope "/", ChesstrainerWeb do scope "/", ChesstrainerWeb do
pipe_through [:browser, :require_authenticated_user] pipe_through [:browser, :noindex, :require_authenticated_user]
live_session :require_authenticated_user, live_session :require_authenticated_user,
on_mount: [ on_mount: [
@@ -124,12 +122,12 @@ defmodule ChesstrainerWeb.Router do
live "/endgames/:public_code/play", EndgameLive.Play, :play live "/endgames/:public_code/play", EndgameLive.Play, :play
live "/users/register", UserLive.Registration, :new live "/users/register", UserLive.Registration, :new
live "/users/log-in", UserLive.Login, :new live "/users/log-in", UserLive.Login, :new
live "/admin/log-in", UserLive.Login, :new
live "/users/reset-password", UserLive.ResetPassword, :new live "/users/reset-password", UserLive.ResetPassword, :new
live "/users/reset-password/:token", UserLive.ResetPassword, :edit live "/users/reset-password/:token", UserLive.ResetPassword, :edit
end end
get "/users/confirm/:token", UserConfirmationController, :edit get "/users/confirm/:token", UserConfirmationController, :edit
get "/mailing-list/confirm/:token", MailingListController, :confirm
post "/users/log-in", UserSessionController, :create post "/users/log-in", UserSessionController, :create
delete "/users/log-out", UserSessionController, :delete delete "/users/log-out", UserSessionController, :delete
@@ -148,7 +146,7 @@ defmodule ChesstrainerWeb.Router do
# Keep this last: routes match in definition order. It gives unmatched paths a # Keep this last: routes match in definition order. It gives unmatched paths a
# branded 404 page with the site chrome instead of Phoenix's bare status page. # branded 404 page with the site chrome instead of Phoenix's bare status page.
scope "/", ChesstrainerWeb do scope "/", ChesstrainerWeb do
pipe_through :browser pipe_through [:browser, :noindex]
match :*, "/*path", PageController, :not_found match :*, "/*path", PageController, :not_found
end end
@@ -1,8 +1,6 @@
defmodule Chesstrainer.AccountsAdminTest do defmodule Chesstrainer.AccountsAdminTest do
use Chesstrainer.DataCase, async: false use Chesstrainer.DataCase, async: false
require Logger
import Chesstrainer.AccountsFixtures import Chesstrainer.AccountsFixtures
import ExUnit.CaptureLog import ExUnit.CaptureLog
import Swoosh.TestAssertions import Swoosh.TestAssertions
+39
View File
@@ -0,0 +1,39 @@
defmodule Chesstrainer.BrandingTest do
use ExUnit.Case, async: false
alias Chesstrainer.Branding
describe "discord_invite_url/0" do
setup do
previous = Application.get_env(:chesstrainer, :branding)
on_exit(fn -> restore(:branding, previous) end)
:ok
end
test "passes a full URL through" do
put_branding(discord_invite: "https://discord.gg/abc123")
assert Branding.discord_invite_url() == "https://discord.gg/abc123"
end
test "expands a bare invite code" do
put_branding(discord_invite: " abc123 ")
assert Branding.discord_invite_url() == "https://discord.gg/abc123"
end
test "returns nil when the invite is blank" do
put_branding(discord_invite: "")
assert Branding.discord_invite_url() == nil
end
end
defp put_branding(overrides) do
config = Application.get_env(:chesstrainer, :branding, [])
Application.put_env(:chesstrainer, :branding, Keyword.merge(config, overrides))
end
defp restore(key, nil), do: Application.delete_env(:chesstrainer, key)
defp restore(key, value), do: Application.put_env(:chesstrainer, key, value)
end
+60 -27
View File
@@ -7,6 +7,7 @@ defmodule Chesstrainer.PuzzlesTest do
alias Chesstrainer.Accounts.Scope alias Chesstrainer.Accounts.Scope
alias Chesstrainer.Attempts alias Chesstrainer.Attempts
alias Chesstrainer.Puzzles alias Chesstrainer.Puzzles
alias Chesstrainer.Repo
# The shared `endgame_fixture/1` picks one of six FENs at random-ish, which # The shared `endgame_fixture/1` picks one of six FENs at random-ish, which
# can collide when one test creates several endgames under async load. Pin # can collide when one test creates several endgames under async load. Pin
@@ -22,71 +23,103 @@ defmodule Chesstrainer.PuzzlesTest do
endgame_fixture(fen: Enum.fetch!(@fens, index), rating: rating) endgame_fixture(fen: Enum.fetch!(@fens, index), rating: rating)
end end
describe "difficulty_range/2" do defp attempt_days_ago(user, endgame, days) do
test "is centred on the rating and open-ended at the extremes" do {:ok, attempt} = Attempts.record_attempt(Scope.for_user(user), endgame, :solved)
assert Puzzles.difficulty_range(1500, :medium) == {1400, 1600}
assert Puzzles.difficulty_range(1500, :easy) == {nil, 1400} attempt
assert Puzzles.difficulty_range(1500, :hard) == {1600, nil} |> Ecto.Changeset.change(
inserted_at: DateTime.utc_now() |> DateTime.add(-days, :day) |> DateTime.truncate(:second)
)
|> Repo.update!()
end
describe "difficulty_target/2" do
test "centres on the rating and offsets easy and hard" do
assert Puzzles.difficulty_target(1500, :medium) == 1500
assert Puzzles.difficulty_target(1500, :easy) == 1300
assert Puzzles.difficulty_target(1500, :hard) == 1700
end
end
describe "selection settings" do
test "uses the configured spread and repeat window" do
assert Puzzles.spread() == 150
assert Puzzles.repeat_window_days() == 30
end end
end end
describe "next_endgame/3" do describe "next_endgame/3" do
test "medium picks an endgame within the band" do test "draws far more often from near the user's rating" do
user = user_fixture() user = user_fixture()
in_band = endgame_at(1550, 0) near = endgame_at(1500, 0)
_out_of_band = endgame_at(1900, 1) _far = endgame_at(4000, 1)
assert Puzzles.next_endgame(user, :medium).id == in_band.id for _ <- 1..50 do
assert Puzzles.next_endgame(user, :medium).id == near.id
end
end end
test "easy picks an endgame below the user's rating" do test "easy never serves above the user's rating plus the spread" do
user = user_fixture() user = user_fixture()
easy = endgame_at(1300, 0) easy = endgame_at(1300, 0)
_medium = endgame_at(1500, 1) _too_hard = endgame_at(3000, 1)
assert Puzzles.next_endgame(user, :easy).id == easy.id assert Puzzles.next_endgame(user, :easy).id == easy.id
end end
test "hard picks an endgame above the user's rating" do test "hard never serves below the user's rating minus the spread" do
user = user_fixture() user = user_fixture()
hard = endgame_at(1700, 0) hard = endgame_at(1700, 0)
_medium = endgame_at(1500, 1) _too_easy = endgame_at(100, 1)
assert Puzzles.next_endgame(user, :hard).id == hard.id assert Puzzles.next_endgame(user, :hard).id == hard.id
end end
test "falls back to the nearest endgame when the band is empty" do test "prefers endgames not attempted inside the repeat window" do
user = user_fixture()
only = endgame_at(2200, 0)
assert Puzzles.next_endgame(user, :medium).id == only.id
end
test "prefers endgames not attempted in the last 30 days" do
user = user_fixture() user = user_fixture()
attempted = endgame_at(1500, 0) attempted = endgame_at(1500, 0)
fresh = endgame_at(1500, 1) fresh = endgame_at(1500, 1)
{:ok, _} = Attempts.record_attempt(Scope.for_user(user), attempted, :solved) attempt_days_ago(user, attempted, 1)
assert Puzzles.next_endgame(user, :medium).id == fresh.id assert Puzzles.next_endgame(user, :medium).id == fresh.id
end end
test "falls back to a recent endgame once the fresh pool is empty" do test "serves an endgame again once its attempt is outside the repeat window" do
user = user_fixture() user = user_fixture()
only = endgame_at(1500, 0) only = endgame_at(1500, 0)
{:ok, _} = Attempts.record_attempt(Scope.for_user(user), only, :solved) attempt_days_ago(user, only, 31)
assert Puzzles.next_endgame(user, :medium).id == only.id assert Puzzles.next_endgame(user, :medium).id == only.id
end end
test "skips excluded ids" do test "falls back to the least recently attempted endgame when all are excluded" do
user = user_fixture() user = user_fixture()
excluded = endgame_at(1500, 0) older = endgame_at(1500, 0)
newer = endgame_at(1500, 1)
attempt_days_ago(user, older, 20)
attempt_days_ago(user, newer, 10)
assert Puzzles.next_endgame(user, :medium).id == older.id
end
test "skips endgames already served in the session" do
user = user_fixture()
served = endgame_at(1500, 0)
other = endgame_at(1500, 1) other = endgame_at(1500, 1)
assert Puzzles.next_endgame(user, :medium, exclude_ids: [excluded.id]).id == other.id assert Puzzles.next_endgame(user, :medium, exclude_ids: [served.id]).id == other.id
end
test "returns nil when every endgame has been served and attempted" do
user = user_fixture()
only = endgame_at(1500, 0)
attempt_days_ago(user, only, 1)
assert Puzzles.next_endgame(user, :medium, exclude_ids: [only.id]) == nil
end end
test "returns nil when no endgames exist" do test "returns nil when no endgames exist" do
@@ -5,6 +5,7 @@ defmodule ChesstrainerWeb.LayoutsTest do
alias Chesstrainer.Accounts.Scope alias Chesstrainer.Accounts.Scope
alias Chesstrainer.Accounts.User alias Chesstrainer.Accounts.User
alias Chesstrainer.Branding
alias ChesstrainerWeb.Layouts alias ChesstrainerWeb.Layouts
describe "navbar/1" do describe "navbar/1" do
@@ -28,6 +29,53 @@ defmodule ChesstrainerWeb.LayoutsTest do
assert html =~ ~p"/users/register" assert html =~ ~p"/users/register"
refute html =~ ~s(class="nav-user-menu") refute html =~ ~s(class="nav-user-menu")
end end
test "renders the utility controls in both the bar and the mobile menu" do
html = render_component(&Layouts.navbar/1, %{current_scope: nil})
assert html =~ ~s(class="nav-menu-tools")
# One copy for the bar, one for the collapsible menu; CSS shows one.
assert length(String.split(html, ~s(role="radiogroup"))) == 3
assert length(String.split(html, ~s(class="discord-link"))) == 3
end
end
describe "discord_link/1" do
setup do
previous = Application.get_env(:chesstrainer, :branding)
on_exit(fn -> restore_env(:branding, previous) end)
:ok
end
test "renders an icon-only link to the configured invite" do
html = render_component(&Layouts.discord_link/1, %{})
assert html =~ ~s(href="#{Branding.discord_invite_url()}")
assert html =~ ~s(aria-label="Join the #{Branding.name()} Discord")
assert html =~ ~s(target="_blank")
assert html =~ "noopener noreferrer"
assert html =~ ~r/<a[^>]*class="discord-link"[^>]*>\s*<svg/
end
test "is rendered by the navbar and the footer" do
navbar = render_component(&Layouts.navbar/1, %{current_scope: nil})
assert navbar =~ ~s(class="discord-link")
footer = render_component(&Layouts.footer/1, %{})
assert footer =~ ~s(class="discord-link")
end
test "renders nothing when no invite is configured" do
Application.put_env(
:chesstrainer,
:branding,
Keyword.put(Application.get_env(:chesstrainer, :branding, []), :discord_invite, "")
)
html = render_component(&Layouts.discord_link/1, %{})
refute html =~ "discord-link"
end
end end
describe "colour_mode_toggle/1" do describe "colour_mode_toggle/1" do
@@ -10,7 +10,7 @@ defmodule ChesstrainerWeb.HealthControllerTest do
assert body["db"] == "ok" assert body["db"] == "ok"
assert body["tablebase"] == "local" assert body["tablebase"] == "local"
assert body["process"] == "ok" assert body["process"] == "ok"
assert get_resp_header(conn, "x-robots-tag") == ["noindex"] assert get_resp_header(conn, "x-robots-tag") == ["noindex, nofollow"]
end end
test "returns degraded when local tablebases are not configured", %{conn: conn} do test "returns degraded when local tablebases are not configured", %{conn: conn} do
@@ -53,7 +53,7 @@ defmodule ChesstrainerWeb.HealthControllerTest do
assert body["db"] == "down" assert body["db"] == "down"
assert body["tablebase"] == "local" assert body["tablebase"] == "local"
assert body["process"] == "ok" assert body["process"] == "ok"
assert get_resp_header(conn, "x-robots-tag") == ["noindex"] assert get_resp_header(conn, "x-robots-tag") == ["noindex, nofollow"]
end end
end end
@@ -68,10 +68,17 @@ defmodule ChesstrainerWeb.PageControllerTest do
assert LazyHTML.text(LazyHTML.query(document, "title")) =~ Branding.home_title() assert LazyHTML.text(LazyHTML.query(document, "title")) =~ Branding.home_title()
refute html =~ "Phoenix Framework" refute html =~ "Phoenix Framework"
eyebrow = LazyHTML.query(document, ".eyebrow") eyebrow = LazyHTML.query(document, ".hero .eyebrow")
assert LazyHTML.text(eyebrow) =~ "Endgames, simplified" 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.text(LazyHTML.query(document, ".puzzle-coming-soon")) =~ "Coming soon"
assert LazyHTML.text(LazyHTML.query(document, ".learning-quote")) =~
"The hardest game to win is a won game."
assert html =~ "Emmanuel Lasker"
assert LazyHTML.attribute(LazyHTML.query(document, ~s(meta[name="description"])), "content") == assert LazyHTML.attribute(LazyHTML.query(document, ~s(meta[name="description"])), "content") ==
[@description] [@description]
@@ -381,7 +388,7 @@ defmodule ChesstrainerWeb.PageControllerTest do
refute html =~ "Browse puzzles" refute html =~ "Browse puzzles"
assert html =~ ~s(class="site-footer") assert html =~ ~s(class="site-footer")
assert html =~ "/assets/js/marketing.js" assert html =~ "/assets/js/marketing.js"
assert html =~ ~s(name="robots") assert html =~ ~s(<meta name="robots" content="noindex, nofollow")
end end
test "premium users see the puzzles link on the 404 page", %{conn: conn} do test "premium users see the puzzles link on the 404 page", %{conn: conn} do
@@ -11,17 +11,16 @@ defmodule ChesstrainerWeb.SitemapControllerTest do
assert body =~ ~s(<?xml version="1.0" encoding="UTF-8"?>) assert body =~ ~s(<?xml version="1.0" encoding="UTF-8"?>)
assert body =~ ~s(<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">) assert body =~ ~s(<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">)
assert body =~ "<loc>#{base_url}/</loc>" assert body =~ "<loc>#{base_url}/</loc>"
assert body =~ "<lastmod>#{Date.utc_today() |> Date.to_iso8601()}</lastmod>"
assert body =~ "<loc>#{base_url}/privacy</loc>" assert body =~ "<loc>#{base_url}/privacy</loc>"
assert body =~ "<loc>#{base_url}/terms-conditions</loc>" assert body =~ "<loc>#{base_url}/terms-conditions</loc>"
assert body =~ "<loc>#{base_url}/mentions-legales</loc>" assert body =~ "<loc>#{base_url}/mentions-legales</loc>"
assert length(:binary.matches(body, "<url>")) == 4 assert length(:binary.matches(body, "<url>")) == 4
end end
test "only dates the landing page", %{conn: conn} do test "does not invent modification dates", %{conn: conn} do
body = conn |> get(~p"/sitemap.xml") |> response(200) body = conn |> get(~p"/sitemap.xml") |> response(200)
assert length(:binary.matches(body, "<lastmod>")) == 1 refute body =~ "<lastmod>"
end end
test "is served as XML", %{conn: conn} do test "is served as XML", %{conn: conn} do
@@ -186,22 +186,6 @@ defmodule ChesstrainerWeb.UserSessionControllerTest do
assert get_session(conn, :user_token) assert get_session(conn, :user_token)
end end
test "the admin login uses the same throttle", %{conn: conn, user: user} do
for _ <- 1..LoginThrottle.max_per_login() do
post(conn, ~p"/admin/log-in", %{
"user" => %{"email" => user.email, "password" => "wrong password"}
})
end
conn =
post(conn, ~p"/admin/log-in", %{
"user" => %{"email" => user.email, "password" => valid_user_password()}
})
refute get_session(conn, :user_token)
assert Phoenix.Flash.get(conn.assigns.flash, :error) =~ "Too many attempts."
end
test "log events contain no raw address or password", %{conn: conn, user: user} do test "log events contain no raw address or password", %{conn: conn, user: user} do
log = log =
capture_log( capture_log(
@@ -0,0 +1,45 @@
defmodule ChesstrainerWeb.CrawlerDirectivesTest do
use ChesstrainerWeb.ConnCase, async: true
@noindex "noindex, nofollow"
describe "X-Robots-Tag" do
test "authenticated routes are noindex even when redirecting to log in", %{conn: conn} do
conn = get(conn, ~p"/train")
assert redirected_to(conn) == ~p"/users/log-in"
assert get_resp_header(conn, "x-robots-tag") == [@noindex]
end
test "the branded 404 page is noindex", %{conn: conn} do
conn = get(conn, "/this-page-does-not-exist")
assert html_response(conn, 404)
assert get_resp_header(conn, "x-robots-tag") == [@noindex]
end
test "the mailing-list confirmation redirect is noindex", %{conn: conn} do
conn = get(conn, "/mailing-list/confirm/oops")
assert redirected_to(conn) == "/#mailing-list"
assert get_resp_header(conn, "x-robots-tag") == [@noindex]
end
test "public pages are not marked noindex", %{conn: conn} do
for path <- [~p"/", ~p"/privacy", ~p"/terms-conditions", ~p"/mentions-legales"] do
conn = get(conn, path)
html = html_response(conn, 200)
assert get_resp_header(conn, "x-robots-tag") == []
refute html =~ ~s(name="robots")
refute html =~ "nofollow"
end
end
test "pages that assign :noindex carry the same policy as the header", %{conn: conn} do
html = conn |> get("/this-page-does-not-exist") |> html_response(404)
assert html =~ ~s(<meta name="robots" content="#{@noindex}")
end
end
end
@@ -170,6 +170,18 @@ defmodule ChesstrainerWeb.EndgameLive.TrainTest do
assert Enum.any?(endgames, &(&1.id == second.id)) assert Enum.any?(endgames, &(&1.id == second.id))
end end
test "does not serve the same puzzle twice in a session", %{conn: conn} do
{view, [only]} = start_medium_session(conn, 1)
solve_current(view)
view |> element("#next-puzzle-button") |> render_click()
assigns = :sys.get_state(view.pid).socket.assigns
assert has_element?(view, "#pool-exhausted")
assert assigns.endgame.id == only.id
assert assigns.session.served_ids == [only.id]
end
test "keeps next puzzle available while reviewing", %{conn: conn} do test "keeps next puzzle available while reviewing", %{conn: conn} do
{view, endgames} = start_medium_session(conn, 2) {view, endgames} = start_medium_session(conn, 2)
first = :sys.get_state(view.pid).socket.assigns.endgame first = :sys.get_state(view.pid).socket.assigns.endgame
+12 -15
View File
@@ -14,12 +14,12 @@ defmodule ChesstrainerWeb.Plugs.PrelaunchTest do
:ok :ok
end end
test "allows the public pages, legal pages, health, and admin login", %{conn: conn} do test "allows the public pages, legal pages, health, and login", %{conn: conn} do
assert conn |> get(~p"/") |> html_response(200) assert conn |> get(~p"/") |> html_response(200)
assert conn |> get(~p"/privacy") |> html_response(200) assert conn |> get(~p"/privacy") |> html_response(200)
assert conn |> get(~p"/terms-conditions") |> html_response(200) assert conn |> get(~p"/terms-conditions") |> html_response(200)
assert conn |> get(~p"/health") |> response(200) assert conn |> get(~p"/health") |> response(200)
assert conn |> get(~p"/admin/log-in") |> html_response(200) assert conn |> get(~p"/users/log-in") |> html_response(200)
end end
test "hides public auth links and start training", %{conn: conn} do test "hides public auth links and start training", %{conn: conn} do
@@ -30,29 +30,26 @@ defmodule ChesstrainerWeb.Plugs.PrelaunchTest do
refute html =~ "Start training" refute html =~ "Start training"
end end
test "the hidden admin login uses the admin form action", %{conn: conn} do test "the prelaunch login form posts to the public login route", %{conn: conn} do
html = conn |> get(~p"/admin/log-in") |> html_response(200) html = conn |> get(~p"/users/log-in") |> html_response(200)
assert html =~ ~s(action="/admin/log-in") assert html =~ ~s(action="/users/log-in")
refute html =~ "Sign up" refute html =~ "Sign up"
end end
test "pauses the public login route", %{conn: conn} do test "an admin can log in through the public login route", %{conn: conn} do
assert conn |> get(~p"/users/log-in") |> redirected_to() == "/" admin =
end
test "admin login redirects to the admin area", %{conn: conn} do
user =
user_fixture() user_fixture()
|> Ecto.Changeset.change(role: :admin) |> Ecto.Changeset.change(role: :admin)
|> Repo.update!() |> Repo.update!()
conn = conn =
post(conn, ~p"/admin/log-in", post(conn, ~p"/users/log-in",
user: %{email: user.email, password: "hello world!", remember_me: "true"} user: %{email: admin.email, password: "hello world!", remember_me: "true"}
) )
assert redirected_to(conn) == "/admin/endgames" assert get_session(conn, :user_token)
assert get_resp_header(conn, "x-robots-tag") == ["noindex, nofollow"]
end end
test "redirects blocked routes to the home page", %{conn: conn} do test "redirects blocked routes to the home page", %{conn: conn} do
@@ -84,7 +81,7 @@ defmodule ChesstrainerWeb.Plugs.PrelaunchTest do
end end
test "blocks registration reached through LiveView navigation", %{conn: conn} do test "blocks registration reached through LiveView navigation", %{conn: conn} do
{:ok, view, _html} = live(conn, ~p"/admin/log-in") {:ok, view, _html} = live(conn, ~p"/users/log-in")
assert {:error, {:redirect, %{to: "/"}}} = assert {:error, {:redirect, %{to: "/"}}} =
live_redirect(view, to: ~p"/users/register") live_redirect(view, to: ~p"/users/register")
@@ -0,0 +1,28 @@
defmodule ChesstrainerWeb.StaticCacheTest do
use ChesstrainerWeb.ConnCase, async: true
# One year, matching `Plug.Static` in the endpoint when code reloading is off.
# A missing max-age here lets the CDN fall back to its own short default.
@one_year "public, max-age=31536000, immutable"
# Piece art is committed already hashed, so it is shaped like digested build
# output without requiring `mix assets.build` first (CI's test job does not
# build assets). The endpoint sets one cache option for every static file.
@digested_piece "/images/pieces/white/king-27fd3307056d10dae685faf4ca8f4488.svg"
test "digested assets are cached for a year", %{conn: conn} do
conn = get(conn, @digested_piece)
assert conn.status == 200
assert get_resp_header(conn, "cache-control") == [@one_year]
end
test "stable-name assets are cached for a year", %{conn: conn} do
for path <- ["/fonts/dm-sans-variable.woff2", "/images/og.png", "/favicon.svg"] do
conn = get(conn, path)
assert conn.status == 200
assert get_resp_header(conn, "cache-control") == [@one_year]
end
end
end