Document codebase: comments, per-area READMEs, deployment guide

Readability pass across all four areas of the stack. Comments explain why
rather than what, concentrated at the points where behaviour is non-obvious:
concurrency, caching, auth, scraping and nginx templating.

Backend: doc comments on every exported declaration across handlers,
services, models and resolvers. Resolver commentary lives inside function
bodies so gqlgen does not strip it on regeneration; schema files use #
comments rather than description blocks so introspection output is
unchanged. Extracted the duplicated auth-cookie blocks into helpers.

Frontend: header comments on every component, store and view, including
STATUS: notes marking which of the parallel/legacy views are still live.
Documented the non-reactive animation-state pattern, the homeData hub and
the WebSocket stale-socket guard. Removed a few dead imports and named the
reconnect-backoff and poll-interval constants.

Python: module and function docstrings covering the Travelodge scraping
contract, the deadline threading, the two-executor concurrency and the
NDJSON streaming protocol.

Infra: header blocks on every compose file, nginx template, Dockerfile and
entrypoint, covering the config selection, envsubst allow-lists, rate-limit
semantics and volume persistence. Hoisted the duplicated envsubst variable
list in nginx/entrypoint.sh.

New: backend/README.md, python/README.md, DEPLOYMENT.md, .env.example,
backend/graph/doc.go. Refreshed vue/README.md. Corrected CLAUDE.md, which
stated a 24h access token where main.go sets 7 days.

