diff --git a/.github/workflows/screenshots.yml b/.github/workflows/screenshots.yml new file mode 100644 index 0000000..473a8d3 --- /dev/null +++ b/.github/workflows/screenshots.yml @@ -0,0 +1,67 @@ +name: Screenshots + +# Phone screenshots of the main screens, in light and dark, from a fresh app +# filled with three weeks of practice (web/scripts/screenshots.mjs). Each pull +# request gets them on the branch screenshots/, which reviews and +# the README link to; nothing is committed to the pull request itself. + +on: + pull_request: + paths: ['web/**', 'backend/**', '.github/workflows/screenshots.yml'] + +concurrency: + group: screenshots-${{ github.head_ref }} + cancel-in-progress: true + +permissions: + contents: write + +jobs: + screenshots: + if: github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 + with: + node-version: 26 + cache: npm + cache-dependency-path: web/package-lock.json + - name: Build the app + run: | + (cd web && npm ci) + make build + - name: Start it with an empty database + run: | + cd dist + ./reckon serve --http=127.0.0.1:8090 --dir="$RUNNER_TEMP/pb_data" > "$RUNNER_TEMP/reckon.log" 2>&1 & + for _ in $(seq 30); do curl -fs http://127.0.0.1:8090/api/health && break; sleep 1; done + - name: Take the screenshots + working-directory: web + env: + TZ: Europe/Brussels + run: | + # the one-time code a fresh install asks for on its setup screen + export RECKON_SETUP_CODE=$(cat "$RUNNER_TEMP/pb_data/setup_code") + npm i --no-save playwright + npx playwright install --with-deps chromium + node scripts/screenshots.mjs "$RUNNER_TEMP/shots" + - name: Server log + if: failure() + run: cat "$RUNNER_TEMP/reckon.log" + - name: Publish them on screenshots/${{ github.head_ref }} + env: + BRANCH: screenshots/${{ github.head_ref }} + SHA: ${{ github.event.pull_request.head.sha }} + TOKEN: ${{ github.token }} + run: | + cd "$RUNNER_TEMP/shots" + git init -q -b "$BRANCH" + git add . + git -c user.name="github-actions[bot]" -c user.email="41898282+github-actions[bot]@users.noreply.github.com" \ + commit -qm "Screenshots of $SHA" + git push -qf "https://x-access-token:$TOKEN@github.com/$GITHUB_REPOSITORY.git" "HEAD:refs/heads/$BRANCH" diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a6246b..8f966a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,23 +1,29 @@ # Changelog -What changed in each release of reckon. Installs update to the newest release; see +What changed in each release of Reckon. Installs update to the newest release; see [docs/deploy.md](docs/deploy.md#updates-and-versions). -## Unreleased +## 0.1.0 (2026-11-17) -- Every published image carries a software bill of materials (SBOM), and an OpenSSF - Scorecard run checks the repository's security practices every week. -- golang.org/x/net 0.62.0, which fixes GO-2026-6860. -- SECURITY.md: how to report a problem privately, and how quickly fixes ship. -- Security scans on every pull request and every Monday: CodeQL, govulncheck, Grype - (web and worker dependencies, released images), dependency review and gitleaks. -- The containers' filesystems are read-only apart from `pb_data` and `/tmp`. -- The compose file follows the major version (`:1`) instead of `:latest`, and the - installer fetches the compose files of the newest release instead of `main`. +The first release: practice for the numerical reasoning tests used in job applications. -## 1.0.0 (2026-11-04) - -- Releases: a `vX.Y.Z` tag publishes `:X.Y.Z`, `:X.Y`, `:X` and `:latest`, and installs follow - `:latest`, so they only update to a release. `main` publishes `:edge`. -- Every published image has a signed provenance attestation (`gh attestation verify`). -- Security and maintenance section in the README. +- Four kinds of question, each with nine levels: number series, number grids, number + figures and function boxes, generated fresh every time. +- Lessons of eight questions with instant feedback. Six right on your own moves a skill up a + level. +- A **Hint** under every question: how to think about this kind of question, and a pointer + for this one that doesn't give the answer away. +- **Show solution**: a plain-language walkthrough, one step at a time, highlighting the boxes + each step is about. +- Adaptive mock tests, full (15 questions, 30 minutes) or quick (8 questions, 12 minutes), + scored as a stanine from 1 to 9 with its margin of error, the score per question type and + what to practise next. +- Progress: test results over time, accuracy and pace per question type, four weeks of + activity, and every lesson and test to review with its worked solutions. +- XP, a daily goal and a streak, with an optional evening reminder when the streak would + break. +- Each person's practice is private to them, the owner included; download it as a file or + start again from **Me**. +- Built on plasto: setup code, accounts for a household, rate-limited sign-in, a locked-down + container, nightly backups, signed images and security scans. Includes Shoppa's fix for push + notifications on iPhones and Troye's fix for missed-job checks. diff --git a/CLAUDE.md b/CLAUDE.md index 1f51fc0..5a32b81 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,7 +1,8 @@ # CLAUDE.md -reckon is a self-hosted app built on the plasto template: a Go backend on PocketBase (`backend/`) -serving a Svelte 5 + Tailwind web app (`web/`). +Reckon is a self-hosted trainer for the numerical reasoning tests used in job applications, +built on the plasto template: a Go backend on PocketBase (`backend/`) serving a Svelte 5 + +Tailwind web app (`web/`). How questions and scores are made is in `docs/plan.md`. ## Commands @@ -22,6 +23,10 @@ serving a Svelte 5 + Tailwind web app (`web/`). - Heavy work (ML, scraping, LLM calls) goes in a Python worker under `workers/` that uses `plasto_worker.Client`; workers write records, Go hooks react. Allow workers in API rules with `@request.auth.collectionName = "workers"`. +- Questions, hints, solutions and adaptive scoring live in `web/src/lib/engine.ts`; its tests + check every worked sum. Keep hint and solution text plain: everyday words, no jargon. +- Each person's practice is private: API rules on `progress` and `practice_sessions` allow + only `user = @request.auth.id`, the owner included. Keep it that way. - `docs/first-feature.md` walks through adding a feature across every layer. - Deploy files are in `deploy/` (see `docs/deploy.md`); `make smoke` runs the images with `deploy/docker-compose.yml` end to end, and CI runs it on every PR. diff --git a/README.md b/README.md index acb0c9d..29a1d8f 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,114 @@ -# reckon +
-A self-hosted app built on [plasto](https://github.com/selfhostit/plasto). + -## Quick start +# Reckon -You need [Go](https://go.dev/dl/) 1.27+, [Node](https://nodejs.org) 22+ and -[uv](https://docs.astral.sh/uv/) (for the Python workers). +**Practise the numerical reasoning tests that job applications ask for, on your own hardware.** + +[![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/selfhostit/reckon/badge)](https://scorecard.dev/viewer/?uri=github.com/selfhostit/reckon) + +
+ +Many employers ask candidates to sit a numerical reasoning test before an interview: rows of +boxes, grids and figures with one number missing, against the clock. The score lands in a +report next to your CV, on a 1–9 scale, and an average result can decide whether you get +the interview. These tests reward practice, but real practice material is hard to find, and +what there is often trains the wrong thing. + +Reckon is a self-hosted trainer for exactly these questions. It makes endless new ones at +nine levels of difficulty, explains each one in plain language when you're stuck, and runs +adaptive mock tests that place you on the same 1–9 scale the reports use. Think Duolingo for +the numbers test: short daily lessons, levels, a streak, and a clear picture of how you're +improving. + + + + + + + + + + + + +
The home screen: today's XP against the daily goal, a button to continue, the latest test level on a 1 to 9 scale, and a tip
A few minutes a day. A daily goal, a streak and where to continue.
A number grid with a missing number, and the hint open below it: how to think about this kind of question, and a pointer for this one
Stuck? Ask for a hint. How to think about it, without the answer.
The solution walkthrough: a row of the grid highlighted in blue, and the worked steps below it
Or walk through it. One step at a time, with the boxes highlighted.
A timed mock test question: four input and output boxes, with the clock in the corner
Mock tests like the real one. Adaptive, timed, no help.
A mock test result: stanine 7 on a bell-shaped 1 to 9 scale, with its likely range, the score per question type and what to practise next
A score you'll recognise. A stanine, its margin of error and what to work on.
The progress screen in dark mode: test results over time with their margin of error, and accuracy and pace per question type
See yourself improve. Every session kept, in light and dark.
+ +Reckon is new: version 0.1 has the four question types, lessons, mock tests and progress. +[docs/plan.md](docs/plan.md) explains how questions and scores are made, and what comes next. +Reckon is built on [plasto](https://github.com/selfhostit/plasto). + +## Install + +On a NAS, a Raspberry Pi or any Linux machine with a terminal (or SSH): + +```sh +curl -fsSL https://github.com/selfhostit/docs/releases/latest/download/install.sh | sh -s -- reckon +``` + +This is the installer for every selfhostit app, set to install only Reckon. It sets up Docker +if it is missing, installs a pinned release of Reckon and checks every file against its +SHA-256, and can give Reckon an `https://` address with Tailscale, so it opens on your phone +at home and away. When it is done, open the address it lists, type the setup code and make +your account. Reckon needs no other selfhostit app. + +Step by step for a [Pi or Linux](https://github.com/selfhostit/docs/blob/main/linux.md), +a [Synology](https://github.com/selfhostit/docs/blob/main/synology.md) or +[another NAS](https://github.com/selfhostit/docs/blob/main/other-nas.md), and +[after you install](https://github.com/selfhostit/docs/blob/main/first-steps.md): adding the +rest of your household, putting Reckon on your phone, and what to try when it doesn't open. + +## How it works + +**Four kinds of question**, the ones these tests are made of. Each has nine levels, from +"add 5 each time" to two series woven together: + +| | What you see | What it trains | +|---|---|---| +| **Number series** | A row of boxes, one missing | Changes between neighbours, multiplying, two series mixed together, squares and cubes | +| **Number grids** | A 3 × 3 grid, one missing | One rule that holds for every row, or every column | +| **Number figures** | Crosses and triangles of numbers | How the outer numbers make the centre | +| **Function boxes** | Inputs and outputs | Finding the one hidden operation, and working backwards | + +**Lessons** are eight questions with instant feedback: two to warm up, five at your level and +one challenge. Get six right on your own and that skill moves up a level. Under every question: + +- **Hint** explains how to think about this kind of question, plus a pointer for this one that + doesn't give the answer away. A right answer with the hint earns half the XP. +- **Show solution** walks through it one step at a time, in plain language, highlighting the + boxes each step is about, until you type the answer yourself. That question earns no XP, + but you've learned the trick. + +**Mock tests** work like the real ones: 15 questions in 30 minutes (or a quick 8 in 12), no +help, and each question picked to match the ability you've shown so far, so most people get +about half right. Your result is a **stanine** from 1 to 9 with its margin of error, the +hardest level you solved, your pace and your score per question type, then a suggestion of +what to practise. After a strong test, your practice levels move up to match. + +**Progress** keeps every lesson and test, with each question, your answer and your time: +your test results over time, accuracy and pace per question type, and four weeks of +activity. Open any session to see every question again with its worked solution. + +The stanine is a practice estimate from the questions' built-in difficulty, not an official +norm score: use it to follow your own progress, and expect real tests to differ by about one +stanine. [docs/plan.md](docs/plan.md#scoring) explains the scoring. + +## Your data + +- **Private to each person.** Everyone on the server has their own account and their own + practice; nobody else can see it, not even the owner. The access rules are tested + (`backend/app/practice_test.go`). +- **On your machine.** Questions are made in the browser and results are saved in `pb_data` on + your server, with a nightly backup kept there. No analytics, no tracking, no selfhostit + account and no third-party service. +- **Yours to take or delete.** **Me → Your data** downloads everything as a file, or starts + again from scratch. Removing a person removes their practice too. + +## Develop + +To work on Reckon itself, you need [Go](https://go.dev/dl/) 1.27+, [Node](https://nodejs.org) 22+ and +[uv](https://docs.astral.sh/uv/) (for the Python workers of the template; Reckon has none yet). ```sh make setup # install dependencies @@ -14,86 +117,77 @@ make dev # backend on :8090, web app with live reload on http://localhost:51 Open the app and create your account with the setup code that `make dev` prints: you become the **owner** and can also sign in to the admin UI at http://localhost:8090/_/ with the same -email and password. Add more people in the app: open **People** at the bottom of the home -screen, add their name and email, and send them the message it shows with their password. +email and password. Add more people in the app: open **Me**, tap **People**, add their +name and email, and send them the message it shows with their password. + +The question engine is `web/src/lib/engine.ts`, with no dependencies; its tests generate +thousands of questions at every level and check that every worked sum in every solution adds +up (`npm test` in `web/`). The rules of the game (levels, XP, streaks, scores) are in +`web/src/lib/practice.ts`. ## What you get - **First-run setup and sign-in.** The first account is made on a setup screen, with a one-time code from the installer or the app's log, so nobody else can claim a fresh install. -- **Users and roles.** The owner adds people, gives them a new password and removes them - on the People screen; members can see each other and edit themselves. Everyone can - change their own password. Nobody can sign themselves up. -- **Push notifications** straight from your server, with no account or third-party - service. Each person turns them on per device; send one from Go with - `push.ToUser(app, userID, push.Message{Title: "…", URL: "/…"})`. Phones need the - app on HTTPS. -- **Scheduled jobs that don't get skipped.** `jobs.MustAdd(app, "digest", "0 7 * * *", fn)` - runs on a cron schedule in your time zone (`TZ`). If the server was off when a job - was due, it runs once when the server starts again. Every run and its error are - listed in the admin UI under the `jobs` collection. -- **Nightly backups** of the database and uploads at 03:00, keeping the last 7, in - `pb_data/backups`. Change the schedule or add S3 storage in the admin UI under - Settings > Backups. -- **Python workers** for the heavy lifting (ML, scraping, LLMs), on this machine or - another. They sign in with a worker account and read and write records through - the API; see [workers/README.md](workers/README.md). -- **An installable app.** It installs to a phone's home screen or a desktop, opens - offline from its cached shell, and follows the system's light or dark mode. +- **Accounts for your household.** The owner adds people, gives them a new password and + removes them on the People screen; everyone can change their own password. Nobody can sign + themselves up. +- **An evening reminder** at 19:00, for people who turn it on, when their streak would break + tonight: a push notification straight from your server, with no third-party service. + Phones need the app on HTTPS. +- **Nightly backups** of the database at 03:00, keeping the last 7, in `pb_data/backups`. + Change the schedule or add S3 storage in the admin UI under Settings > Backups. +- **An installable app.** It installs to a phone's home screen or a desktop, opens offline + from its cached shell, and follows the system's light or dark mode. ## How it fits together ```mermaid flowchart LR - phone["Phone or laptop
installable web app"] + phone["Phone or laptop
installable web app
makes the questions"] subgraph box["Your NAS, Pi or server"] - app["Go app on PocketBase
API, auth, realtime, admin UI"] - db[("SQLite and files
pb_data/")] - jobs["Scheduled jobs
and nightly backups"] + app["Go app on PocketBase
API, accounts, admin UI"] + db[("SQLite
pb_data/")] + jobs["Evening reminder
and nightly backups"] app --- db app --- jobs end - worker["Python workers
ML, scraping, LLMs"] phone -- "HTTPS over Tailscale" --> app - worker -- "records through the API" --> app app -. "Web Push" .-> phone ``` -Everything a person sees is the web app, served by the Go app. Heavy work runs in -Python workers, here or on another machine, which write records; Go hooks react to -those records and notify people. +Questions are generated and scored in the web app, so practice keeps working smoothly on a +slow connection; the Go app stores each person's progress and sessions and enforces who can +read them. -## Deploy +## Deploy on its own -On any Linux machine with Docker (a NAS, a Raspberry Pi, a server): +Reckon's own installer is an alternative to [the one above](#install): it gives Reckon its own +Tailscale machine, `https://reckon..ts.net`, signed in with an auth key. It runs +from `main` and takes the newest release, without the SHA-256 checks of the shared installer. +On any Linux machine with Docker: ```sh curl -fsSL https://raw.githubusercontent.com/selfhostit/reckon/main/deploy/install.sh | sh ``` -It asks for a Tailscale auth key, so your devices reach the app at -`https://reckon..ts.net`, and starts it with Docker Compose. See -[docs/deploy.md](docs/deploy.md) for updates, backups, workers, Synology and the Pi. +See [docs/deploy.md](docs/deploy.md) for updates, backups, Synology and the Pi. ## Layout ``` backend/ Go app on PocketBase - main.go entry point - app/ routes, hooks and jobs (start here) + app/ routes, hooks and the streak reminder (start here) + migrations/ database schema as code: progress and practice sessions jobs/ scheduled jobs with catch-up push/ Web Push: keys, subscriptions, sending - migrations/ database schema as code web/ Svelte 5 + Tailwind web app - src/App.svelte picks setup, sign-in or the app - src/components/ screens; Home.svelte is where your app starts - src/lib/ shared code (API client, session, install) and its tests - public/ manifest, service worker and icons -workers/ Python worker kit, your workers, their tests and image + src/lib/engine.ts the question engine: generators, hints, solutions, adaptive scoring + src/lib/practice.ts levels, XP, streaks and scores + src/components/ screens: Today, Lesson, MockTest, Result, Review, Progress, Me + scripts/ the screenshot script CI runs on every pull request deploy/ compose files, Tailscale sidecar, install script, smoke test -docs/ decisions, the deploy guide and the first-feature guide -Dockerfile the app's multi-arch image -Makefile run `make` to see every command +docs/ the plan, the brand and the deploy guide ``` ## Commands @@ -105,10 +199,9 @@ Makefile run `make` to see every command | `make test` | Run the Go, web and worker tests | | `make build` | Build `dist/reckon` with the web app next to it | | `make run` | Build the Docker image and run it on :8090 | -| `make smoke` | Deploy both images with Compose and test end to end | +| `make smoke` | Deploy the images with Compose and test end to end | -Pushes to `main` publish `ghcr.io/selfhostit/reckon` and -`ghcr.io/selfhostit/reckon-worker` for amd64, arm64 and armv7; a `v*` tag +Pushes to `main` publish `ghcr.io/selfhostit/reckon` for amd64, arm64 and armv7; a `v*` tag publishes that version. ## Security and maintenance @@ -119,24 +212,27 @@ publishes that version. can't gain new ones; its filesystem is read-only apart from its data. - **Nobody claims a new install before you:** the first account needs the one-time setup code the install prints (`backend/app/setup.go`). -- **Sign-ins are rate limited** (10 a minute, `backend/migrations/*_rate_limits.go`), and the - web app sends a Content Security Policy (`backend/app/headers.go`). -- **Tested on every change:** Go, web and Python worker tests and an end-to-end run of the published images +- **Private by rule:** each person's progress and sessions can only be read by them, and a + finished session can't be edited (`backend/migrations/1762000000_practice.go`). +- **Sign-ins are rate limited** (10 a minute), and the web app sends a Content Security + Policy (`backend/app/headers.go`). +- **Tested on every change:** Go and web tests and an end-to-end run of the published images (`make smoke`) in [CI](.github/workflows/ci.yml); Actions are pinned to commit hashes and Dependabot keeps Go, npm, Python, Docker and Actions dependencies current. - **Security scans** on every pull request and every week: CodeQL, govulncheck on the Go code, Grype on the other dependencies and the released images, dependency review and - gitleaks - ([security.yml](.github/workflows/security.yml)). + gitleaks ([security.yml](.github/workflows/security.yml)). - **Versioned releases:** installs update to a release, not to every change on `main`, and every image has a signed attestation of the commit and workflow that built it ([CHANGELOG.md](CHANGELOG.md), [docs/deploy.md](docs/deploy.md#check-where-an-image-came-from)). -- **No analytics or tracking,** and no account anywhere else: the data stays in `pb_data` on your - machine, with a nightly backup kept there. + +Found a security problem? Please report it privately, not in an issue: see [SECURITY.md](SECURITY.md) +for how, and how quickly it gets fixed. [Security and privacy](https://github.com/selfhostit/docs/blob/main/security.md) covers every selfhostit app: +what protects an install, what you are trusting and what is not done yet. ## Support -If reckon saves you time, you can [buy me a coffee](https://buymeacoffee.com/kalfasyan). +If Reckon helps you land the job, you can [buy me a coffee](https://buymeacoffee.com/kalfasyan). ## License diff --git a/SECURITY.md b/SECURITY.md index 6bb6c48..31e50eb 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -4,6 +4,7 @@ Please don't open a public issue for a security problem. Use **Report a vulnerability** on this repository's [Security tab](https://github.com/selfhostit/reckon/security/advisories/new), +or write to **kalfasyan@pm.me** with which version (the image tag), what you found, how to reproduce it and what someone could do with it. @@ -21,7 +22,7 @@ could do with it. ## Supported versions Fixes go into a new release of the newest version. Installs follow its major version -(`:1`), so `docker compose pull` or `selfhostit update` brings the fix; older releases +(`:0`), so `docker compose pull` or `selfhostit update` brings the fix; older releases are not patched. See [docs/deploy.md](docs/deploy.md#updates-and-versions). ## How installs are protected diff --git a/backend/app/app.go b/backend/app/app.go index a698e55..2a06b97 100644 --- a/backend/app/app.go +++ b/backend/app/app.go @@ -27,6 +27,8 @@ func Register(app core.App, cfg Config) { // scheduled jobs and backups follow the server's time zone (TZ) app.Cron().SetTimezone(time.Local) + registerStreakReminder(app) + app.OnServe().BindFunc(func(se *core.ServeEvent) error { se.Router.GET("/api/app/info", info) if err := registerSetupRoutes(se); err != nil { diff --git a/backend/app/practice_test.go b/backend/app/practice_test.go new file mode 100644 index 0000000..ff16267 --- /dev/null +++ b/backend/app/practice_test.go @@ -0,0 +1,110 @@ +package app_test + +import ( + "net/http" + "strings" + "testing" + + "github.com/pocketbase/pocketbase/core" + "github.com/pocketbase/pocketbase/tests" +) + +// addSession saves a finished lesson for a user. +func addSession(t testing.TB, a core.App, user string) *core.Record { + c, err := a.FindCollectionByNameOrId("practice_sessions") + if err != nil { + t.Fatal(err) + } + s := core.NewRecord(c) + s.Load(map[string]any{ + "user": user, "kind": "practice", "family": "series", "level": 2, "level_after": 3, + "started": "2026-11-17 10:00:00.000Z", "ended": "2026-11-17 10:04:00.000Z", + "items": []any{map[string]any{"given": 47, "correct": true, "ms": 5200}}, "result": map[string]any{"correct": 7, "answered": 8}, + }) + if err := a.Save(s); err != nil { + t.Fatal(err) + } + return s +} + +// Practice is private: each person reads and writes only their own, the owner included. +func TestPracticeIsPrivate(t *testing.T) { + session := `{"user":"BOB","kind":"test","mode":"quick","started":"2026-11-17 11:00:00.000Z","ended":"2026-11-17 11:10:00.000Z","items":[],"result":{"stanine":5}}` + cases := []struct { + name, who, method, url, body string + status int + want string + }{ + {"a member saves their own session", "bob", http.MethodPost, "/api/collections/practice_sessions/records", session, http.StatusOK, `"stanine":5`}, + {"nobody saves a session for someone else", "ada", http.MethodPost, "/api/collections/practice_sessions/records", session, http.StatusBadRequest, `"data":{}`}, + {"the owner can't list a member's sessions", "ada", http.MethodGet, "/api/collections/practice_sessions/records", "", http.StatusOK, `"totalItems":1`}, + {"a member can't open the owner's session", "bob", http.MethodGet, "/api/collections/practice_sessions/records/ADA_SESSION", "", http.StatusNotFound, `"data":{}`}, + {"a finished session can't be edited", "ada", http.MethodPatch, "/api/collections/practice_sessions/records/ADA_SESSION", `{"result":{"stanine":9}}`, http.StatusForbidden, `"data":{}`}, + {"signed-out visitors see no sessions", "", http.MethodGet, "/api/collections/practice_sessions/records", "", http.StatusOK, `"totalItems":0`}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + a := newApp(t) + ada, adaToken := addUser(t, a, "ada@example.com", "owner") + bob, bobToken := addUser(t, a, "bob@example.com", "member") + addSession(t, a, bob.Id) // the owner must not see this one + adaSession := addSession(t, a, ada.Id).Id + s := tests.ApiScenario{ + Name: c.name, + Method: c.method, + URL: strings.ReplaceAll(c.url, "ADA_SESSION", adaSession), + ExpectedStatus: c.status, + ExpectedContent: []string{c.want}, + TestAppFactory: func(testing.TB) *tests.TestApp { return a }, + } + if c.body != "" { + s.Body = strings.NewReader(strings.ReplaceAll(c.body, "BOB", bob.Id)) + } + switch c.who { + case "ada": + s.Headers = map[string]string{"Authorization": adaToken} + case "bob": + s.Headers = map[string]string{"Authorization": bobToken} + } + s.Test(t) + }) + } +} + +func TestProgressIsOnePerPerson(t *testing.T) { + a := newApp(t) + defer a.Cleanup() + ada, _ := addUser(t, a, "ada@example.com", "owner") + c, err := a.FindCollectionByNameOrId("progress") + if err != nil { + t.Fatal(err) + } + for i := range 2 { + p := core.NewRecord(c) + p.Load(map[string]any{"user": ada.Id, "xp": 10, "daily_goal": 50, "days": map[string]int{"2026-11-17": 10}}) + err := a.Save(p) + if i == 0 && err != nil { + t.Fatal(err) + } + if i == 1 && err == nil { + t.Fatal("a second progress record for the same person was saved") + } + } +} + +func TestDeletingAPersonDeletesTheirPractice(t *testing.T) { + a := newApp(t) + defer a.Cleanup() + bob, _ := addUser(t, a, "bob@example.com", "member") + addSession(t, a, bob.Id) + if err := a.Delete(bob); err != nil { + t.Fatal(err) + } + left, err := a.FindRecordsByFilter("practice_sessions", "", "", 0, 0) + if err != nil { + t.Fatal(err) + } + if len(left) != 0 { + t.Fatalf("%d sessions left after their person was deleted", len(left)) + } +} diff --git a/backend/app/streak.go b/backend/app/streak.go new file mode 100644 index 0000000..4b324d6 --- /dev/null +++ b/backend/app/streak.go @@ -0,0 +1,54 @@ +package app + +import ( + "fmt" + "time" + + "github.com/pocketbase/pocketbase/core" + + "github.com/selfhostit/reckon/jobs" + "github.com/selfhostit/reckon/push" +) + +// An evening nudge for people who turned reminders on: they practised +// yesterday but not yet today, so their streak ends at midnight. +func registerStreakReminder(app core.App) { + jobs.MustAdd(app, "streak-reminder", "0 19 * * *", func(app core.App) error { + return sendStreakReminders(app, time.Now()) + }) +} + +func sendStreakReminders(app core.App, now time.Time) error { + list, err := app.FindRecordsByFilter("progress", "reminders = true", "", 0, 0) + if err != nil { + return err + } + for _, p := range list { + var days map[string]float64 + if err := p.UnmarshalJSONField("days", &days); err != nil { + continue + } + if n := streakAtRisk(days, now); n > 0 { + push.ToUser(app, p.GetString("user"), push.Message{ + Title: fmt.Sprintf("Keep your %d-day streak", n), + Body: "One short lesson today keeps it going.", + URL: "/", + Tag: "streak", + }) + } + } + return nil +} + +// streakAtRisk is the length of the streak that ends tonight: the run of days +// with XP up to yesterday, if there is none yet today. 0 means nothing to remind. +func streakAtRisk(days map[string]float64, now time.Time) int { + if days[now.Format(time.DateOnly)] > 0 { + return 0 + } + n := 0 + for d := now.AddDate(0, 0, -1); days[d.Format(time.DateOnly)] > 0; d = d.AddDate(0, 0, -1) { + n++ + } + return n +} diff --git a/backend/app/streak_test.go b/backend/app/streak_test.go new file mode 100644 index 0000000..42a6f4a --- /dev/null +++ b/backend/app/streak_test.go @@ -0,0 +1,27 @@ +package app + +import ( + "testing" + "time" +) + +func TestStreakAtRisk(t *testing.T) { + now := time.Date(2026, 11, 17, 19, 0, 0, 0, time.Local) + cases := []struct { + name string + days map[string]float64 + want int + }{ + {"no practice ever", nil, 0}, + {"already practised today", map[string]float64{"2026-11-16": 20, "2026-11-17": 10}, 0}, + {"three days in a row up to yesterday", map[string]float64{"2026-11-14": 10, "2026-11-15": 30, "2026-11-16": 10}, 3}, + {"a gap breaks the run", map[string]float64{"2026-11-13": 10, "2026-11-15": 30, "2026-11-16": 10}, 2}, + {"last practice two days ago: the streak is already gone", map[string]float64{"2026-11-15": 30}, 0}, + {"a day with no XP doesn't count", map[string]float64{"2026-11-16": 0}, 0}, + } + for _, c := range cases { + if got := streakAtRisk(c.days, now); got != c.want { + t.Errorf("%s: got %d, want %d", c.name, got, c.want) + } + } +} diff --git a/backend/jobs/jobs.go b/backend/jobs/jobs.go index 44e15cd..65ec39c 100644 --- a/backend/jobs/jobs.go +++ b/backend/jobs/jobs.go @@ -42,7 +42,11 @@ func MustAdd(app core.App, name, cronExpr string, fn Func) { app.Cron().MustAdd(name, cronExpr, func() { Run(app, name, fn) }) app.OnServe().BindFunc(func(se *core.ServeEvent) error { - go catchUp(se.App, name, schedule, fn, time.Now()) + // checked before serving, so it never outlives the app; only a run goes + // to the background, so a slow job doesn't hold up the start + if due(se.App, name, schedule, time.Now()) { + go Run(se.App, name, fn) + } return se.Next() }) } @@ -97,15 +101,22 @@ func record(app core.App, name string, start time.Time, took time.Duration, runE return app.Save(rec) } -// catchUp runs the job if a scheduled time passed since its last run. A job -// seen for the first time is only recorded, so adding one doesn't run it. +// catchUp runs the job if a scheduled time passed since its last run. func catchUp(app core.App, name string, schedule *cron.Schedule, fn Func, now time.Time) { + if due(app, name, schedule, now) { + Run(app, name, fn) + } +} + +// due reports whether a scheduled time passed since the job's last run. A job +// seen for the first time is only recorded, so adding one doesn't run it. +func due(app core.App, name string, schedule *cron.Schedule, now time.Time) bool { rec, err := app.FindFirstRecordByData(Collection, "name", name) if err != nil { col, err := app.FindCollectionByNameOrId(Collection) if err != nil { app.Logger().Error("Jobs collection missing", "error", err) - return + return false } rec = core.NewRecord(col) rec.Set("name", name) @@ -113,13 +124,14 @@ func catchUp(app core.App, name string, schedule *cron.Schedule, fn Func, now ti if err := app.Save(rec); err != nil { app.Logger().Error("Could not record new job", "job", name, "error", err) } - return + return false } last := rec.GetDateTime("last_run").Time() - if missed(schedule, last, now) { - app.Logger().Info("Catching up on a missed job run", "job", name, "last_run", last) - Run(app, name, fn) + if !missed(schedule, last, now) { + return false } + app.Logger().Info("Catching up on a missed job run", "job", name, "last_run", last) + return true } // missed reports whether the schedule was due at any minute after last, up to diff --git a/backend/migrations/1762000000_practice.go b/backend/migrations/1762000000_practice.go new file mode 100644 index 0000000..1f63713 --- /dev/null +++ b/backend/migrations/1762000000_practice.go @@ -0,0 +1,79 @@ +package migrations + +import ( + "github.com/pocketbase/pocketbase/core" + m "github.com/pocketbase/pocketbase/migrations" + "github.com/pocketbase/pocketbase/tools/types" +) + +// Each person's practice: their levels, XP and streak ("progress", one record +// each) and every lesson and mock test they finish ("practice_sessions"). Both +// are private: nobody else, not even the owner, can read them. A finished +// session is a record of what happened, so it can't be edited, only deleted. +func init() { + m.Register(func(app core.App) error { + users, err := app.FindCollectionByNameOrId("users") + if err != nil { + return err + } + own := types.Pointer(`user = @request.auth.id`) + create := types.Pointer(`@request.auth.collectionName = "users" && @request.body.user = @request.auth.id`) + + progress := core.NewBaseCollection("progress") + progress.Fields.Add( + &core.RelationField{Name: "user", CollectionId: users.Id, Required: true, MaxSelect: 1, CascadeDelete: true}, + &core.NumberField{Name: "xp", OnlyInt: true, Min: types.Pointer(0.0), Max: types.Pointer(100_000_000.0)}, + &core.NumberField{Name: "daily_goal", OnlyInt: true, Min: types.Pointer(0.0), Max: types.Pointer(1000.0)}, + // level per question type, {"series": {"level": 3}, ...} + &core.JSONField{Name: "skills", MaxSize: 2_000}, + // XP earned per day, {"2026-11-17": 60, ...}; the web app keeps about a year + &core.JSONField{Name: "days", MaxSize: 32_000}, + // an evening notification when the streak is about to break + &core.BoolField{Name: "reminders"}, + &core.AutodateField{Name: "created", OnCreate: true}, + &core.AutodateField{Name: "updated", OnCreate: true, OnUpdate: true}, + ) + progress.AddIndex("idx_progress_user", true, "user", "") + progress.ListRule, progress.ViewRule, progress.DeleteRule = own, own, own + progress.CreateRule = create + progress.UpdateRule = types.Pointer(`user = @request.auth.id && (@request.body.user:isset = false || @request.body.user = @request.auth.id)`) + if err := app.Save(progress); err != nil { + return err + } + + sessions := core.NewBaseCollection("practice_sessions") + sessions.Fields.Add( + &core.RelationField{Name: "user", CollectionId: users.Id, Required: true, MaxSelect: 1, CascadeDelete: true}, + &core.SelectField{Name: "kind", Values: []string{"practice", "test"}, MaxSelect: 1, Required: true}, + // which skill a lesson practised (mix: all four) + &core.SelectField{Name: "family", Values: []string{"series", "grid", "shapes", "pairs", "mix"}, MaxSelect: 1}, + // a mock test's length + &core.SelectField{Name: "mode", Values: []string{"full", "quick"}, MaxSelect: 1}, + &core.NumberField{Name: "level", OnlyInt: true, Min: types.Pointer(0.0), Max: types.Pointer(9.0)}, + &core.NumberField{Name: "level_after", OnlyInt: true, Min: types.Pointer(0.0), Max: types.Pointer(9.0)}, + &core.DateField{Name: "started", Required: true}, + &core.DateField{Name: "ended", Required: true}, + // every question, the answer given, the time taken and any help used + &core.JSONField{Name: "items", MaxSize: 400_000}, + // the score: correct answers, and for a test the stanine and its margin + &core.JSONField{Name: "result", MaxSize: 4_000}, + &core.AutodateField{Name: "created", OnCreate: true}, + ) + sessions.AddIndex("idx_practice_sessions_user", false, "user, started", "") + sessions.ListRule, sessions.ViewRule, sessions.DeleteRule = own, own, own + sessions.CreateRule = create + sessions.UpdateRule = nil // superusers only + return app.Save(sessions) + }, func(app core.App) error { + for _, name := range []string{"practice_sessions", "progress"} { + c, err := app.FindCollectionByNameOrId(name) + if err != nil { + return err + } + if err := app.Delete(c); err != nil { + return err + } + } + return nil + }) +} diff --git a/backend/push/push.go b/backend/push/push.go index b1fb12a..3e0452f 100644 --- a/backend/push/push.go +++ b/backend/push/push.go @@ -11,9 +11,11 @@ package push import ( "encoding/json" "errors" + "io" "net/http" "os" "path/filepath" + "strings" "sync" "time" @@ -86,14 +88,17 @@ func loadKeys(app core.App) (*keyPair, error) { } // contact goes in every message so push services know whom to reach about -// problems: RECKON_PUSH_CONTACT if set, otherwise the owner's email. +// problems: RECKON_PUSH_CONTACT if set, otherwise the owner's email. It is an +// email address or an https URL, as webpush-go wants it: the library adds +// "mailto:" to an email itself, and Apple's push service refuses a message +// whose contact reads "mailto:mailto:…", so iPhones would get nothing. func contact(app core.App) string { - if c := os.Getenv("RECKON_PUSH_CONTACT"); c != "" { - return c + if c := strings.TrimSpace(os.Getenv("RECKON_PUSH_CONTACT")); c != "" { + return strings.TrimPrefix(c, "mailto:") } owner, err := app.FindFirstRecordByFilter("users", "role = 'owner'") if err == nil && owner.Email() != "" { - return "mailto:" + owner.Email() + return owner.Email() } return "https://github.com/selfhostit/reckon" } @@ -111,6 +116,33 @@ func ToEveryone(app core.App, exceptUserID string, msg Message) { send(app, dbx.Not(dbx.HashExp{"user": exceptUserID}), msg) } +// Reachable returns which of these users have at least one device with +// notifications on, in the order given. +func Reachable(app core.App, userIDs []string) ([]string, error) { + if len(userIDs) == 0 { + return nil, nil + } + ids := make([]any, len(userIDs)) + for i, id := range userIDs { + ids[i] = id + } + subs, err := app.FindAllRecords(Collection, dbx.In("user", ids...)) + if err != nil { + return nil, err + } + has := map[string]bool{} + for _, s := range subs { + has[s.GetString("user")] = true + } + var reachable []string + for _, id := range userIDs { + if has[id] { + reachable = append(reachable, id) + } + } + return reachable, nil +} + func send(app core.App, where dbx.Expression, msg Message) { subs, err := app.FindAllRecords(Collection, where) if err != nil || len(subs) == 0 { @@ -149,6 +181,8 @@ func deliver(app core.App, subs []*core.Record, msg Message) { app.Logger().Warn("Push failed", "error", err) continue } + // push services say why they refused, as in {"reason":"BadJwtToken"} + reason, _ := io.ReadAll(io.LimitReader(res.Body, 512)) res.Body.Close() switch { case res.StatusCode == http.StatusNotFound || res.StatusCode == http.StatusGone: @@ -156,7 +190,7 @@ func deliver(app core.App, subs []*core.Record, msg Message) { app.Logger().Warn("Could not forget a push subscription", "error", err) } case res.StatusCode >= 400: - app.Logger().Warn("Push rejected", "status", res.StatusCode) + app.Logger().Warn("Push rejected", "status", res.StatusCode, "reason", strings.TrimSpace(string(reason))) } } } diff --git a/backend/push/push_test.go b/backend/push/push_test.go index 4bdf747..87e2f87 100644 --- a/backend/push/push_test.go +++ b/backend/push/push_test.go @@ -4,6 +4,7 @@ import ( "crypto/ecdh" "crypto/rand" "encoding/base64" + "encoding/json" "net/http" "net/http/httptest" "strings" @@ -224,3 +225,57 @@ func TestRoutes(t *testing.T) { s.Test(t) } } + +// The contact in each message must read "mailto:owner@example.com" or an https +// URL: Apple's push service refuses anything else, so iPhones get nothing. +func TestContact(t *testing.T) { + a := newApp(t) + defer a.Cleanup() + owner, _ := addUser(t, a, "owner@example.com") + owner.Set("role", "owner") + if err := a.Save(owner); err != nil { + t.Fatal(err) + } + + hits := make(chan *http.Request, 1) + service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits <- r + w.WriteHeader(http.StatusCreated) + })) + defer service.Close() + subscribe(t, a, owner, service.URL+"/owner") + + // the "sub" claim of the VAPID token: Authorization: vapid t=, k= + sub := func() string { + push.ToUser(a, owner.Id, push.Message{Title: "Hi"}) + var r *http.Request + select { + case r = <-hits: + case <-time.After(5 * time.Second): + t.Fatal("no push was sent") + } + token, _, _ := strings.Cut(strings.TrimPrefix(r.Header.Get("Authorization"), "vapid t="), ",") + parts := strings.Split(token, ".") + if len(parts) != 3 { + t.Fatalf("Authorization %q", r.Header.Get("Authorization")) + } + claims, _ := base64.RawURLEncoding.DecodeString(parts[1]) + var c struct{ Sub string } + if err := json.Unmarshal(claims, &c); err != nil { + t.Fatal(err) + } + return c.Sub + } + + for _, tc := range []struct{ env, want string }{ + {"", "mailto:owner@example.com"}, + {"mailto:ops@example.com", "mailto:ops@example.com"}, + {"ops@example.com", "mailto:ops@example.com"}, + {"https://example.com/contact", "https://example.com/contact"}, + } { + t.Setenv("RECKON_PUSH_CONTACT", tc.env) + if got := sub(); got != tc.want { + t.Errorf("RECKON_PUSH_CONTACT=%q: sub %q, want %q", tc.env, got, tc.want) + } + } +} diff --git a/deploy/.env.example b/deploy/.env.example index f1d0983..c72c160 100644 --- a/deploy/.env.example +++ b/deploy/.env.example @@ -7,7 +7,7 @@ PUID=1000 PGID=1000 # The port on this machine (localhost only) PORT=8090 -# Who push services can contact about this server: mailto:you@example.com +# Who push services can contact about this server: you@example.com, or an https URL # (defaults to the owner's email) RECKON_PUSH_CONTACT= diff --git a/deploy/docker-compose.tailscale.yml b/deploy/docker-compose.tailscale.yml index 88ac554..567825d 100644 --- a/deploy/docker-compose.tailscale.yml +++ b/deploy/docker-compose.tailscale.yml @@ -15,22 +15,8 @@ services: TS_SERVE_CONFIG: /config/serve.json volumes: - ./tailscale:/var/lib/tailscale - configs: - - source: serve - target: /config/serve.json + # HTTPS on port 443 of the tailnet address, forwarded to the app, and port 80 + # redirecting to it, so a typed http:// address works too. A file rather than + # an inline config, which the Docker Compose on a Synology can't read. + - ./tailscale-serve.json:/config/serve.json:ro mem_limit: 256m - -configs: - # HTTPS on port 443 of the tailnet address, forwarded to the app, and port 80 - # redirecting to it, so a typed http:// address works too. - serve: - content: | - { - "TCP": { "443": { "HTTPS": true }, "80": { "HTTP": true } }, - "Web": { - "$${TS_CERT_DOMAIN}:443": { "Handlers": { "/": { "Proxy": "http://app:8090" } } }, - "$${TS_CERT_DOMAIN}:80": { - "Handlers": { "/": { "Redirect": "https://$${TS_CERT_DOMAIN}$${REQUEST_URI}" } } - } - } - } diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index f649fb2..6326f90 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -1,11 +1,11 @@ # Runs the app, and optionally a worker, from the published images. They follow the -# 1.x releases (`:1`); see docs/deploy.md to pin one release. +# 0.x releases (`:0`); see docs/deploy.md to pin one release. # Settings come from .env next to this file (see .env.example); deploy/install.sh # sets everything up. Update with: docker compose pull && docker compose up -d services: app: - image: ${RECKON_IMAGE:-ghcr.io/selfhostit/reckon:1} + image: ${RECKON_IMAGE:-ghcr.io/selfhostit/reckon:0} restart: unless-stopped # Run as the owner of ./pb_data, so the data folder stays yours (and a NAS user's). user: ${PUID:-1000}:${PGID:-1000} @@ -28,7 +28,7 @@ services: # Runs one of the workers in workers/, RECKON_WORKER_SCRIPT (worker.py by default). # Enabled with COMPOSE_PROFILES=worker in .env. worker: - image: ${RECKON_WORKER_IMAGE:-ghcr.io/selfhostit/reckon-worker:1} + image: ${RECKON_WORKER_IMAGE:-ghcr.io/selfhostit/reckon-worker:0} command: [python, "${RECKON_WORKER_SCRIPT:-worker.py}"] profiles: [worker] restart: unless-stopped diff --git a/deploy/install.sh b/deploy/install.sh index 318889a..4ffb556 100755 --- a/deploy/install.sh +++ b/deploy/install.sh @@ -14,7 +14,7 @@ set -eu app=reckon repo=${RECKON_REPO:-selfhostit/reckon} dir=${1:-${RECKON_DIR:-$HOME/$app}} -files="docker-compose.yml docker-compose.tailscale.yml .env.example" +files="docker-compose.yml docker-compose.tailscale.yml tailscale-serve.json .env.example" say() { printf '\033[1m%s\033[0m\n' "$*"; } die() { printf 'Error: %s\n' "$*" >&2; exit 1; } diff --git a/deploy/tailscale-serve.json b/deploy/tailscale-serve.json new file mode 100644 index 0000000..dbc00b6 --- /dev/null +++ b/deploy/tailscale-serve.json @@ -0,0 +1,9 @@ +{ + "TCP": { "443": { "HTTPS": true }, "80": { "HTTP": true } }, + "Web": { + "${TS_CERT_DOMAIN}:443": { "Handlers": { "/": { "Proxy": "http://app:8090" } } }, + "${TS_CERT_DOMAIN}:80": { + "Handlers": { "/": { "Redirect": "https://${TS_CERT_DOMAIN}${REQUEST_URI}" } } + } + } +} diff --git a/docs/brand.md b/docs/brand.md new file mode 100644 index 0000000..9919dd8 --- /dev/null +++ b/docs/brand.md @@ -0,0 +1,35 @@ +# Reckon brand + +Reckon's look comes from the questions themselves: **boxes of numbers with one missing**. +The icon is three solid boxes and a dashed fourth one holding a question mark, the same +dashed, gently pulsing box that marks the missing number in every question. + +## Colours + +| Use | Colour | +| --- | --- | +| Brand, buttons, right answers | emerald (`--color-brand-*` in `web/src/app.css`; buttons use emerald-700 so white text reads at WCAG AA) | +| The missing box in the icon | amber-300, `#fcd34d` | +| Hint | amber | +| Solution walkthrough and highlighted boxes | blue | +| Wrong answers | red | + +Green, blue and red always come with an icon or a word as well (a tick, a cross, "Solved with +the walkthrough"), so no state is shown by colour alone. + +## Icons + +| File | Use | +| --- | --- | +| `web/public/icons/icon.svg` | App icon: favicon, sign-in header | +| `web/public/icons/icon-192.png`, `icon-512.png` | PWA icons, rendered from `icon.svg` | +| `web/public/icons/icon-maskable-512.png`, `apple-touch-icon.png` | Full-bleed versions with the boxes inside the safe zone | + +To regenerate the PNGs after changing the SVG, render it at each size (192, 512, and 180 for +`apple-touch-icon.png`) with any SVG renderer, for example `rsvg-convert -w 512 icon.svg`. + +## Words + +Plain and encouraging. Say what to do ("Try it yourself first"), explain rather than judge +("Not quite. The answer is 17"), and name the trick in everyday words ("the change between +neighbours", not "first-order differences"). diff --git a/docs/deploy.md b/docs/deploy.md index 24681ff..59564bd 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -15,7 +15,7 @@ anything to the internet. Two images are published for amd64, arm64 and armv7: `ghcr.io/selfhostit/reckon` (the app) and `ghcr.io/selfhostit/reckon-worker` (the Python workers). A release tag like `v1.2.0` publishes `:1.2.0`, `:1.2`, `:1` and `:latest` of both; installs follow the -major version (`:1`), so they only update to a release and never to a new major +major version (`:0`), so they only update to a release and never to a new major version on their own. Every push to `main` publishes `:edge` and the commit hash, for trying out what's next. Each image comes with a signed [provenance attestation](#check-where-an-image-came-from). @@ -69,7 +69,7 @@ To add Tailscale later, set `TS_AUTHKEY` and uncomment the `COMPOSE_FILE` line i cd ~/reckon && docker compose pull && docker compose up -d ``` -Updates bring the newest 1.x release, listed with what changed in +Updates bring the newest 0.x release, listed with what changed in [CHANGELOG.md](../CHANGELOG.md). Running the install script again also refreshes the compose files from the newest release (or from `RECKON_REF`, a tag or branch), which is how an install moves to a new major version. To stay on a release line, or go back to a release, set @@ -101,7 +101,7 @@ docker buildx imagetools inspect ghcr.io/selfhostit/reckon:latest --format '{{ j Add what changed under a new version in `CHANGELOG.md`, merge, then publish a GitHub release with a tag like `v1.2.0` (Releases > Draft a new release) and paste the changelog entry as its notes. CI tests it, publishes the images and attests them. For a new major -version, also change the image tags in `deploy/docker-compose.yml` (`:1`) in the same +version, also change the image tags in `deploy/docker-compose.yml` (`:0`) in the same release. ### Security checks diff --git a/docs/images/screens/correct-dark.png b/docs/images/screens/correct-dark.png new file mode 100644 index 0000000..6fa74b7 Binary files /dev/null and b/docs/images/screens/correct-dark.png differ diff --git a/docs/images/screens/correct.png b/docs/images/screens/correct.png new file mode 100644 index 0000000..d957648 Binary files /dev/null and b/docs/images/screens/correct.png differ diff --git a/docs/images/screens/hint-dark.png b/docs/images/screens/hint-dark.png new file mode 100644 index 0000000..2dcc322 Binary files /dev/null and b/docs/images/screens/hint-dark.png differ diff --git a/docs/images/screens/hint.png b/docs/images/screens/hint.png new file mode 100644 index 0000000..1cabcbb Binary files /dev/null and b/docs/images/screens/hint.png differ diff --git a/docs/images/screens/level-up-dark.png b/docs/images/screens/level-up-dark.png new file mode 100644 index 0000000..7b02f01 Binary files /dev/null and b/docs/images/screens/level-up-dark.png differ diff --git a/docs/images/screens/level-up.png b/docs/images/screens/level-up.png new file mode 100644 index 0000000..5cb4e81 Binary files /dev/null and b/docs/images/screens/level-up.png differ diff --git a/docs/images/screens/mock-test.png b/docs/images/screens/mock-test.png new file mode 100644 index 0000000..0efcdf4 Binary files /dev/null and b/docs/images/screens/mock-test.png differ diff --git a/docs/images/screens/progress-dark.png b/docs/images/screens/progress-dark.png new file mode 100644 index 0000000..18b32b4 Binary files /dev/null and b/docs/images/screens/progress-dark.png differ diff --git a/docs/images/screens/progress.png b/docs/images/screens/progress.png new file mode 100644 index 0000000..f862b6c Binary files /dev/null and b/docs/images/screens/progress.png differ diff --git a/docs/images/screens/review.png b/docs/images/screens/review.png new file mode 100644 index 0000000..d458443 Binary files /dev/null and b/docs/images/screens/review.png differ diff --git a/docs/images/screens/solution-dark.png b/docs/images/screens/solution-dark.png new file mode 100644 index 0000000..93ed5f9 Binary files /dev/null and b/docs/images/screens/solution-dark.png differ diff --git a/docs/images/screens/solution.png b/docs/images/screens/solution.png new file mode 100644 index 0000000..fb3a3cd Binary files /dev/null and b/docs/images/screens/solution.png differ diff --git a/docs/images/screens/test-result.png b/docs/images/screens/test-result.png new file mode 100644 index 0000000..1156942 Binary files /dev/null and b/docs/images/screens/test-result.png differ diff --git a/docs/images/screens/today-dark.png b/docs/images/screens/today-dark.png new file mode 100644 index 0000000..75ba30f Binary files /dev/null and b/docs/images/screens/today-dark.png differ diff --git a/docs/images/screens/today.png b/docs/images/screens/today.png new file mode 100644 index 0000000..5276d5b Binary files /dev/null and b/docs/images/screens/today.png differ diff --git a/docs/plan.md b/docs/plan.md new file mode 100644 index 0000000..1146368 --- /dev/null +++ b/docs/plan.md @@ -0,0 +1,85 @@ +# Reckon: how it works and what comes next + +## Why + +Numerical reasoning tests are part of many job applications. A candidate sits an online test +of around 15 questions in 30 minutes, and the employer gets a report that places them on a +1–9 scale (a **stanine**) against other candidates. The questions are mostly visual number +patterns: a row of boxes with one missing, a grid where every row follows the same rule, +figures whose centre is made from the numbers around it. An average result can cost an +interview, and the tests reward practice, yet good practice material is scarce: free sets are +small, and many "numerical" practice tests drill table-reading arithmetic instead of +pattern-finding. + +Reckon trains the pattern-finding: endless questions at a difficulty that follows the person, +explanations in plain language, and mock tests that give the same kind of score the reports do. + +## What runs where + +- **The web app makes and scores the questions** (`web/src/lib/engine.ts`). The engine has no + dependencies, so it is fast on a phone, works on a slow connection, and is tested on its own. +- **The Go app stores each person's practice** (`backend/migrations/1762000000_practice.go`): + one `progress` record (levels, XP, XP per day, reminder setting) and a `practice_sessions` + record per finished lesson or test (every question with the answer given, the time taken and + any help used, plus a summary). The API rules let each person read only their own; a session + can't be edited after it is saved. +- **An evening job** (`backend/app/streak.go`) sends a push notification at 19:00 to people + who turned the reminder on, practised yesterday and not yet today. + +The progress screen reads only the session summaries, which carry a tally per question type, +so it stays fast after months of practice; a session's answers are fetched when it is reviewed. + +## Questions + +Four families, each with levels 1–9 (grids start at 2, figures and function boxes at 3): + +- **Series**: built from small rules (add, multiply, alternate two steps, a cycle of three, + two series interleaved, sums of earlier terms, squares, cubes, primes, changes that follow + their own pattern). The missing box is the last one at low levels and anywhere later on. +- **Grids**: three rows where the third number is made from the first two by the same rule, + rows that all add up to the same total, or columns where top + middle = bottom. From level 6 + the missing number can be one of the inputs, which means working backwards. +- **Figures**: plus-shaped clusters and triangles whose centre is made from the outer numbers. +- **Function boxes**: input → output pairs through one hidden operation, with the input + missing at higher levels. + +Every question comes with: + +- `think`: how to approach this kind of question, the same for the family (hint, part 1); +- `nudge`: a pointer for this rule that doesn't give the answer away (hint, part 2); +- `guide`: the solution as steps a person would take, each with the worked sums and the cells + to highlight. The tests check that every sum in every generated solution is right. + +A missing input is only asked for when exactly one whole number fits, found by trying them all. + +## Lessons and levels + +A lesson is eight questions in one family (or a mix of all four): two warm-ups a level below, +five at the person's level and a challenge a level above. Six right **on their own** moves the +skill up a level; two or fewer moves it down. XP: 10 for a right answer, 5 with the hint, none +with the solution, and 20 more for a perfect lesson. The streak counts days with any XP. + +## Scoring + +Each level has a fixed difficulty on an ability scale: b = (level − 5) × 0.7. A mock test uses +a two-parameter item response model, P(right) = 1 / (1 + e^(−1.3 (θ − b))), and after every +answer works out the expected ability θ given the answers so far, starting from a normal prior +(EAP). The next question is aimed at that estimate, a level either side now and then, rotating +through the families. + +The stanine is round(5 + 2θ), limited to 1–9; the margin of error is the spread of the +estimate. In simulations of 15-question tests, the estimate lands within about 0.4 of the true +ability (0.8 of a stanine) for most people, and up to 0.5 at the ends of the scale, where the +prior pulls it towards the middle. + +These difficulties are Reckon's own calibration, not a test publisher's norms, so the stanine +is a practice estimate: right for following your own progress, and typically within about one +stanine of a real test. + +## Next + +- Calibrate the level difficulties from real answers: an optional export of anonymous + (level, right or wrong) pairs, so the ability scale can be fitted to data. +- More question families seen in these tests: tables and charts, and number analogies. +- A coach view, opt-in per person, for a teacher or career coach to follow a group. +- Timed lessons, to practise the pace as well as the patterns. diff --git a/web/index.html b/web/index.html index 09d0240..399dd79 100644 --- a/web/index.html +++ b/web/index.html @@ -6,11 +6,14 @@ - + - reckon + Reckon
diff --git a/web/public/icons/apple-touch-icon.png b/web/public/icons/apple-touch-icon.png index bb9893a..18966fe 100644 Binary files a/web/public/icons/apple-touch-icon.png and b/web/public/icons/apple-touch-icon.png differ diff --git a/web/public/icons/icon-192.png b/web/public/icons/icon-192.png index 03d1ae3..26d2f47 100644 Binary files a/web/public/icons/icon-192.png and b/web/public/icons/icon-192.png differ diff --git a/web/public/icons/icon-512.png b/web/public/icons/icon-512.png index e9d2090..6c4949d 100644 Binary files a/web/public/icons/icon-512.png and b/web/public/icons/icon-512.png differ diff --git a/web/public/icons/icon-maskable-512.png b/web/public/icons/icon-maskable-512.png index c8ddf11..e63edd5 100644 Binary files a/web/public/icons/icon-maskable-512.png and b/web/public/icons/icon-maskable-512.png differ diff --git a/web/public/icons/icon.svg b/web/public/icons/icon.svg index ff9dafa..36a49e4 100644 --- a/web/public/icons/icon.svg +++ b/web/public/icons/icon.svg @@ -1,8 +1,8 @@ - - - - - - + + + + + + ? diff --git a/web/public/manifest.webmanifest b/web/public/manifest.webmanifest index 85ed1f4..992adae 100644 --- a/web/public/manifest.webmanifest +++ b/web/public/manifest.webmanifest @@ -1,12 +1,12 @@ { - "name": "reckon", - "short_name": "reckon", - "description": "A self-hosted app built on plasto", + "name": "Reckon", + "short_name": "Reckon", + "description": "Practise the numerical reasoning tests used in job applications", "start_url": "/", "scope": "/", "display": "standalone", "background_color": "#fafafa", - "theme_color": "#4f46e5", + "theme_color": "#047857", "icons": [ { "src": "/icons/icon-192.png", "sizes": "192x192", "type": "image/png" }, { "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png" }, diff --git a/web/scripts/screenshots.mjs b/web/scripts/screenshots.mjs new file mode 100644 index 0000000..a52be4b --- /dev/null +++ b/web/scripts/screenshots.mjs @@ -0,0 +1,251 @@ +// Takes the phone screenshots for the README and pull requests, in light and +// dark, from a fresh app with three weeks of someone's practice. CI runs it +// against the built app; to run it yourself: +// +// make build && dist/reckon serve --dir=/tmp/reckon-shots & +// cd web && npm i --no-save playwright && npx playwright install chromium +// RECKON_SETUP_CODE=$(cat /tmp/reckon-shots/setup_code) node scripts/screenshots.mjs ../docs/images/screens +import { mkdirSync } from 'node:fs'; +import { chromium } from 'playwright'; +import { + estimate, + makeItem, + nextAdaptive, + pCorrect, + percentile, + thetaToStanine, +} from '../src/lib/engine.ts'; + +const base = process.env.RECKON_URL ?? 'http://127.0.0.1:8090'; +const out = process.argv[2] ?? 'screenshots'; +const email = 'sofia@example.com'; +const password = 'screenshots123'; +mkdirSync(out, { recursive: true }); + +async function api(path, { token, body, method = body ? 'POST' : 'GET' } = {}) { + const res = await fetch(base + path, { + method, + headers: { 'Content-Type': 'application/json', ...(token ? { Authorization: token } : {}) }, + body: body && JSON.stringify(body), + }); + if (!res.ok) throw new Error(`${method} ${path}: ${res.status} ${await res.text()}`); + return res.status === 204 ? null : res.json(); +} + +// Sofia is preparing for job applications: three weeks of lessons and four +// mock tests, getting better as she goes +if (process.env.RECKON_SETUP_CODE) { + await api('/api/app/setup', { + body: { name: 'Sofia', email, password, code: process.env.RECKON_SETUP_CODE }, + }); +} +const auth = await api('/api/collections/users/auth-with-password', { + body: { + identity: process.env.RECKON_EMAIL ?? email, + password: process.env.RECKON_PASSWORD ?? password, + }, +}); +const token = auth.token; +const user = auth.record.id; + +const day = (ago, hour = 19) => { + const d = new Date(); + d.setDate(d.getDate() - ago); + d.setHours(hour, 10, 0, 0); + return d; +}; +const iso = (d) => d.toISOString().replace('T', ' '); +const key = (d) => + `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; +const families = ['series', 'grid', 'shapes', 'pairs']; +const days = {}; +let xp = 0; + +function tally(answers) { + const t = {}; + for (const a of answers) { + const f = (t[a.item.family] ??= [0, 0, 0]); + f[0]++; + if (a.correct) f[1]++; + f[2] += a.ms; + } + return t; +} + +async function save(when, session) { + const ms = session.items.reduce((n, a) => n + a.ms, 0); + await api('/api/collections/practice_sessions/records', { + token, + body: { user, started: iso(when), ended: iso(new Date(+when + ms)), ...session }, + }); +} + +for (let ago = 20; ago >= 1; ago--) { + if (ago === 12 || ago === 6) continue; // two days off + const theta = -0.6 + (20 - ago) * 0.06; + const family = families[ago % 4]; + const level = Math.min(9, 2 + Math.floor((20 - ago) / 6) + (family === 'series' ? 1 : 0)); + const items = Array.from({ length: 8 }, (_, i) => { + const item = makeItem(family, level + [-1, -1, 0, 0, 0, 0, 0, 1][i]); + const correct = Math.random() < pCorrect(theta + 0.4, item.b); + return { + item, + given: correct ? item.answer : item.answer + 1, + correct, + ms: 25_000 + Math.random() * 50_000, + }; + }); + const correct = items.filter((a) => a.correct).length; + const gained = correct * 10; + days[key(day(ago))] = gained; + xp += gained; + await save(day(ago), { + kind: 'practice', + family, + level, + level_after: correct >= 6 ? level + 1 : level, + items, + result: { correct, answered: 8, fam: tally(items), change: correct >= 6 ? 1 : 0, xp: gained }, + }); + + if ([18, 13, 8, 2].includes(ago)) { + const answers = []; + for (let q = 0; q < 15; q++) { + const item = nextAdaptive( + answers.map((a) => ({ b: a.item.b, correct: a.correct })), + answers.map((a) => a.item), + ); + const correct = Math.random() < pCorrect(theta, item.b); + answers.push({ + item, + given: correct ? item.answer : item.answer + 2, + correct, + ms: 60_000 + Math.random() * 80_000, + }); + } + const est = estimate(answers.map((a) => ({ b: a.item.b, correct: a.correct }))); + await save(day(ago, 20), { + kind: 'test', + mode: 'full', + items: answers, + result: { + correct: answers.filter((a) => a.correct).length, + answered: 15, + fam: tally(answers), + theta: est.theta, + se: est.se, + stanine: thetaToStanine(est.theta), + lo: thetaToStanine(est.theta - est.se), + hi: thetaToStanine(est.theta + est.se), + pct: percentile(est.theta), + maxLevel: Math.max(0, ...answers.filter((a) => a.correct).map((a) => a.item.level)), + }, + }); + } +} +days[key(new Date())] = 30; +await api('/api/collections/progress/records', { + token, + body: { + user, + xp: xp + 30, + daily_goal: 50, + days, + reminders: true, + skills: { series: { level: 5 }, grid: { level: 4 }, shapes: { level: 4 }, pairs: { level: 4 } }, + }, +}); + +const browser = await chromium.launch({ executablePath: process.env.CHROME || undefined }); +for (const scheme of ['light', 'dark']) { + const page = await browser.newPage({ + viewport: { width: 390, height: 844 }, + deviceScaleFactor: 2, + colorScheme: scheme, + reducedMotion: 'reduce', + }); + // a virtual clock, so answers take a realistic time + await page.clock.install(); + const think = (seconds) => page.clock.fastForward(seconds * 1000); + const shot = async (name) => { + await page.waitForTimeout(250); + await page.screenshot({ path: `${out}/${name}${scheme === 'dark' ? '-dark' : ''}.png` }); + }; + const answer = () => page.evaluate(() => window.reckonAnswer); + const typeAnswer = async (value, seconds = 35) => { + await think(seconds); + await page.getByLabel('Your answer').fill(String(value)); + await page.keyboard.press('Enter'); + }; + + // lets the script read each answer (src/lib/demo.ts) + await page.addInitScript(() => localStorage.setItem('reckon.demo', '1')); + await page.goto(base); + await page.getByLabel('Email').fill(process.env.RECKON_EMAIL ?? email); + await page.getByLabel('Password').fill(process.env.RECKON_PASSWORD ?? password); + await page.getByRole('button', { name: 'Sign in' }).click(); + await page.getByText('Your level').waitFor(); + await shot('today'); + + // a lesson: the hint, the walkthrough, a right answer and a level up + await page.goto(`${base}/#practice`); + await page.getByRole('button', { name: /Number grids/ }).click(); + await page.getByRole('button', { name: /Hint/ }).click(); + await shot('hint'); + await page.getByRole('button', { name: /Show solution/ }).click(); + await page + .getByRole('button', { name: /Next step/ }) + .first() + .click(); + await page + .getByRole('button', { name: /Next step/ }) + .first() + .click(); + // the question at the top, the newest step below it + await page.evaluate(() => scrollTo(0, 70)); + await shot('solution'); + await typeAnswer(await answer()); + await page.getByRole('button', { name: 'Continue' }).click(); + await typeAnswer(await answer()); + await shot('correct'); + for (let i = 0; i < 6; i++) { + await page.getByRole('button', { name: 'Continue' }).click(); + await typeAnswer(await answer()); + } + await page.getByRole('button', { name: 'Continue' }).click(); + await page.getByText(/unlocked/).waitFor(); + await shot('level-up'); + + if (scheme === 'light') { + // a quick mock test, answered like someone around stanine 6 + await page.goto(`${base}/#test`); + await page.getByRole('button', { name: /Quick check/ }).click(); + await page.getByRole('button', { name: /Start the quick check/ }).click(); + for (let q = 0; q < 8; q++) { + if (q === 2) { + await think(48); + await shot('mock-test'); + } + const right = await answer(); + await typeAnswer(q % 3 === 2 ? right + 3 : right, 55 + 15 * (q % 3)); + } + await page.getByText('Stanine', { exact: true }).waitFor(); + await shot('test-result'); + } + + await page.goto(`${base}/#progress`); + await page.getByText('Mock test results').waitFor(); + await shot('progress'); + + if (scheme === 'light') { + await page.locator('a[href^="#review-"]').first().click(); + await page + .getByText(/Your answer/) + .first() + .waitFor(); + await shot('review'); + } + await page.close(); +} +await browser.close(); +console.log(`Screenshots saved in ${out}`); diff --git a/web/src/App.svelte b/web/src/App.svelte index 30df85a..e69e0f7 100644 --- a/web/src/App.svelte +++ b/web/src/App.svelte @@ -1,6 +1,7 @@ {#if session.user} {#if route === '#/people' && session.isOwner} - {:else} + {:else if practice.error} +
+ + +
+ {:else if practice.loaded} {/if} {:else if error} diff --git a/web/src/app.css b/web/src/app.css index 388a61b..2bdd1e4 100644 --- a/web/src/app.css +++ b/web/src/app.css @@ -3,10 +3,47 @@ @theme { --font-sans: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif; /* the brand color: change these to restyle every button and link */ - --color-brand-400: var(--color-indigo-400); - --color-brand-500: var(--color-indigo-500); - --color-brand-600: var(--color-indigo-600); - --color-brand-700: var(--color-indigo-700); + --color-brand-400: var(--color-emerald-400); + --color-brand-500: var(--color-emerald-500); + /* buttons use 600 with white text: emerald-700 keeps that readable (WCAG AA) */ + --color-brand-600: var(--color-emerald-700); + --color-brand-700: var(--color-emerald-800); +} + +/* Colors the question pictures and feedback use, for light and dark */ +:root { + --ok: var(--color-emerald-600); + --ok-soft: var(--color-emerald-50); + --ok-ink: var(--color-emerald-800); + --bad: var(--color-red-600); + --bad-soft: var(--color-red-50); + --help: var(--color-blue-600); + --help-soft: var(--color-blue-50); + --hint: var(--color-amber-500); + --hint-soft: var(--color-amber-50); + --box: var(--color-white); + --box-line: var(--color-zinc-300); + --box-centre: var(--color-zinc-100); + --ink: var(--color-zinc-900); + --muted: var(--color-zinc-500); +} +@media (prefers-color-scheme: dark) { + :root { + --ok: var(--color-emerald-400); + --ok-soft: color-mix(in oklab, var(--color-emerald-500) 18%, transparent); + --ok-ink: var(--color-emerald-300); + --bad: var(--color-red-400); + --bad-soft: color-mix(in oklab, var(--color-red-500) 18%, transparent); + --help: var(--color-blue-400); + --help-soft: color-mix(in oklab, var(--color-blue-500) 18%, transparent); + --hint: var(--color-amber-400); + --hint-soft: color-mix(in oklab, var(--color-amber-500) 14%, transparent); + --box: var(--color-zinc-900); + --box-line: var(--color-zinc-600); + --box-centre: var(--color-zinc-800); + --ink: var(--color-zinc-100); + --muted: var(--color-zinc-400); + } } @layer base { @@ -34,17 +71,109 @@ } @utility btn { - @apply inline-flex items-center justify-center rounded-xl px-4 py-3 font-semibold transition disabled:opacity-50; + @apply inline-flex items-center justify-center gap-2 rounded-xl px-4 py-3 font-semibold transition disabled:opacity-50; } @layer components { .btn-primary { - @apply btn bg-brand-600 text-white shadow-sm hover:bg-brand-700 active:bg-brand-700; + @apply btn bg-brand-600 text-white shadow-[0_3px_0_var(--color-emerald-900)] hover:bg-brand-700 active:translate-y-0.5 active:shadow-none; } .btn-secondary { @apply btn border border-zinc-300 bg-white hover:bg-zinc-100 dark:border-zinc-700 dark:bg-zinc-900 dark:hover:bg-zinc-800; } + .btn-bad { + @apply btn bg-red-600 text-white shadow-[0_3px_0_var(--color-red-800)] active:translate-y-0.5 active:shadow-none; + } + .btn-help { + @apply btn bg-blue-600 text-white shadow-[0_3px_0_var(--color-blue-800)] active:translate-y-0.5 active:shadow-none; + } .card { @apply rounded-2xl border border-zinc-200 bg-white p-5 dark:border-zinc-800 dark:bg-zinc-900; } + /* answers to pick from; add .chosen to the picked one */ + .choice { + @apply flex flex-col items-start gap-0.5 rounded-xl border-2 border-zinc-200 bg-white px-4 py-3 text-left transition dark:border-zinc-800 dark:bg-zinc-900; + } + .chosen { + @apply border-brand-600 bg-brand-600/5 dark:border-brand-400; + } + .eyebrow { + @apply text-xs font-bold tracking-wider text-zinc-500 uppercase dark:text-zinc-400; + } + .badge { + @apply inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-bold tracking-wide uppercase; + } + .kpi { + @apply rounded-xl bg-zinc-100 px-3 py-2 dark:bg-zinc-800; + } + .kpi b { + @apply block text-xl tabular-nums; + } + .kpi span { + @apply text-xs text-zinc-500 dark:text-zinc-400; + } + + /* the numbers of a question */ + .bx { + @apply relative grid aspect-square min-w-0 place-items-center rounded-xl border-2 font-semibold tabular-nums; + border-color: var(--box-line); + background: var(--box); + font-size: clamp(16px, 4.4vw, 24px); + } + .bx.q { + @apply border-dashed; + border-color: var(--ok); + color: var(--ok); + background: var(--ok-soft); + animation: pulse-ring 2s ease-in-out infinite; + } + .bx.c { + background: var(--box-centre); + border-color: var(--muted); + } + .bx.hl { + border-color: var(--help); + background: var(--help-soft); + box-shadow: 0 0 0 3px color-mix(in oklab, var(--help) 25%, transparent); + } + .bx.is-ok { + border-color: var(--ok); + background: var(--ok-soft); + color: var(--ok-ink); + animation: none; + } + .bx.is-bad { + border-color: var(--bad); + background: var(--bad-soft); + color: var(--bad); + animation: none; + } + .bx.is-help { + border-color: var(--help); + background: var(--help-soft); + color: var(--help); + animation: none; + border-style: solid; + } +} + +@keyframes pulse-ring { + 50% { + box-shadow: 0 0 0 5px color-mix(in oklab, var(--ok) 20%, transparent); + } +} +@keyframes rise { + from { + opacity: 0; + transform: translateY(6px); + } +} +.rise { + animation: rise 0.22s ease-out; +} +@media (prefers-reduced-motion: reduce) { + .bx.q, + .rise { + animation: none; + } } diff --git a/web/src/components/AnswerInput.svelte b/web/src/components/AnswerInput.svelte new file mode 100644 index 0000000..eb0661a --- /dev/null +++ b/web/src/components/AnswerInput.svelte @@ -0,0 +1,54 @@ + + +
+ + { + if (e.key === 'Enter') { + // this Enter submits; it must not also reach the "Enter = Continue" shortcut + e.preventDefault(); + e.stopPropagation(); + if (valid(value)) onsubmit(); + } + }} + class="!m-0 min-w-0 flex-1 !rounded-none !border-0 !bg-transparent !p-0 text-2xl font-semibold tabular-nums !shadow-none !ring-0" + inputmode="numeric" + autocomplete="off" + enterkeyhint="go" + placeholder="Your answer" + /> + +
diff --git a/web/src/components/Guide.svelte b/web/src/components/Guide.svelte new file mode 100644 index 0000000..35b021a --- /dev/null +++ b/web/src/components/Guide.svelte @@ -0,0 +1,44 @@ + + +
    + {#each steps.slice(0, upto) as s, i (i)} + {@const current = i === upto - 1 && !all} +
  1. + + {#if s.final}{:else}{i + 1}{/if} + +
    +

    {s.t}

    + {#if s.lines?.length} +
    + {#each s.lines as line (line)} + {line} + {/each} +
    + {/if} +
    +
  2. + {/each} +
diff --git a/web/src/components/Home.svelte b/web/src/components/Home.svelte index 1f3bc10..f57432b 100644 --- a/web/src/components/Home.svelte +++ b/web/src/components/Home.svelte @@ -1,50 +1,84 @@ - -
-
-

Hi {user.name || user.email}

- -
+ // The signed-in app: tabs, each with its own #address so Back works, and the + // full-screen lesson, test and result on top of them (lib/nav.svelte.ts). + const tabs: { id: string; label: string; icon: IconName }[] = [ + { id: 'today', label: 'Today', icon: 'today' }, + { id: 'practice', label: 'Practice', icon: 'practice' }, + { id: 'test', label: 'Mock test', icon: 'test' }, + { id: 'progress', label: 'Progress', icon: 'progress' }, + { id: 'me', label: 'Me', icon: 'me' }, + ]; -
-

Your app starts here

-

- Edit web/src/components/Home.svelte and save. -

-
+ const fromHash = () => location.hash.slice(1); + let hash = $state(fromHash()); + const review = $derived(hash.startsWith('review-') ? hash.slice(7) : ''); + const tab = $derived(review ? 'progress' : (tabs.find((t) => t.id === hash)?.id ?? 'today')); - {#if install.canPrompt} -
-

Install this app for quick access from your home screen.

- -
- {:else if install.needsIosSteps} -
-

To install this app, tap Share in Safari, then Add to Home Screen.

-
- {/if} - - + onMount(() => { + const onHash = () => { + hash = fromHash(); + // Back from a lesson or result returns to the tabs + if (nav.screen.name !== 'tabs') nav.screen = { name: 'tabs' }; + }; + addEventListener('hashchange', onHash); + return () => removeEventListener('hashchange', onHash); + }); + - +{#if nav.screen.name === 'lesson'} + {#key nav.screen}{/key} +{:else if nav.screen.name === 'test'} + +{:else if nav.screen.name === 'result'} + {#key nav.screen.id}{/key} +{:else} +
+
+ {#if review} + {#key review}{/key} + {:else if tab === 'today'} + + {:else if tab === 'practice'} + + {:else if tab === 'test'} + + {:else if tab === 'progress'} + + {:else} + + {/if} +
- {#await version then v} - {#if v}

Version {v}

{/if} - {/await} -
+ + +{/if} diff --git a/web/src/components/Icon.svelte b/web/src/components/Icon.svelte new file mode 100644 index 0000000..3aec68d --- /dev/null +++ b/web/src/components/Icon.svelte @@ -0,0 +1,48 @@ + + + + + diff --git a/web/src/components/ItemView.svelte b/web/src/components/ItemView.svelte new file mode 100644 index 0000000..d46ff15 --- /dev/null +++ b/web/src/components/ItemView.svelte @@ -0,0 +1,186 @@ + + +{#snippet box(c: Cell, i: number, extra = '')} + {#if c === null} + {#if reveal} +
{fmt(reveal.answer)}
+ {:else} +
?
+ {/if} + {:else} +
{fmt(c)}
+ {/if} +{/snippet} + +{#if v.kind === 'series'} + {@const cols = `grid-template-columns: repeat(${v.cells.length}, minmax(0, 64px))`} +
+
+ {#each v.cells as c, i (i)}{@render box(c, i)}{/each} +
+ {#if gapRow} +
+ {#each gapRow as d, i (i)} + {d === null ? '?' : (d >= 0 ? '+' : '−') + Math.abs(d)} + {/each} + +
+ {/if} +
+{:else if v.kind === 'grid'} +
+ {#each v.cells.flat() as c, i (i)}{@render box(c, i, 'text-[clamp(17px,4.5vw,26px)]')}{/each} +
+{:else if v.kind === 'plus'} +
+ {#each v.figs as f, k (k)} + {@const B = k * 5} +
+
+ {@render box(f.outer[0], B, 'rounded-lg text-[clamp(13px,3.2vw,18px)]')} +
+ {@render box(f.outer[1], B + 1, 'rounded-lg text-[clamp(13px,3.2vw,18px)]')} + {@render box(f.centre, B + 4, 'c rounded-lg text-[clamp(13px,3.2vw,18px)]')} + {@render box(f.outer[2], B + 2, 'rounded-lg text-[clamp(13px,3.2vw,18px)]')} +
+ {@render box(f.outer[3], B + 3, 'rounded-lg text-[clamp(13px,3.2vw,18px)]')} +
+
+ {/each} +
+{:else if v.kind === 'tri'} +
+ {#each v.figs as f, k (k)} + {@const B = k * 4} + {@const lit = [0, 1, 2, 3].some((j) => hl.has(B + j))} + + + {#each [[80, 30], [20, 128], [140, 128]] as [x, y], j (j)} + {@const c = f.outer[j]} + {@const missing = c === null} + {@const col = missing + ? reveal + ? colors[reveal.state] + : 'var(--ok)' + : hl.has(B + j) + ? 'var(--help)' + : 'var(--box-line)'} + + {missing ? (reveal ? fmt(reveal.answer) : '?') : fmt(c)} + {/each} + {#if f.centre === null} + {@const col = reveal ? colors[reveal.state] : 'var(--ok)'} + + {reveal ? fmt(reveal.answer) : '?'} + {:else} + {fmt(f.centre)} + {/if} + + {/each} +
+{:else if v.kind === 'pairs'} +
+ {#each v.pairs as [x, y], k (k)} +
+ {@render box(x, k * 2)} + + {@render box(y, k * 2 + 1)} +
+ {/each} +
+{/if} diff --git a/web/src/components/Lesson.svelte b/web/src/components/Lesson.svelte new file mode 100644 index 0000000..f205d44 --- /dev/null +++ b/web/src/components/Lesson.svelte @@ -0,0 +1,452 @@ + + +
+
+ +
+ {#each plan as _, i (i)} + {@const a = answers[i]} + + {/each} +
+
+ +
+
+ {FAMILIES[item.family].short} · level {item.level} + {#if isChallenge}Challenge{/if} +
+

{item.prompt}

+ +
+ s.gaps) + ? revealed + ? 'full' + : 'partial' + : null} + /> +
+ + {#if phase === 'ask'} +
+ + +
+

+ {#if sol} + A question solved with the walkthrough gives no XP and doesn't count towards levelling up, + but it's how you learn the trick. + {:else if hinted} + Using the hint halves the XP for this question (+5). + {:else} + Try it yourself first: a right answer with no help earns +10 XP. + {/if} +

+ {/if} + + {#if hinted && phase === 'ask'} + {#if sol} +
+ +

Hint: {item.nudge}

+
+ {:else} +
+

+ How to think about it +

+
    + {#each item.think as t (t)}
  1. {t}
  2. {/each} +
+

+ For this question: + {item.nudge} +

+
+ {/if} + {/if} + + {#if sol} +
+

+ + {phase === 'feedback' ? "Here's how it works" : "Let's solve it together"} + {Math.min(sol, steps.length)} / {steps.length} +

+ + {#if sol < steps.length} +
+ + +
+ {:else if phase === 'ask'} +

+ Now type {fmt(item.answer)} in the answer box and press + Check. +

+ {/if} +
+ {/if} +
+ + {#if phase === 'ask'} +
+
+ check()} autofocus={!sol} /> + + +
+
+ {:else} + {@const state = earned(last) ? 'ok' : last.correct ? 'help' : 'bad'} +
+
+
+ +
+

+ {#if state === 'ok'}{praise}{:else if state === 'help'}That's it. Solved with the + walkthrough.{:else if last.given === null}Skipped. The answer is {fmt( + item.answer, + )}{:else}Not quite. The answer is {fmt(item.answer)}{/if} +

+

+ {[ + secs(last.ms), + last.solved ? 'solution used' : last.hinted ? 'hint used' : '', + xpFor(last) ? `+${xpFor(last)} XP` : '', + ] + .filter(Boolean) + .join(' · ')} +

+
+
+ {#if !sol} +
    + {#each item.steps as s, i (i)}
  • {s}
  • {/each} +
+ {/if} + {#if saveError}{/if} +
+ {#if !last.correct && sol < steps.length} + + {/if} + +
+
+
+ {/if} +
+ +{#if confirmLeave} + +{/if} diff --git a/web/src/components/Login.svelte b/web/src/components/Login.svelte index d4f4a44..01fd144 100644 --- a/web/src/components/Login.svelte +++ b/web/src/components/Login.svelte @@ -24,7 +24,7 @@
- +