Trim comments to the non-obvious why
Test and deploy / test (push) Successful in 28s
Test and deploy / deploy (push) Successful in 31s

Drop narration, history and restated-code comments across the repo,
keep short ones for security boundaries, upstream quirks and ordering
constraints, and record the convention in CLAUDE.md.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-24 20:49:03 +00:00
co-authored by Claude Opus 5.5
parent effddd2794
commit 4530cb8dc4
222 changed files with 1173 additions and 5423 deletions
-4
View File
@@ -1,8 +1,4 @@
<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>
+7 -33
View File
@@ -1,33 +1,13 @@
/**
* The REST half of the API client, beside graphql.js: a thin axios wrapper for
* the Go backend's JSON endpoints under /api (file uploads, admin tooling,
* OAuth starts — everything backend/README.md lists as "not GraphQL").
*
* It does two things a bare axios call does not:
* - prefixes `/api`, so callers name the route (`api.get("/radio/songs")`);
* - turns a failure into an ApiError whose `message` is the backend's
* `{"error": "..."}` body when there is one. Every handler reports errors
* in that shape, and each view used to dig it out of `err.response` itself.
*
* Resolves to the parsed response body, not the axios response.
*
* Auth is the same HTTP-only cookies graphql.js relies on; nothing here handles
* tokens.
*
* NOT for: the Python service's NDJSON streams (views/hotels/hotelsStream.js
* reads those incrementally with fetch) or the `/radio/stream` HEAD probe —
* neither is under /api nor answers with this error shape.
* REST client for /api: prefixes the path, resolves to the body, and turns
* failures into an ApiError carrying the backend's `error` message. Not for
* the NDJSON streams or the radio probe.
*/
import axios from "axios";
export class ApiError extends Error {
/**
* @param {string} message
* @param {number|undefined} status HTTP status; undefined when no response
* arrived at all (network down, backend restarting)
* @param {*} data the parsed error body, if any
*/
/** `status` is undefined when no response arrived at all. */
constructor(message, status, data) {
super(message);
this.name = "ApiError";
@@ -37,15 +17,9 @@ export class ApiError extends Error {
}
/**
* @param {string} method
* @param {string} path route below /api, with its leading slash
* @param {object} [options]
* @param {*} [options.body] JSON-serialisable body, or a FormData for
* multipart uploads (axios sets the boundary itself)
* @param {string} [options.fallback] message to use when the backend sent no
* `error` string — callers pass the sentence their UI shows
* Any other option (`headers`, `params`, `onUploadProgress`, `signal`, …) is
* handed to axios unchanged.
* @param {string} path below /api, with its leading slash
* @param {object} [options] `body` (JSON or FormData), `fallback` message
* when the backend sent none; anything else goes to axios.
*/
async function request(method, path, { body, fallback, ...config } = {}) {
try {
+8 -38
View File
@@ -1,31 +1,11 @@
/*
* Global stylesheet — the single place the site's look is defined.
*
* 1. Fonts @font-face for the two custom fonts
* 2. Tokens colours, fonts, spacing. Declared with Tailwind's @theme, so
* every token is BOTH a utility class in templates
* (text-primary, bg-surface, font-heading) AND a CSS variable
* in component <style> blocks (var(--color-primary)).
* 3. Base default look of plain HTML elements (the dark theme),
* including the keyboard focus ring
* 4. Components reusable classes: gif borders, A4 sheet, halftone background
* 5. Transitions <Transition name="slide"> and <Transition name="fade">,
* and the reduced-motion override
* 6. Print
*
* The CV pages are a light theme: src/layouts/CVLayout.vue re-points the colour
* tokens below to ink-on-paper values, so the same base styles render light.
*
* Rule of thumb for components: use Tailwind utilities for layout and
* one-off tweaks; use a scoped <style> only for things utilities can't express
* (grid-template-areas, animations, media-query-specific layout).
* The site's look. @theme tokens are both Tailwind utilities and CSS
* variables; CVLayout.vue re-points the colours for the light CV theme.
*/
@import "tailwindcss";
/* ------------------------------------------------------------------ */
/* 1. Fonts */
/* ------------------------------------------------------------------ */
/* ---- 1. Fonts ---- */
@font-face {
font-family: "big_noodle_titling";
@@ -43,9 +23,7 @@
font-display: swap;
}
/* ------------------------------------------------------------------ */
/* 2. Tokens */
/* ------------------------------------------------------------------ */
/* ---- 2. Tokens ---- */
/* `static` = always emit these variables, even when no utility uses them,
because component <style> blocks reference them with var(). */
@@ -72,9 +50,7 @@
--spacing: 3px;
}
/* ------------------------------------------------------------------ */
/* 3. Base element styles (dark theme) */
/* ------------------------------------------------------------------ */
/* ---- 3. Base element styles (dark theme) ---- */
body {
margin: 0 auto;
@@ -188,9 +164,7 @@ th {
border-right: 1px dotted var(--color-tertiary);
}
/* ------------------------------------------------------------------ */
/* 4. Reusable component classes */
/* ------------------------------------------------------------------ */
/* ---- 4. Reusable component classes ---- */
/* Animated gif borders */
.bdr-1 {
@@ -238,9 +212,7 @@ th {
var(--grid-size) var(--grid-size);
}
/* ------------------------------------------------------------------ */
/* 5. Transitions */
/* ------------------------------------------------------------------ */
/* ---- 5. Transitions ---- */
/* <Transition name="slide"> — route changes in DefaultLayout */
.slide-enter-active,
@@ -291,9 +263,7 @@ th {
}
}
/* ------------------------------------------------------------------ */
/* 6. Print */
/* ------------------------------------------------------------------ */
/* ---- 6. Print ---- */
@media print {
.no-print,
+1 -6
View File
@@ -1,10 +1,5 @@
<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.
*/
/** Decorative waybar-style footer; only the clock is real. */
import { ref, onMounted, onUnmounted } from "vue";
const clock = ref("");
+1 -10
View File
@@ -1,14 +1,5 @@
<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.
*/
/** Top bar: an UP button to the parent path (hidden at the root) and a marquee. */
import Headline from "@/components/text/Headline.vue";
import { computed } from "vue";
import { useRoute } from "vue-router";
+1 -5
View File
@@ -1,9 +1,5 @@
<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.
*/
/** Explicit modelValue/emit rather than defineModel, so ToggleHeader can intercept. */
import { ref } from "vue";
const props = defineProps({
+4 -12
View File
@@ -1,14 +1,8 @@
<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.
* Infinite marquee: the slot rendered twice and wrapped by one copy's width.
* Plain `let` and direct style writes avoid a re-render per frame; width comes
* from a ResizeObserver to avoid forced layouts.
*/
import { onMounted, useTemplateRef, onUnmounted } from "vue";
@@ -51,9 +45,7 @@ function animate() {
let resizeObserver;
onMounted(() => {
// A visitor who asked the OS for less motion gets the text standing still.
// The CSS reduced-motion override in styles.css can't reach this: the
// movement is a transform written every frame, not a transition.
// styles.css's reduced-motion rule can't reach a per-frame transform.
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
measureWidth();
+1 -5
View File
@@ -1,9 +1,5 @@
<script setup>
/**
* Link styled to sit inside running prose (bold italic, no underline). Same
* `to` vs `href` and auto-`rel` behaviour as Link.vue, shared through
* useLinkAttrs.js.
*/
/** Link.vue styled for running prose. */
import { linkProps, useComputedRel } from "@/components/text/useLinkAttrs";
const props = defineProps({ ...linkProps });
+1 -6
View File
@@ -1,10 +1,5 @@
<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
* (shared with InlineLink.vue via useLinkAttrs.js).
*/
/** <RouterLink> for `to`, <a> for `href`; `bare` drops the styling. */
import { linkProps, useComputedRel } from "@/components/text/useLinkAttrs";
const props = defineProps({
+2 -6
View File
@@ -1,11 +1,7 @@
<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.
* The whole bar toggles; the inner button is pointer-events-none so a click
* can't fire twice.
*/
import { ref } from "vue";
import ToggleButton from "@/components/input/ToggleButton.vue";
+1 -8
View File
@@ -1,6 +1,3 @@
// Shared link behaviour for components/text/Link.vue and InlineLink.vue, which
// render the same thing (a <RouterLink> for `to`, an <a> for `href`) and differ
// only in styling.
import { computed } from "vue";
@@ -12,11 +9,7 @@ export const linkProps = {
rel: { type: String, default: undefined },
};
/**
* `rel` for the rendered <a>: an explicit `rel` prop wins, otherwise
* target="_blank" links get noopener/noreferrer so the opened page cannot
* reach back through window.opener.
*/
/** target="_blank" gets noopener/noreferrer unless `rel` is given. */
export function useComputedRel(props) {
return computed(() => {
if (props.rel !== undefined) return props.rel;
+3 -11
View File
@@ -11,14 +11,8 @@
<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.
* Drifts its content up and down, pausing at each end. Clamped to
* 0.001..0.999 so the end test doesn't re-fire the pause.
*/
import { useTemplateRef, onMounted, onBeforeUnmount } from "vue";
@@ -36,9 +30,7 @@ let cachedScrollHeight = 0;
function measureScrollHeight() {
const el = container.value;
// Scrollable range, not full content height: scrollTop saturates at
// scrollHeight - clientHeight, so using scrollHeight would stop the drift
// one viewport short of the end while pos still climbed to 1.
// scrollTop saturates here, not at scrollHeight.
if (el) cachedScrollHeight = Math.max(0, el.scrollHeight - el.clientHeight);
}
+1 -5
View File
@@ -1,9 +1,5 @@
<script setup>
/**
* The public chat widget. All of it is ChatPanel.vue; the admins-only channel
* is the separate PrivateChat.vue widget. This file keeps the name the canvas
* stores ("Chat" in widgetRegistry.js) pointing at the public channel.
*/
/** Public chat; the name "Chat" is what canvas boxes store (widgetRegistry.js). */
import ChatPanel from "./ChatPanel.vue";
</script>
+7 -29
View File
@@ -1,17 +1,7 @@
<script setup>
/**
* One chat channel: message list, composer, file attach and admin delete.
* Drives stores/messages.js. Not a widget itself — Chat.vue shows the public
* channel and PrivateChat.vue the admins-only one.
*
* The socket carries both channels in one stream (the server only sends
* private messages to admin connections), so `isPrivate` picks which half of
* `messages` to show and also marks what you send — you cannot post to a
* channel you are not looking at.
*
* Holds the socket while mounted — connect() on mount, disconnect() on
* unmount; the store counts them, so two panels share one socket and it
* exists only while a chat is on screen.
* One chat channel over stores/messages.js. `isPrivate` picks which messages
* to show and marks what you send. Holds a socket reference while mounted.
*/
import { ref, computed, watch, nextTick, onMounted, onUnmounted } from "vue";
import Button from "@/components/input/Button.vue";
@@ -34,14 +24,11 @@ const props = defineProps({
isPrivate: { type: Boolean, default: false },
});
// The private panel is the only place private messages are shown, so the
// public one stays public even for an admin.
const messages = computed(() =>
messagesStore.messages.filter((m) => !!m.private === props.isPrivate),
);
// 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.
// Don't yank a reader scrolled up into history.
const isNearBottom = ref(true);
const SCROLL_THRESHOLD = 100;
let resizeObserver = null;
@@ -94,23 +81,16 @@ async function onFileSelected(e) {
const file = e.target.files[0];
if (!file) return;
isNearBottom.value = true;
// The private flag both routes the upload to /uploads/private/ and marks the
// message itself private; the two must agree.
await messagesStore.uploadAndSendFile(file, props.isPrivate);
fileInput.value.value = "";
}
// Attachments are rendered only if isUploadUrl() accepts them: the fileUrl
// arrives over the socket and is otherwise attacker-controlled.
// fileUrl is attacker-controlled; render only if isUploadUrl() accepts it.
// 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.
// A /g regex keeps lastIndex; safe only because the loop runs exec() to null.
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. */
/** Text/link parts, so URLs render as anchors without v-html. */
function parseMessageParts(text) {
const parts = [];
let lastIndex = 0;
@@ -140,9 +120,7 @@ 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.
// Media loads after insert and changes the height.
if (messagesInner.value) {
resizeObserver = new ResizeObserver(scrollToBottomIfNear);
resizeObserver.observe(messagesInner.value);
+1 -7
View File
@@ -1,11 +1,5 @@
<script setup>
/**
* Sidebar widget showing the most recent Gitea action, read straight from
* homeData.gitFeed (the backend proxies and caches the Gitea API).
*
* The loading state keys off `settled` rather than `loaded` so a failed home
* query ends in "No activity found." instead of loading forever.
*/
/** Latest Gitea action. Keys off `settled` so a failure doesn't spin forever. */
import { useHomeDataStore } from "@/stores/homeData";
import { storeToRefs } from "pinia";
import Header from "@/components/text/Header.vue";
+1 -9
View File
@@ -1,13 +1,5 @@
<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> (and a
* .h-fit.w-full div); without a title the items are rendered bare. The items
* themselves live in LinkTableItems.vue so both branches share one copy.
* Used by the Bookmarks, Favorites, Consumption and Links widgets.
*/
/** {name, link, type} items as a list or table, collapsible when given `title`. */
import { ref } from "vue";
import LinkTableItems from "@/components/util/LinkTableItems.vue";
import ToggleHeader from "@/components/text/ToggleHeader.vue";
+1 -8
View File
@@ -1,12 +1,5 @@
<script setup>
/**
* The body of LinkTable.vue: the items rendered either as stacked link buttons
* (variant="list") or as a two-column table (variant="table").
*
* Split out only so LinkTable can render the same markup inside and outside its
* collapsible <ToggleHeader> wrapper without duplicating it. A component adds no
* DOM of its own, so the rendered output is unchanged.
*/
/** LinkTable's body, shared by its collapsible and bare branches. */
import Link from "@/components/text/Link.vue";
defineProps({
+1 -7
View File
@@ -1,11 +1,5 @@
<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.
*/
/** Markdown with KaTeX. v-html is safe only because DOMPurify runs first. */
import MarkdownIt from "markdown-it";
import { katex } from "@mdit/plugin-katex";
import DOMPurify from "dompurify";
+1 -4
View File
@@ -1,8 +1,5 @@
<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.
*/
/** STATUS: not imported anywhere. Columns are the union of every row's keys. */
import { computed } from "vue";
const props = defineProps({
+2 -5
View File
@@ -1,10 +1,7 @@
<script setup>
/**
* The admins-only chat widget: ChatPanel.vue on the private channel.
*
* The panel is mounted for admins only, so a non-admin never holds the socket
* on its account. The box itself is not hidden: a canvas box shows to everyone
* unless it is marked admin-only, and an empty box would look broken.
* Admins-only chat. The panel mounts only for admins; the box itself stays
* visible, or it would look broken.
*/
import { computed } from "vue";
import ChatPanel from "./ChatPanel.vue";
+2 -6
View File
@@ -16,12 +16,8 @@
<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.
* Icecast widget: probes the stream every 2 minutes and mounts <audio> only
* once it answers (hence nextTick before load()). Volume starts low.
*/
import Button from "@/components/input/Button.vue";
import Header from "@/components/text/Header.vue";
-4
View File
@@ -1,8 +1,4 @@
<script setup>
/**
* 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,
+2 -7
View File
@@ -1,12 +1,7 @@
<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.
* Crossfading image rotator. A re-armed timeout, not setInterval, so a click
* restarts the full delay.
*/
import { ref, computed, onMounted, onUnmounted } from "vue";
import Header from "@/components/text/Header.vue";
-5
View File
@@ -1,9 +1,4 @@
<script setup>
/**
* Clock and date widget. updateDateTime() runs once immediately and then every
* minute, with the interval owned by the component lifecycle so it is cleared
* on unmount.
*/
import Header from "@/components/text/Header.vue";
import { ref, onMounted, onUnmounted } from "vue";
+1 -8
View File
@@ -1,12 +1,5 @@
<script setup>
/**
* Countdown widget with minute/second sliders and a sound on completion.
*
* `state` is an explicit state machine — "idle" (sliders), "running",
* "paused" and "finished" — one screen per state. Completion is decided by
* comparing total elapsed seconds with the total target, so it does not depend
* on the minute and second fields crossing their targets independently.
*/
/** Countdown. Completion compares total seconds, not minutes and seconds apart. */
import Button from "@/components/input/Button.vue";
import Header from "@/components/text/Header.vue";
+1 -7
View File
@@ -13,13 +13,7 @@
</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.
*/
/** Drag-to-scroll. preventDefault stops a text selection mid-drag. */
import { ref } from "vue";
const container = ref(null);
+2 -8
View File
@@ -1,14 +1,8 @@
<script setup>
/**
* Choose a file that is already uploaded, instead of uploading it again: a
* modal grid of every public upload (listUploads in @/uploads), newest first.
* Admin only, because the listing is. Used by the canvas's Background panel,
* Box editor and "+ From uploads" button.
*
* Pick an existing upload (admin only).
* <UploadPicker v-if="picking" v-model="picking" :kinds="['image']" @pick="use" />
*
* `kinds` filters by kindOf(url). The bucket holds hundreds of megabytes, so
* thumbnails load lazily and videos fetch only their metadata.
* Thumbnails load lazily and videos fetch metadata only.
*/
import { computed, ref } from "vue";
import { kindOf, listUploads } from "@/uploads";
+1 -5
View File
@@ -1,9 +1,5 @@
<script setup>
/**
* 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.
*/
/** preload="none" so the page doesn't download every clip. */
defineProps({
sourceArr: {
type: Array,
+1 -8
View File
@@ -1,11 +1,4 @@
/**
* 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 (Caddy in production, the Vite proxy in dev).
*/
/** Thin GraphQL client; auth rides on same-origin HTTP-only cookies. */
import axios from "axios";
+3 -10
View File
@@ -1,11 +1,5 @@
// The shared body of the admin "create X" forms (CreatePost, CreateFavorite,
// CreateActivity, CreateBookmark): a ref per field, a GraphQL mutation taking a
// single `input`, clear the fields on success, then emit "done" so the host
// modal can close. A failure leaves the fields alone and its message on
// `error` for the form to show — it used to go only to the console, so a
// refused save looked exactly like a button that did nothing. `submitting`
// disables the button while the request is out, and a second submit in that
// window is ignored, so a double click cannot create the row twice.
// Shared admin "create X" form logic. Errors land on `error`; double submits
// are ignored while `submitting`.
import { ref } from "vue";
import { gql } from "@/graphql";
@@ -15,8 +9,7 @@ import { gql } from "@/graphql";
* @param {string} options.mutation GraphQL mutation with one $input variable
* @param {string[]} options.fields input field names, one text ref each
* @param {(event: string) => void} options.emit the component's emit
* @param {string[]} [options.optional] fields sent as undefined when blank,
* so the backend sees "not set" rather than an empty string
* @param {string[]} [options.optional] sent as undefined when blank
* @param {string} [options.resultKey] mutation field to log on success
* @returns {{
* values: Record<string, import("vue").Ref<string>>,
+2 -7
View File
@@ -1,10 +1,5 @@
// Rotate through a list on a timer, as the Listening and Steam widgets do.
//
// A self-rearming setTimeout rather than setInterval, so clicking to advance
// manually restarts the full delay instead of leaving whatever was left of the
// current tick. An optional periodic refresh callback covers the "re-poll the
// source every few minutes" half of the same pattern. Both timers are cleared
// on unmount.
// Rotates a list on a re-armed timeout (so a manual advance restarts the
// delay), with an optional periodic refresh.
import { ref, unref, onMounted, onUnmounted } from "vue";
+1 -8
View File
@@ -1,11 +1,4 @@
/**
* 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)`.
*/
/** Shuffles in place and returns nothing. */
export function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
+2 -7
View File
@@ -1,12 +1,7 @@
<script setup>
/**
* Layout shell for /cv. 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.
* Re-points the design tokens to ink-on-paper for /cv. The style block is
* unscoped on purpose, so it reaches the CV templates.
*/
import { RouterView } from "vue-router";
</script>
+3 -10
View File
@@ -1,15 +1,8 @@
<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.
*
* The background is the halftone unless the page on screen has one of its
* own (stores/background.js — set per canvas page, landing page and shrines
* included). The inline style overrides the halftone's layers.
* Shell for `/`. Keyed on the path so the transition runs between routes that
* share a component. Paints the page's background (stores/background.js) over
* the halftone.
*/
import { RouterView } from "vue-router";
import { useBackgroundStore } from "@/stores/background";
-4
View File
@@ -1,7 +1,3 @@
/**
* App entry point. Mounts <App> on #app with the router and a fresh Pinia.
*/
import { createApp } from "vue";
import { createPinia } from "pinia";
import App from "./App.vue";
+7 -39
View File
@@ -1,18 +1,6 @@
/**
* Route table and the single sign-in/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.
*
* Pages made in the browser (views/canvas/) have no entries here: the
* catch-all at the end looks the path up and renders the page if one exists.
*
* 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.
* Routes and the sign-in/admin guard. Canvas pages have no entries: the
* catch-all looks them up. Route `name`s are used by links; don't rename them.
*/
import { createRouter, createWebHistory } from "vue-router";
@@ -44,9 +32,7 @@ const router = createRouter({
component: () => import("@/views/admin/Admin.vue"),
meta: { requiresAdmin: true },
},
// A signed-in user's own page: the gated services they have
// been granted. /no-access is the same page with a notice,
// where Caddy's permission gate sends a refused visitor.
// Also /no-access, where Caddy's permission gate sends refusals.
{
path: "account",
name: "account",
@@ -76,13 +62,8 @@ const router = createRouter({
component: () =>
import("@/views/architecture/Architecture.vue"),
},
// /stp, /shrines and the shrines under it are canvas pages,
// made from the admin panel's Pages tab and served by the
// catch-all below. /stp's old route (views/home3/Home3.vue)
// and the hand-written shrines (views/home/shrines/) are
// unrouted.
// Anything else is an admin-created canvas page if one exists
// at that address (the Page GraphQL type), else the 404.
// Canvas pages (/stp, /shrines, admin-created) via the
// catch-all, else the 404.
{
path: ":pathMatch(.*)*",
name: "404",
@@ -104,26 +85,13 @@ const router = createRouter({
name: "cv",
component: () => import("@/views/CV/CV.vue"),
},
// /cv/jobs and /cv/leads moved to the job tracker app at
// /jobs/; Caddy redirects the old paths.
],
},
],
});
// Guard for routes marked `meta: { requiresAdmin: true }` or
// `meta: { requiresSignIn: true }` (any account, admin or not).
//
// The admin flag arrives asynchronously, so navigating straight to /admin on a
// cold load would otherwise read an empty user and bounce a legitimate admin to
// the login page. The guard therefore awaits auth.ensureLoaded(), which issues
// a standalone `me` query unless the user is already known.
//
// It deliberately does not wait on the home query (stores/homeData.js): that
// one fans out to Spotify, Steam and Gitea, and a guard that waited on it hung
// forever when it failed. ensureLoaded() always settles — a failed `me` reads
// as "not signed in" — and `user` is re-read on every navigation, so a login or
// logout during the session is honoured.
// Awaits auth.ensureLoaded() so a cold load of /admin doesn't bounce a real
// admin. Not the home query: that fans out to third parties and can fail.
router.beforeEach(async (to) => {
if (!to.meta.requiresAdmin && !to.meta.requiresSignIn) return;
const auth = useAuthStore();
+1 -5
View File
@@ -1,8 +1,4 @@
/**
* Media/activity log for the Consumption widget. A view over homeData.activities,
* built by createMirrorStore(); see stores/createMirrorStore.js for the
* placeholder-then-overwrite pattern.
*/
/** homeData.activities, via createMirrorStore(). */
import { defineStore } from "pinia";
import { createMirrorStore } from "@/stores/createMirrorStore";
+17 -50
View File
@@ -1,45 +1,25 @@
/**
* Current user + login/logout mutations.
*
* `user` is populated three ways:
* - ensureLoaded(): a standalone `me` query, fired at most once per page load.
* The router guard awaits it, and so does the login page.
* - adoptSession(): stores/homeData.js hands over the `me` it got back from
* the home query, so the /stp page never needs the standalone query.
* - logIn() / refreshToken() / logOut(), which set it directly.
*
* This store deliberately does NOT import homeData. It used to mirror
* homeData.me with a watch, which meant that merely asking "who is signed in?"
* instantiated homeData and so fired the nine-field home query — Spotify, Steam
* and Gitea upstreams included — and the guard then had to wait on it. The
* dependency now points the other way: homeData pushes `me` in here.
*
* 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.
* Current user and login/logout. `user` is filled by ensureLoaded() (the
* router guard's `me` query), by homeData via adoptSession(), or directly by
* the auth actions. Don't import homeData here: that would fire the whole
* home query just to learn who is signed in.
*/
import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { gql } from "@/graphql";
// The user fields every query here selects, so `user` has the same shape
// whichever one filled it. `permissions` is the list of gated services
// (/receipt/ and so on) a non-admin may open; see views/Account.vue.
// Selected by every query here, so `user` has one shape.
export const USER_FIELDS = "id username admin permissions";
export const useAuthStore = defineStore("auth", () => {
const user = ref({});
const loggedIn = computed(() => !!user.value.username);
// True once something has answered "who is signed in?" — the `me` query,
// the home query, or a login/logout. Until then an empty `user` means
// "unknown", not "signed out", which is the distinction the guard needs.
// Until true, an empty `user` means "unknown", not "signed out".
const resolved = ref(false);
// Bumped by every login/logout/refresh. A `me` answer that was requested
// before the bump describes the previous session, so it is dropped rather
// than allowed to sign a logged-out user back in (or the reverse).
// Bumped on every session change; older `me` answers are dropped.
let epoch = 0;
let pending = null;
@@ -49,10 +29,8 @@ export const useAuthStore = defineStore("auth", () => {
}
/**
* Apply a `me` answer that was requested when the session was at
* `requestedAt` (a value from sessionEpoch()). Only a truthy `me` overwrites
* `user`: a signed-out answer is null and must not clobber a user that
* logIn() set while the request was in flight.
* Only a truthy `me` overwrites `user`, so a null answer can't clobber a
* login that happened while it was in flight.
*/
function adoptSession(me, requestedAt = epoch) {
if (requestedAt !== epoch) return;
@@ -66,11 +44,8 @@ export const useAuthStore = defineStore("auth", () => {
}
/**
* Resolve once the signed-in user is known, fetching `me` if nothing has
* supplied it yet. NEVER rejects and never hangs: a failed query settles as
* "not signed in", because the router guard awaits this and a navigation
* that never resolves is worse than a bounce to the login page. A failure is
* not remembered, so the next call tries again.
* Never rejects or hangs (the router guard awaits it): failure settles as
* signed out, and isn't remembered.
*/
function ensureLoaded() {
if (resolved.value) return Promise.resolve();
@@ -86,8 +61,7 @@ export const useAuthStore = defineStore("auth", () => {
return pending;
}
/** Clear the session cookies server-side, then blank the local user.
* Deliberately clears `user` even if the mutation fails. */
/** Clears `user` even if the mutation fails. */
async function logOut() {
try {
await gql(`mutation { logout }`);
@@ -98,8 +72,7 @@ export const useAuthStore = defineStore("auth", () => {
markSessionChanged();
}
/** Log in and populate `user`. Swallows errors: on a bad password `user`
* is left untouched, so `loggedIn` simply stays false. */
/** Swallows errors: a bad password leaves `loggedIn` false. */
async function logIn(username, password) {
try {
const data = await gql(
@@ -113,8 +86,7 @@ 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. */
/** Admin-only. Re-throws so the form can show the message. */
async function createUser(username, password) {
try {
const data = await gql(
@@ -128,8 +100,6 @@ 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(
@@ -156,8 +126,7 @@ export const useAuthStore = defineStore("auth", () => {
}
}
/** Admin-only: replace a user's permission list. Returns the updated user;
* re-throws. */
/** Admin-only. Re-throws. */
async function setUserPermissions(userId, permissions) {
try {
const data = await gql(
@@ -171,15 +140,13 @@ export const useAuthStore = defineStore("auth", () => {
}
}
/** Signed-in only: every grantable service, as [{ key, label, path }].
* Re-throws. */
/** Re-throws. Returns [{ key, label, path }]. */
async function fetchPermissionTypes() {
const data = await gql(`query { permissionTypes { key label path } }`);
return data.permissionTypes;
}
/** Whether the signed-in user may open the service gated on `key`. Admins
* may open them all, as on the server. */
/** Admins may open every service, as on the server. */
function can(key) {
return !!user.value.admin || (user.value.permissions ?? []).includes(key);
}
+2 -11
View File
@@ -1,15 +1,6 @@
/**
* Page backgrounds (the `Background` GraphQL type), one per canvas page key —
* "index" for the landing page, or a Page slug such as "stp" or
* "shrines/evangelion" — and which one is on screen.
*
* DefaultLayout paints `style` behind everything, navbar included, so a
* background covers the whole window rather than just the canvas. Each
* BoxCanvas calls show(page) when it mounts and hide(page) when it goes;
* a page with no background (null) keeps the theme's halftone.
*
* `preview` is BackgroundEditor's unsaved draft: while it is set for the page
* on screen, it is what the layout paints, so every change shows at once.
* Page backgrounds, one per page key, and which is on screen. DefaultLayout
* paints it behind the whole window. `preview` is BackgroundEditor's draft.
*/
import { defineStore } from "pinia";
+6 -27
View File
@@ -1,24 +1,8 @@
/**
* Boxes on one canvas page (views/home3/BoxCanvas.vue) — full CRUD, built on
* createCrudStore().
*
* `useBoxesStore(page)` returns the store for that page key: "index" for the
* landing page, or a Page slug ("stp" for the home page). Each key
* gets its own Pinia store (id `boxes:<page>`), so moving between pages
* neither refetches a page already visited nor mixes two pages' boxes.
*
* Not part of the homeData query: the canvas has to know which boxes exist
* before it can mount the widgets that then trigger homeData, and keeping the
* two apart means a failing Spotify/Steam upstream can't blank the layout.
*
* The list query returns boxes ordered by z, so a new box (given the top z)
* belongs at the end. adminOnly boxes only come back for an admin — the
* server filters them — so the canvas refetches when the session changes.
*
* A box with a `componentId` is linked to that component (stores/components.js):
* the server answers with the component's html in `html`, and editing it goes
* to the component. patchLinked() keeps every page already loaded in step when
* a component changes, without refetching them.
* Boxes for one page key, one Pinia store per key (`boxes:<page>`). Separate
* from homeData so a failing upstream can't blank the layout. Ordered by z.
* The canvas refetches on session change since adminOnly boxes are filtered
* server-side.
*/
import { createCrudStore } from "@/stores/createCrudStore";
@@ -42,9 +26,7 @@ const BOX_FIELDS = `
componentId
`;
// The fields a duplicate copies. kind and widget/html are what make it the
// same box — or componentId, which keeps a copy of a linked box linked;
// geometry is offset so the copy is visibly separate.
// What a duplicate copies; geometry is offset.
const COPIED = [
"page", "kind", "widget", "html", "title", "w", "h", "framed", "shadow", "hideOnMobile", "adminOnly", "componentId",
];
@@ -90,10 +72,7 @@ export function useBoxesStore(page) {
return stores.get(page)();
}
/**
* Apply `patch` to every loaded box linked to component `componentId`, on
* every page visited so far.
*/
/** Patches linked boxes on every page loaded so far. */
export function patchLinked(componentId, patch) {
for (const use of stores.values()) {
for (const box of use().boxes) {
+7 -30
View File
@@ -1,18 +1,7 @@
/**
* Saved components (the `Component` GraphQL type): named HTML boxes that can
* be placed on any canvas page as a copy or linked — full CRUD, built on
* createCrudStore(), plus the box-side actions.
*
* A linked box shows its component's html, so `update` is wrapped to push a
* new html into every loaded page's boxes (stores/boxes.js patchLinked), and
* `remove` unlinks them locally the way the server just did (each keeps the
* html it showed). `uses` is kept roughly right locally (countUse) as this
* tab places, detaches and deletes linked boxes, and the panel refetches the
* list when it opens for the true figure.
*
* Admin only, so nothing fetches it until an admin opens the canvas's
* Components panel or "+ New box" menu (views/home3/ComponentPanel.vue,
* BoxCanvas.vue).
* Saved components. `update` pushes new html into every loaded page's linked
* boxes (patchLinked); `remove` unlinks them locally as the server did.
* `uses` is approximate locally; the panel refetches on open. Admin only.
*/
import { createCrudStore } from "@/stores/createCrudStore";
@@ -33,8 +22,7 @@ const COMPONENT_FIELDS = `
uses
`;
// Matches BOX_FIELDS in stores/boxes.js, for the mutations that answer with
// a box.
// Matches BOX_FIELDS in stores/boxes.js.
const BOX_FIELDS = `
id page kind widget html title x y w h z framed shadow hideOnMobile adminOnly componentId
`;
@@ -74,10 +62,7 @@ export const useComponentsStore = createCrudStore("components", {
patchLinked(id, { componentId: null });
},
/**
* Make html box `box` into a component named `name` and link it.
* Throws on failure.
*/
/** Makes html box `box` a component and links it. Throws. */
async saveFromBox(box, name) {
const data = await gql(
`mutation SaveBoxAsComponent($id: ID!, $name: String!) {
@@ -99,11 +84,7 @@ export const useComponentsStore = createCrudStore("components", {
countUse(box.componentId, -1);
},
/**
* Put `component` on page key `page` at `at` ({ x, y, z }): linked, or
* as an ordinary box with a copy of its html. Answers with the new box.
* Throws on failure.
*/
/** Places `component` at `at` ({ x, y, z }), linked or copied. Throws. */
async place(component, page, at, linked) {
const input = {
kind: "html",
@@ -122,11 +103,7 @@ export const useComponentsStore = createCrudStore("components", {
return created;
},
/**
* Create a component from each built-in starter in templates.js whose
* name is free, and answer with how many were added. Deleted ones come
* back; ones still there are left as they are. Throws on failure.
*/
/** Imports the templates.js starters whose names are free. Throws. */
async importBuiltins() {
const taken = new Set(items.value.map((c) => c.name));
let added = 0;
+1 -10
View File
@@ -1,13 +1,4 @@
/**
* Saved cover letters (the `CoverLetter` GraphQL type) for the /cv Cover
* Letter tab — full CRUD, built on createCrudStore().
*
* `body` is the whole letter as a JSON string; views/CV/coverLetter.js owns
* its shape (parseBody / serialize), the server only checks it is an object.
*
* Admin only, so nothing fetches it until views/CV/CoverLetters.vue sees an
* admin signed in.
*/
/** Saved cover letters; `body` is JSON owned by views/CV/coverLetter.js. Admin only. */
import { createCrudStore } from "@/stores/createCrudStore";
+1 -11
View File
@@ -1,14 +1,4 @@
/**
* The cover-letter paragraph bank (the `CoverSnippet` GraphQL type): reusable
* paragraphs dragged into a letter as copies — full CRUD, built on
* createCrudStore().
*
* `section` is the title of the section a snippet was written for and only
* groups the bank (views/CV/CoverSnippetBank.vue); editing a snippet never
* changes letters it was already dropped into.
*
* Admin only, like stores/coverLetters.js.
*/
/** The paragraph bank; snippets drop into letters as copies. Admin only. */
import { createCrudStore } from "@/stores/createCrudStore";
+10 -30
View File
@@ -1,21 +1,7 @@
/**
* Factory for the "CRUD store" pattern, used by stores/places.js.
*
* A store built with it is one GraphQL type with the schema's standard quartet — a list
* query, `create<Type>(input:)`, `update<Type>(id:, input:)` and
* `delete<Type>(id:)` — plus a local array that is patched after each mutation
* instead of being refetched. The operation and input-type names are derived
* from `type` because the schema is consistent about them
* (`Create<Type>Input`, `Update<Type>Input`); a type that breaks the convention
* should not be forced through here.
*
* `fields` is interpolated into every query and mutation so the selection set
* can never drift between them.
*
* Error contract, which callers rely on: fetch() never throws — it records the
* failure on `error` — because it is fired from lifecycle hooks with nothing to
* catch it. create/update/remove DO throw, so the form or row that triggered
* them can show the message and keep the user's typing.
* A store for one GraphQL type with the standard list/create/update/delete
* operations, patching a local array instead of refetching. fetch() never
* throws (it records `error`); the mutations throw so forms can show it.
*/
import { defineStore } from "pinia";
@@ -28,19 +14,13 @@ import { gql } from "@/graphql";
* @param {string} options.type GraphQL type name, e.g. "Place"
* @param {string} options.list list query field, e.g. "places"
* @param {string} options.fields selection set shared by every operation
* @param {string} [options.itemsKey] name the array is exposed under (defaults
* to `list`); components import it by that name
* @param {"prepend"|"append"} [options.insert] where create() puts the new row
* locally, matching the order the list query returns
* @param {"object"|"boolean"} [options.deleteReturns] what the delete mutation
* returns. An object type needs a selection set and a scalar must not have
* one, so the mutation text differs; the schema has both kinds.
* @param {(ctx: object) => object} [options.extend] extra state/actions merged
* into the store; receives the base members
* @param {Record<string, {type: string, value: *}>} [options.args] arguments
* for the list query, e.g. `{ page: { type: "String!", value: "stp" } }`.
* Fixed for the store's lifetime, so a list that varies needs one store per
* value (stores/boxes.js does this per page).
* @param {string} [options.itemsKey] name of the exposed array (default `list`)
* @param {"prepend"|"append"} [options.insert] where create() adds the row
* @param {"object"|"boolean"} [options.deleteReturns] the delete mutation's
* return kind (only an object takes a selection set)
* @param {(ctx: object) => object} [options.extend] extra state/actions
* @param {Record<string, {type: string, value: *}>} [options.args] fixed list
* query arguments, e.g. `{ page: { type: "String!", value: "stp" } }`
*/
export function createCrudStore(
id,
+3 -14
View File
@@ -1,14 +1,6 @@
/**
* Factory for the "mirror store" pattern shared by stores/posts.js,
* favorites.js and activity.js.
*
* Each of those is a thin view over one slice of the shared home query
* (stores/homeData.js): a ref seeded with placeholder content, an `immediate`
* watch that copies the homeData slice in, a count computed and a fetch
* function that just re-runs the whole home query.
*
* The state/getter/action names differ per store and components import them by
* name, so the caller supplies them explicitly rather than having them derived.
* A thin store mirroring one homeData slice (posts, favorites, activity),
* with a placeholder until data arrives.
*/
import { computed, ref, watch } from "vue";
@@ -26,10 +18,7 @@ export function createMirrorStore({ slice, template }) {
const count = computed(() => items.value.length);
const homeData = useHomeDataStore();
// `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.
// `immediate` catches data already loaded; empty keeps the placeholder.
watch(
() => homeData[slice],
(newItems) => {
+1 -5
View File
@@ -1,8 +1,4 @@
/**
* Favourites for the Favorites widget. A view over homeData.favorites, built by
* createMirrorStore(); see stores/createMirrorStore.js for the
* placeholder-then-overwrite pattern.
*/
/** homeData.favorites, via createMirrorStore(). */
import { defineStore } from "pinia";
import { createMirrorStore } from "@/stores/createMirrorStore";
+7 -36
View File
@@ -1,24 +1,7 @@
/**
* 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) are thin views
* over this one — they `watch` their slice of it rather than fetching. The
* session user is the exception: `me` is pushed into stores/auth.js, which owns
* it and can also fetch it alone (the router guard does not wait on this query).
*
* 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.
*
* Two flags, because "finished" and "succeeded" are different questions:
* `settled` — a fetch has completed, either way. Wait on / show a spinner
* against THIS; it always becomes true.
* `loaded` — a fetch has succeeded at least once, so the data refs are real.
* Anything that waited on `loaded` alone would wait forever when the query
* fails outright, which is how the router guard used to hang.
* One GraphQL query for every /stp widget; the per-domain stores watch their
* slice of it. `me` is pushed into stores/auth.js. Wait on `settled` (always
* becomes true), not `loaded` (only on success).
*/
import { defineStore } from "pinia";
@@ -43,16 +26,10 @@ 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, and `settled` either way; never throws. Safe to call again to
* refresh.
*/
/** Never throws; safe to call again to refresh. */
async function fetchAll() {
const auth = useAuthStore();
// Read before the request goes out: if the user logs in or out while it is
// in flight, the `me` it returns is stale and auth will ignore it.
// Read before the request, so a session change in flight is detected.
const sessionAt = auth.sessionEpoch();
try {
const [data] = await Promise.all([
@@ -80,8 +57,6 @@ export const useHomeDataStore = defineStore("homeData", () => {
gitFeed.value = data.giteaFeed || null;
steamStatus.value = data.steamStatus || null;
me.value = data.me || null;
// The home query already says who is signed in, so hand it to the auth
// store rather than have it issue its own `me` query on this page.
auth.adoptSession(me.value, sessionAt);
loaded.value = true;
// A refresh that works clears the failure a previous one left behind.
@@ -94,10 +69,7 @@ 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.
*/
/** A failed probe means offline, not an error. */
async function fetchRadioStatus() {
try {
await axios.head("/radio/stream");
@@ -107,8 +79,7 @@ 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.
// Pinia setup stores run once, so this is the one initial load.
fetchAll();
return {
+3 -18
View File
@@ -1,14 +1,4 @@
/**
* Saved layouts (the `Layout` GraphQL type): named copies of a canvas page's
* boxes and background — full CRUD, built on createCrudStore(), plus apply().
*
* `create({ name, page })` saves that page as it is now; `update` only
* renames. What a layout holds never reaches the browser, only its size: the
* server does both the copying in and the copying out.
*
* Admin only, so nothing fetches it until an admin opens a layouts list
* (views/home3/LayoutPanel.vue, the admin panel's Pages tab).
*/
/** Saved layouts. Their contents never reach the browser. Admin only. */
import { createCrudStore } from "@/stores/createCrudStore";
import { gql } from "@/graphql";
@@ -32,10 +22,7 @@ export const useLayoutsStore = createCrudStore("layouts", {
insert: "prepend",
deleteReturns: "object",
extend: ({ fetch }) => ({
/**
* Copy layout `id` onto page key `page`, replacing what is there or
* adding on top. Throws on failure.
*/
/** Throws on failure. */
async apply(id, page, replace) {
await gql(
`mutation ApplyLayout($id: ID!, $page: String!, $replace: Boolean!) {
@@ -43,9 +30,7 @@ export const useLayoutsStore = createCrudStore("layouts", {
}`,
{ id, page, replace },
);
// The page's own stores are refetched rather than patched from the
// answer, so they stay in the shape their list query gives. A replace
// also saved the old page as a new layout, hence the list too.
// Refetched, not patched; a replace also saved a new layout.
await Promise.all([useBoxesStore(page).fetch(), useBackgroundStore().load(page), replace && fetch()]);
},
}),
+14 -44
View File
@@ -1,14 +1,7 @@
/**
* WebSocket-backed chat, used by components/util/ChatPanel.vue (behind both the
* public Chat and the admins-only PrivateChat widgets).
*
* 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 close.
*
* Both chat widgets can be on screen at once and share the socket (it carries
* both channels), so connect()/disconnect() are counted: the socket opens with
* the first widget and closes with the last.
* WebSocket chat for ChatPanel.vue. Reconnects with backoff (1s to 30s) unless
* closed on purpose. Both chat widgets share the socket, so connect() and
* disconnect() are reference-counted.
*/
import { defineStore } from "pinia";
@@ -16,12 +9,7 @@ import { ref, computed, watch } from "vue";
import { uploadFile } from "@/uploads";
import { useAuthStore } from "@/stores/auth";
/**
* Same-origin ws:// or wss:// URL for the chat socket, derived from the page's
* own protocol and host. Nothing is configurable: Caddy (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.
*/
/** Same origin as the page, or the auth cookies wouldn't travel. */
function getWebSocketURL() {
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
return `${protocol}//${window.location.host}/api/ws`;
@@ -61,11 +49,8 @@ export const useMessagesStore = defineStore("messages", () => {
intentionalClose = false;
clearTimeout(reconnectTimer);
// Every handler checks it still belongs to the current socket. A socket
// closed by disconnect() can fire onclose after connect() has already
// opened a replacement; without this guard it would null the new socket
// and schedule a second reconnect, leaving two live sockets that each
// push every broadcast (duplicate messages).
// Handlers ignore stale sockets: a closed socket's late onclose would
// otherwise null its replacement and open a duplicate.
const ws = new WebSocket(getWebSocketURL());
socket.value = ws;
@@ -80,11 +65,8 @@ export const useMessagesStore = defineStore("messages", () => {
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.
// Replaced in one go so keyed rows (and images) patch in place.
messages.value = data.messages || [];
return;
}
@@ -92,8 +74,7 @@ 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`).
// The server can echo our sends or overlap with history.
if (data.id && messages.value.some((m) => m.id === data.id)) return;
messages.value.push(data);
} catch {
@@ -120,11 +101,7 @@ export const useMessagesStore = defineStore("messages", () => {
};
}
/**
* 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 open() is not fought over by the dying one.
*/
/** Clearing socket.value before close() is what makes the stale guard work. */
function close() {
intentionalClose = true;
clearTimeout(reconnectTimer);
@@ -135,9 +112,8 @@ export const useMessagesStore = defineStore("messages", () => {
ws.close();
}
// Admin status is fixed when the socket connects (from the auth cookies), so
// reopen after a login/logout to pick up or drop private messages. Here
// rather than in the widgets so two mounted chats reconnect once, not twice.
// Admin status is fixed at connect, so reconnect on login/logout. Here, not
// in the widgets, so two chats reconnect once.
const auth = useAuthStore();
watch(
() => !!auth.user.admin,
@@ -154,8 +130,7 @@ export const useMessagesStore = defineStore("messages", () => {
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. */
/** The removal arrives back as a "delete" broadcast. */
function deleteMessage(id) {
if (!socket.value || !isConnected.value) return;
socket.value.send(JSON.stringify({ action: "delete", id }));
@@ -166,13 +141,8 @@ export const useMessagesStore = defineStore("messages", () => {
}
/**
* Store a file (uploads.js), then send its URL over the socket as a normal
* message. Two steps because the socket carries JSON text only. Errors
* surface via `lastError`.
*
* `private` goes to both: the upload is stored under /uploads/private/,
* which Caddy gates behind an admin check, and the message is marked
* private. The two must agree.
* Uploads, then sends the URL (the socket carries JSON only). `private`
* must apply to both the upload and the message.
*/
async function uploadAndSendFile(file, isPrivate = false) {
try {
+1 -7
View File
@@ -1,10 +1,4 @@
/**
* 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.
*/
/** STATUS: not imported anywhere. Kept as a record of the intended shapes. */
export class User {
constructor({ id, createdAt, updatedAt, deletedAt, username, admin }) {
+2 -8
View File
@@ -1,12 +1,6 @@
/**
* Admin-created canvas pages (the `Page` GraphQL type) — full CRUD, built on
* createCrudStore().
*
* A page is only a slug and a title; what is on it lives in that slug's boxes
* store (stores/boxes.js). The list is public apart from adminOnly pages,
* which the server only returns to an admin. Single pages are looked up by
* views/canvas/CanvasPage.vue with its own `page(slug:)` query, so that
* opening one page doesn't download the whole list.
* Canvas pages (slug and title only). Single pages are fetched by
* CanvasPage.vue's own query so opening one doesn't load the list.
*/
import { createCrudStore } from "@/stores/createCrudStore";
+1 -7
View File
@@ -1,10 +1,4 @@
/**
* Places-to-go list (the Places widget, views/home/Places.vue) — full CRUD,
* built on createCrudStore().
*
* Not part of the homeData query because it is sign-in-only; PlacesTable.vue
* fetches it lazily once the user is logged in.
*/
/** Places list; sign-in only, so not part of homeData. */
import { createCrudStore } from "@/stores/createCrudStore";
+1 -8
View File
@@ -1,11 +1,4 @@
/**
* Blog posts for the Feed widget. A view over homeData.posts, built by
* createMirrorStore(); see stores/createMirrorStore.js for the
* placeholder-then-overwrite pattern.
*
* `post_template` is placeholder content rendered before (or instead of) a
* successful fetch, so the widget never flashes empty.
*/
/** homeData.posts, via createMirrorStore(). */
import { defineStore } from "pinia";
import { gql } from "@/graphql";
+3 -15
View File
@@ -1,10 +1,4 @@
/**
* 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.
*/
/** Spotify tracks; has its own fetchSongs() for the widget's 2-minute poll. */
import { defineStore } from "pinia";
import { ref, computed, watch } from "vue";
@@ -22,19 +16,13 @@ const song_template = {
export const useSongsStore = defineStore("songs", () => {
const songs = ref([song_template]);
// signalEnglish (see below) plus an admin-only "needs Spotify re-auth"
// flag, fetched alongside the songs. The widget uses it to offer the
// reconnect link; non-admins also get the field (false) because the query
// is public and the resolver simply gates it.
// Always false for non-admins.
const needsReauth = ref(false);
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.
// `immediate` catches data already loaded; empty keeps the placeholder.
watch(
() => homeData.spotifyRecent,
(newSongs) => {
+1 -5
View File
@@ -1,8 +1,4 @@
/**
* 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.
*/
/** homeData.steamStatus, plus fetchSteam() for the widget's own refresh. */
import { defineStore } from "pinia";
import { ref, watch } from "vue";
+11 -49
View File
@@ -1,34 +1,11 @@
/**
* Uploaded files: the one module to use whenever the frontend stores a file
* or shows one it stored.
*
* import { uploadFile, ACCEPT, kindOf, tagFor } from "@/uploads";
*
* <input type="file" :accept="ACCEPT.images" @change="…">
* const url = await uploadFile(file); // "/uploads/3f9c….png"
* kindOf(url) // "image"
*
* Files go to POST /api/uploads (backend/handlers/handle_upload.go). The
* backend decides everything that matters: the allowed types and the 10MB
* limit (backend/services/uploads.go, UploadTypes), the random file name, and
* where it is stored (the Garage bucket, falling back to disk). The URL it
* returns is permanent and public — anyone with it can load the file, no login
* — so never upload something that shouldn't be public unless it is a private
* chat attachment (`{ private: true }`, admin only).
*
* A refused file (wrong type, too large) rejects with an ApiError whose
* `message` is the backend's sentence, ready to show the user.
*
* listUploads() lists what is already stored, for reusing a file instead of
* uploading it again (components/util/UploadPicker.vue). It is admin-only:
* the listing is what would turn every unguessable URL into a known one.
* Every frontend upload goes through here. The backend enforces types, size
* and naming (backend/services/uploads.go). Returned URLs are public to anyone
* who has them. A refusal rejects with an ApiError carrying a showable message.
*/
import { api } from "@/api";
/**
* `accept` values for file pickers, matching what the backend allows. They
* only steer the picker; the backend enforces the real list.
*/
/** Picker hints only; the backend enforces the real list. */
export const ACCEPT = {
images: "image/jpeg,image/png,image/gif,image/webp",
media: "image/jpeg,image/png,image/gif,image/webp,video/mp4,video/webm,audio/mpeg,audio/ogg",
@@ -36,15 +13,10 @@ export const ACCEPT = {
};
/**
* Store one file; resolves to its URL.
*
* @param {File} file
* @param {object} [options]
* @param {boolean} [options.private] admin-only: store it under
* /uploads/private/, readable only by admins. Never use it for anything
* shown inside a canvas box — a box's sandboxed frame loads without the
* login cookie, so the file would not load.
* @returns {Promise<string>} "/uploads/<name>" or "/uploads/private/<name>"
* @param {boolean} [options.private] admin-only. Never for canvas boxes: their
* sandboxed frames load without the login cookie.
* @returns {Promise<string>} the file's URL
*/
export async function uploadFile(file, { private: isPrivate = false } = {}) {
const body = new FormData();
@@ -54,11 +26,7 @@ export async function uploadFile(file, { private: isPrivate = false } = {}) {
return url;
}
/**
* Every public upload, newest first. Admin only.
*
* @returns {Promise<Array<{name: string, url: string, size: number, modified: string}>>}
*/
/** Admin only: the listing would reveal every unguessable URL. */
export async function listUploads() {
const { files } = await api.get("/uploads", { fallback: "Couldn't list uploads" });
return files;
@@ -76,11 +44,8 @@ export const isImage = (url) => kindOf(url) === "image";
export const isVideo = (url) => kindOf(url) === "video";
/**
* Whether a URL is one of our own uploads. Use it before rendering a URL that
* came from somebody else (a chat message's fileUrl arrives over the socket
* and is otherwise attacker-controlled). A strict prefix check, so absolute
* ("https://evil/uploads/x") and protocol-relative ("//evil/uploads/x") URLs
* fail, and ".." is refused outright.
* Use before rendering an untrusted URL (e.g. a chat fileUrl). Absolute,
* protocol-relative and ".." URLs fail.
*/
export function isUploadUrl(url) {
return typeof url === "string" && !url.includes("..") && url.startsWith("/uploads/");
@@ -100,10 +65,7 @@ export function tagFor(url) {
}
}
/**
* Natural size of an image or video — a File, or the URL of one already
* stored — or null if it can't be read.
*/
/** Natural size of an image or video (File or URL), or null. */
export function mediaSize(file) {
return new Promise((resolve) => {
const isFile = typeof file !== "string";
+4 -15
View File
@@ -1,15 +1,7 @@
<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.
* Route `/cv`: template picker and Print. Uncomment an import and its entry
* below to bring a template back.
*/
import { ref, shallowRef } from "vue";
// import CVGeneral from "./CVGeneral.vue";
@@ -37,9 +29,7 @@ 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.
// shallowRef: a deep ref would make the component definition reactive.
const currentComponent = shallowRef(templates[0].component);
function select(index) {
@@ -47,8 +37,7 @@ 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. */
/** `no-print` hides the chrome; cv-shared.css sizes the pages. */
function print() {
window.print();
}
+2 -5
View File
@@ -1,10 +1,7 @@
<script setup>
/**
* The live CV template — the only one currently listed in CV.vue.
*
* Both sheets are fixed A4 with overflow hidden (cv-shared.css), so anything
* added here has to be checked in print preview: text that doesn't fit is
* silently clipped, not pushed onto another page.
* The live CV template. Sheets are fixed A4 with overflow hidden: check print
* preview, since overflow is clipped silently.
*/
import Project from "./Project.vue";
</script>
+11 -30
View File
@@ -1,27 +1,12 @@
<script setup>
/**
* Editable cover letter (contenteditable fields, print to PDF), split into
* named sections whose paragraphs can be dragged within and between them.
* STATUS: live — CV.vue imports it as the "Cover Letter" tab on /cv.
*
* Everyone gets the editor; /cv is public and nothing here needs the server
* until something is saved. An admin also gets the toolbar (saved letters,
* stores/coverLetters.js) and the paragraph bank (CoverSnippetBank.vue,
* stores/coverSnippets.js). The letter's data shape and the moves live in
* ./coverLetter.js.
*
* Section titles are editor furniture: they are `no-print`, so the printed
* letter is one run of paragraphs, as it was before sections existed.
*
* Editing: contenteditable elements are filled with v-text and read back on
* blur. v-text, not {{ }}, because it replaces the element's whole content —
* an interpolated text node would sit alongside the <div>s a browser adds on
* Enter and duplicate the text when Vue patched it.
*
* Dragging is native HTML5 DnD. `drag` holds what is in flight (dataTransfer
* can't be read until the drop) and `dropAt` where it would land, which is
* what draws the indicator line. Only the ⋮⋮ handle is draggable, so text in
* a paragraph stays selectable.
* Editable cover letter with draggable paragraphs and sections.
* STATUS: live — the "Cover Letter" tab on /cv.
* Admins also get saved letters and the paragraph bank. Data shape and moves
* are in ./coverLetter.js.
* contenteditable fields use v-text, not {{ }}: an interpolated text node would
* duplicate text alongside the <div>s browsers add on Enter. Only the ⋮⋮
* handle drags, so paragraph text stays selectable.
*/
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { useAuthStore } from "@/stores/auth";
@@ -46,8 +31,7 @@ const isAdmin = computed(() => auth.loggedIn && !!auth.user.admin);
const letter = ref(newLetter());
// The open saved letter's id, or null for one never saved (or deleted).
const currentId = ref(null);
// The body as last saved or loaded; the letter is unsaved when it differs.
// Starts as the blank template so an untouched page doesn't nag.
// Starts as the blank template so an untouched page isn't "unsaved".
const savedBody = ref(serialize(letter.value));
const dirty = computed(() => serialize(letter.value) !== savedBody.value);
const current = computed(() =>
@@ -59,8 +43,7 @@ const error = ref("");
onMounted(() => auth.ensureLoaded());
// The stores are admin only, so they are fetched once an admin is known,
// which can be after mount on a cold load.
// Admin is known only after mount on a cold load.
watch(
isAdmin,
(admin) => {
@@ -71,8 +54,7 @@ watch(
{ immediate: true },
);
// Closing the tab with unsaved changes asks first. Only for an admin, who
// can save; a visitor's letter is throwaway by design.
// Only admins can save; a visitor's letter is throwaway.
function onBeforeUnload(event) {
if (isAdmin.value && dirty.value) event.preventDefault();
}
@@ -102,8 +84,7 @@ function discardOk() {
function open(letterRow) {
letter.value = parseBody(letterRow.body);
currentId.value = letterRow.id;
// The normalised form, not the raw body, so an older row doesn't open
// already marked unsaved.
// Normalised, so an older row doesn't open as unsaved.
savedBody.value = serialize(letter.value);
}
+4 -14
View File
@@ -1,14 +1,7 @@
<script setup>
/**
* The paragraph bank beside the cover letter (admin only, never printed):
* reusable paragraphs from stores/coverSnippets.js, grouped by the section
* they were written for.
*
* Dragging works through the parent, which owns the one drag in progress:
* dragging a snippet out emits `drag-snippet` so CoverLetters.vue can drop a
* copy into the letter, and a letter paragraph dropped here (`accepting` is
* true while one is being dragged) emits `drop-paragraph` for the parent to
* save. Snippets are edited in place and saved on blur.
* The admin's paragraph bank beside the cover letter. CoverLetters.vue owns
* the drag in progress; this emits `drag-snippet` and `drop-paragraph`.
*/
import { computed, ref } from "vue";
import { useCoverSnippetsStore } from "@/stores/coverSnippets";
@@ -30,8 +23,6 @@ const over = ref(false);
const newText = ref("");
const newSection = ref("");
/** [{ section, snippets }] in the store's order (section, then newest),
* narrowed by the filter, which matches text or section. */
const groups = computed(() => {
const q = filter.value.trim().toLowerCase();
const out = [];
@@ -79,9 +70,8 @@ function onDragStart(snippet, event) {
event.dataTransfer.effectAllowed = "copy";
// Firefox won't start a drag without some data set.
event.dataTransfer.setData("text/plain", snippet.text);
// Only the grip is draggable, so text in the textareas stays selectable
// (Firefox can't place a caret inside a draggable element); show the
// whole card moving rather than the grip.
// Only the grip drags (Firefox can't put a caret in a draggable), so show
// the whole card as the drag image.
event.dataTransfer.setDragImage(event.target.closest(".snippet"), 12, 12);
emit("drag-snippet", snippet);
}
+8 -27
View File
@@ -1,24 +1,15 @@
/**
* The cover letter as data, with no Vue in it: the default letter, the JSON
* body stored in a CoverLetter row (stores/coverLetters.js), and the moves
* the drag and drop in CoverLetters.vue makes.
*
* Body shape (v: 1):
* The cover letter as plain data. Body shape (v: 1):
* { v, name, phone, email, role, signoff,
* sections: [{ id, title, paragraphs: [{ id, text }] }] }
*
* Every section and paragraph carries an id because the template keys its
* v-for on it. Keying on the index would leave a contenteditable showing the
* old text after a reorder, since Vue would reuse the element in place.
*
* A position is `{ section, index }`: a section's index and a paragraph's
* index inside it. `index` may equal the paragraph count, meaning "at the end".
* Ids exist because index keys would leave a contenteditable showing stale
* text after a reorder. A position is `{ section, index }`; index may equal
* the count, meaning the end.
*/
export const BODY_VERSION = 1;
/** A short id, unique enough within one letter. crypto.randomUUID would do,
* but it is missing outside a secure context (the dev stack over a LAN IP). */
/** crypto.randomUUID is missing outside a secure context (dev over a LAN IP). */
export function newId() {
return Math.random().toString(36).slice(2, 10) + Date.now().toString(36);
}
@@ -50,11 +41,7 @@ export function newLetter() {
const str = (v, fallback) => (typeof v === "string" ? v : fallback);
/**
* Read a stored body back into a letter. Anything missing or malformed
* falls back to the default field by field, so a hand-edited or older row
* still opens rather than blanking the page; ids are regenerated if absent.
*/
/** Malformed or missing fields fall back to defaults one by one. */
export function parseBody(json) {
const base = newLetter();
let raw;
@@ -88,8 +75,7 @@ export function parseBody(json) {
};
}
/** The JSON stored as a CoverLetter's body. Also what the "unsaved" marker
* compares, so the key order here must stay fixed. */
/** Also what "unsaved" compares, so key order must stay fixed. */
export function serialize(letter) {
return JSON.stringify({
v: BODY_VERSION,
@@ -106,12 +92,7 @@ export function serialize(letter) {
});
}
/**
* Move the paragraph at `from` to `to`, both positions as they are before the
* move. Moving down within one section shifts the target up by one once the
* paragraph has been taken out, which is corrected here so a drop lands where
* the indicator showed.
*/
/** Positions are as before the move; a downward move within a section is corrected. */
export function moveParagraph(letter, from, to) {
const src = letter.sections[from.section];
const dst = letter.sections[to.section];
+1 -11
View File
@@ -1,14 +1,4 @@
/*
* Shared styles for the CV templates (src/views/CV/CV*.vue).
*
* Loaded once, unscoped, by CV.vue. Each template wraps itself in
* <main class="cv-template"> and lays out each sheet as <div class="cv-page">.
*
* Colours are the site tokens from src/assets/styles.css. CVLayout.vue has
* already switched them to ink-on-paper; this file only adds the template's
* own accents (blue links, red table rules). Sizes are exposed as --cv-*
* variables so a template can tune them from its own scoped <style>.
*/
/* Shared CV template styles, loaded unscoped by CV.vue. --cv-* sizes are tunable per template. */
.cv-template {
--color-primary: black;
+2 -11
View File
@@ -1,16 +1,7 @@
<script setup>
/**
* Routes `/account` and `/no-access` (both `meta.requiresSignIn`): the landing
* page for a signed-in account that is not an admin, listing the gated
* services it has been granted (backend/services/permissions.go) as links.
*
* `/no-access` is where Caddy's permission gate sends a signed-in visitor who
* lacks the permission (`@auth_forbidden`, with the refused address in
* `?path=`). It is this same page with a notice on top, since "what can I
* open instead" is the useful answer to "you can't open that".
*
* The links are plain <a href>, not RouterLinks: every service lives in
* another container behind Caddy, so it needs a real page load.
* `/account` and `/no-access` (Caddy's permission gate refusal): the services
* this account may open. Plain <a href>, since they live behind Caddy.
*/
import { ref, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
+3 -10
View File
@@ -1,10 +1,5 @@
<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.
*/
/** Route `/admin`: a tab per create/manage form. */
import { ref, computed } from "vue";
import { useRouter } from "vue-router";
import { useAuthStore } from "@/stores/auth";
@@ -42,10 +37,8 @@ const activeSection = computed(() =>
sections.find((s) => s.id === active.value),
);
// The create forms emit "done"/"cancel" and leave it to the host to react
// (the Feed widget's modal closes on them). Here the form stays open, so
// "done" needs a visible confirmation, and "cancel" remounts the form via
// formKey, which is the only way to clear fields the form keeps to itself.
// The form stays open here, so "done" needs a notice and "cancel" remounts
// it via formKey to clear its fields.
const notice = ref("");
const formKey = ref(0);
+1 -4
View File
@@ -1,8 +1,5 @@
<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.
*/
/** Goes through stores/places.js so the row appears immediately. */
import Button from "@/components/input/Button.vue";
import { ref } from "vue";
import { usePlacesStore } from "@/stores/places";
+1 -5
View File
@@ -1,9 +1,5 @@
<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. The submit plumbing is shared via useCreateForm().
*/
/** Emits "done"/"cancel"; the host decides what to close. */
import Button from "@/components/input/Button.vue";
import { useCreateForm } from "@/js/useCreateForm";
+2 -7
View File
@@ -1,12 +1,7 @@
<script setup>
/**
* Admin form: upload photos of an erg monitor. The Go backend has each image read
* (by Claude, via the Python service) 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.
* Uploads erg photos to /api/rowing (multipart, so REST). Time comes back in
* nanoseconds.
*/
import Button from "@/components/input/Button.vue";
import { ref } from "vue";
+7 -29
View File
@@ -1,17 +1,8 @@
<script setup>
/**
* Route `/admin/login`, the one login page for everyone: admins and accounts
* granted a gated service (the receipt printer, say). On success redirects to
* `?redirect=`, or else to /admin for an admin and /account for anyone else
* (a non-admin would only bounce off /admin's guard back to here).
*
* The `?redirect=` is set by two different gates: the SPA router guard
* (`meta.requiresAdmin`) and Caddy's `forward_auth` gate in front of the
* proxied containers (/notes/, /sb/, /receipt/). The latter means the
* destination is frequently NOT a Vue route, so see goTo() below.
*
* auth.logIn() never throws — it swallows the error — so success is detected by
* re-reading `auth.loggedIn` afterwards rather than by a try/catch.
* Route `/admin/login` for every account. Redirects to `?redirect=`, else
* /admin or /account. Caddy's gates also set `?redirect=`, often to a non-Vue
* path (see goTo).
*/
import { ref } from "vue";
import { useRouter, useRoute } from "vue-router";
@@ -20,10 +11,7 @@ import { useAuthStore } from "@/stores/auth";
import Button from "@/components/input/Button.vue";
const auth = useAuthStore();
// Nothing else on this route resolves the session: the guard only runs for
// admin routes and the home query is not issued here. Without this, someone
// already signed in who opens /admin/login directly would see the login form
// instead of the "Already signed in" card.
// Nothing else here resolves the session, so a signed-in visitor would see the form.
auth.ensureLoaded();
const router = useRouter();
const route = useRoute();
@@ -32,17 +20,8 @@ const password = ref("");
const submitting = ref(false);
const errorMsg = ref("");
// Send the browser to `dest`, choosing SPA navigation vs. a real page load.
//
// Caddy bounces /notes/, /sb/, /receipt/ and the like here when the session
// is missing; those paths belong to other containers, so router.push() would just
// match the catch-all 404 route and never leave the SPA. Resolving the path
// first tells us which it is: the catch-all matches everything, so landing on
// the route named "404" means no real Vue route exists and the browser needs a
// full document request for Caddy to proxy it.
//
// `dest` comes from the query string, so it is only followed when it is a
// site-relative path — a leading "//" or a scheme would be an open redirect.
// Caddy-gated paths aren't Vue routes, so landing on "404" means a full page
// load. Only site-relative paths are followed, or it's an open redirect.
function goTo(dest) {
if (typeof dest !== "string" || !dest.startsWith("/") || dest.startsWith("//")) {
router.push(home());
@@ -65,8 +44,7 @@ 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.
// logIn() swallows errors, so re-read `loggedIn`.
await auth.logIn(username.value, password.value);
if (auth.loggedIn) {
goTo(route.query.redirect || home());
+2 -11
View File
@@ -1,16 +1,7 @@
<script setup>
/**
* Admin tab: the canvas pages made in the browser (views/canvas/). Lists them
* all, admin-only ones included, and creates new ones. A page's title,
* address and visibility are edited from "Page settings" on the page itself.
*
* "New shrine" is the same form with the address fixed under /shrines/. It
* starts blank and adds no link anywhere: /shrines is itself a canvas page,
* and its links are boxes put there by hand.
*
* "Layouts" lists the saved layouts (stores/layouts.js) and copies one onto
* any page without opening it — the same as "Load here" in that page's
* Layouts panel, where layouts are also saved and renamed.
* Admin tab: list and create canvas pages (a shrine is a page under
* /shrines/), and load saved layouts onto any page.
*/
import { usePagesStore } from "@/stores/pages";
import { pagePath, useLayoutsStore } from "@/stores/layouts";
+1 -6
View File
@@ -1,10 +1,5 @@
<script setup>
/**
* Admin panel: list and upload tracks for the Icecast radio. REST
* (multipart/form-data) rather than GraphQL because it moves files.
* Deleting removes the file from the radio's library for good, so it asks
* first; a failed list, enable/disable or delete is shown above the list.
*/
/** Radio tracks; REST because it moves files. Deleting is permanent, so it asks. */
import Button from "@/components/input/Button.vue";
import ConfirmDialog from "@/components/util/ConfirmDialog.vue";
import { ref, onMounted } from "vue";
+4 -15
View File
@@ -1,16 +1,7 @@
<script setup>
/**
* Admin panel: list users, toggle their admin flag, and grant non-admins the
* gated services in `permissionTypes` (the receipt printer and so on; see
* backend/services/permissions.go). Mutates the local `user` object in place
* from each mutation's response, so the row updates without a refetch. A
* failed load or change is shown above the table rather than only logged, and
* a row's controls are disabled while a change to it is in flight.
*
* Admins pass every permission check on the server, so their checkboxes are
* replaced with "all" rather than shown with grants that would mean nothing.
* A grant or revoke applies on the user's next request (the gate reads the
* database, not their token), so there is nothing to tell them to do.
* Users, admin flags and per-service grants. Admins show "all", since they
* pass every check anyway. Grants apply on the user's next request.
*/
import Button from "@/components/input/Button.vue";
import { ref, onMounted } from "vue";
@@ -58,10 +49,8 @@ function toggleAdmin(user) {
return change(user, () => auth.setUserAdmin(user.id, !user.admin));
}
// The mutation replaces the whole list, so send the row's list with this one
// key flipped. Afterwards the box is set from the row: on a failure the row
// is unchanged, so Vue sees nothing to patch and would leave the box showing
// the click that did not take.
// Reset the box from the row afterwards: on failure Vue sees no change and
// would leave the box showing the click that didn't take.
async function togglePermission(user, key, event) {
const current = user.permissions ?? [];
const next = current.includes(key)
+2 -11
View File
@@ -1,16 +1,7 @@
<script setup>
/**
* Route `/architecture` — how the whole site fits together, drawn.
*
* One long page of hand-written SVG diagrams, grouped into five sections
* (sections/*Section.vue), each of which lists its diagrams
* (diagrams/<section>/*.vue). Every diagram sits in a <DiagramFigure> and draws
* with the `dg-` classes in diagram.css; DiagramDefs supplies the shared
* arrowheads. No chart or graph library: the diagrams are static pictures of
* the code, so plain SVG is the smallest thing that does the job.
*
* The diagrams describe the code as it was when they were drawn. When a
* behaviour they show changes, redraw the diagram in the same commit.
* Route `/architecture`: hand-drawn SVG diagrams of the site. When a behaviour
* a diagram shows changes, redraw it in the same commit.
*/
import "./diagram.css";
import Header from "@/components/text/Header.vue";
+2 -11
View File
@@ -1,15 +1,6 @@
/*
* The diagram kit: every SVG on /architecture draws with these classes, so
* fifty-odd diagrams written separately still read as one set. Colours come
* from the site's design tokens (assets/styles.css), never literals.
*
* Not scoped: the classes are applied to elements inside each diagram
* component's own template, and a scoped block would only reach its own file.
* Everything is prefixed `dg-` so nothing leaks into the rest of the site.
*
* Arrowheads are <marker>s defined once on the page by DiagramDefs.vue and
* referenced by the edge classes below, so diagrams never declare their own
* (duplicate ids across many inline SVGs would collide).
* Shared, unscoped `dg-` diagram classes. Arrowhead markers live once in
* DiagramDefs.vue, since duplicate ids across inline SVGs collide.
*/
.dg {
@@ -5,7 +5,7 @@
AuthContextMiddleware -> gqlgen -> directive -> resolver. Everything ends at
handlers.Store.
Reflects: backend/main.go (r.Use, route groups, gqlSrv setup),
handlers/handle_auth.go (AuthMiddlewear, AdminMiddleware),
handlers/handle_auth.go (AuthMiddleware, AdminMiddleware),
graph/middleware.go, graph/directives.go, nginx/nginx_routes.conf.template.
-->
<template>
@@ -69,7 +69,7 @@
<text class="dg-code" x="340" y="275">GET /spotify/listening · GET /spotify/recent · GET /ws · GET /</text>
<!-- Lane 2: protected -->
<text class="dg-group-label" x="100" y="316">PROTECTED GROUP · r.Group("/", AuthMiddlewear)</text>
<text class="dg-group-label" x="100" y="316">PROTECTED GROUP · r.Group("/", AuthMiddleware)</text>
<rect class="dg-box dg-box--pink" x="100" y="330" width="190" height="60" rx="4" />
<text class="dg-title dg-title--sm dg-title--pink" x="195" y="354" text-anchor="middle">AUTHMIDDLEWEAR</text>
<text class="dg-text dg-text--pink" x="195" y="374" text-anchor="middle">bad token → 401</text>
@@ -81,7 +81,7 @@
<text class="dg-small" x="560" y="384">private=true checks the admin claim itself (requestIsAdmin)</text>
<!-- Lane 3: admin -->
<text class="dg-group-label" x="100" y="426">ADMIN GROUP · AuthMiddlewear, AdminMiddleware</text>
<text class="dg-group-label" x="100" y="426">ADMIN GROUP · AuthMiddleware, AdminMiddleware</text>
<rect class="dg-box dg-box--pink" x="100" y="450" width="190" height="60" rx="4" />
<text class="dg-title dg-title--sm dg-title--pink" x="195" y="474" text-anchor="middle">AUTHMIDDLEWEAR</text>
<text class="dg-text dg-text--pink" x="195" y="494" text-anchor="middle">bad token → 401</text>
@@ -147,7 +147,7 @@
<code>TrafficLogFormatter</code> and <code>Recovery</code>. After that there are four kinds of chain:
open routes ① that check cookies themselves if they need to, the <code>protected</code> group ②,
the <code>admin</code> group ③ (whose <code>AdminMiddleware</code> reads the claims
<code>AuthMiddlewear</code> stored, so the order matters), and GraphQL ④ (the animated path),
<code>AuthMiddleware</code> stored, so the order matters), and GraphQL ④ (the animated path),
which has no guard in front of it at all: each field's directive decides. Pink marks the auth
checks. <code>SetTrustedProxies</code> pins the Docker network so <code>ClientIP()</code>, which
the login rate limiter keys on, can't be spoofed with <code>X-Forwarded-For</code>.
@@ -53,7 +53,7 @@
<!-- 2 checks -->
<rect class="dg-box dg-box--tint" x="445" y="160" width="270" height="74" rx="3" />
<text class="dg-small" x="455" y="180">AuthMiddlewear → AdminMiddleware</text>
<text class="dg-small" x="455" y="180">AuthMiddleware → AdminMiddleware</text>
<text class="dg-small" x="455" y="198">exif.Decode → DateTime, else 400</text>
<text class="dg-small" x="455" y="216">≤ 10MB · jpeg / png / gif / webp only</text>
+26 -84
View File
@@ -1,25 +1,15 @@
<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.
* Route `/automata`: a mobile automaton simulator on a <canvas>. Each `delta`
* line is "<read>,<write>,<L|R>". Canvas can't read CSS variables, so colours
* here are literal.
*/
import { ref, computed, onMounted, onBeforeUnmount } from "vue";
import InlineLink from "@/components/text/InlineLink.vue";
import Header from "@/components/text/Header.vue";
import Paragraph from "@/components/text/Paragraph.vue";
// ---------------------------------------------------------------------------
// Presets
// ---------------------------------------------------------------------------
// ---- Presets ----
const PRESETS = [
{
id: "chaos",
@@ -59,10 +49,8 @@ const PRESETS = [
].join("\n"),
},
{
// The 5-state Busy Beaver champion Turing Machine, converted to a
// Mobile Automaton with the construction from the dissertation:
// each cell holds (symbol, state-or-κ); lowercase = state over a 0,
// uppercase = state over a 1. Halts (after ~47M steps!) on z/Z words.
// The 5-state Busy Beaver as a mobile automaton: lowercase = state
// over a 0, uppercase = state over a 1. Halts after ~47M steps.
id: "busybeaver",
name: "Busy Beaver — a 5-state Turing Machine, converted",
tape: "a",
@@ -125,9 +113,7 @@ const PRESETS = [
const STORAGE_KEY = "mobile-automata-config";
// ---------------------------------------------------------------------------
// Editable configuration
// ---------------------------------------------------------------------------
// ---- Editable configuration ----
const tapeStr = ref(PRESETS[0].tape);
const headStr = ref(String(PRESETS[0].head));
const blankSym = ref(PRESETS[0].blank);
@@ -143,9 +129,7 @@ const derivedF = ref("");
const errorMsg = ref("");
// ---------------------------------------------------------------------------
// Machine state
// ---------------------------------------------------------------------------
// ---- Machine state ----
let machine = null; // { n, delta: Map(word -> [outputChars, dir]), blank, gamma, accepting: Set }
let tape = []; // array of single-char symbols
let origin = 0; // cell index of tape[0]
@@ -157,8 +141,7 @@ 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.
// Logarithmic: slider 0..100 maps to 1..~2000 steps/sec.
const stepsPerSecond = computed(() =>
Math.max(1, Math.round(10 ** ((speed.value * 3.3) / 100))),
);
@@ -169,9 +152,7 @@ const statusText = computed(() => {
return running.value ? "Running" : "Paused";
});
// ---------------------------------------------------------------------------
// Parsing (same formats as the original simulator)
// ---------------------------------------------------------------------------
// ---- Parsing ----
function parseDelta(str) {
if (str.trim() === "")
throw new Error("Transition function cannot be empty");
@@ -202,8 +183,7 @@ 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. */
/** Every word of length n over `gamma`: the candidate halting words. */
function allWords(gamma, n) {
let words = [""];
for (let i = 0; i < n; i++) {
@@ -262,8 +242,7 @@ 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.
// Only when small, or a wide alphabet hangs the page.
if (machine.gamma.length ** n <= 4096) {
derivedF.value = allWords(machine.gamma, n)
.filter((w) => !delta.has(w))
@@ -298,16 +277,12 @@ 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.
// The tape is unbounded; absolute cell i lives at tape[i - origin].
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) {
@@ -320,15 +295,9 @@ function setCell(i, 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.
* One transition. No match halts; acceptance is decided by the word under the
* head, since state lives in the tape symbols.
* @returns {boolean} false if the machine halted.
*/
function stepMachine() {
if (!machine || terminated.value) return false;
@@ -348,9 +317,7 @@ function stepMachine() {
return true;
}
// ---------------------------------------------------------------------------
// Rendering
// ---------------------------------------------------------------------------
// ---- Rendering ----
const historyCanvas = ref(null);
const tapeCanvas = ref(null);
const canvasWrap = ref(null);
@@ -370,9 +337,7 @@ 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.
// Blank stays background-coloured so the plot shows only written cells.
function assignColors() {
colorOf = {};
let k = 0;
@@ -391,14 +356,7 @@ 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`.
*/
/** Bitmaps are sized in device pixels, so every constant is scaled by `dpr`. */
function resetCanvases() {
const hc = historyCanvas.value;
const tc = tapeCanvas.value;
@@ -425,13 +383,8 @@ function resetCanvases() {
}
/**
* 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.
* Appends one row of the space-time diagram. Old rows are scrolled by blitting
* the canvas onto itself, so each step costs the same however long it runs.
*/
function drawHistoryRow() {
if (!hctx || !machine) return;
@@ -473,9 +426,7 @@ 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. */
/** The close-up strip around the head, with the next read window highlighted. */
function drawTapeStrip() {
if (!tctx || !machine) return;
const tc = tapeCanvas.value;
@@ -509,21 +460,14 @@ function drawTapeStrip() {
}
}
// ---------------------------------------------------------------------------
// Animation loop
// ---------------------------------------------------------------------------
// ---- Animation loop ----
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.
* Steps accumulate as debt from elapsed time, so the rate is independent of
* refresh rate. dt is clamped (backgrounded tabs) and steps capped per frame.
*/
function frame(now) {
rafId = requestAnimationFrame(frame);
@@ -545,9 +489,7 @@ function frame(now) {
if (moved) drawTapeStrip();
}
// ---------------------------------------------------------------------------
// UI actions
// ---------------------------------------------------------------------------
// ---- UI actions ----
function onToggleRun() {
if (!machine || terminated.value) return;
running.value = !running.value;
+2 -10
View File
@@ -1,15 +1,7 @@
<script setup>
/**
* The router's catch-all: any path no other route claims is looked up as an
* admin-created canvas page (the `Page` GraphQL type) and, if there is one,
* rendered as a BoxCanvas whose page key is the slug. Otherwise it is the
* site's 404 — with, for an admin, a form to create a page right here.
*
* Static routes always win, which is why the server refuses slugs under the
* SPA's and Caddy's own paths (validateSlug in backend/graph/page_helpers.go).
*
* An adminOnly page answers null to anyone else, so to them it is simply a
* 404.
* The catch-all route: a canvas page for the slug, else the 404 (with a create
* form for admins). Hidden pages read as 404 to everyone else.
*/
import { computed, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
+3 -10
View File
@@ -1,11 +1,5 @@
<script setup>
/**
* Create a canvas page: its address, title, a starting layout from
* pageStarters.js, and whether only admins may see it. On success it opens
* the new page and emits `created`. Used on the admin panel's Pages tab
* (twice: any page, and a shrine under /shrines/) and on the 404 an admin sees
* at an address that has no page yet.
*/
/** Creates a canvas page with an optional starter layout, then opens it. */
import { ref } from "vue";
import { useRouter } from "vue-router";
import Button from "@/components/input/Button.vue";
@@ -44,9 +38,8 @@ async function submit() {
busy.value = true;
try {
const page = await pages.create({ slug: fullSlug, title: title.value.trim(), adminOnly: adminOnly.value });
// Page first, then its boxes: a starter that fails halfway leaves a page
// with some boxes, which is easy to finish by hand, rather than boxes
// under an address with no page.
// Page first: a half-failed starter leaves a page with some boxes, not
// boxes under no page.
const boxes = useBoxesStore(page.slug);
for (const box of STARTERS.find((s) => s.id === starter.value).boxes(page.title)) {
await boxes.create(box);
+1 -9
View File
@@ -1,12 +1,4 @@
/**
* Starting layouts for a new canvas page, offered when one is created
* (PageForm.vue). Each `boxes(title)` returns box inputs for
* stores/boxes.js — without `page`, which the store adds. Everything is an
* ordinary box afterwards: move it, edit it, delete it.
*
* These are built into the code; layouts saved from a page in the browser
* live in stores/layouts.js and are loaded from the canvas's Layouts panel.
*/
/** Built-in starting layouts for a new page; `boxes(title)` omits `page`. */
import { defaultLayout } from "@/views/home3/defaultLayout";
const html = (title, body, geom, extra = {}) => ({ kind: "html", title, html: body, ...geom, ...extra });
-4
View File
@@ -1,8 +1,4 @@
<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";
-4
View File
@@ -1,8 +1,4 @@
<script setup>
/**
* "鸟" widget on /stp — a <Slideshow>. The Places list that used to share it
* as a second tab is its own widget now, views/home/Places.vue.
*/
import Slideshow from "@/components/util/Slideshow.vue";
const images = [{ url: "/img/memes/pidgeon.gif", comment: "鸟" }];
-4
View File
@@ -1,8 +1,4 @@
<script setup>
/**
* "Consumption" widget on /stp (books/films/games logged as activities). Same
* shape as Favorites.vue — both are ListWidget.vue with a different store.
*/
import ListWidget from "@/views/home/ListWidget.vue";
import { defineAsyncComponent } from "vue";
-4
View File
@@ -1,8 +1,4 @@
<script setup>
/**
* "Favorites" widget on /stp. All of the markup lives in ListWidget.vue; this
* file only binds the favourites store and the (lazily imported) create form.
*/
import ListWidget from "@/views/home/ListWidget.vue";
import { defineAsyncComponent } from "vue";
+1 -5
View File
@@ -1,9 +1,5 @@
<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.
*/
/** Blog posts one at a time; delete only for the author. */
import Button from "@/components/input/Button.vue";
import Markdown from "@/components/util/Markdown.vue";
import Modal from "@/components/util/Modal.vue";
+3 -21
View File
@@ -1,20 +1,5 @@
<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.
*/
/** The "Rowing" widget on /stp: a hand-drawn SVG chart of sessions. */
import { ref, computed, defineAsyncComponent } from "vue";
import Header from "@/components/text/Header.vue";
import Modal from "@/components/util/Modal.vue";
@@ -32,8 +17,7 @@ const showCreate = ref(false);
// slice() first: reverse() mutates in place and would reorder the store's array.
const rows = computed(() => rowingSessions.value.slice().reverse());
// `settled`, not `loaded`: a home query that fails never sets `loaded`, and the
// error branch below would be unreachable behind a permanent spinner.
// `settled`, not `loaded`, or a failed query spins forever.
const loading = computed(() => !settled.value);
const metric = ref("distance");
@@ -70,9 +54,7 @@ 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.
// `range || 1` guards identical values; a single point is centred.
const points = computed(() => {
const data = chartData.value;
const n = data.length;
+2 -25
View File
@@ -1,28 +1,7 @@
<script setup>
/**
* STATUS: legacy — no route points here. `/stp` is now a canvas page (see
* views/canvas/CanvasPage.vue); views/home3/defaultLayout.js is this page's
* arrangement redrawn as boxes, offered as the "Old /stp grid" starter.
* Kept for reference.
*
* Was 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.
*
* Below 1360px there is no room for the sidebars, so their widgets collapse
* into a single tabbed panel under the sheet. That is done purely in CSS — the
* tab bar only sets `data-tab` on the wrapper and the media query hides the
* other widgets — so every widget stays mounted exactly once at every width
* (Chat holds a WebSocket, Steam a rotation timer) and resizing across the
* breakpoint loses no state.
*
* 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: Intro3 and Gym2, not Intro/Intro2/Gym.
* STATUS: legacy — no route points here. `/stp` is a canvas page now;
* views/home3/defaultLayout.js is this grid redrawn as boxes. Kept for reference.
*/
import Timer from "@/components/util/Timer.vue";
import Time from "@/components/util/Time.vue";
@@ -45,8 +24,6 @@ import Bookmarks from "./Bookmarks.vue";
import { ref } from "vue";
// Small-screen tab bar. `id` matches the [data-tab] selectors in the tablet
// media query below.
const TABS = [
{ id: "chat", label: "Chat" },
{ id: "bookmarks", label: "Bookmarks" },
+2 -11
View File
@@ -1,16 +1,7 @@
<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.
* Bouncing phrases. Animation state is a plain array, not the reactive
* `items`, to avoid a re-render per frame; sizes are cached until resize.
*/
import { rand } from "@vueuse/core";
import { ref, onMounted, onUnmounted, nextTick } from "vue";
+3 -15
View File
@@ -1,20 +1,8 @@
<script setup lang="ts">
/**
* Intro tile: Bad Apple rendered as ASCII text.
*
* Source is `vue/public/img/badapple.mp4`, bound via a const rather than written
* as a literal `src` because Vite would otherwise try to resolve it as a bundled
* asset import; files under public/ are served as-is and must stay unbundled.
*
* The <video> stays in the DOM (hidden,
* muted, looping) because only a playing element decodes frames — drawing a
* detached/paused video to a canvas yields nothing.
*
* Per frame we downscale the video straight into a tiny canvas whose pixel grid
* IS the character grid, so the browser's scaler does the averaging for us and
* we read back exactly one pixel per character. Sampling is throttled to ~24fps
* (source framerate); the grid is only re-measured on resize, since reading
* offsetWidth every frame forces a synchronous layout.
* Bad Apple as ASCII. The src is a const so Vite doesn't bundle a public/
* file. The hidden <video> must keep playing to decode frames. Each frame is
* downscaled into a canvas whose pixels are the character grid.
*/
import { ref, useTemplateRef, onMounted, onUnmounted } from "vue";
-4
View File
@@ -1,8 +1,4 @@
<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";
+1 -9
View File
@@ -1,13 +1,5 @@
<script setup>
/**
* Shared shape of the "favs" and "Consumption" widgets on /stp: a header with a
* create toggle, a self-scrolling <AutoScroll> list rendered through
* <LinkTable>, and an admin-only create form in a <Modal>.
*
* `createForm` is the component to show in the modal. The hosts pass a
* defineAsyncComponent() so the admin form is still only fetched when a widget
* is actually opened.
*/
/** Shared list widget; hosts pass `createForm` as an async component. */
import Header from "@/components/text/Header.vue";
import CreateToggle from "@/components/input/CreateToggle.vue";
import LinkTable from "@/components/util/LinkTable.vue";
+3 -14
View File
@@ -1,10 +1,5 @@
<script setup>
/**
* "Listening" widget on /stp: rotates through recent Spotify plays.
*
* Two timers, both owned by useRotation(): a 5s rotation and a 2-minute re-poll
* of Spotify.
*/
/** Rotates recent Spotify plays (5s) and re-polls every 2 minutes. */
import Header from "@/components/text/Header.vue";
import { computed, onMounted } from "vue";
import { useSongsStore } from "@/stores/songs";
@@ -24,19 +19,13 @@ const { idx, next: nextSong } = useRotation(() => songsStore.songs, ROTATE_MS, {
const song = computed(() => songsStore.songs[idx.value]);
// Admin-only reconnect: when spotifyNeedsReauth comes back true the backend
// has no Spotify client (OAuth never completed or the token was revoked), so
// the widget offers the OAuth start endpoint instead of the template song.
// Non-admins get none of this.
// Admin-only: offers the OAuth start when the backend has no Spotify client.
const auth = useAuthStore();
const showReconnect = computed(
() => auth.loggedIn && auth.user.admin && songsStore.needsReauth,
);
// GET /api/spotify/auth returns { url } — the Spotify authorisation URL with
// a one-shot state nonce. Navigating to it runs the OAuth dance; the callback
// installs the client server-side. Errors are swallowed: the widget simply
// stays as it was.
// Errors are swallowed; the widget stays as it was.
async function reconnect() {
try {
const { url } = await api.get("/spotify/auth");
+1 -5
View File
@@ -1,10 +1,6 @@
<script setup>
/**
* Places-to-go widget: the <PlacesTable> under a header whose "+" opens the
* create form. Sign-in only, like the places mutations themselves, so a
* signed-out visitor gets a one-line prompt instead of an empty table.
*
* Its own "+" rather than <CreateToggle>, because that one is admin-only and
* Places widget. Its own "+" rather than <CreateToggle>, which is admin-only:
* any signed-in user may add a place.
*/
import { computed, ref } from "vue";
+3 -10
View File
@@ -1,11 +1,5 @@
<script setup>
/**
* The Places-to-go table inside the Places widget (Places.vue). 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.
*/
/** Sign-in only; fetched lazily, at most once. */
import { computed, onMounted, ref, watch } from "vue";
import { usePlacesStore } from "@/stores/places";
import { useAuthStore } from "@/stores/auth";
@@ -17,9 +11,8 @@ const loggedIn = computed(() => auth.loggedIn);
const removeTarget = ref(null);
const confirmationOpen = ref(false);
// 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 for the already signed in, the watcher for signing in later;
// !loaded && !loading stops both firing.
onMounted(() => {
if (loggedIn.value && !places.loaded && !places.loading) places.fetch();
});
+6 -31
View File
@@ -1,17 +1,7 @@
<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 the
* wall is re-sized whenever the cell is.
*
* The wall is a fixed-track grid whose column and row counts are derived from
* the cell's own size (see fitWall), so it always overflows on both axes. A
* wrapping flex row only overflowed when the cell happened to be narrower than
* the wall, which left it motionless at tablet widths.
* 88x31 webring stamps on /stp, drifting and bouncing. The grid is sized from
* the cell (fitWall) so it always overflows both axes.
*/
import { ref, computed, onMounted, onUnmounted } from "vue";
@@ -32,8 +22,6 @@ let srcs = [
"/img/stamps/tf2.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);
// The two linked stamps stay first; the shuffled local ones follow.
@@ -54,9 +42,7 @@ const touchscreen = ref(null);
const cols = ref(4);
const rows = ref(4);
// Every grid slot is filled, cycling through the stamps when the wall needs
// more slots than there are stamps — a ragged last row would leave a blank
// strip drifting into view.
// Cycle stamps to fill every slot; a ragged row would show a blank strip.
const cells = computed(() =>
Array.from(
{ length: cols.value * rows.value },
@@ -64,11 +50,7 @@ const cells = computed(() =>
),
);
/**
* Size the wall to between one and two stamps larger than the cell on each
* axis, so there is always something to bounce across whatever the page size.
* Rows are also raised, if need be, until every stamp appears at least once.
*/
/** One to two stamps larger than the cell per axis; enough rows to show every stamp. */
function fitWall() {
const el = touchscreen.value?.$el;
if (!el) return;
@@ -87,13 +69,7 @@ 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 fitWall changes the bounds whenever the cell is resized.
*/
/** Writes scroll position directly (no re-render) and re-reads bounds each frame. */
function bounce() {
const el = touchscreen.value?.$el;
if (!el) return;
@@ -129,8 +105,7 @@ function bounce() {
onMounted(() => {
fitWall();
// The cell's size follows the box it sits in, not just window resizes, so
// observe the element.
// The cell follows its box, not just the window.
resizeObserver = new ResizeObserver(fitWall);
resizeObserver.observe(touchscreen.value.$el);
animId = requestAnimationFrame(bounce);
+1 -7
View File
@@ -1,11 +1,5 @@
<script setup>
/**
* Steam widget on /stp: online status plus a rotation through recent games
* (5s rotation, 5-minute re-poll, both from useRotation()). `settled` comes from
* homeData so the widget can tell "not fetched yet" from "fetched, nothing to
* show" — and, unlike `loaded`, it also turns true when the fetch fails, so the
* widget cannot sit on "Loading..." forever.
*/
/** Online status and recent games. Uses `settled` so a failure can't spin forever. */
import { computed } from "vue";
import { storeToRefs } from "pinia";
import { useSteamStore } from "@/stores/steam";
+1 -7
View File
@@ -1,11 +1,5 @@
<script setup>
/**
* STATUS: no route points here — removed so /shrines/demoman can be made
* again as a canvas page (views/canvas/CanvasPage.vue). The clips are still
* in public/img/demoman/.
*
* Was route `/shrines/demoman` — a wall of TF2 Demoman clips via <VideoTable>.
*/
/** STATUS: unrouted; /shrines/<name> are canvas pages now. */
import VideoTable from "@/components/util/VideoTable.vue";
import Link from "@/components/text/Link.vue";
+1 -6
View File
@@ -1,10 +1,5 @@
<script setup>
/**
* STATUS: no route points here — /shrines/<name> is a canvas page now
* (views/canvas/CanvasPage.vue), created from the /shrines index.
*
* Was route `/shrines/evangelion` — placeholder, renders <Wip>.
*/
/** STATUS: unrouted; /shrines/<name> are canvas pages now. */
import Wip from "@/components/util/Wip.vue";
</script>
+1 -6
View File
@@ -1,10 +1,5 @@
<script setup>
/**
* STATUS: no route points here — /shrines/<name> is a canvas page now
* (views/canvas/CanvasPage.vue), created from the /shrines index.
*
* Was route `/shrines/gto` — placeholder, renders <Wip>.
*/
/** STATUS: unrouted; /shrines/<name> are canvas pages now. */
import Wip from "@/components/util/Wip.vue";
</script>
+1 -10
View File
@@ -1,14 +1,5 @@
<script setup>
/**
* STATUS: unused — unrouted. /shrines is now an admin-made canvas page whose
* links are boxes; new shrines are made on the admin panel's Pages tab.
*
* Was route `/shrines` — index of the shrine pages: every canvas page
* (views/canvas/) whose address starts with "shrines/", from the pages query.
* Admins — and only admins; the server refuses createPage to anyone else
* anyway — get a button that opens a form to start one from the Shrine
* layout (since removed).
*/
/** STATUS: unrouted; /shrines is a canvas page now. */
import { computed, ref } from "vue";
import RouterTable from "@/components/util/RouterTable.vue";
import { useAuthStore } from "@/stores/auth";
@@ -1,10 +1,5 @@
<script setup>
/**
* STATUS: no route points here — /shrines/<name> is a canvas page now
* (views/canvas/CanvasPage.vue), created from the /shrines index.
*
* Was route `/shrines/skipskipbenben` — placeholder, renders <Wip>.
*/
/** STATUS: unrouted; /shrines/<name> are canvas pages now. */
import Wip from "@/components/util/Wip.vue";
</script>

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