No behaviour change. go build/vet, vite build, py_compile and docker
compose config all pass.

Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
2026-09-16 15:57:48 +01:00
co-authored by Claude Opus 5
parent a1102b4aa1
commit 64df70e5d2
183 changed files with 4691 additions and 204 deletions
+32
View File
@@ -1,3 +1,35 @@
# =============================================================================
# Vue frontend image — compiles Rust to WASM, then builds the SPA.
#
# THIS IS A BUILD CONTAINER, NOT A SERVER. In production the container runs
# `vite build` into /output (the shared vue_dist volume) and EXITS. nginx then
# serves those files. Seeing `vue` as Exited(0) in `docker compose ps` is the
# success case, not a failure. The dev override replaces the CMD with the Vite
# dev server, and then it does stay running.
#
# STAGE 1 — WASM
# Builds crates/stp_wasm with wasm-pack into src/wasm. Only that crate
# directory is copied in, so touching Vue source never invalidates the (slow)
# Rust layer. The two cache mounts persist the cargo registry and the Rust
# target directory between builds on the host — on a Raspberry Pi this turns
# a very long compile into an incremental one. src/wasm is gitignored: it is
# generated, never committed.
#
# STAGE 2 — Vue
# package.json + package-lock.json are copied first so `npm ci` is cached
# independently of source changes; the npm cache is also a BuildKit cache
# mount. `npm ci` (not `npm install`) installs exactly the lockfile, so a
# rebuild can never silently pick up a different dependency version.
# `make` and `git` are installed because some npm dependencies build native
# code or resolve git URLs during install.
#
# --emptyOutDir is required: /output is a mounted volume, and vite refuses to
# clear a directory outside the project root without it. Without the flag,
# stale assets from a previous build would accumulate and be served.
#
# Note stage 2 is not named and is the final stage; both base images are
# multi-arch so this builds on the Pi unchanged.
# =============================================================================
# Stage 1: Build WASM from Rust
FROM rust:slim AS wasm-builder
RUN rustup target add wasm32-unknown-unknown \
+136
View File
@@ -18,6 +18,142 @@ The Vite dev server proxies API requests:
- `/api` -> `http://localhost:8080` (Go backend)
- `/gitea` -> `http://localhost:3000` (Gitea)
- `/radio` -> `http://localhost:8000` (Icecast2)
- `/py` -> `http://localhost:8000` (FastAPI; the `/py` prefix is stripped, as nginx does in production)
## Structure
```
src/
main.js entry point — awaits the wasm init, then mounts <App>
App.vue empty shell; all chrome lives in the layouts
router/index.js route table + the single admin route guard
graphql.js the entire GraphQL client (one axios POST)
layouts/ DefaultLayout (dark, navbar+footer) and CVLayout (light, print)
stores/ Pinia stores
components/ reusable UI — text/, input/, util/, borders/, elle/
views/ page components, one directory per area
assets/styles.css design tokens + base styles (see Styling)
js/ small shared helpers
wasm/ GENERATED by `npm run build:wasm`; gitignored, do not edit
crates/stp_wasm the Rust source for the above
```
## Routing
Two layout shells, defined in `src/router/index.js`:
| Path | Layout | Notes |
| --- | --- | --- |
| `/` | DefaultLayout | Landing page (statically imported — it's the first paint) |
| `/stp` | DefaultLayout | The personal home page: the widget grid |
| `/admin`, `/admin/login` | DefaultLayout | `/admin` is guarded by `meta.requiresAdmin` |
| `/automata`, `/hotels`, `/shrines/*` | DefaultLayout | |
| `/cv`, `/cv/jobs` | CVLayout | Light print theme; `/cv/jobs` is admin-only |
| `/stp2` | (none) | Bare full-bleed mock, deliberately outside both layouts |
| `:pathMatch(.*)*` | DefaultLayout | 404 |
Everything except the landing page is a dynamic `import()`, so Vite gives each
view its own chunk.
Route `name`s are contracts used by `RouterLink`/`router.push` — renaming one
breaks every link to it.
**The admin guard** (`router.beforeEach`) has one subtlety: the admin flag comes
from the `me` field of the home-data query, which arrives asynchronously.
Navigating straight to `/admin` on a cold load would otherwise read an empty
user and bounce a real admin to the login page, so the guard first awaits
`homeData.loaded` via a self-stopping watcher.
## Data flow
There is no GraphQL cache or codegen. `src/graphql.js` is a single function:
```js
const data = await gql(`query { ... }`, variables);
```
It POSTs to `/api/graphql` and throws on an error response with no data. Auth
rides along in **HTTP-only cookies** set by the Go backend, so nothing here
touches tokens — the request just has to be same-origin (nginx in production,
the Vite proxy in dev).
**`stores/homeData.js` is the hub.** It issues *one* query for everything the
`/stp` page needs (posts, favourites, activities, Spotify, rowing, bookmarks,
Gitea feed, Steam status, current user) instead of letting a dozen widgets each
fire their own request. That fetch is kicked off as a side effect of the first
`useHomeDataStore()` call, so no component has to start it.
The other stores are thin views over it:
| Store | Role |
| --- | --- |
| `homeData` | the one query; owns `loaded` / `error` |
| `auth` | current user; mirrors `homeData.me`, plus login/logout mutations |
| `posts`, `favorites`, `activity`, `songs`, `steam` | mirror one slice of `homeData` via an `immediate` watch, and keep a placeholder value until real data arrives |
| `places` | independent CRUD; sign-in only, so it is fetched lazily |
| `messages` | the chat WebSocket — not GraphQL at all |
| `models` | dormant; not imported anywhere |
The mirroring watches are `immediate` on purpose: a store created *after*
`homeData` has already loaded would never see the existing value otherwise.
## Component conventions
- Layout and one-off tweaks go in Tailwind utilities; reach for a scoped
`<style>` only for what utilities can't express (`grid-template-areas`,
keyframes, media-query-specific layouts).
- Never hard-code a colour — use a token. The one exception is `<canvas>`
drawing (`views/automata/MobileAutomata.vue`), which cannot read CSS
variables.
- Home widgets: title goes in `<Header>`; admin create forms use
`<CreateToggle v-model="showCreate">` in the header's `#action` slot and
render the form inside `<Modal v-model="showCreate">`.
- Admin create forms are loaded with `defineAsyncComponent`, so a visitor who
is not signed in never downloads them.
- Create forms emit `done` / `cancel` and never close themselves — the host
decides what to dismiss and refresh.
- Animation loops (`Headline`, `Intro2`, `Stamps`, `AutoScroll`, `Elle`) keep
their state in plain `let`s and write to the DOM directly. Putting per-frame
state in a `ref` would queue a Vue re-render 30–60 times a second. They also
cache measurements in a `ResizeObserver` rather than reading `offsetWidth` in
the rAF callback, which forces a synchronous layout every frame.
## Dev vs production
- **Dev** (`npm run dev`): Vite serves the SPA and proxies `/api`, `/gitea`,
`/radio` and `/py` (see the table above and `vite.config.js`). The `/py`
proxy strips the prefix, matching what nginx does in production.
- **Production** (`npm run build`): `dist/` is built into the nginx container
and served as static files, with nginx doing the same reverse-proxying.
Note `npm run build` runs `build:wasm` first, which needs **wasm-pack** on the
PATH. If you only want the Vue bundle and `src/wasm/` is already populated,
`npx vite build` skips that step.
## Live vs legacy views
Several files are kept around but not reachable. Each carries a `STATUS:` note
in its header comment; the summary:
| File | Status |
| --- | --- |
| `views/home/Home.vue` | live (`/stp`) — imports **Intro2** and **Gym2** |
| `views/home/Intro.vue` | superseded by `Intro2.vue`; not imported |
| `views/home/Gym.vue` | superseded by `Gym2.vue`; not imported |
| `views/home2/Home2.vue` | reachable at `/stp2`, but a static mock and unlinked |
| `views/home/BadApple.vue` | unfinished ASCII video player; not imported |
| `views/CV/CVProgramming.vue` | live — the only CV template listed in `CV.vue` |
| `views/CV/CV{General,Backend,Frontend,Security,Electrical,Hospitality,Analyst,Temp}.vue` | commented out of `CV.vue`'s list; unreachable |
| `views/unused/CoverLetters.vue` | **live** despite the directory — it is the "Cover Letter" tab on `/cv` |
| `views/unused/Notes.vue` | no route points at it; not imported |
| `components/util/wasm/AutoScroll.vue` | Rust port of the JS AutoScroll; not imported |
| `components/util/{MusicPlayer,ObjectTable}.vue` | not imported |
| `components/elle/Elle.vue`, `components/borders/UtenaFrame.vue` | decorative; not imported |
| `stores/models.js`, `js/mobile-automata.mjs` | not imported |
Nothing in this list is dead weight the build ships — unimported files are
tree-shaken out. They are kept deliberately; don't delete without asking.
## Styling
+4
View File
@@ -1,4 +1,8 @@
<script setup>
/**
* Root component. Deliberately empty: all chrome lives in the layout components
* (layouts/DefaultLayout.vue, layouts/CVLayout.vue) that the router mounts.
*/
import { RouterView } from "vue-router";
</script>
+6
View File
@@ -1,4 +1,10 @@
<script setup>
/**
* Fake waybar status bar (a nod to the author's Linux setup) for DefaultLayout.
*
* Everything except the clock is hard-coded decoration — CPU/MEM/DISK/NET/BAT are
* not real readings. `.hide-sm` drops them on narrow screens.
*/
import { ref, onMounted, onUnmounted } from "vue";
const clock = ref("");
+10
View File
@@ -1,4 +1,14 @@
<script setup>
/**
* Top bar for DefaultLayout: an "UP" breadcrumb button and a scrolling marquee.
*
* `parentPath` strips the last path segment, so /shrines/gto -> /shrines and any
* one-segment route -> "/". It is null only at the root, which is what hides the
* button on the landing page.
*
* The kaomoji are joined into one long string and handed to <Headline>, which
* duplicates and scrolls it — see Headline.vue for why one string and not a list.
*/
import Headline from "@/components/text/Headline.vue";
import { computed } from "vue";
import { useRoute } from "vue-router";
@@ -1,3 +1,9 @@
<!--
Decorative frame: four counter-rotating flowers around the slotted content.
Each corner sets its own `--start` angle so the four are permanently offset by
90 degrees while sharing one keyframe animation.
STATUS: not imported anywhere.
-->
<template>
<div class="container">
<img src="/img/borders/utena.png" class="flower tl antirotate" />
+8
View File
@@ -1,4 +1,12 @@
<script setup>
/**
* Decorative animated colour bars. STATUS: not imported anywhere.
*
* Two known problems if it is ever revived: the call
* `generateOffsets((150, 15, 10))` uses the comma operator, so it passes a single
* argument 10 as `width` and the other two defaults apply; and animate() logs to
* the console on every frame.
*/
import { ref, onMounted, useTemplateRef, onUnmounted } from "vue";
import { getRandomColor } from "@/js/utils";
+4
View File
@@ -1,3 +1,7 @@
<!--
The site's standard button. Wraps a native <button>, so all attributes and
listeners (including @click) fall through to it via Vue's attribute inheritance.
-->
<script setup></script>
<template>
@@ -1,4 +1,9 @@
<script setup>
/**
* Sliding on/off switch. v-model via the explicit modelValue prop +
* update:modelValue emit pair (rather than defineModel) because ToggleHeader
* needs to pass the value down and intercept the event.
*/
import { ref } from "vue";
const props = defineProps({
+13
View File
@@ -1,4 +1,15 @@
<script setup>
/**
* Infinite horizontal marquee. Renders its slot twice side by side and
* translates the pair left; when the offset passes one copy's width it wraps by
* adding that width back, so the seam is never visible.
*
* The offset is a plain `let`, not a ref, and the transform is written straight
* to element.style — a reactive ref here would queue a Vue re-render on every one
* of the 60 frames per second. The width is measured once and re-measured by a
* ResizeObserver rather than read each frame, because reading offsetWidth in the
* rAF callback forces a layout on every frame.
*/
import { onMounted, useTemplateRef, onUnmounted } from "vue";
const container = useTemplateRef("container");
@@ -54,6 +65,8 @@ onUnmounted(() => {
</script>
<template>
<!-- The slot is rendered twice: the second copy fills the gap the first
leaves as it scrolls off, which is what makes the loop seamless. -->
<div class="root">
<div class="container" ref="container">
<div ref="item1">
+4
View File
@@ -1,4 +1,8 @@
<script setup>
/**
* Link styled to sit inside running prose (bold italic, no underline). Same
* `to` vs `href` and auto-`rel` behaviour as Link.vue.
*/
import { computed } from "vue";
const props = defineProps({
+5
View File
@@ -1,4 +1,9 @@
<script setup>
/**
* Standard link. Renders a <RouterLink> when given `to`, a plain <a> when given
* `href`. `bare` drops the styling (used where the parent styles the anchor).
* External `target="_blank"` links get rel="noopener noreferrer" automatically.
*/
import { computed } from "vue";
const props = defineProps({
+3
View File
@@ -1,3 +1,6 @@
<!--
Padded <p>. Exists purely so prose spacing is defined in one place.
-->
<template>
<p class="p-1">
<slot />
+8
View File
@@ -1,4 +1,12 @@
<script setup>
/**
* Section header with a show/hide switch, used by LinkTable's collapsible mode.
*
* The whole bar is clickable: the click handler forwards to the inner
* <ToggleButton>'s DOM node via its $el. The button itself is
* `pointer-events-none` with `@click.stop`, so a direct click on it cannot fire
* the handler twice.
*/
import { ref } from "vue";
import ToggleButton from "@/components/input/ToggleButton.vue";
+10
View File
@@ -10,6 +10,16 @@
</template>
<script setup>
/**
* Scroll container that drifts its own content up and down forever, pausing at
* each end. Used by the Favorites and Consumption widgets.
*
* Position is kept as a 0..1 fraction so it survives content resizing. On the
* edges it is clamped to 0.999 / 0.001 rather than exactly 1 / 0 so the next
* tick's `reachedBottom` / `reachedTop` test doesn't immediately fire again and
* re-trigger the pause. scrollHeight is measured by a ResizeObserver instead of
* being read every frame, which would force a layout 60 times a second.
*/
import { useTemplateRef, onMounted, onBeforeUnmount } from "vue";
const container = useTemplateRef("container");
+22
View File
@@ -1,4 +1,12 @@
<script setup>
/**
* The chat widget: message list, composer, file attach, admin delete and an
* admins-only "private" mode. Drives stores/messages.js and is mounted in the
* right-hand sidebar of views/home/Home.vue.
*
* Owns the socket lifecycle — connect() on mount, disconnect() on unmount — so
* the socket exists only while the widget is on screen.
*/
import { ref, computed, watch, nextTick, onMounted, onUnmounted } from "vue";
import Button from "@/components/input/Button.vue";
import ToggleButton from "@/components/input/ToggleButton.vue";
@@ -17,6 +25,8 @@ const fileInput = ref(null);
const isAdmin = computed(() => !!authStore.user.admin);
const sendPrivate = ref(false);
// Autoscroll only when the reader is already at the bottom: scrolling up to
// read history must not be yanked back down by an incoming message.
const isNearBottom = ref(true);
const SCROLL_THRESHOLD = 100;
let resizeObserver = null;
@@ -45,6 +55,7 @@ function goToBottom() {
scrollToBottom();
}
// nextTick: scrollHeight is only correct once Vue has patched the new row in.
watch(
() => messages.value.length,
() => {
@@ -91,12 +102,20 @@ function isVideoUrl(url) {
return /\.(mp4|webm|ogg|mov)$/i.test(url);
}
/** Only render attachments the backend served from its own upload directory —
* the fileUrl arrives over the socket and is otherwise attacker-controlled. */
function isSafeFileUrl(url) {
return typeof url === "string" && url.startsWith("/uploads/");
}
// NOTE: a module-level /g regex carries `lastIndex` between calls. It is safe
// here only because parseMessageParts() below always runs exec() to completion
// (exec returns null, resetting lastIndex) before returning. An early return
// from that loop would make the next message parse from the wrong offset.
const urlRegex = /(https?:\/\/[^\s<]+)/g;
/** Split message text into alternating {type:'text'|'link', value} parts so
* URLs can be rendered as anchors without using v-html. */
function parseMessageParts(text) {
const parts = [];
let lastIndex = 0;
@@ -126,6 +145,9 @@ onMounted(() => {
});
}
// Images and videos load after their row is inserted and change its height,
// which the length watcher above has already missed. Observing the inner
// wrapper catches those late reflows.
if (messagesInner.value) {
resizeObserver = new ResizeObserver(scrollToBottomIfNear);
resizeObserver.observe(messagesInner.value);
@@ -1,4 +1,8 @@
<script setup>
/**
* Sidebar widget showing the most recent Gitea action, read straight from
* homeData.gitFeed (the backend proxies and caches the Gitea API).
*/
import { useHomeDataStore } from "@/stores/homeData";
import { storeToRefs } from "pinia";
import Header from "@/components/text/Header.vue";
+7
View File
@@ -1,4 +1,11 @@
<script setup>
/**
* Renders a list of {name, link, type} either as stacked link buttons
* (variant="list") or as a two-column table (variant="table").
*
* Passing `title` wraps the whole thing in a collapsible <ToggleHeader>.
* Used by the Bookmarks, Favorites, Consumption and Links widgets.
*/
import { ref } from "vue";
import Link from "@/components/text/Link.vue";
import ToggleHeader from "@/components/text/ToggleHeader.vue";
+7
View File
@@ -1,4 +1,11 @@
<script setup>
/**
* Renders a markdown string, with KaTeX maths support, into sanitised HTML.
*
* The v-html is safe only because DOMPurify strips scripts and event handlers
* from markdown-it's output first — post content is admin-authored but still
* untrusted input. Used by the Feed widget.
*/
import MarkdownIt from "markdown-it";
import { katex } from "@mdit/plugin-katex";
import DOMPurify from "dompurify";
+5
View File
@@ -14,6 +14,9 @@ function onKeydown(e) {
if (e.key === "Escape") open.value = false;
}
// The Escape listener is attached only while open, so several modals on one
// page can't all react to a single keypress. `immediate` covers a modal that
// mounts already open.
watch(
open,
(isOpen) => {
@@ -30,6 +33,8 @@ onUnmounted(() => window.removeEventListener("keydown", onKeydown));
</script>
<template>
<!-- Teleported to <body> so the backdrop escapes any ancestor with
overflow/transform/z-index that would otherwise clip or trap it. -->
<Teleport to="body">
<div v-if="open" class="modal-backdrop" @click.self="open = false">
<div class="modal bdr-1" :style="{ maxWidth: props.maxWidth }">
+4
View File
@@ -1,4 +1,8 @@
<script setup>
/**
* Unfinished layout sketch for a custom audio player — the <audio> element has no
* source and none of the controls are wired up. STATUS: not imported anywhere.
*/
import Button from "@/components/input/Button.vue";
</script>
+6
View File
@@ -1,4 +1,8 @@
<script setup>
/**
* Generic table that derives its columns from the union of keys across all rows,
* so heterogeneous objects still line up. STATUS: not imported anywhere.
*/
import { computed } from "vue";
const props = defineProps({
@@ -8,6 +12,8 @@ const props = defineProps({
},
});
// Union of keys across every row, in first-seen order, so rows with different
// shapes still line up under one header.
const resolvedColumns = computed(() => {
const keys = new Set();
+15 -2
View File
@@ -15,15 +15,28 @@
</template>
<script setup>
/**
* Icecast radio widget. Probes /radio/stream with a HEAD request on mount and
* every 2 minutes, and only mounts the <audio> element once the stream answers.
*
* The nextTick() before load() matters: the <audio> only exists after `streamLive`
* flips and Vue has re-rendered, so calling load() any earlier would hit null.
* Volume is knocked down to 20% because the stream is loud.
*/
import Button from "@/components/input/Button.vue";
import Header from "@/components/text/Header.vue";
import { ref, useTemplateRef, onMounted, nextTick } from "vue";
import axios from "axios";
const POLL_INTERVAL_MS = 120000; // re-probe the stream every 2 minutes
const INITIAL_VOLUME = 0.2; // the stream is loud
const streamUrl = ref("");
const streamLive = ref(false);
const audio = useTemplateRef("audio");
/** HEAD the stream; on the first success mount and prime the <audio>.
* A rejected request just means the station is off air. */
async function checkStream() {
try {
await axios.head("/radio/stream");
@@ -33,7 +46,7 @@ async function checkStream() {
await nextTick();
if (audio.value) {
audio.value.load();
audio.value.volume = 0.2;
audio.value.volume = INITIAL_VOLUME;
}
}
} catch (err) {
@@ -43,7 +56,7 @@ async function checkStream() {
onMounted(() => {
checkStream();
setInterval(checkStream, 120000);
setInterval(checkStream, POLL_INTERVAL_MS);
});
</script>
+5 -5
View File
@@ -1,14 +1,14 @@
<script setup>
import { computed } from "vue";
const props = defineProps({
/**
* A column of in-app <RouterLink> buttons from a list of {name, link}. Used by
* the Links widget and the shrines index.
*/
defineProps({
linkArr: {
type: Array,
required: true,
},
});
const keys = ["name", "link"];
</script>
<template>
+9
View File
@@ -1,4 +1,13 @@
<script setup>
/**
* Crossfading image rotator. Clicking advances immediately.
*
* Each advance clears and re-arms its own timeout rather than using setInterval,
* so a manual click restarts the full interval instead of leaving a short
* remainder. The fade works because `:key="currentIndex"` makes Vue treat each
* image as a new element for the global `fade` transition, and the wrapper is
* `position: relative` so the outgoing copy can be absolutely positioned over it.
*/
import { ref, computed, onMounted, onUnmounted } from "vue";
import Header from "@/components/text/Header.vue";
+5
View File
@@ -1,4 +1,9 @@
<script setup>
/**
* Clock and date widget. updateDateTime() runs once immediately and then every
* minute. Note the interval is module-level and never cleared — harmless because
* the widget lives for the life of the home page, but it would leak if reused.
*/
import Header from "@/components/text/Header.vue";
import { ref } from "vue";
+6
View File
@@ -1,4 +1,10 @@
<script setup>
/**
* Countdown widget with minute/second sliders and a sound on completion.
*
* The four mutually exclusive v-if blocks are a state machine over
* (finished, paused): set/idle, finished, paused, running.
*/
import Button from "@/components/input/Button.vue";
import Header from "@/components/text/Header.vue";
+10 -1
View File
@@ -13,6 +13,13 @@
</template>
<script setup>
/**
* Click-and-drag-to-scroll container ("grab" cursor), for content wider than its
* box. Used by the Stamps widget, which also scrolls it programmatically.
*
* preventDefault on mousedown/mousemove is what stops the browser starting a text
* selection mid-drag.
*/
import { ref } from "vue";
const container = ref(null);
@@ -40,7 +47,9 @@ const handleMouseMove = (e) => {
const x = e.pageX - container.value.offsetLeft;
const y = e.pageY - container.value.offsetTop;
const walkX = (x - startX.value) * 1; // Multiply by scroll speed factor
// The `* 1` is a scroll-speed factor left at 1:1 (content follows the cursor
// exactly). Raise it to make dragging move the content further than the mouse.
const walkX = (x - startX.value) * 1;
const walkY = (y - startY.value) * 1;
container.value.scrollLeft = scrollLeft.value - walkX;
+7 -5
View File
@@ -1,18 +1,20 @@
<script setup>
import { computed } from "vue";
const props = defineProps({
/**
* Grid of <video> players from a list of {link}. The MIME type is guessed from
* the file extension. `preload="none"` keeps the page from downloading every clip
* on load. Used by the Demoman shrine.
*/
defineProps({
sourceArr: {
type: Array,
required: true,
},
});
/** Guess a <source> MIME type from the file extension, e.g. "a.webm" -> "video/webm". */
function sourceType(link) {
return "video/" + link.split(".").pop();
}
const keys = ["name", "link"];
</script>
<template>
+4
View File
@@ -1,3 +1,7 @@
<!--
"Work in progress" placeholder page. Used as the whole body of the GTO,
Evangelion and Skipskipbenben shrines.
-->
<template>
<div class="page-a4 bdr-1 flex flex-col relative overflow-scroll">
<RouterLink to="/" class="bdr-2">
@@ -5,6 +5,16 @@
</template>
<script setup>
/**
* Rust/wasm port of components/util/AutoScroll.vue — the whole rAF loop lives in
* the AutoScroller struct from src/wasm/.
*
* Note the two-step teardown: destroy() detaches the loop and listeners, free()
* releases the Rust-side memory. Skipping free() leaks the wasm allocation, which
* JS garbage collection cannot reclaim.
*
* STATUS: not imported anywhere; the JS AutoScroll is what the widgets use.
*/
import { useTemplateRef, onMounted, onBeforeUnmount } from "vue";
import { AutoScroller } from "@/wasm/stp_wasm.js";
+9
View File
@@ -1,3 +1,12 @@
/**
* The app's entire GraphQL client: a thin axios POST to the Go backend.
* Every Pinia store goes through this; there is no cache or normalisation layer.
*
* Auth rides along in HTTP-only cookies set by the backend, so no token handling
* is needed here — axios sends them automatically because the request is
* same-origin (nginx in production, the Vite proxy in dev).
*/
import axios from "axios";
export async function gql(query, variables = {}) {
+9
View File
@@ -1,3 +1,12 @@
/**
* Mobile-automaton rule maths (rule enumeration, single-step evolution, batch
* evolution) ported from a Python/Mathematica dissertation prototype.
*
* STATUS: not imported anywhere. views/automata/MobileAutomata.vue is a
* self-contained Turing-machine simulator and does not use this module. Kept as
* reference for the rule-numbering scheme; safe to treat as dormant.
*/
function integerDigits(n, b = 10, length = null) {
// Get the list of digits in base b
const digits = [];
+9
View File
@@ -1,3 +1,11 @@
/**
* Small shared helpers. Used by components/elle/Elle.vue and views/home/Stamps.vue.
*/
/**
* Fisher-Yates shuffle. Mutates `array` in place and returns nothing —
* callers must not do `arr = shuffleArray(arr)`.
*/
export function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
@@ -7,6 +15,7 @@ export function shuffleArray(array) {
}
}
/** @returns {string} a random opaque colour as a `#RRGGBB` string. */
export function getRandomColor() {
var letters = "0123456789ABCDEF";
var color = "#";
+9
View File
@@ -1,4 +1,13 @@
<script setup>
/**
* Layout shell for /cv and /cv/jobs. It renders nothing but the RouterView —
* its whole job is the UNSCOPED <style> block below, which re-points the site's
* design tokens from the dark palette in assets/styles.css to ink-on-paper
* values for everything inside .cv-layout.
*
* Unscoped is deliberate: scoped styles would not reach the CV template
* components, and the point is to override the *global* element styles.
*/
import { RouterView } from "vue-router";
</script>
+8
View File
@@ -1,4 +1,12 @@
<script setup>
/**
* Shell for everything under `/`: sticky navbar, scrolling <main>, sticky footer.
*
* The RouterView is wrapped in the global `slide` transition (defined in
* assets/styles.css). `:key="$route.path"` forces a full remount on every path
* change so the transition actually runs even between two routes that share a
* component; `mode="out-in"` stops the outgoing and incoming pages overlapping.
*/
import { RouterView } from "vue-router";
import Navbar from "@/components/Navbar.vue";
import Footer from "@/components/Footer.vue";
+9
View File
@@ -1,3 +1,12 @@
/**
* App entry point. Mounts <App> on #app with the router and a fresh Pinia.
*
* The top-level `await init()` loads the Rust/wasm bundle before anything else
* renders, so components that reach for a wasm export (components/util/wasm/)
* never see an uninitialised module. Top-level await in an entry module is what
* `vite-plugin-top-level-await` in vite.config.js is there to support.
*/
import { createApp } from "vue";
import { createPinia } from "pinia";
import App from "./App.vue";
+22
View File
@@ -1,3 +1,17 @@
/**
* Route table and the single admin route guard.
*
* Structure: two layout shells. `/` mounts DefaultLayout (navbar + footer, dark
* theme) and holds most routes; `/cv` mounts CVLayout (light print theme).
* `/stp2` is deliberately outside both — it is a bare full-bleed mock.
*
* Only the landing page is statically imported; every other view is a dynamic
* import so Vite code-splits it into its own chunk.
*
* Route `name`s are public contracts (used by RouterLink/`router.push`) — don't
* rename them.
*/
import { createRouter, createWebHistory } from "vue-router";
import { watch } from "vue";
import DefaultLayout from "@/layouts/DefaultLayout.vue";
@@ -104,6 +118,14 @@ const router = createRouter({
],
});
// Guard for routes marked `meta: { requiresAdmin: true }`.
//
// The admin flag comes from homeData's `me` field, which arrives asynchronously.
// Navigating straight to /admin on a cold load would otherwise read an empty
// user and bounce a legitimate admin to the login page, so the guard first
// blocks on homeData.loaded. The watcher is self-stopping: `stop()` is called
// from inside the callback before resolving, so the promise settles exactly
// once and the watcher does not leak across navigations.
router.beforeEach(async (to) => {
if (!to.meta.requiresAdmin) return;
const homeData = useHomeDataStore();
+10
View File
@@ -1,3 +1,8 @@
/**
* Media/activity log for the Consumption widget. A view over homeData.activities;
* see stores/posts.js for the placeholder-then-overwrite pattern.
*/
import { defineStore } from "pinia";
import { computed, ref, watch } from "vue";
import { useHomeDataStore } from "@/stores/homeData";
@@ -14,6 +19,10 @@ export const useActivityStore = defineStore("activity", () => {
const activityCount = computed(() => activity.value.length);
const homeData = useHomeDataStore();
// Mirror the shared home query. `immediate` matters: homeData may already
// have loaded by the time this store is first used, and a plain watch would
// never fire for that existing value. The `length > 0` test keeps the
// placeholder on screen when the backend returns nothing.
watch(
() => homeData.activities,
(newActivities) => {
@@ -24,6 +33,7 @@ export const useActivityStore = defineStore("activity", () => {
{ immediate: true },
);
/** Refresh by re-running the whole home query; the watch above applies it. */
async function fetchActivity() {
await homeData.fetchAll();
}
+26
View File
@@ -1,3 +1,16 @@
/**
* Current user + login/logout mutations.
*
* `user` is populated two ways: mirrored from homeData.me (the shared home query
* also returns the session user), and set directly by logIn()/refreshToken().
* The watch is `immediate` so a store created after homeData has already loaded
* still picks up the user.
*
* The JWTs themselves are never visible here — the backend sets access_token and
* refresh_token as HTTP-only cookies, so `loggedIn` is inferred purely from
* whether a username came back.
*/
import { defineStore } from "pinia";
import { computed, ref, watch } from "vue";
import { gql } from "@/graphql";
@@ -8,6 +21,10 @@ export const useAuthStore = defineStore("auth", () => {
const loggedIn = computed(() => !!user.value.username);
const homeData = useHomeDataStore();
// Mirror the `me` field from the shared home query. `immediate` so a store
// created after homeData loaded still sees the user. Only overwrite on a
// truthy `me` — a logged-out response is null and must not clobber a user
// that logIn() just set.
watch(
() => homeData.me,
(me) => {
@@ -18,6 +35,8 @@ export const useAuthStore = defineStore("auth", () => {
{ immediate: true },
);
/** Clear the session cookies server-side, then blank the local user.
* Deliberately clears `user` even if the mutation fails. */
async function logOut() {
try {
await gql(`mutation { logout }`);
@@ -27,6 +46,8 @@ export const useAuthStore = defineStore("auth", () => {
user.value = {};
}
/** Log in and populate `user`. Swallows errors: on a bad password `user`
* is left untouched, so `loggedIn` simply stays false. */
async function logIn(username, password) {
try {
const data = await gql(
@@ -39,6 +60,8 @@ export const useAuthStore = defineStore("auth", () => {
}
}
/** Admin-only: create an account. Returns the new user; re-throws on failure
* so the calling form can show a message. */
async function createUser(username, password) {
try {
const data = await gql(
@@ -52,6 +75,8 @@ export const useAuthStore = defineStore("auth", () => {
}
}
/** Exchange the long-lived refresh_token cookie for a fresh access_token and
* re-read the user. */
async function refreshToken() {
try {
const data = await gql(
@@ -63,6 +88,7 @@ export const useAuthStore = defineStore("auth", () => {
}
}
/** Admin-only: grant/revoke admin. Returns the updated user; re-throws. */
async function setUserAdmin(userId, admin) {
try {
const data = await gql(
+10
View File
@@ -1,3 +1,8 @@
/**
* Favourites for the Favorites widget. A view over homeData.favorites; see
* stores/posts.js for the placeholder-then-overwrite pattern.
*/
import { defineStore } from "pinia";
import { computed, ref, watch } from "vue";
import { useHomeDataStore } from "@/stores/homeData";
@@ -14,6 +19,10 @@ export const useFavoritesStore = defineStore("favorites", () => {
const favoritesCount = computed(() => favorites.value.length);
const homeData = useHomeDataStore();
// Mirror the shared home query. `immediate` matters: homeData may already
// have loaded by the time this store is first used, and a plain watch would
// never fire for that existing value. The `length > 0` test keeps the
// placeholder on screen when the backend returns nothing.
watch(
() => homeData.favorites,
(newFavorites) => {
@@ -24,6 +33,7 @@ export const useFavoritesStore = defineStore("favorites", () => {
{ immediate: true },
);
/** Refresh by re-running the whole home query; the watch above applies it. */
async function fetchFavorites() {
await homeData.fetchAll();
}
+26
View File
@@ -1,3 +1,18 @@
/**
* The single source of truth for the home page.
*
* One GraphQL query fetches everything the /stp widgets need (posts, favorites,
* activities, Spotify, rowing, bookmarks, Gitea feed, Steam, current user) in a
* single round trip, instead of each widget issuing its own request. The
* per-domain stores (posts, favorites, activity, songs, steam, auth) are thin
* views over this one — they `watch` their slice of it rather than fetching.
*
* fetchAll() is called once at the bottom of the setup function, i.e. the first
* time any component calls useHomeDataStore(). That is why no component has to
* kick off the initial load, and why `loaded` is the flag the router guard waits
* on to know whether `me` has been resolved yet.
*/
import { defineStore } from "pinia";
import { ref } from "vue";
import { gql } from "@/graphql";
@@ -18,6 +33,11 @@ export const useHomeDataStore = defineStore("homeData", () => {
const bookmarks = ref([]);
const radioLive = ref(false);
/**
* Fetch every home-page dataset in one GraphQL round trip, plus the radio
* liveness probe in parallel. Sets `loaded` on success and `error` on
* failure; never throws. Safe to call again to refresh.
*/
async function fetchAll() {
try {
const [data] = await Promise.all([
@@ -52,6 +72,10 @@ export const useHomeDataStore = defineStore("homeData", () => {
}
}
/**
* Probe the Icecast stream with a HEAD request and set `radioLive`.
* A failure (404/connection refused) means "offline", not an error.
*/
async function fetchRadioStatus() {
try {
await axios.head("/radio/stream");
@@ -61,6 +85,8 @@ export const useHomeDataStore = defineStore("homeData", () => {
}
}
// Kick off the initial load as a side effect of the first useHomeDataStore()
// call. Pinia setup stores run once, so this fires exactly once per page load.
fetchAll();
return {
+39 -3
View File
@@ -1,7 +1,21 @@
/**
* WebSocket-backed chat, used by components/util/Chat.vue.
*
* Owns one socket at a time, auto-reconnects with exponential backoff (1s
* doubling to a 30s ceiling, reset on a successful open) and refuses to reconnect
* after an intentional disconnect().
*/
import { defineStore } from "pinia";
import { ref, computed } from "vue";
import axios from "axios";
/**
* Same-origin ws:// or wss:// URL for the chat socket, derived from the page's
* own protocol and host. Nothing is configurable: nginx (prod) and the Vite
* proxy (dev) both serve /api/ws from the same origin as the page, and the
* auth cookies only travel if the origin matches.
*/
function getWebSocketURL() {
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
return `${protocol}//${window.location.host}/api/ws`;
@@ -12,12 +26,16 @@ export const useMessagesStore = defineStore("messages", () => {
const messages = ref([]);
const isConnected = ref(false);
const lastError = ref(null);
const INITIAL_RECONNECT_DELAY_MS = 1000;
const MAX_RECONNECT_DELAY_MS = 30000;
let intentionalClose = false;
let reconnectDelay = 1000;
let reconnectDelay = INITIAL_RECONNECT_DELAY_MS;
let reconnectTimer = null;
const messagesCount = computed(() => messages.value.length);
/** Open the socket (no-op if one already exists) and arm auto-reconnect. */
function connect() {
if (socket.value) return;
intentionalClose = false;
@@ -35,13 +53,15 @@ export const useMessagesStore = defineStore("messages", () => {
if (socket.value !== ws) return;
isConnected.value = true;
lastError.value = null;
reconnectDelay = 1000;
reconnectDelay = INITIAL_RECONNECT_DELAY_MS;
};
ws.onmessage = (event) => {
if (socket.value !== ws) return;
try {
const data = JSON.parse(event.data);
// Sent once per connection. On a reconnect it repeats messages we
// already have.
if (data.action === "history") {
// Replace in one go so keyed rows (and their images) are patched in
// place rather than unmounted and recreated.
@@ -52,9 +72,12 @@ export const useMessagesStore = defineStore("messages", () => {
messages.value = messages.value.filter((m) => m.id !== data.id);
return;
}
// Dedup by id: the server can re-broadcast a message we already hold
// (e.g. our own send echoed back, or an overlap with `history`).
if (data.id && messages.value.some((m) => m.id === data.id)) return;
messages.value.push(data);
} catch {
// Non-JSON frame: show it verbatim rather than dropping it.
messages.value.push({ text: event.data });
}
};
@@ -72,11 +95,16 @@ export const useMessagesStore = defineStore("messages", () => {
reconnectTimer = setTimeout(() => {
connect();
}, reconnectDelay);
reconnectDelay = Math.min(reconnectDelay * 2, 30000);
reconnectDelay = Math.min(reconnectDelay * 2, MAX_RECONNECT_DELAY_MS);
}
};
}
/**
* Close the socket and suppress auto-reconnect. Clearing `socket.value`
* *before* calling close() is what makes the onclose guard above see a stale
* socket, so a later connect() is not fought over by the dying one.
*/
function disconnect() {
intentionalClose = true;
clearTimeout(reconnectTimer);
@@ -87,11 +115,14 @@ export const useMessagesStore = defineStore("messages", () => {
ws.close();
}
/** Send a chat line. Silently drops it if the socket is not open. */
function sendMessage(text, isPrivate = false) {
if (!socket.value || !isConnected.value) return;
socket.value.send(JSON.stringify({ text, private: isPrivate }));
}
/** Ask the server to delete a message; the removal arrives back as a
* broadcast "delete" frame, so local state is not touched here. */
function deleteMessage(id) {
if (!socket.value || !isConnected.value) return;
socket.value.send(JSON.stringify({ action: "delete", id }));
@@ -101,6 +132,11 @@ export const useMessagesStore = defineStore("messages", () => {
messages.value = [];
}
/**
* POST a file to the REST upload endpoint, then send its returned URL over
* the socket as a normal message. Two steps because the socket carries JSON
* text only. Errors surface via `lastError`.
*/
async function uploadAndSendFile(file, isPrivate = false) {
try {
const formData = new FormData();
+8
View File
@@ -1,3 +1,11 @@
/**
* Hand-written classes that coerce raw API JSON into real Date objects.
*
* STATUS: not imported anywhere. Stores consume the GraphQL payloads directly and
* format dates at the point of display, so these are dormant; kept as a record of
* the intended shape of User/Message/Post.
*/
export class User {
constructor({ id, createdAt, updatedAt, deletedAt, username, admin }) {
this.id = id;
+15
View File
@@ -1,7 +1,17 @@
/**
* Places-to-go list (the "Places" tab inside the Collage widget) — full CRUD.
*
* Not part of the homeData query because it is sign-in-only; PlacesTable.vue
* fetches it lazily once the user is logged in. PLACE_FIELDS is interpolated into
* every query/mutation so the selection set can never drift between them.
*/
import { defineStore } from "pinia";
import { ref } from "vue";
import { gql } from "@/graphql";
// Shared selection set: interpolated into every query and mutation so they can
// never drift apart.
const PLACE_FIELDS = `
id
title
@@ -22,6 +32,7 @@ export const usePlacesStore = defineStore("places", () => {
const loading = ref(false);
const error = ref(null);
/** Load all places into `places`. Records failures on `error` rather than throwing. */
async function fetch() {
loading.value = true;
try {
@@ -36,6 +47,7 @@ export const usePlacesStore = defineStore("places", () => {
}
}
/** Create a place and prepend it locally (newest first). Throws on failure. */
async function create(input) {
const data = await gql(
`mutation CreatePlace($input: CreatePlaceInput!) {
@@ -47,6 +59,7 @@ export const usePlacesStore = defineStore("places", () => {
return data.createPlace;
}
/** Patch a place and replace it in the local list. Throws on failure. */
async function update(id, input) {
const data = await gql(
`mutation UpdatePlace($id: ID!, $input: UpdatePlaceInput!) {
@@ -59,10 +72,12 @@ export const usePlacesStore = defineStore("places", () => {
return data.updatePlace;
}
/** Flip a place's `done` flag. */
async function toggleDone(place) {
return update(place.id, { done: !place.done });
}
/** Soft-delete a place and drop it from the local list. */
async function remove(id) {
await gql(
`mutation DeletePlace($id: ID!) { deletePlace(id: $id) { id } }`,
+14
View File
@@ -1,3 +1,11 @@
/**
* Blog posts for the Feed widget. A view over homeData.posts.
*
* `post_template` is placeholder content rendered before (or instead of) a
* successful fetch — the watch only overwrites `posts` when the fetch returned a
* non-empty list, so the widget never flashes empty.
*/
import { defineStore } from "pinia";
import { computed, ref, watch } from "vue";
import { gql } from "@/graphql";
@@ -19,6 +27,10 @@ export const usePostsStore = defineStore("posts", () => {
const postsCount = computed(() => posts.value.length);
const homeData = useHomeDataStore();
// Mirror the shared home query. `immediate` matters: homeData may already
// have loaded by the time this store is first used, and a plain watch would
// never fire for that existing value. The `length > 0` test keeps the
// placeholder on screen when the backend returns nothing.
watch(
() => homeData.posts,
(newPosts) => {
@@ -29,10 +41,12 @@ export const usePostsStore = defineStore("posts", () => {
{ immediate: true },
);
/** Refresh by re-running the whole home query; the watch above applies it. */
async function fetchPosts() {
await homeData.fetchAll();
}
/** Soft-delete a post, then refetch so every widget sees the new list. */
async function deletePost(post) {
try {
await gql(
+13
View File
@@ -1,3 +1,11 @@
/**
* Recently played Spotify tracks for the Listening widget.
*
* Unlike the other derived stores this one also has its own fetchSongs(), because
* Listening.vue re-polls Spotify every 2 minutes and re-running the whole
* homeData query for that would be wasteful.
*/
import { defineStore } from "pinia";
import { ref, computed, watch } from "vue";
import { gql } from "@/graphql";
@@ -17,6 +25,10 @@ export const useSongsStore = defineStore("songs", () => {
const songsCount = computed(() => songs.value.length);
const homeData = useHomeDataStore();
// Mirror the shared home query. `immediate` matters: homeData may already
// have loaded by the time this store is first used, and a plain watch would
// never fire for that existing value. The `length > 0` test keeps the
// placeholder on screen when the backend returns nothing.
watch(
() => homeData.spotifyRecent,
(newSongs) => {
@@ -27,6 +39,7 @@ export const useSongsStore = defineStore("songs", () => {
{ immediate: true },
);
/** Re-poll Spotify alone (cheaper than fetchAll). Keeps the old list on error. */
async function fetchSongs() {
try {
const data = await gql(`
+9
View File
@@ -1,3 +1,9 @@
/**
* Steam online status and recent games for the Steam widget. Mirrors
* homeData.steamStatus, plus a standalone fetchSteam() used for the widget's own
* 5-minute refresh.
*/
import { defineStore } from "pinia";
import { ref, watch } from "vue";
import { gql } from "@/graphql";
@@ -7,6 +13,8 @@ export const useSteamStore = defineStore("steam", () => {
const steamStatus = ref({ online: false, recentGames: [] });
const homeData = useHomeDataStore();
// Mirror the shared home query; `immediate` so a store created after
// homeData has already loaded still picks up the value.
watch(
() => homeData.steamStatus,
(newStatus) => {
@@ -17,6 +25,7 @@ export const useSteamStore = defineStore("steam", () => {
{ immediate: true },
);
/** Re-poll Steam alone (cheaper than fetchAll). Keeps the old value on error. */
async function fetchSteam() {
try {
const data = await gql(`
+3
View File
@@ -1,3 +1,6 @@
<!--
Catch-all route for unmatched paths under `/`.
-->
<template>
<main class="flex flex-col items-center">
<div
+17
View File
@@ -1,4 +1,16 @@
<script setup>
/**
* Route `/cv` — the CV shell: a template picker, a Print button and a link to the
* job tracker. Rendered inside CVLayout, which supplies the light print theme.
*
* The selected template is held in a shallowRef: the value is a component
* definition, and a deep `ref` would try to make the whole component object
* reactive. Most templates are commented out of `templates` — uncomment a pair of
* lines (the import and the entry) to bring one back.
*
* Printing is just window.print(); the `no-print` class (assets/styles.css) hides
* the chrome, and cv-shared.css sizes the pages.
*/
import { ref, shallowRef } from "vue";
import { RouterLink } from "vue-router";
// import CVGeneral from "./CVGeneral.vue";
@@ -26,6 +38,9 @@ const templates = [
];
const selected = ref(0);
// shallowRef, not ref: the value is a component definition. A deep ref would
// walk the whole component object making it reactive — wasteful and a known
// source of warnings.
const currentComponent = shallowRef(templates[0].component);
function select(index) {
@@ -33,6 +48,8 @@ function select(index) {
currentComponent.value = templates[index].component;
}
/** Browser print dialog. The `no-print` class (assets/styles.css) hides the
* selector bar; cv-shared.css handles page sizing and breaks. */
function print() {
window.print();
}
+4
View File
@@ -1,4 +1,8 @@
<script setup>
/**
* Alternative CV template, tailored for analyst roles.
* STATUS: commented out of CV.vue's template list; not currently reachable.
*/
import Project from "./Project.vue";
</script>
+4
View File
@@ -1,4 +1,8 @@
<script setup>
/**
* Alternative CV template, tailored for backend roles.
* STATUS: commented out of CV.vue's template list; not currently reachable.
*/
import Project from "./Project.vue";
</script>
+4
View File
@@ -1,4 +1,8 @@
<script setup>
/**
* Alternative CV template, tailored for electrical engineering roles.
* STATUS: commented out of CV.vue's template list; not currently reachable.
*/
import Project from "./Project.vue";
</script>
+4
View File
@@ -1,4 +1,8 @@
<script setup>
/**
* Alternative CV template, tailored for frontend roles.
* STATUS: commented out of CV.vue's template list; not currently reachable.
*/
import Project from "./Project.vue";
</script>
+4
View File
@@ -1,4 +1,8 @@
<script setup>
/**
* Alternative CV template, tailored for general applications.
* STATUS: commented out of CV.vue's template list; not currently reachable.
*/
import Project from "./Project.vue";
</script>
+4
View File
@@ -1,4 +1,8 @@
<script setup>
/**
* Alternative CV template, tailored for hospitality roles.
* STATUS: commented out of CV.vue's template list; not currently reachable.
*/
import Project from "./Project.vue";
</script>
+3
View File
@@ -1,4 +1,7 @@
<script setup>
/**
* The live CV template — the only one currently listed in CV.vue.
*/
import Project from "./Project.vue";
</script>
+4
View File
@@ -1,4 +1,8 @@
<script setup>
/**
* Alternative CV template, tailored for security roles.
* STATUS: commented out of CV.vue's template list; not currently reachable.
*/
import Project from "./Project.vue";
</script>
+4
View File
@@ -1,4 +1,8 @@
<script setup>
/**
* Scratch copy of a CV template, kept for cannibalising wording.
* STATUS: commented out of CV.vue's template list; not currently reachable.
*/
import Project from "./Project.vue";
</script>
+6
View File
@@ -1,4 +1,10 @@
<script setup>
/**
* Route `/cv/jobs` (guarded by `meta.requiresAdmin`) — a private tracker for job
* applications and for the reusable reference snippets that feed the CV copy.
* Two independent CRUD tables over GraphQL; editing is inline via an `editingId`
* plus a scratch copy of the row.
*/
import { ref, onMounted } from "vue";
import { RouterLink } from "vue-router";
import { gql } from "@/graphql";
+4
View File
@@ -1,3 +1,7 @@
<!--
Layout wrapper used inside every CV template: a left gutter (#left slot, e.g.
dates), a heading row (#top slot) and the default slot for the body.
-->
<script setup></script>
<template>
+6
View File
@@ -1,4 +1,10 @@
<script setup>
/**
* Route `/admin` (guarded by `meta.requiresAdmin`) — a tab strip over every
* create/manage form. Each entry in `sections` maps a tab id to a component
* rendered by <component :is>. Unlike the home widgets these are eagerly
* imported, since reaching this page means you want them.
*/
import { ref, computed } from "vue";
import { useAuthStore } from "@/stores/auth";
import Button from "@/components/input/Button.vue";
+3
View File
@@ -1,4 +1,7 @@
<script setup>
/**
* Admin form: log a consumed book/film/game. Emits "done"/"cancel".
*/
import Button from "@/components/input/Button.vue";
import { ref } from "vue";
+3
View File
@@ -1,4 +1,7 @@
<script setup>
/**
* Admin form: create a categorised bookmark. Emits "done"/"cancel".
*/
import Button from "@/components/input/Button.vue";
import { ref } from "vue";
import { gql } from "@/graphql";
+3
View File
@@ -1,4 +1,7 @@
<script setup>
/**
* Admin form: create a favourite. Emits "done"/"cancel" (see CreatePost.vue).
*/
import Button from "@/components/input/Button.vue";
import { ref } from "vue";
+4
View File
@@ -1,4 +1,8 @@
<script setup>
/**
* Admin form: create a place / thing to do. Goes through stores/places.js rather
* than gql() directly, so the new row appears in the Places table immediately.
*/
import Button from "@/components/input/Button.vue";
import { ref } from "vue";
import { usePlacesStore } from "@/stores/places";
+5
View File
@@ -1,4 +1,9 @@
<script setup>
/**
* Admin form: create a blog post. Emits "done" on success and "cancel" when
* dismissed, so the host (the Feed widget's modal, or Admin.vue) decides what to
* close or refresh.
*/
import Button from "@/components/input/Button.vue";
import { ref } from "vue";
import { gql } from "@/graphql";
+10
View File
@@ -1,4 +1,13 @@
<script setup>
/**
* Admin form: upload photos of an erg monitor. The Go backend OCRs each image and
* returns the parsed session, so this posts multipart/form-data to /api/rowing
* rather than using GraphQL. Uploads run in parallel and each file's row reports
* its own outcome.
*
* The returned Time is a Go duration in nanoseconds, hence the /1e9 before
* splitting into minutes and seconds.
*/
import Button from "@/components/input/Button.vue";
import { ref } from "vue";
import axios from "axios";
@@ -28,6 +37,7 @@ async function submit() {
const res = await axios.post("/api/rowing", formData, {
headers: { "Content-Type": "multipart/form-data" },
});
// Time comes back as a Go time.Duration, i.e. nanoseconds.
const mins = Math.floor(res.data.Time / 1e9 / 60);
const secs = String(Math.floor((res.data.Time / 1e9) % 60)).padStart(
2,
+3
View File
@@ -1,4 +1,7 @@
<script setup>
/**
* Admin form: create an account. Reports success or failure inline.
*/
import Button from "@/components/input/Button.vue";
import { ref } from "vue";
import { useAuthStore } from "@/stores/auth";
+9
View File
@@ -1,4 +1,11 @@
<script setup>
/**
* Route `/admin/login`. On success redirects to `?redirect=` (set by the router
* guard when it bounced you here) or to /admin.
*
* auth.logIn() never throws — it swallows the error — so success is detected by
* re-reading `auth.loggedIn` afterwards rather than by a try/catch.
*/
import { ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useAuthStore } from "@/stores/auth";
@@ -18,6 +25,8 @@ async function handleLogin() {
submitting.value = true;
errorMsg.value = "";
try {
// logIn() swallows its error, so success is detected by re-reading
// `loggedIn` rather than by catching.
await auth.logIn(username.value, password.value);
if (auth.loggedIn) {
const dest = route.query.redirect || "/admin";
+4
View File
@@ -1,4 +1,8 @@
<script setup>
/**
* Admin panel: list and upload tracks for the Icecast radio. REST
* (multipart/form-data) rather than GraphQL because it moves files.
*/
import Button from "@/components/input/Button.vue";
import { ref, onMounted } from "vue";
import axios from "axios";
+5
View File
@@ -1,4 +1,9 @@
<script setup>
/**
* Admin panel: list users and toggle their admin flag. Mutates the local `user`
* object in place from the mutation's response, so the row updates without a
* refetch.
*/
import Button from "@/components/input/Button.vue";
import { ref, onMounted } from "vue";
import { useAuthStore } from "@/stores/auth";
+67
View File
@@ -1,4 +1,17 @@
<script setup>
/**
* Route `/automata` — an interactive Turing machine / mobile automaton
* simulator, rendered to a <canvas>.
*
* A machine is described by a transition table: each `delta` line is
* "<read>,<write>,<L|R>" over single characters, so the whole configuration is
* editable as plain text and shareable. Configuration is kept in localStorage
* under STORAGE_KEY.
*
* The canvas draws colours literally rather than via CSS variables — this is
* the one place in the codebase exempt from the "always use a design token"
* rule, because canvas has no access to CSS custom properties.
*/
import { ref, computed, onMounted, onBeforeUnmount } from "vue";
import InlineLink from "@/components/text/InlineLink.vue";
import Header from "@/components/text/Header.vue";
@@ -144,6 +157,8 @@ const terminated = ref(false);
const accepted = ref(false);
const speed = ref(55); // slider 0..100, log scale
// The slider is 0..100 but useful speeds span 1 to ~2000 steps/sec, so map it
// logarithmically: 10^(slider*3.3/100) gives 1 at 0 and ~10^3.3 (~2000) at 100.
const stepsPerSecond = computed(() =>
Math.max(1, Math.round(10 ** ((speed.value * 3.3) / 100))),
);
@@ -187,6 +202,8 @@ function parseDelta(str) {
return { delta, n };
}
/** Every word of length n over the alphabet `gamma` (|gamma|^n of them) —
* used to list the inputs that have NO transition, i.e. the halting words. */
function allWords(gamma, n) {
let words = [""];
for (let i = 0; i < n; i++) {
@@ -245,6 +262,8 @@ function loadMachine() {
derivedN.value = n;
derivedSigma.value = [...sigma].join(",");
derivedGamma.value = machine.gamma.join(",");
// |gamma|^n halting words: only enumerate when the count is small,
// otherwise a wide alphabet would hang the page building the list.
if (machine.gamma.length ** n <= 4096) {
derivedF.value = allWords(machine.gamma, n)
.filter((w) => !delta.has(w))
@@ -279,11 +298,16 @@ function loadMachine() {
}
}
// The tape is conceptually infinite in both directions but stored as a finite
// array. `origin` is the absolute cell index of tape[0], so absolute index i
// lives at tape[i - origin]; anything outside the array reads as blank.
function cellAt(i) {
const j = i - origin;
return j >= 0 && j < tape.length ? tape[j] : machine.blank;
}
/** Write to absolute cell `i`, growing the tape (and shifting `origin` when
* growing leftwards) so the array always covers every written cell. */
function setCell(i, v) {
let j = i - origin;
while (j < 0) {
@@ -295,6 +319,17 @@ function setCell(i, v) {
tape[j] = v;
}
/**
* Apply one transition: read the n-cell window starting at the head, look it up
* in delta, write the output back and move the head one cell.
*
* No matching transition means the machine halts. Whether that counts as
* accepting is decided by the word under the head, not by a separate state —
* this is the mobile-automaton formulation, where state is encoded in the tape
* symbols themselves (see the Busy Beaver preset above).
*
* @returns {boolean} true if a step was taken, false if the machine halted.
*/
function stepMachine() {
if (!machine || terminated.value) return false;
let word = "";
@@ -335,6 +370,9 @@ const HEAD_COLOR = "#ffffff";
let colorOf = {};
// One palette colour per non-blank symbol, assigned in alphabet order and
// wrapping round. Blank stays background-coloured so the history plot shows
// only the written cells.
function assignColors() {
colorOf = {};
let k = 0;
@@ -353,6 +391,14 @@ let viewLeft = 0;
let hctx = null;
let tctx = null;
/**
* Size both canvases to the wrapper and clear them.
*
* Canvas bitmaps are sized in device pixels (cssWidth * devicePixelRatio) so
* the drawing is sharp on HiDPI screens; CSS sizes the elements back down.
* Every constant below (cell size, 420px history, 56px tape strip) is therefore
* multiplied by `dpr`.
*/
function resetCanvases() {
const hc = historyCanvas.value;
const tc = tapeCanvas.value;
@@ -378,6 +424,15 @@ function resetCanvases() {
drawTapeStrip();
}
/**
* Draw one row of the space-time diagram: the tape at this instant, one pixel
* block per cell, appended below the previous row.
*
* History is never re-rendered from scratch — old rows are scrolled by blitting
* the canvas onto itself (drawImage(canvas, dx, dy)) and repainting only the
* strip that scrolled in. That keeps the cost per step constant no matter how
* long the machine has been running.
*/
function drawHistoryRow() {
if (!hctx || !machine) return;
const hc = historyCanvas.value;
@@ -418,6 +473,9 @@ function drawHistoryRow() {
rowY += cell;
}
/** Redraw the close-up tape strip, centred on the head, with the n cells the
* next transition will read highlighted. Fully repainted each time — it is
* only ~40 cells wide. */
function drawTapeStrip() {
if (!tctx || !machine) return;
const tc = tapeCanvas.value;
@@ -458,6 +516,15 @@ let rafId = 0;
let lastTime = 0;
let stepDebt = 0;
/**
* Animation loop. Steps are decoupled from frames: `stepDebt` accumulates
* elapsed-time * stepsPerSecond and whole steps are drained each frame, so the
* simulation runs at the requested rate regardless of display refresh rate.
*
* dt is clamped to 0.25s so a backgrounded tab does not come back and try to
* run thousands of steps at once, and `budget` is capped at 64 steps per frame
* so a fast setting cannot freeze the page.
*/
function frame(now) {
rafId = requestAnimationFrame(frame);
if (!running.value || !machine) {
+5
View File
@@ -1,4 +1,9 @@
<script setup lang="ts">
/**
* Start of an ASCII-video player: sizes a monospace <pre> to the available box and
* fills it with blank rows. No frame data or playback is wired up yet.
* STATUS: not imported anywhere.
*/
import { useTemplateRef, ref, onMounted, onUnmounted } from "vue";
const display = useTemplateRef("display");
+4
View File
@@ -1,4 +1,8 @@
<script setup>
/**
* Bookmarks sidebar widget on /stp. Groups homeData.bookmarks by category into
* [category, items] pairs, one collapsible <LinkTable> each.
*/
import { computed, ref, defineAsyncComponent } from "vue";
import LinkTable from "@/components/util/LinkTable.vue";
import Modal from "@/components/util/Modal.vue";
+10
View File
@@ -1,4 +1,12 @@
<script setup>
/**
* "鸟" widget on /stp — a two-tab cell: a <Slideshow> and, once signed in, the
* Places list.
*
* The Places tab is added to `tabs` only when logged in, and the watcher forces
* the view back to the collage on logout so a signed-out user is never left
* staring at an empty private tab.
*/
import { ref, computed, watch } from "vue";
import Slideshow from "@/components/util/Slideshow.vue";
import Modal from "@/components/util/Modal.vue";
@@ -19,6 +27,8 @@ const tabs = computed(() => [
const activeTab = ref("collage");
const showAdd = ref(false);
// On logout the Places tab disappears from `tabs`; without this the component
// would be left pointing at a tab that no longer exists and render nothing.
watch(loggedIn, (isIn) => {
if (!isIn && activeTab.value === "places") activeTab.value = "collage";
});
+4
View File
@@ -1,4 +1,8 @@
<script setup>
/**
* "Consumption" widget on /stp (books/films/games logged as activities). Same
* shape as Favorites.vue: AutoScroll list + admin-only lazy create form.
*/
import AutoScroll from "@/components/util/AutoScroll.vue";
import Modal from "@/components/util/Modal.vue";
import LinkTable from "@/components/util/LinkTable.vue";
+4
View File
@@ -1,4 +1,8 @@
<script setup>
/**
* "Favorites" widget on /stp: a self-scrolling <AutoScroll> list, plus an
* admin-only create form in a <Modal> (lazily imported).
*/
import Header from "@/components/text/Header.vue";
import CreateToggle from "@/components/input/CreateToggle.vue";
import LinkTable from "@/components/util/LinkTable.vue";
+5
View File
@@ -1,4 +1,9 @@
<script setup>
/**
* Blog-post widget on /stp. Shows one post at a time with prev/next paging
* (`idx`), rendered through <Markdown>. Delete is offered only when the signed-in
* user is the post's author; the admin create form is lazily imported.
*/
import Button from "@/components/input/Button.vue";
import Markdown from "@/components/util/Markdown.vue";
import Modal from "@/components/util/Modal.vue";
+4
View File
@@ -1,4 +1,8 @@
<script setup>
/**
* First version of the /stp gym widget: a static list of exercises.
* STATUS: superseded by Gym2.vue; not imported anywhere.
*/
import Header from "@/components/text/Header.vue";
import LinkTable from "@/components/util/LinkTable.vue";
const gym = [
+20
View File
@@ -1,4 +1,20 @@
<script setup>
/**
* The live "Rowing" widget on /stp: a hand-drawn SVG line chart of rowing
* sessions, with a metric selector and a hover tooltip.
*
* No chart library — points are projected by hand into a fixed 290x120 viewBox
* (W/H) inset by the PL/PT/PR/PB padding constants. The y axis is normalised to
* the visible min..max of the selected metric, so `range || 1` guards the
* divide-by-zero when every session has the same value, and a single data point
* is centred rather than pinned to x=0.
*
* Rows are reversed (oldest first) for the chart; `slice()` first so the store's
* array is not mutated.
*
* The admin create form is a defineAsyncComponent so CreateRowing.vue is only
* downloaded when an admin actually opens it.
*/
import { ref, computed, defineAsyncComponent } from "vue";
import Header from "@/components/text/Header.vue";
import Modal from "@/components/util/Modal.vue";
@@ -14,6 +30,7 @@ const store = useHomeDataStore();
const { loaded, error, rowingSessions } = storeToRefs(store);
const showCreate = ref(false);
// slice() first: reverse() mutates in place and would reorder the store's array.
const rows = computed(() => rowingSessions.value.slice().reverse());
const loading = computed(() => !loaded.value);
@@ -51,6 +68,9 @@ const chartData = computed(() =>
const minVal = computed(() => Math.min(...chartData.value.map((d) => d.value)));
const maxVal = computed(() => Math.max(...chartData.value.map((d) => d.value)));
// Project each session into SVG coordinates inside the PL/PT/PR/PB padded plot
// area. `range || 1` avoids a divide-by-zero when every value is identical, and
// a single point is centred horizontally rather than pinned to the left edge.
const points = computed(() => {
const data = chartData.value;
const n = data.length;
+13
View File
@@ -1,4 +1,17 @@
<script setup>
/**
* Route `/stp` — the personal home page: an A4-shaped widget grid flanked by two
* sidebars.
*
* Layout is entirely CSS `grid-template-areas`: each child gets a `grid-area`
* class and the three breakpoints below (desktop / <=1360px tablet / <=700px
* phone) re-draw the whole area map rather than moving elements around.
*
* The widgets do not fetch individually — they all read stores/homeData.js, which
* issues one GraphQL query for the whole page.
*
* Note which variants are wired up: Intro2 and Gym2, not Intro/Gym.
*/
import Timer from "@/components/util/Timer.vue";
import Time from "@/components/util/Time.vue";
import Radio from "@/components/util/Radio.vue";
+5
View File
@@ -1,4 +1,9 @@
<script setup>
/**
* First version of the /stp intro widget. Nearly all of its content is commented
* out and Home.vue imports Intro2 instead.
* STATUS: superseded by Intro2.vue; not imported anywhere.
*/
import Header from "@/components/text/Header.vue";
import Paragraph from "@/components/text/Paragraph.vue";
</script>
+13
View File
@@ -1,4 +1,17 @@
<script setup lang="ts">
/**
* The live intro widget on /stp: DVD-logo-style bouncing phrases.
*
* The animation deliberately keeps its state in the plain `animState` array, not
* in the reactive `items` ref — mutating a ref 30 times a second would trigger a
* Vue re-render per frame. `items` exists only to render the initial DOM; after
* that, positions are written straight onto the elements. Element and container
* sizes are cached and re-measured on resize rather than read each frame, since
* reading offsetWidth in a rAF callback forces a synchronous layout.
*
* Frames are throttled to ~30fps via FRAME_INTERVAL because the motion is slow
* and this is a background decoration.
*/
import { rand } from "@vueuse/core";
import { ref, onMounted, onUnmounted, nextTick } from "vue";
+4
View File
@@ -1,4 +1,8 @@
<script setup>
/**
* "Links" widget on /stp: internal routes via <RouterTable>, external profiles
* via <LinkTable>.
*/
import RouterTable from "@/components/util/RouterTable.vue";
import LinkTable from "@/components/util/LinkTable.vue";
import Header from "@/components/text/Header.vue";
+9
View File
@@ -1,4 +1,11 @@
<script setup>
/**
* "Listening" widget on /stp: rotates through recent Spotify plays.
*
* Two timers: a 5s rotation (self-rearming setTimeout, so a manual change would
* reset the full interval) and a 2-minute re-poll of Spotify. Both are cleared on
* unmount.
*/
import Header from "@/components/text/Header.vue";
import { ref, computed, onMounted, onUnmounted } from "vue";
import { useSongsStore } from "@/stores/songs";
@@ -10,6 +17,8 @@ const song = computed(() => songsStore.songs[idx.value]);
let nextId = null;
let refreshId = null;
// Self-rearming timeout rather than setInterval, so the full 5s is restarted
// whenever the song changes rather than leaving a short remainder.
function nextSong() {
clearTimeout(nextId);
nextId = setTimeout(nextSong, 5000);
+3
View File
@@ -1,4 +1,7 @@
<script setup>
/**
* Decorative Miku GIF slideshow in the /stp right sidebar.
*/
import Slideshow from "@/components/util/Slideshow.vue";
const images = [
+10
View File
@@ -1,4 +1,11 @@
<script setup>
/**
* The Places-to-go table inside the Collage widget. Sign-in only.
*
* Fetches lazily and at most once: onMounted covers an already-signed-in visitor,
* the `loggedIn` watcher covers someone who signs in while the page is open, and
* both check `!loaded && !loading` so the two paths can't fire two requests.
*/
import { computed, onMounted, watch } from "vue";
import { usePlacesStore } from "@/stores/places";
import { useAuthStore } from "@/stores/auth";
@@ -7,6 +14,9 @@ const places = usePlacesStore();
const auth = useAuthStore();
const loggedIn = computed(() => auth.loggedIn);
// Two entry points, one fetch: onMounted covers an already-signed-in visitor,
// the watcher covers signing in with the page already open. The
// !loaded && !loading test is what stops them both firing a request.
onMounted(() => {
if (loggedIn.value && !places.loaded && !places.loading) places.fetch();
});
+18
View File
@@ -1,4 +1,13 @@
<script setup>
/**
* 88x31 webring "stamps" widget on /stp, inside a drag-scrollable <Touchscreen>.
*
* The order is shuffled on module load so the wall looks different each visit.
* The rAF loop then drifts the scroll position diagonally and bounces off each
* edge — it drives the DOM's scrollLeft/scrollTop directly rather than any
* reactive state, and reads scrollWidth/clientWidth each frame because images
* load in progressively and change the bounds.
*/
import { ref, onMounted, onUnmounted } from "vue";
import Touchscreen from "@/components/util/Touchscreen.vue";
@@ -21,6 +30,8 @@ let srcs = [
"/img/stamps/demo.gif",
"/img/stamps/demo.gif",
];
// Shuffled once at module evaluation, so the wall is ordered differently each
// page load but stable while the widget is mounted. Mutates in place.
shuffleArray(srcs);
const touchscreen = ref(null);
@@ -30,6 +41,13 @@ let posY = 0;
let dx = 0.2;
let dy = 0.12;
/**
* rAF loop drifting the scroll position diagonally and bouncing off the edges.
*
* Writes scrollLeft/scrollTop on the DOM node directly (no reactive state, so
* no re-render per frame), and re-reads scrollWidth/clientWidth every frame
* because the stamp images load in progressively and keep changing the bounds.
*/
function bounce() {
const el = touchscreen.value?.$el;
if (!el) return;
+5
View File
@@ -1,4 +1,9 @@
<script setup>
/**
* Steam widget on /stp: online status plus a rotation through recent games
* (5s rotation, 5-minute re-poll). `loaded` comes from homeData so the widget can
* tell "not fetched yet" from "fetched, nothing to show".
*/
import { ref, computed, onMounted, onUnmounted } from "vue";
import { storeToRefs } from "pinia";
import { useSteamStore } from "@/stores/steam";
+3
View File
@@ -1,4 +1,7 @@
<script setup>
/**
* Route `/shrines/demoman` — a wall of TF2 Demoman clips via <VideoTable>.
*/
import VideoTable from "@/components/util/VideoTable.vue";
import Link from "@/components/text/Link.vue";
@@ -1,4 +1,7 @@
<script setup>
/**
* Route `/shrines/evangelion` — placeholder, renders <Wip>.
*/
import Wip from "@/components/util/Wip.vue";
</script>
+3
View File
@@ -1,4 +1,7 @@
<script setup>
/**
* Route `/shrines/gto` — placeholder, renders <Wip>.
*/
import Wip from "@/components/util/Wip.vue";
</script>
+3
View File
@@ -1,4 +1,7 @@
<script setup>
/**
* Route `/shrines` — index of the shrine pages.
*/
import RouterTable from "@/components/util/RouterTable.vue";
const shrine_links = [
{ name: "Demoman", link: "/shrines/demoman" },
@@ -1,4 +1,7 @@
<script setup>
/**
* Route `/shrines/skipskipbenben` — placeholder, renders <Wip>.
*/
import Wip from "@/components/util/Wip.vue";
</script>
+6
View File
@@ -1,3 +1,9 @@
<!--
Route `/stp2` — a static CSS mock of an osu!-style game menu (coloured blocks
over a screenshot). No data, no interaction; mounted outside DefaultLayout so
it gets no navbar or footer.
STATUS: reachable but experimental; not linked from anywhere in the UI.
-->
<template>
<div class="menu">
<div class="header">
+8
View File
@@ -1,4 +1,12 @@
<script setup>
/**
* Route `/hotels` — Travelodge price scanner, front end for the FastAPI service
* under /py/hotels.
*
* Two panels behind a tab strip. The form state is created here and passed down
* as a prop, so shared fields (origin, guests, travel budget) survive tab
* switches; the chosen tab itself is remembered in localStorage.
*/
import { ref, computed, onMounted } from "vue";
import Header from "@/components/text/Header.vue";
import Paragraph from "@/components/text/Paragraph.vue";
@@ -1,4 +1,9 @@
<script setup>
/**
* "Cheapest night" tab of /hotels: scans a date range (capped at MAX_SPAN_DAYS,
* optionally filtered to particular weekdays) and reports the best hotel per
* night. Same streaming/abort/ticker mechanics as SingleStayPanel.vue.
*/
import { ref, computed, onMounted, onBeforeUnmount } from "vue";
import SharedFields from "./SharedFields.vue";
import HotelRows from "./HotelRows.vue";
+5
View File
@@ -1,4 +1,9 @@
<script setup>
/**
* The form fields common to both hotel panels (location, guests, railcards,
* origin, departure time, travel/distance limits). Mutates the shared `form`
* object from useHotelForm() directly — it is a prop by reference on purpose.
*/
import { CUSTOM_ORIGIN } from "./useHotelForm.js";
defineProps({
+22
View File
@@ -1,4 +1,15 @@
<script setup>
/**
* "Single stay" tab of /hotels: cheapest hotels for one specific check-in date.
*
* Results stream in: the backend sends a `hotels` event with room prices first,
* then a `transport` event per hotel as each route is priced, then `done`. Rows
* are patched in place by hotel `code` so the table fills in rather than
* reloading, and PENDING_ROUTE marks the not-yet-priced ones.
*
* An AbortController cancels an in-flight stream; a 1s ticker drives the elapsed
* counter. Both are torn down in the `finally` and on unmount.
*/
import { ref, computed, onMounted, onBeforeUnmount } from "vue";
import SharedFields from "./SharedFields.vue";
import HotelRows from "./HotelRows.vue";
@@ -157,6 +168,15 @@ function buildRequest() {
};
}
/**
* Apply one NDJSON event from the search stream.
*
* Order is `hotels` (room prices for all candidates) -> many `transport`
* (one per hotel as its route is priced) -> `done`. Transport events patch the
* existing row in place, matched on hotel `code`, so the table fills in
* column-by-column instead of being rebuilt — that is what keeps scroll
* position and sort order stable while results arrive.
*/
function applyEvent(ev) {
switch (ev.event) {
case "hotels":
@@ -194,6 +214,8 @@ async function onSearch() {
searching.value = true;
elapsed.value = 0;
saveConfig();
// 1s elapsed counter plus an AbortController to cancel the stream; both
// are torn down in the finally below and on unmount.
ticker = setInterval(() => elapsed.value++, 1000);
aborter = new AbortController();
try {

Some files were not shown because too many files have changed in this diff Show More