Add analyzer and frontend lint guardrails

This commit is contained in:
2026-02-07 02:12:00 +01:00
parent 34d274d244
commit 5b06e279f3
19 changed files with 1313 additions and 53 deletions

7
.editorconfig Normal file
View File

@@ -0,0 +1,7 @@
root = true
[*.cs]
dotnet_diagnostic.CA1707.severity = none
dotnet_diagnostic.CA1852.severity = none
dotnet_diagnostic.CA1825.severity = none
dotnet_diagnostic.CA1861.severity = none

View File

@@ -14,6 +14,20 @@ jobs:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: 22
- name: Install frontend tooling
run: npm install
- name: Lint frontend
run: npm run lint
- name: Check frontend formatting
run: npm run format:check
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:

1
.gitignore vendored
View File

@@ -7,6 +7,7 @@ artifacts/
# IDE
.vs/
.vscode/
node_modules/
# User secrets / configs
appsettings.Development.json

7
Directory.Build.props Normal file
View File

@@ -0,0 +1,7 @@
<Project>
<PropertyGroup>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<AnalysisLevel>latest-recommended</AnalysisLevel>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
</PropertyGroup>
</Project>

View File

@@ -133,7 +133,12 @@ internal static class EndpointHelpers
return false;
var path = uri.AbsolutePath.ToLowerInvariant();
return path.EndsWith(".png") || path.EndsWith(".jpg") || path.EndsWith(".jpeg") || path.EndsWith(".gif") || path.EndsWith(".webp") || path.EndsWith(".avif");
return path.EndsWith(".png", StringComparison.Ordinal)
|| path.EndsWith(".jpg", StringComparison.Ordinal)
|| path.EndsWith(".jpeg", StringComparison.Ordinal)
|| path.EndsWith(".gif", StringComparison.Ordinal)
|| path.EndsWith(".webp", StringComparison.Ordinal)
|| path.EndsWith(".avif", StringComparison.Ordinal);
}
public static async Task<bool> IsReachableImageAsync(string? url, IHttpClientFactory httpFactory, HttpMessageHandler? handler = null, CancellationToken ct = default)
@@ -193,7 +198,7 @@ internal static class EndpointHelpers
await using var stream = await resp.Content.ReadAsStreamAsync(cts.Token);
var rented = new byte[12];
var read = await stream.ReadAsync(rented, 0, rented.Length, cts.Token);
var read = await stream.ReadAsync(rented.AsMemory(0, rented.Length), cts.Token);
var sig = new ReadOnlySpan<byte>(rented, 0, read);
if (IsMagic(sig, "PNG"))

View File

@@ -12,6 +12,11 @@ public static class PlayerIdentityExtensions
public const string PlayerCookieName = "player";
public const string AdminClaim = "is_admin";
public const string AdminPolicy = "AdminOnly";
private static readonly Action<ILogger, Exception?> LogUnhandledException =
LoggerMessage.Define(
LogLevel.Error,
new EventId(1001, nameof(LogUnhandledException)),
"Unhandled exception");
public static async Task SignInPlayerAsync(HttpContext ctx, Player player)
{
@@ -40,7 +45,7 @@ public static class PlayerIdentityExtensions
var logger = context.RequestServices.GetRequiredService<ILoggerFactory>().CreateLogger("GlobalException");
if (feature?.Error != null)
{
logger.LogError(feature.Error, "Unhandled exception");
LogUnhandledException(logger, feature.Error);
}
context.Response.StatusCode = StatusCodes.Status500InternalServerError;

View File

@@ -13,6 +13,13 @@ Pick'n'Play is a .NET 10 ASP.NET Core Minimal API app with a static HTML/CSS/JS
4. Open:
`http://localhost:5000` (or the URL shown by `dotnet run`)
## Frontend Tooling
- Install tooling: `npm install`
- Lint JS: `npm run lint`
- Check formatting: `npm run format:check`
- Apply formatting: `npm run format`
## Core Behavior
- Authentication: username/password with HttpOnly `player` cookie.
@@ -44,5 +51,6 @@ Pick'n'Play is a .NET 10 ASP.NET Core Minimal API app with a static HTML/CSS/JS
GitHub Actions workflow: `.github/workflows/ci.yml`
- Restores dependencies
- Runs frontend lint and format checks
- Builds with warnings treated as errors
- Runs `GameList.Tests`

View File

@@ -6,20 +6,12 @@ This document tracks only active work. Completed work is intentionally omitted a
Active maintainability risks (priority order):
1. Static analysis and frontend lint guardrails are still missing (Medium)
- CI currently gates restore/build/test only (`.github/workflows/ci.yml:23`-`.github/workflows/ci.yml:29`).
- Impact: style drift and low-signal warnings can enter the codebase undetected.
1. Externalized frontend content assets are still pending (Low)
- Translation and FAQ payloads are still embedded in executable JS (`wwwroot/js/i18n.js:1`-`wwwroot/js/i18n.js:799`).
- Impact: content changes require touching behavior modules and increase review noise.
## B) Active task list
[P2] Add static analysis and JS lint/format guardrails
- Problem: Severity `Medium`, Category `Tooling`. CI does not enforce analyzers or JS lint/format checks.
- Evidence: `.github/workflows/ci.yml:23`-`.github/workflows/ci.yml:29`.
- Recommendation: add .NET analyzer configuration and ESLint/Prettier checks, then enforce in CI.
- Acceptance criteria (testable): CI fails on analyzer/lint violations; local scripts are documented in root docs.
- Effort / Risk: `M / Low`.
- Dependencies (if any): none.
[P2] Externalize i18n and FAQ content from executable JS
- Problem: Severity `Low`, Category `Complexity/Documentation`. Translation and FAQ payloads are embedded in code.
- Evidence: `wwwroot/js/i18n.js:1`-`wwwroot/js/i18n.js:799`.
@@ -30,8 +22,7 @@ Active maintainability risks (priority order):
## C) Suggested execution order
1. Add analyzers + JS lint gates in CI.
2. Externalize i18n/FAQ assets.
1. Externalize i18n/FAQ assets.
## D) Guardrails

21
eslint.config.js Normal file
View File

@@ -0,0 +1,21 @@
import js from "@eslint/js";
import globals from "globals";
export default [
{
files: ["wwwroot/**/*.js"],
...js.configs.recommended,
languageOptions: {
...js.configs.recommended.languageOptions,
ecmaVersion: 2024,
sourceType: "module",
globals: {
...globals.browser,
},
},
rules: {
...js.configs.recommended.rules,
"no-unused-vars": ["error", { argsIgnorePattern: "^_" }],
},
},
];

1101
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

16
package.json Normal file
View File

@@ -0,0 +1,16 @@
{
"name": "picknplay-frontend",
"private": true,
"type": "module",
"scripts": {
"lint": "eslint \"wwwroot/**/*.js\"",
"format": "prettier --write \"eslint.config.js\" \"wwwroot/js/{admin-ui,modals-ui,results-ui,suggestions-ui,ui-runtime,ui-utils,ui,votes-ui}.js\"",
"format:check": "prettier --check \"eslint.config.js\" \"wwwroot/js/{admin-ui,modals-ui,results-ui,suggestions-ui,ui-runtime,ui-utils,ui,votes-ui}.js\""
},
"devDependencies": {
"@eslint/js": "9.21.0",
"eslint": "9.21.0",
"globals": "15.15.0",
"prettier": "3.5.0"
}
}

View File

@@ -1,6 +1,6 @@
import { api, adminApi } from "./js/api.js";
import { t, setLanguage, getLanguage, initI18n, onLanguageChange, faqMarkdown } from "./js/i18n.js";
import { state, clearUserState, getSavedUsername, setSavedUsername } from "./js/state.js";
import { state, clearUserState, setSavedUsername } from "./js/state.js";
import { $, toast } from "./js/dom.js";
import {
setAuthUI,
@@ -22,10 +22,8 @@ import {
configureUiRuntime,
} from "./js/ui.js";
import {
loadState,
loadSuggestData,
loadVoteData,
loadResults,
refreshPhaseData,
} from "./js/data.js";
initI18n();

View File

@@ -7,7 +7,10 @@ function displayPlayerStatus(player) {
if (!player) return "";
const phase = player.phase;
if (phase === "Suggest") return t("admin.statusSuggesting");
if (phase === "Vote") return player.finalized ? t("admin.statusFinished") : t("admin.statusVoting");
if (phase === "Vote")
return player.finalized
? t("admin.statusFinished")
: t("admin.statusVoting");
if (phase === "Results") return t("admin.statusFinished");
return phase;
}
@@ -59,7 +62,9 @@ export function renderAdminLinker() {
const previousSource = source.value;
const previousTarget = target.value;
const options = (state.allSuggestions ?? []).slice().sort((a, b) => a.name.localeCompare(b.name));
const options = (state.allSuggestions ?? [])
.slice()
.sort((a, b) => a.name.localeCompare(b.name));
const fillSelect = (select, placeholderKey) => {
select.innerHTML = "";
@@ -81,8 +86,10 @@ export function renderAdminLinker() {
fillSelect(source, "admin.linkSourcePlaceholder");
fillSelect(target, "admin.linkTargetPlaceholder");
if (previousSource && options.some((s) => String(s.id) === previousSource)) source.value = previousSource;
if (previousTarget && options.some((s) => String(s.id) === previousTarget)) target.value = previousTarget;
if (previousSource && options.some((s) => String(s.id) === previousSource))
source.value = previousSource;
if (previousTarget && options.some((s) => String(s.id) === previousTarget))
target.value = previousTarget;
const preventSameSelection = () => {
const sourceVal = source.value;

View File

@@ -24,7 +24,13 @@ export function openLightbox(url, title) {
document.body.appendChild(overlay);
}
export function openConfirmModal({ title, body, confirmLabel, cancelLabel = t("modal.cancel"), onConfirm }) {
export function openConfirmModal({
title,
body,
confirmLabel,
cancelLabel = t("modal.cancel"),
onConfirm,
}) {
const overlay = document.createElement("div");
overlay.className = "edit-modal";
const panel = document.createElement("div");

View File

@@ -1,7 +1,12 @@
import { t } from "./i18n.js";
import { state } from "./state.js";
import { $ } from "./dom.js";
import { linkRootId, renderLinkBadge, escapeHtml, safeUrl } from "./ui-utils.js";
import {
linkRootId,
renderLinkBadge,
escapeHtml,
safeUrl,
} from "./ui-utils.js";
import { scoreToEmoji } from "./votes-ui.js";
import { openLightbox } from "./modals-ui.js";
@@ -35,9 +40,23 @@ export function renderResults() {
rank = nextRank++;
rankByRoot.set(root, rank);
}
const medal = rank === 1 ? "🥇" : rank === 2 ? "🥈" : rank === 3 ? "🥉" : `${rank}`;
const medal =
rank === 1
? "🥇"
: rank === 2
? "🥈"
: rank === 3
? "🥉"
: `${rank}`;
const row = document.createElement("tr");
const podiumClass = rank === 1 ? "podium podium-1" : rank === 2 ? "podium podium-2" : rank === 3 ? "podium podium-3" : "";
const podiumClass =
rank === 1
? "podium podium-1"
: rank === 2
? "podium podium-2"
: rank === 3
? "podium podium-3"
: "";
row.className = podiumClass;
const safeName = escapeHtml(r.name);
const safeAuthor = escapeHtml(r.author ?? "—");
@@ -79,9 +98,14 @@ export function renderResults() {
function buildResultMeta(r) {
const hasPlayers = r.minPlayers || r.maxPlayers;
const players = hasPlayers
? t("card.players", { min: r.minPlayers ?? "?", max: r.maxPlayers ?? "?" })
? t("card.players", {
min: r.minPlayers ?? "?",
max: r.maxPlayers ?? "?",
})
: null;
const bits = [r.genre ? escapeHtml(r.genre) : null, players].filter(Boolean);
const bits = [r.genre ? escapeHtml(r.genre) : null, players].filter(
Boolean,
);
if (bits.length === 0) return "";
return `<div class="muted small">${bits.join(" • ")}</div>`;
}

View File

@@ -10,7 +10,6 @@ import {
escapeHtml,
isLinked,
linkedPeerTitles,
renderLinkBadge,
safeUrl,
sortByName,
} from "./ui-utils.js";
@@ -23,7 +22,9 @@ function updateSuggestButtonState() {
const count = state.mySuggestions?.length ?? 0;
const blocked = count >= limit;
btn.disabled = blocked || state.phase !== "Suggest";
btn.textContent = blocked ? t("suggest.maxReached") : t("suggest.addButton");
btn.textContent = blocked
? t("suggest.maxReached")
: t("suggest.addButton");
}
export function renderMySuggestions() {
@@ -35,7 +36,12 @@ export function renderMySuggestions() {
const allowDelete = state.phase === "Suggest" || state.me?.isAdmin;
sortByName(state.mySuggestions).forEach((s) =>
wrap.appendChild(
buildCard(s, { showAuthor: false, allowDelete, allowEdit, lockTitle }),
buildCard(s, {
showAuthor: false,
allowDelete,
allowEdit,
lockTitle,
}),
),
);
updateSuggestButtonState();
@@ -69,7 +75,12 @@ export function renderPhaseTitles() {
export function buildCard(
s,
{ showAuthor = false, allowDelete = false, allowEdit = false, lockTitle = false },
{
showAuthor = false,
allowDelete = false,
allowEdit = false,
lockTitle = false,
},
) {
const card = document.createElement("article");
card.className = "game-card";
@@ -92,7 +103,8 @@ export function buildCard(
const linkChip = linked
? `<button class="chip icon link-chip${state.me?.isAdmin ? " link-chip-action" : ""}" data-unlink="${s.id}" type="button" title="${linkTooltipSafe}">🔗</button>`
: "";
const visual = hasImage && safeShot
const visual =
hasImage && safeShot
? `<button class="card-visual" data-img="${safeShot}" aria-label="${t("card.openScreenshot")}" style="background-image:url('${cssEscapeUrl(safeShot)}')"></button>`
: `<div class="card-visual"></div>`;
const hasPlayers = s.minPlayers || s.maxPlayers;
@@ -252,9 +264,13 @@ function buildSuggestionForm(initial = {}, lockTitle = false) {
return form;
function initCharCounters(formEl) {
const inputs = formEl.querySelectorAll("input[maxlength], textarea[maxlength]");
const inputs = formEl.querySelectorAll(
"input[maxlength], textarea[maxlength]",
);
inputs.forEach((input) => {
const counter = formEl.querySelector(`.char-counter[data-for="${input.name}"]`);
const counter = formEl.querySelector(
`.char-counter[data-for="${input.name}"]`,
);
if (!counter) return;
const update = () => {
const max = input.maxLength;
@@ -268,7 +284,13 @@ function buildSuggestionForm(initial = {}, lockTitle = false) {
}
}
function openSuggestionModal({ title, submitLabel, initial = {}, onSubmit, lockTitle = false }) {
function openSuggestionModal({
title,
submitLabel,
initial = {},
onSubmit,
lockTitle = false,
}) {
const overlay = document.createElement("div");
overlay.className = "edit-modal";
const panel = document.createElement("div");
@@ -323,7 +345,8 @@ function openSuggestionModal({ title, submitLabel, initial = {}, onSubmit, lockT
clearError();
const min = data.minPlayers;
const max = data.maxPlayers;
const inRange = (v) => v == null || (Number.isInteger(v) && v >= 1 && v <= 32);
const inRange = (v) =>
v == null || (Number.isInteger(v) && v >= 1 && v <= 32);
const valid =
inRange(min) &&
inRange(max) &&
@@ -450,7 +473,9 @@ function openDeleteConfirmModal(s) {
function openUnlinkConfirm(s) {
const peers = linkedPeerTitles(s);
const names = peers.length ? peers.join(", ") : t("admin.unlinkUnknownPeers");
const names = peers.length
? peers.join(", ")
: t("admin.unlinkUnknownPeers");
openConfirmModal({
title: t("admin.unlinkTitle"),
body: t("admin.unlinkBody", { name: s.name, peers: names }),

View File

@@ -4,7 +4,9 @@ import { state } from "./state.js";
export const sortByName = (items) =>
(items ?? [])
.slice()
.sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: "base" }));
.sort((a, b) =>
a.name.localeCompare(b.name, undefined, { sensitivity: "base" }),
);
export const truncate = (text, max) => {
if (!text) return "";

View File

@@ -10,9 +10,20 @@ import {
openNewSuggestionModal,
normalizeSuggestionForm,
} from "./suggestions-ui.js";
import { renderVotes, scoreToEmoji, syncVoteScores, neutralEmoji, updatePhaseNav } from "./votes-ui.js";
import {
renderVotes,
scoreToEmoji,
syncVoteScores,
neutralEmoji,
updatePhaseNav,
} from "./votes-ui.js";
import { renderResults } from "./results-ui.js";
import { openConfirmModal, openLightbox, openResultsRelockModal, openSuggestionsChangedModal } from "./modals-ui.js";
import {
openConfirmModal,
openLightbox,
openResultsRelockModal,
openSuggestionsChangedModal,
} from "./modals-ui.js";
export function setAuthUI(isAuthed) {
const main = document.querySelector("main");
@@ -74,9 +85,9 @@ export function handleAuthError(err, clearUserState) {
}
export function renderPhasePill() {
document.querySelectorAll(".phase-view").forEach((el) =>
el.classList.add("hidden"),
);
document
.querySelectorAll(".phase-view")
.forEach((el) => el.classList.add("hidden"));
const viewMap = {
Suggest: "suggest-view",
Vote: "vote-view",

View File

@@ -74,7 +74,8 @@ export function renderVotes() {
const warn = $("warn-" + suggestionId);
const fallbackValue = prevScore ?? 5;
const fallbackDisplay = prevScore ?? "—";
const fallbackEmoji = prevScore != null ? scoreToEmoji(prevScore) : "⚠️";
const fallbackEmoji =
prevScore != null ? scoreToEmoji(prevScore) : "⚠️";
e.target.value = fallbackValue;
if (label) label.textContent = fallbackDisplay;
if (emoji) emoji.textContent = fallbackEmoji;
@@ -89,7 +90,9 @@ export function renderVotes() {
linkedIds.forEach((id) => {
const peerWarn = $("warn-" + id);
if (peerWarn) peerWarn.classList.add("hidden");
const peerSlider = document.querySelector(`input[type=range][data-id="${id}"]`);
const peerSlider = document.querySelector(
`input[type=range][data-id="${id}"]`,
);
if (peerSlider) delete peerSlider.dataset.pending;
});
await getUiRuntime().loadVoteData();
@@ -174,7 +177,9 @@ function syncLinkedSliders(sourceEl, value) {
if (!linkedAttr) return;
const ids = linkedAttr.split(",").filter(Boolean);
ids.forEach((id) => {
const slider = document.querySelector(`input[type=range][data-id="${id}"]`);
const slider = document.querySelector(
`input[type=range][data-id="${id}"]`,
);
if (!slider || slider === sourceEl) return;
slider.value = value;
const scoreLabel = $("score-" + id);
@@ -206,7 +211,9 @@ export function updatePhaseNav() {
const finalizeBtn = $("finalize-votes");
if (finalizeBtn) {
finalizeBtn.textContent = state.votesFinal ? t("vote.unfinalize") : t("vote.finalize");
finalizeBtn.textContent = state.votesFinal
? t("vote.unfinalize")
: t("vote.finalize");
}
const voteMissingBadge = $("vote-missing");
@@ -226,7 +233,9 @@ export function updatePhaseNav() {
const voteStatusText = $("vote-status-text");
if (voteStatusText) {
voteStatusText.textContent = state.votesFinal ? t("nav.voteFinalized") : t("nav.voteHint");
voteStatusText.textContent = state.votesFinal
? t("nav.voteFinalized")
: t("nav.voteHint");
}
renderAdminVoteStatus();
@@ -243,7 +252,9 @@ export function updatePhaseNav() {
if (voteNext) {
const locked = !state.resultsOpen && !isAdmin;
voteNext.disabled = locked;
voteNext.textContent = locked ? t("nav.waitingForResults") : t("nav.next");
voteNext.textContent = locked
? t("nav.waitingForResults")
: t("nav.next");
}
const adminResultsToggle = $("results-open");