Trim comments to the non-obvious why
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:
+4
-15
@@ -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();
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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,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;
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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,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,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";
|
||||
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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,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";
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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>
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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,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 });
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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: "鸟" }];
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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,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";
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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" },
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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";
|
||||
|
||||
|
||||
@@ -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,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";
|
||||
|
||||
@@ -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,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";
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
|
||||
@@ -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,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,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,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,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,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>
|
||||
|
||||
|
||||
@@ -1,13 +1,7 @@
|
||||
<script setup>
|
||||
/**
|
||||
* The admin's background panel for one canvas page, opened from BoxCanvas's
|
||||
* "Background" button: a colour, an image (uploaded, dropped on the panel,
|
||||
* chosen from what is already uploaded, or given as a URL) and how the image
|
||||
* fills the window.
|
||||
*
|
||||
* Every change previews live through the background store; Cancel (or
|
||||
* closing) puts the saved one back. Saving with neither colour nor image is
|
||||
* the same as "Theme default", which removes the page's background.
|
||||
* Background panel. Changes preview live; Cancel restores the saved one.
|
||||
* Saving with neither colour nor image removes the background.
|
||||
*/
|
||||
import { computed, onBeforeUnmount, ref, watch } from "vue";
|
||||
import { FITS, useBackgroundStore } from "@/stores/background";
|
||||
|
||||
@@ -1,44 +1,10 @@
|
||||
<script setup>
|
||||
/**
|
||||
* A free-form canvas of boxes the admin arranges in the browser, for one page
|
||||
* key (see stores/boxes.js). The landing page and every admin-created page
|
||||
* (views/canvas/CanvasPage.vue, /stp included) are this component.
|
||||
*
|
||||
* Every box (the `Box` GraphQL type) has a position, size and z-index in px
|
||||
* on a fixed CANVAS_W-wide design canvas. The canvas is drawn at that width
|
||||
* and shrunk with transform: scale() to fit narrower windows, so what the
|
||||
* admin arranges is exactly what every desktop visitor sees, just smaller.
|
||||
* The canvas is as tall as its lowest box.
|
||||
*
|
||||
* At phone width the canvas would be unreadably small, so the boxes are laid
|
||||
* out in a single column instead: reading order is top-to-bottom then
|
||||
* left-to-right by their canvas position, each keeps its height, and any box
|
||||
* flagged hideOnMobile is skipped. There is no separate mobile layout to
|
||||
* maintain, and no editing at that width.
|
||||
*
|
||||
* Admins get an Edit toggle. In edit mode boxes drag and resize (BoxFrame),
|
||||
* changes save on release, and the selected box opens in BoxEditor. A dragged
|
||||
* box snaps its edges and centre to other boxes' and to the canvas's sides
|
||||
* and centre, drawing a guide along each line it shares (./alignment.js); the
|
||||
* Align button turns that off, and Ctrl/⌘ while dragging skips it once. Boxes
|
||||
* marked adminOnly are never sent to anyone else (the server filters them);
|
||||
* admins see them outlined. Image and video files dropped onto the canvas in
|
||||
* edit mode are uploaded and each becomes a box where it was dropped; "+ From
|
||||
* uploads" does the same with a file that is already uploaded.
|
||||
*
|
||||
* The canvas also owns its page's background (stores/background.js), which
|
||||
* DefaultLayout paints behind the whole window while the canvas is mounted;
|
||||
* admins change it with the Background button.
|
||||
*
|
||||
* The Layouts button saves the page as a named layout, or loads a saved one
|
||||
* onto it (LayoutPanel.vue, stores/layouts.js) — which is how a layout moves
|
||||
* from one page to another.
|
||||
*
|
||||
* "+ New box" offers the saved components (stores/components.js) as starters,
|
||||
* each placed as an ordinary box with a copy of its html, plus the widgets.
|
||||
* The Components button (ComponentPanel.vue) places them linked as well: a
|
||||
* linked box shows its component's html, so editing it in BoxEditor edits
|
||||
* every box linked to that component. Linked boxes are labelled with ⛓.
|
||||
* A canvas of admin-arranged boxes for one page key (stores/boxes.js), used
|
||||
* by the landing page and every CanvasPage. Boxes are px on a fixed
|
||||
* CANVAS_W-wide canvas scaled to fit, so every desktop visitor sees the same
|
||||
* arrangement. At phone width they stack in reading order instead (no
|
||||
* editing, hideOnMobile skipped). The canvas also owns its page's background.
|
||||
*/
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
|
||||
import { useMediaQuery } from "@vueuse/core";
|
||||
@@ -63,8 +29,7 @@ import { isVideo, mediaSize, uploadFile } from "@/uploads";
|
||||
|
||||
const props = defineProps({
|
||||
page: { type: String, required: true },
|
||||
// Layout offered by the "Import starter layout" button in edit mode: a
|
||||
// function returning box inputs, or null for no button.
|
||||
// Returns box inputs for "Import starter layout", or null for no button.
|
||||
starter: { type: Function, default: null },
|
||||
starterLabel: { type: String, default: "Import starter layout" },
|
||||
});
|
||||
@@ -74,9 +39,7 @@ const MOBILE_QUERY = "(max-width: 700px)";
|
||||
|
||||
const auth = useAuthStore();
|
||||
const store = useBoxesStore(props.page);
|
||||
// The standalone `me` query, not the home query: a canvas of only HTML boxes
|
||||
// mounts no widget, and the landing page must not fan out to Spotify and
|
||||
// Steam just to learn whether to show an Edit button.
|
||||
// Not the home query: an HTML-only canvas mustn't fan out to Spotify and Steam.
|
||||
auth.ensureLoaded();
|
||||
|
||||
store.fetch();
|
||||
@@ -84,15 +47,12 @@ store.fetch();
|
||||
const background = useBackgroundStore();
|
||||
background.show(props.page);
|
||||
onBeforeUnmount(() => background.hide(props.page));
|
||||
// Which of the left-hand panels is open: "background", "layouts",
|
||||
// "components" or null. They sit in the same place, so only one at a time.
|
||||
// "background", "layouts", "components" or null; they share one spot.
|
||||
const panel = ref(null);
|
||||
const confirmation = ref(null);
|
||||
|
||||
const isMobile = useMediaQuery(MOBILE_QUERY);
|
||||
const isAdmin = computed(() => auth.loggedIn && !!auth.user.admin);
|
||||
// adminOnly boxes come and go with the session, and so does an adminOnly
|
||||
// page's background.
|
||||
watch(isAdmin, () => {
|
||||
store.fetch();
|
||||
background.load(props.page);
|
||||
@@ -122,8 +82,7 @@ onMounted(() => {
|
||||
if (viewport.value) observer.observe(viewport.value);
|
||||
});
|
||||
onBeforeUnmount(() => observer?.disconnect());
|
||||
// The viewport is only rendered on desktop, so it appears and disappears as
|
||||
// the window crosses the phone breakpoint.
|
||||
// Only rendered on desktop, so it comes and goes at the breakpoint.
|
||||
watch(viewport, (el, old) => {
|
||||
if (old) observer?.unobserve(old);
|
||||
if (el) observer?.observe(el);
|
||||
@@ -131,15 +90,11 @@ watch(viewport, (el, old) => {
|
||||
|
||||
const scale = computed(() => Math.min(1, availableW.value / CANVAS_W));
|
||||
const contentH = computed(() => Math.max(0, ...store.boxes.map((b) => b.y + b.h)));
|
||||
// Spare room below the lowest box while editing, so there is somewhere to
|
||||
// drag to.
|
||||
// Spare room to drag into while editing.
|
||||
const canvasH = computed(() => Math.max(400, contentH.value + (inEditMode.value ? 400 : 40)));
|
||||
|
||||
// ---- Alignment -----------------------------------------------------------
|
||||
// What a dragged box can line up with: every other box, and the canvas. Only
|
||||
// the dragged box reports guides, so one list serves the whole canvas. One
|
||||
// function for every BoxFrame, so redrawing the guides on each pointermove
|
||||
// doesn't hand every frame a new prop and redraw it too.
|
||||
// One shared callback, so redrawing guides doesn't re-render every BoxFrame.
|
||||
const guides = ref([]);
|
||||
function targetsFor(box) {
|
||||
return snapping.value ? snapTargets(store.boxes.filter((b) => b.id !== box.id), CANVAS_W) : null;
|
||||
@@ -164,9 +119,7 @@ function report(err) {
|
||||
setTimeout(() => (errorMsg.value = ""), 6000);
|
||||
}
|
||||
|
||||
// The new geometry is applied locally before the request so the box stays
|
||||
// where it was dropped instead of snapping back until the server answers;
|
||||
// on failure it is put back.
|
||||
// Applied optimistically, reverted on failure.
|
||||
async function commitGeometry(box, geom) {
|
||||
const before = { x: box.x, y: box.y, w: box.w, h: box.h };
|
||||
Object.assign(box, geom);
|
||||
@@ -231,14 +184,11 @@ function labelOf(box) {
|
||||
// ---- Creating ------------------------------------------------------------
|
||||
const canvasEl = ref(null);
|
||||
|
||||
// Top-left of the part of the canvas currently on screen, so a new box
|
||||
// appears where the admin is looking rather than at the top of the page.
|
||||
// So a new box appears where the admin is looking.
|
||||
function visibleOrigin() {
|
||||
const rect = canvasEl.value?.getBoundingClientRect();
|
||||
const top = rect ? Math.max(0, -rect.top / scale.value) : 0;
|
||||
const origin = { x: 40, y: Math.round(top / 5) * 5 + 40 };
|
||||
// Cascade, so adding several boxes in a row doesn't stack them exactly on
|
||||
// top of one another.
|
||||
while (store.boxes.some((b) => b.x === origin.x && b.y === origin.y)) {
|
||||
origin.x += 20;
|
||||
origin.y += 20;
|
||||
@@ -269,9 +219,7 @@ function addBox() {
|
||||
});
|
||||
}
|
||||
|
||||
// From "+ New box" (always a copy) or the Components panel (either). The
|
||||
// panel is closed, like selecting a box closes it, since the new box opens in
|
||||
// the editor and lands where the panel would cover it.
|
||||
// The panel closes because the new box opens in the editor beneath it.
|
||||
function placeComponent(component, linked) {
|
||||
panel.value = null;
|
||||
run(async () => {
|
||||
@@ -280,9 +228,7 @@ function placeComponent(component, linked) {
|
||||
});
|
||||
}
|
||||
|
||||
// Offered on a canvas that already has boxes too — the landing page had notes
|
||||
// pinned over its old content before that content became boxes — but then
|
||||
// it asks first, since importing twice doubles every box.
|
||||
// Asks first on a non-empty canvas, since importing twice doubles every box.
|
||||
const importing = ref(false);
|
||||
async function importStarter() {
|
||||
const count = store.boxes.length;
|
||||
@@ -314,8 +260,7 @@ function isMedia(file) {
|
||||
return file.type.startsWith("image/") || file.type.startsWith("video/");
|
||||
}
|
||||
|
||||
// A box showing one stored image or video at (x, y), sized to the file's own
|
||||
// aspect ratio so nothing is cropped. Selected once made.
|
||||
// Sized to the file's aspect ratio so nothing is cropped.
|
||||
async function placeMedia(url, size, title, x, y) {
|
||||
const fit = size ? Math.min(1, DROP_MAX / Math.max(size.w, size.h)) : 1;
|
||||
const created = await store.create({
|
||||
@@ -332,8 +277,6 @@ async function placeMedia(url, size, title, x, y) {
|
||||
selectedId.value = created.id;
|
||||
}
|
||||
|
||||
// Each file is uploaded and placed at the drop point, then cascaded like
|
||||
// visibleOrigin().
|
||||
async function onDrop(event) {
|
||||
dragOver.value = false;
|
||||
const files = [...(event.dataTransfer?.files ?? [])].filter(isMedia);
|
||||
@@ -369,8 +312,7 @@ async function placePicked(url) {
|
||||
}
|
||||
|
||||
// ---- Selection -----------------------------------------------------------
|
||||
// Leaving a box saves its unsaved HTML; BoxEditor does that itself as the
|
||||
// selection changes or it unmounts.
|
||||
// BoxEditor saves unsaved HTML itself when the selection changes.
|
||||
function select(box) {
|
||||
panel.value = null;
|
||||
selectedId.value = box.id;
|
||||
|
||||
@@ -1,32 +1,9 @@
|
||||
<script setup>
|
||||
/**
|
||||
* Side panel for the selected box in edit mode.
|
||||
*
|
||||
* Two save rhythms, matching how each kind of field is used:
|
||||
* - Settings (title, geometry, frame, shadow, mobile, widget) save as soon as they
|
||||
* change — on blur/Enter for numbers, on change for the rest — the same
|
||||
* "instant" model as dragging.
|
||||
* - HTML is a draft. Typing updates the box on the canvas live (through the
|
||||
* `preview` event, so the parent can render the draft without touching the
|
||||
* store) and is saved by Save or Ctrl/Cmd+S, or automatically on leaving
|
||||
* the box: selecting another one, clicking empty canvas, Done, or closing
|
||||
* the panel. Saving every keystroke would push half-written markup to
|
||||
* every visitor; leaving is the point it is finished.
|
||||
*
|
||||
* A box linked to a component (stores/components.js) edits the component: its
|
||||
* html is saved there, and so changes on every box linked to it. Detach gives
|
||||
* the box its own copy — an unsaved draft is kept, and then saves to this box
|
||||
* alone. An unlinked html box can be saved as a new component, which links it.
|
||||
*
|
||||
* "Insert upload" uploads a file (@/uploads) and puts a tag for it at the
|
||||
* cursor — the way to add pictures to an existing box, e.g. a gallery.
|
||||
* "Choose upload" does the same with a file that is already uploaded.
|
||||
*
|
||||
* The panel is teleported to <body>, so it is fixed to the window whatever
|
||||
* transform or stacking context the page puts around the canvas. Its width
|
||||
* (drag the left edge; double-click it to reset) and the code's text size
|
||||
* (A−/A+, or Ctrl/Cmd with +, - or 0 in the editor) are remembered per
|
||||
* browser through ./editorPrefs.
|
||||
* Side panel for the selected box. Settings save on change; HTML is a draft
|
||||
* shown live via `preview` and saved on Save, Ctrl/Cmd+S or leaving the box,
|
||||
* so visitors never see half-written markup. A linked box edits its
|
||||
* component. Teleported to <body> so the canvas's transforms don't move it.
|
||||
*/
|
||||
import { computed, onBeforeUnmount, ref, watch } from "vue";
|
||||
import { useBoxesStore } from "@/stores/boxes";
|
||||
@@ -68,17 +45,13 @@ function storeHtml(box, html) {
|
||||
return box.componentId ? components.update(box.componentId, { html }) : store.update(box.id, { html });
|
||||
}
|
||||
|
||||
// Save the draft of box `id` if it differs from what is stored. Fire and
|
||||
// forget: it runs as the editor moves on or unmounts, with nothing left to
|
||||
// show progress in, so a failure is only reported through `error`.
|
||||
// Fire and forget; failures surface through `error`.
|
||||
function flush(id) {
|
||||
const box = store.boxes.find((b) => b.id === id);
|
||||
if (!box || box.kind !== "html" || draftHtml.value === (box.html ?? "")) return;
|
||||
storeHtml(box, draftHtml.value).catch((err) => emit("error", err));
|
||||
}
|
||||
|
||||
// Switching to another box: save the old one's draft, drop its preview, start
|
||||
// from the new box's saved html.
|
||||
watch(
|
||||
() => props.box.id,
|
||||
(_, oldId) => {
|
||||
@@ -102,8 +75,7 @@ watch(draftHtml, (html) => {
|
||||
previewTimer = setTimeout(() => emit("preview", dirty.value ? html : null), 300);
|
||||
});
|
||||
|
||||
// Starting points for a box's shadow, which is any CSS box-shadow value.
|
||||
// Ticking "Shadow" uses the first; the text field takes anything else.
|
||||
// "Shadow" ticks the first; the text field takes any box-shadow.
|
||||
const SHADOWS = {
|
||||
Hard: "6px 6px 0 var(--color-quaternary)",
|
||||
Soft: "0 6px 18px rgb(0 0 0 / 0.5)",
|
||||
@@ -136,8 +108,7 @@ async function saveHtml() {
|
||||
}
|
||||
}
|
||||
|
||||
// The draft is saved to the box first, so the component starts from what is
|
||||
// on screen.
|
||||
// Save the draft first so the component starts from what is on screen.
|
||||
async function saveAsComponent() {
|
||||
const name = componentName.value.trim();
|
||||
if (!name) return;
|
||||
@@ -193,10 +164,7 @@ function close() {
|
||||
emit("close");
|
||||
}
|
||||
|
||||
// The panel is pinned to the right of the window, so its width is simply the
|
||||
// distance from the pointer to that edge. Pointer capture keeps the drag
|
||||
// alive when the pointer crosses a box's iframe, which would otherwise take
|
||||
// the events.
|
||||
// Pointer capture keeps the drag alive over a box's iframe.
|
||||
function startResize(event) {
|
||||
if (event.button !== 0) return;
|
||||
event.preventDefault();
|
||||
|
||||
@@ -1,23 +1,8 @@
|
||||
<script setup>
|
||||
/**
|
||||
* One positioned box on the canvas, plus its edit-mode drag/resize overlay.
|
||||
*
|
||||
* Geometry is canvas px (see models.Box). The canvas is drawn with
|
||||
* transform: scale(), so pointer deltas, which are screen px, are divided by
|
||||
* `scale` before they are applied.
|
||||
*
|
||||
* In edit mode an overlay covers the whole box. That is what makes dragging
|
||||
* work at all over an HTML box: pointer events that land on an iframe go to
|
||||
* the iframe's document and never reach this one. It also means the box
|
||||
* contents can't be clicked while editing, which is intended — leave edit mode
|
||||
* to use them.
|
||||
*
|
||||
* While a drag is in progress the box draws from a local `draft`. On release
|
||||
* the final geometry is emitted once as `commit`; the parent saves it. A press
|
||||
* that never moves is a click (select only) and commits nothing. Drags snap
|
||||
* to the lines `targets` returns (see ./alignment.js), and the guides for
|
||||
* what the box currently lines up with are emitted as `guides` for the canvas
|
||||
* to draw, since a guide runs outside this box.
|
||||
* One box plus its edit-mode overlay. Pointer deltas are divided by `scale`.
|
||||
* The overlay is needed because events over an iframe never reach us. A
|
||||
* press with no movement selects without committing.
|
||||
*/
|
||||
import { computed, toRef } from "vue";
|
||||
import { useBoxInteraction } from "./useBoxInteraction";
|
||||
@@ -86,9 +71,7 @@ const style = computed(() => ({
|
||||
top: `${geom.value.y}px`,
|
||||
width: `${geom.value.w}px`,
|
||||
height: `${geom.value.h}px`,
|
||||
// The selected box is lifted above everything while editing: its resize
|
||||
// handles sit just outside its edges, where an overlapping neighbour with a
|
||||
// higher z would otherwise cover them and take the press.
|
||||
// Lifted so neighbours can't cover its outside resize handles.
|
||||
zIndex: props.selected ? 100000 : props.box.z,
|
||||
// Applied inline because it is any CSS box-shadow value the admin typed.
|
||||
boxShadow: props.box.shadow || undefined,
|
||||
|
||||
@@ -1,18 +1,8 @@
|
||||
<script setup>
|
||||
/**
|
||||
* CodeMirror 6 HTML editor with v-model, used by BoxEditor.
|
||||
*
|
||||
* CodeMirror is imported dynamically on mount, so the ~150 KB of editor code
|
||||
* is only downloaded by an admin who opens a box for editing — never by a
|
||||
* visitor to /stp.
|
||||
*
|
||||
* The document is owned by CodeMirror; `modelValue` is pushed in only when it
|
||||
* differs from what the editor already holds, otherwise every keystroke would
|
||||
* round-trip through the parent and reset the cursor.
|
||||
*
|
||||
* `fontSize` scales the code. Ctrl/Cmd with +, - or 0 inside the editor asks
|
||||
* the parent to change it (`zoom` with +1, -1 or 0 for reset) instead of
|
||||
* zooming the whole page.
|
||||
* CodeMirror 6 HTML editor (v-model), loaded on mount so visitors never
|
||||
* download it. modelValue is pushed in only when it differs, or each
|
||||
* keystroke would reset the cursor. Ctrl/Cmd +/-/0 emit `zoom`.
|
||||
*/
|
||||
import { nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
|
||||
|
||||
@@ -42,13 +32,10 @@ onMounted(async () => {
|
||||
"&": { height: "100%", fontSize: "var(--code-font-size)", backgroundColor: "var(--color-surface-deep)", color: "var(--color-muted)" },
|
||||
".cm-content": { caretColor: "var(--color-primary)" },
|
||||
".cm-gutters": { backgroundColor: "var(--color-surface)", color: "var(--color-quaternary)", border: "none" },
|
||||
// The selection is drawn in a layer *behind* the text, so an opaque
|
||||
// active-line colour would hide it on the cursor's line: keep it
|
||||
// translucent.
|
||||
// Translucent: the selection layer is drawn behind the text.
|
||||
".cm-activeLine": { backgroundColor: "#55ffbb0d" },
|
||||
".cm-activeLineGutter": { backgroundColor: "var(--color-surface-tint)" },
|
||||
// Same selectors as CodeMirror's base theme — a shorter one loses to
|
||||
// its focused rule, which paints #233, all but invisible here.
|
||||
// Must match the base theme's selectors to beat its focused rule.
|
||||
"& .cm-selectionBackground, &.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground": {
|
||||
backgroundColor: "#1f6b5c",
|
||||
},
|
||||
@@ -90,9 +77,7 @@ watch(
|
||||
},
|
||||
);
|
||||
|
||||
// The size comes in through a CSS variable, which CodeMirror can't see change:
|
||||
// have it re-measure line heights once the new size is applied, or clicks and
|
||||
// the cursor land on the wrong line.
|
||||
// CodeMirror can't see the CSS variable change; re-measure or clicks miss.
|
||||
watch(
|
||||
() => props.fontSize,
|
||||
() => nextTick(() => view?.requestMeasure()),
|
||||
@@ -100,8 +85,7 @@ watch(
|
||||
|
||||
onBeforeUnmount(() => view?.destroy());
|
||||
|
||||
/** Put text at the cursor (replacing any selection); false if the editor
|
||||
* isn't loaded, so the caller can fall back to appending it. */
|
||||
/** Inserts at the cursor; false if the editor isn't loaded yet. */
|
||||
function insert(text) {
|
||||
if (!view) return false;
|
||||
view.dispatch(view.state.replaceSelection(text));
|
||||
|
||||
@@ -1,16 +1,7 @@
|
||||
<script setup>
|
||||
/**
|
||||
* The admin's components panel, opened from BoxCanvas's "Components" button:
|
||||
* place a saved component on this page, linked or as a copy, and rename or
|
||||
* delete them (stores/components.js).
|
||||
*
|
||||
* Placing is BoxCanvas's job (it knows where the admin is looking), so this
|
||||
* only emits `place`. A component is made by "Save as component" in the box
|
||||
* editor, or by "Import built-ins", which turns the starters in templates.js
|
||||
* into components. Its html is edited through any box linked to it.
|
||||
*
|
||||
* The list is refetched on opening, because `uses` changes whenever a linked
|
||||
* box is placed or deleted, on any page.
|
||||
* Components panel; emits `place` for BoxCanvas to position. Refetched on
|
||||
* open because `uses` changes from any page.
|
||||
*/
|
||||
import { ref } from "vue";
|
||||
import { useComponentsStore } from "@/stores/components";
|
||||
|
||||
@@ -1,16 +1,5 @@
|
||||
<script setup>
|
||||
/**
|
||||
* STATUS: legacy — no route points here. `/stp` is now an ordinary canvas
|
||||
* Page (slug "stp", created by ensureStpPage in backend/services/database.go)
|
||||
* served by views/canvas/CanvasPage.vue; the "Old /stp grid" starter in
|
||||
* views/canvas/pageStarters.js replaces this view's import button. Kept for
|
||||
* reference.
|
||||
*
|
||||
* Was route `/stp` — the home page as a free-form canvas of boxes the admin
|
||||
* arranges in the browser (page key "stp"). Replaces views/home/Home.vue's
|
||||
* fixed grid. The canvas itself is BoxCanvas.vue, shared with the landing
|
||||
* page's notes and the admin-created pages.
|
||||
*/
|
||||
/** STATUS: legacy — unrouted; /stp is an ordinary canvas Page now. */
|
||||
import BoxCanvas from "./BoxCanvas.vue";
|
||||
import { defaultLayout } from "./defaultLayout";
|
||||
</script>
|
||||
|
||||
@@ -1,19 +1,9 @@
|
||||
<script setup>
|
||||
/**
|
||||
* An admin-authored HTML box, rendered in a sandboxed iframe.
|
||||
*
|
||||
* The sandbox is the security boundary for the whole "write HTML in the
|
||||
* browser" feature. `allow-scripts` without `allow-same-origin` gives the frame
|
||||
* an opaque origin: its scripts run, but cannot read our cookies, call /api as
|
||||
* the visitor, or reach into the parent page. NEVER add allow-same-origin —
|
||||
* together with allow-scripts it lets the frame remove its own sandbox.
|
||||
*
|
||||
* The popup and top-navigation flags only let links work: target="_blank"
|
||||
* opens a normal (unsandboxed) tab, and target="_top" can navigate the page on
|
||||
* a real click.
|
||||
*
|
||||
* Nothing is rendered until the frame stylesheet (fonts inlined, see
|
||||
* frameStyles.js) is ready, so boxes don't flash in fallback fonts.
|
||||
* Admin HTML in a sandboxed iframe. The sandbox is the feature's security
|
||||
* boundary: NEVER add allow-same-origin, which with allow-scripts lets the
|
||||
* frame remove its own sandbox. Not rendered until the frame stylesheet is
|
||||
* ready, to avoid a font flash.
|
||||
*/
|
||||
import { computed, ref } from "vue";
|
||||
import { buildSrcdoc, frameCss } from "./frameStyles";
|
||||
|
||||
@@ -1,14 +1,7 @@
|
||||
<script setup>
|
||||
/**
|
||||
* The admin's layouts panel for one canvas page, opened from BoxCanvas's
|
||||
* "Layouts" button: save the page as a named layout, or load a saved one
|
||||
* onto it (stores/layouts.js).
|
||||
*
|
||||
* Loading onto a page that already has boxes asks whether to replace them or
|
||||
* add the layout on top. A replace is undoable: the server saves the page
|
||||
* first, as a layout named "<page> before <layout>, <time>", which shows up
|
||||
* at the top of this list. Onto an empty page it simply replaces, so the
|
||||
* layout's background comes with it.
|
||||
* Layouts panel. Replacing a non-empty page is undoable: the server saves the
|
||||
* old page as a layout first.
|
||||
*/
|
||||
import { ref } from "vue";
|
||||
import { pagePath, useLayoutsStore } from "@/stores/layouts";
|
||||
|
||||
@@ -1,12 +1,5 @@
|
||||
<script setup>
|
||||
/**
|
||||
* A box showing one of the built-in Vue widgets from widgetRegistry.js.
|
||||
*
|
||||
* The widgets were written for Home.vue's grid cells and sidebars, and a few
|
||||
* size their own root (Steam is 54mm tall). On the canvas the box decides the
|
||||
* size, so the root is forced to fill it — hence the !important, which has to
|
||||
* beat each widget's own scoped rule regardless of stylesheet order.
|
||||
*/
|
||||
/** Some widgets size their own root, so !important forces them to fill the box. */
|
||||
import { computed } from "vue";
|
||||
import { WIDGETS } from "./widgetRegistry";
|
||||
|
||||
|
||||
@@ -1,15 +1,7 @@
|
||||
/**
|
||||
* Geometry for dragging and resizing a box, with smart guides.
|
||||
*
|
||||
* While a box is dragged, its left edge, centre and right edge (and top,
|
||||
* middle and bottom) are compared with every other box's, and with the
|
||||
* canvas's sides, centre and top. When one comes within SNAP_PX screen px of
|
||||
* another it snaps onto it, and every line the box then shares is returned as
|
||||
* a guide for BoxCanvas to draw. A resize does the same for the edges being
|
||||
* dragged only. Away from all of them the 5px grid applies, as it always did.
|
||||
*
|
||||
* Everything here is canvas px. The threshold is in screen px because that is
|
||||
* what the hand feels; the caller divides it by the canvas scale.
|
||||
* Drag/resize geometry with smart guides: moving edges and centres snap to
|
||||
* other boxes and the canvas within a threshold, else to the 5px grid. All
|
||||
* canvas px; the caller converts the screen-px threshold.
|
||||
*/
|
||||
export const GRID = 5;
|
||||
export const MIN_SIZE = 40;
|
||||
@@ -20,9 +12,8 @@ const grid = (n) => Math.round(n / GRID) * GRID;
|
||||
const thirds = (start, size) => [start, start + size / 2, start + size];
|
||||
|
||||
/**
|
||||
* The lines a dragged box can snap to, per axis. Each carries the extent of
|
||||
* what it came from on the other axis, so a guide can be drawn between the
|
||||
* two boxes rather than across the whole canvas. Computed once per drag.
|
||||
* Snap lines per axis, each carrying its source's extent so a guide spans only
|
||||
* the two boxes. Computed once per drag.
|
||||
*/
|
||||
export function snapTargets(others, canvasW) {
|
||||
const x = thirds(0, canvasW).map((at) => ({ at, from: 0, to: 0 }));
|
||||
@@ -37,16 +28,12 @@ export function snapTargets(others, canvasW) {
|
||||
|
||||
export const NO_TARGETS = { x: [], y: [] };
|
||||
|
||||
// Which of the box's edges a gesture moves: all four for a move, otherwise
|
||||
// the ones named by the handle ("ne", "w", …). Spelled out because "move"
|
||||
// itself contains an "e".
|
||||
// Spelled out because "move" contains an "e".
|
||||
function edgesOf(mode) {
|
||||
if (mode === "move") return { w: true, e: true, n: true, s: true };
|
||||
return { w: mode.includes("w"), e: mode.includes("e"), n: mode.includes("n"), s: mode.includes("s") };
|
||||
}
|
||||
|
||||
// The lines of `g` that the gesture is moving, per axis. A move carries the
|
||||
// centres along too; a resize only moves the edge under the pointer.
|
||||
function movingLines(g, mode) {
|
||||
if (mode === "move") return { x: thirds(g.x, g.w), y: thirds(g.y, g.h) };
|
||||
const edges = edgesOf(mode);
|
||||
@@ -59,8 +46,6 @@ function movingLines(g, mode) {
|
||||
return { x, y };
|
||||
}
|
||||
|
||||
// The smallest shift that puts one of the moving lines on a target, or null
|
||||
// if none is within `threshold`.
|
||||
function nearest(moving, targets, threshold) {
|
||||
let best = null;
|
||||
for (const m of moving) {
|
||||
@@ -72,9 +57,7 @@ function nearest(moving, targets, threshold) {
|
||||
return best;
|
||||
}
|
||||
|
||||
// One axis of the result. `lo` and `hi` say whether the gesture moves the
|
||||
// box's start and end edge on this axis; `shift` is the snap from nearest(),
|
||||
// or null to fall back to the grid.
|
||||
// `lo`/`hi`: whether the gesture moves this axis's start/end edge.
|
||||
function resolve(start, size, delta, lo, hi, shift) {
|
||||
const fit = (n) => (shift === null ? grid(n) : Math.round(n + shift));
|
||||
if (lo && hi) return [Math.max(0, fit(start + delta)), size];
|
||||
@@ -86,11 +69,7 @@ function resolve(start, size, delta, lo, hi, shift) {
|
||||
return [start, size];
|
||||
}
|
||||
|
||||
/**
|
||||
* The geometry for a drag of (dx, dy) canvas px from `from`, in `mode`
|
||||
* ("move" or a handle), snapped to `targets` within `threshold` canvas px.
|
||||
* Pass NO_TARGETS for the grid alone.
|
||||
*/
|
||||
/** Pass NO_TARGETS for the grid alone. */
|
||||
export function place(from, mode, dx, dy, targets, threshold) {
|
||||
const edges = edgesOf(mode);
|
||||
// Where the pointer alone would put the box, before any snapping.
|
||||
@@ -108,14 +87,11 @@ export function place(from, mode, dx, dy, targets, threshold) {
|
||||
return { x, y, w, h };
|
||||
}
|
||||
|
||||
// Each target line that one of the moving lines now sits on, spanning both
|
||||
// the box (from..to) and whatever the line came from. Lines from several
|
||||
// boxes at the same place merge into one guide.
|
||||
// Coincident lines from several boxes merge into one guide.
|
||||
function matches(moving, targets, from, to) {
|
||||
const found = new Map();
|
||||
for (const t of targets) {
|
||||
// Within a px, since centres of odd sizes fall on half px and the
|
||||
// geometry is rounded.
|
||||
// Odd-sized centres fall on half px.
|
||||
if (!moving.some((m) => Math.abs(t.at - m) < 1)) continue;
|
||||
const [lo, hi] = found.get(t.at) ?? [from, to];
|
||||
found.set(t.at, [Math.min(lo, t.from), Math.max(hi, t.to)]);
|
||||
|
||||
@@ -1,13 +1,4 @@
|
||||
/**
|
||||
* The pre-Home3 /stp page (views/home/Home.vue) redrawn as boxes, offered
|
||||
* as the "Old /stp grid" starter when a page is created
|
||||
* (views/canvas/pageStarters.js).
|
||||
*
|
||||
* Home.vue was an A4 sheet (~800×1120px) holding a 10×10 CSS grid with 5px
|
||||
* gaps, between two 240px sidebars. The grid areas below are copied from its
|
||||
* grid-template-areas and turned into px here so they can be read against the
|
||||
* original; the sidebars are stacked top to bottom.
|
||||
*/
|
||||
/** The old Home.vue grid redrawn as boxes: the "Old /stp grid" starter. */
|
||||
import { imageHtml } from "./templates";
|
||||
|
||||
const SHEET = { x: 300, y: 20, w: 800, h: 1120 };
|
||||
|
||||
@@ -1,11 +1,4 @@
|
||||
/**
|
||||
* The box editor panel's size and its code's text size, shared between
|
||||
* BoxEditor (which draws the panel and its controls) and BoxCanvas (which
|
||||
* pads itself by the panel's width so the canvas rescales beside it rather
|
||||
* than under it), and whether dragged boxes snap to each other (BoxCanvas's
|
||||
* Align button). They are one admin's preference for their own screen, so
|
||||
* they live in localStorage, not the database.
|
||||
*/
|
||||
/** Per-browser editor preferences (panel width, code size, snapping), in localStorage. */
|
||||
import { ref, watch } from "vue";
|
||||
|
||||
const KEY = "boxEditor";
|
||||
|
||||
@@ -1,16 +1,7 @@
|
||||
/**
|
||||
* The stylesheet injected at the top of every HTML box's iframe, so admin
|
||||
* HTML looks like the rest of the site without restating the palette.
|
||||
*
|
||||
* Two things a sandboxed iframe cannot do for itself:
|
||||
* - Inherit CSS. It is a separate document, so the design tokens are copied
|
||||
* in as literal values, read from the live page so a re-themed layout
|
||||
* (CVLayout re-points the tokens) would carry through.
|
||||
* - Load our fonts. Without allow-same-origin its origin is opaque ("null"),
|
||||
* which makes /fonts/*.woff2 a cross-origin font load that Caddy and the
|
||||
* Vite dev server would both refuse without CORS headers. Instead the page
|
||||
* fetches the two files (28 KB) once, same-origin, and inlines them as
|
||||
* data: URLs.
|
||||
* Injected into every HTML box's iframe. Tokens are copied in as literals
|
||||
* (a separate document can't inherit them), and fonts are inlined as data:
|
||||
* URLs because the frame's opaque origin makes /fonts/ a refused CORS load.
|
||||
*/
|
||||
|
||||
const TOKENS = [
|
||||
|
||||
@@ -1,19 +1,7 @@
|
||||
/**
|
||||
* The built-in starter HTML. The "+ New box" menu no longer reads TEMPLATES
|
||||
* directly: it lists saved components, and TEMPLATES is what the Components
|
||||
* panel's "Import built-ins" turns into components (stores/components.js), so
|
||||
* they can be edited and deleted like any other. Changing an entry here only
|
||||
* reaches a site whose admin imports it again (after deleting the old one).
|
||||
* The helpers at the bottom are still used directly, by dropped uploads and
|
||||
* the starter layouts.
|
||||
*
|
||||
* Each runs inside the sandboxed iframe (see HtmlBox.vue), so scripts work but
|
||||
* can only reach APIs that allow cross-origin requests from an opaque origin —
|
||||
* i.e. that answer with `Access-Control-Allow-Origin: *` and need no key.
|
||||
* Open-Meteo is one.
|
||||
*
|
||||
* The site's colour and font tokens are already defined in the frame
|
||||
* (frameStyles.js), so templates use var(--color-…) freely.
|
||||
* Built-in starter HTML, turned into components by "Import built-ins".
|
||||
* Editing an entry only reaches a site that re-imports it. Boxes run in a
|
||||
* sandboxed iframe, so fetches need `Access-Control-Allow-Origin: *`.
|
||||
*/
|
||||
|
||||
const CLOCK = `<style>
|
||||
@@ -93,8 +81,6 @@ const imageHtml = (src) => `<style>
|
||||
const EMPTY = `<h3>New box</h3>
|
||||
<p>Edit me.</p>`;
|
||||
|
||||
// A sticky note for reminders to self. Unframed, since the note is its own
|
||||
// frame; the menu entry makes it adminOnly.
|
||||
const NOTE = `<style>
|
||||
body { padding: 0; }
|
||||
.note {
|
||||
@@ -129,10 +115,7 @@ const TEXT = `<h3>Heading</h3>
|
||||
</p>
|
||||
<blockquote>“A quote you like.”</blockquote>`;
|
||||
|
||||
// Links. An HTML box is its own document in a sandboxed frame, so a link
|
||||
// must name where it opens: target="_top" replaces the site page (a full
|
||||
// load, not a router navigation — fine for leaving the page), and
|
||||
// target="_blank" a new tab. Without a target it would load inside the box.
|
||||
// Links must set a target, or they load inside the box's frame.
|
||||
const LINK_STYLE = `<style>
|
||||
body { display: grid; place-items: center; padding: 4px; }
|
||||
.links { display: flex; flex-wrap: wrap; justify-content: space-around; gap: 1rem; }
|
||||
@@ -165,11 +148,7 @@ const videoHtml = (src) => `<style>
|
||||
</style>
|
||||
<video src="${src}" controls loop muted></video>`;
|
||||
|
||||
/**
|
||||
* Built-in starters; `label` becomes the component's name and `size` ([w, h]
|
||||
* in canvas px) its default size. `adminOnly` sets a new box's flag, which can
|
||||
* be changed afterwards in the editor.
|
||||
*/
|
||||
/** `size` is [w, h] in canvas px. */
|
||||
export const TEMPLATES = [
|
||||
{ label: "Note (admin only)", title: "Note", html: NOTE, size: [260, 200], framed: false, adminOnly: true },
|
||||
{ label: "Heading", title: "Heading", html: HEADING, size: [600, 140], framed: false },
|
||||
|
||||
@@ -2,12 +2,8 @@ import { onUnmounted, ref, toValue } from "vue";
|
||||
import { NO_TARGETS, SNAP_PX, guidesFor, place } from "./alignment";
|
||||
|
||||
/**
|
||||
* Owns pointer lifecycle and optimistic geometry while a box is manipulated.
|
||||
*
|
||||
* `targets` returns what the box can line up with (alignment.snapTargets), or
|
||||
* null when snapping is off; it is asked once per drag, since nothing else
|
||||
* moves meanwhile. The guides for each position are emitted as `guides`, and
|
||||
* an empty list on release. Holding Ctrl/⌘ places the box on the grid alone.
|
||||
* Pointer lifecycle and optimistic geometry. `targets` is asked once per drag
|
||||
* (null when snapping is off). Ctrl/⌘ uses the grid alone.
|
||||
*/
|
||||
export function useBoxInteraction({ box, scale, targets, emit }) {
|
||||
const draft = ref(null);
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
/**
|
||||
* The built-in Vue widgets a "widget" box can show, by the name stored in
|
||||
* Box.widget. Renaming a key orphans every box saved under the old name
|
||||
* (WidgetBox shows a placeholder for it), so treat the keys as stored data.
|
||||
*
|
||||
* Each is an async component so a widget nobody has placed on the canvas
|
||||
* never loads. `size` is what a newly added box of that kind starts at.
|
||||
* Widgets by the name stored in Box.widget. Renaming a key orphans saved
|
||||
* boxes, so treat keys as data.
|
||||
*/
|
||||
import { defineAsyncComponent } from "vue";
|
||||
|
||||
|
||||
@@ -1,12 +1,5 @@
|
||||
<script setup>
|
||||
/**
|
||||
* Route `/hotels` — Travelodge price scanner, front end for the FastAPI service
|
||||
* under /py/hotels.
|
||||
*
|
||||
* Two panels behind a tab strip. The form state is created here and passed down
|
||||
* as a prop, so shared fields (origin, guests, travel budget) survive tab
|
||||
* switches; the chosen tab itself is remembered in localStorage.
|
||||
*/
|
||||
/** Route `/hotels`. Form state lives here so shared fields survive tab switches. */
|
||||
import { ref, computed, onMounted } from "vue";
|
||||
import Header from "@/components/text/Header.vue";
|
||||
import Paragraph from "@/components/text/Paragraph.vue";
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
<script setup>
|
||||
/**
|
||||
* "Cheapest night" tab of /hotels: scans a date range (capped at MAX_SPAN_DAYS,
|
||||
* optionally filtered to particular weekdays) and reports the best hotel per
|
||||
* night. Shares the streaming/abort/ticker lifecycle with SingleStayPanel.vue
|
||||
* through useHotelSearch(); only the event shapes differ.
|
||||
*/
|
||||
/** "Cheapest night" tab of /hotels: the best hotel per night over a date range. */
|
||||
import { ref, computed, onMounted } from "vue";
|
||||
import SharedFields from "./SharedFields.vue";
|
||||
import HotelRows from "./HotelRows.vue";
|
||||
@@ -37,9 +32,7 @@ const RANKINGS = [
|
||||
{ key: "date", label: "Date" },
|
||||
];
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Form state (this panel's own fields; shared ones live in props.form)
|
||||
// ---------------------------------------------------------------------------
|
||||
// ---- Form state (shared fields are in props.form) ----
|
||||
const start = ref(todayIso());
|
||||
const end = ref(addDays(start.value, 60));
|
||||
const weekdays = ref([...ALL_DAYS]);
|
||||
@@ -53,10 +46,7 @@ function setDays(list) {
|
||||
weekdays.value = [...list];
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Scan state (searching/errorMsg/summary/done/elapsed come from the
|
||||
// composable; the night rows and their transport cache are this panel's own)
|
||||
// ---------------------------------------------------------------------------
|
||||
// ---- Scan state ----
|
||||
const nightRows = ref([]);
|
||||
const cached = ref(false);
|
||||
const expanded = ref(new Set());
|
||||
@@ -222,9 +212,7 @@ function toggle(n) {
|
||||
else expanded.value.add(n.checkin);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Persistence
|
||||
// ---------------------------------------------------------------------------
|
||||
// ---- Persistence ----
|
||||
function saveConfig() {
|
||||
props.form.save();
|
||||
saveTo(SCAN_KEY, {
|
||||
@@ -250,9 +238,7 @@ function loadConfig() {
|
||||
if (RANKINGS.some((r) => r.key === c.rankBy)) rankBy.value = c.rankBy;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Scan
|
||||
// ---------------------------------------------------------------------------
|
||||
// ---- Scan ----
|
||||
function buildRequest() {
|
||||
return {
|
||||
...props.form.sharedBody(),
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
<script setup>
|
||||
/**
|
||||
* The form fields common to both hotel panels (location, guests, railcards,
|
||||
* origin, departure time, travel/distance limits). Mutates the shared `form`
|
||||
* object from useHotelForm() directly — it is a prop by reference on purpose.
|
||||
*/
|
||||
/** Fields shared by both panels; mutates the `form` prop by reference on purpose. */
|
||||
import { CUSTOM_ORIGIN } from "./useHotelForm.js";
|
||||
|
||||
defineProps({
|
||||
|
||||
@@ -1,14 +1,7 @@
|
||||
<script setup>
|
||||
/**
|
||||
* "Single stay" tab of /hotels: cheapest hotels for one specific check-in date.
|
||||
*
|
||||
* Results stream in: the backend sends a `hotels` event with room prices first,
|
||||
* then a `transport` event per hotel as each route is priced, then `done`. Rows
|
||||
* are patched in place by hotel `code` so the table fills in rather than
|
||||
* reloading, and PENDING_ROUTE marks the not-yet-priced ones.
|
||||
*
|
||||
* The abort/ticker/stream lifecycle lives in useHotelSearch(); this panel only
|
||||
* supplies the request body and how to apply each streamed event.
|
||||
* "Single stay" tab of /hotels. The stream lifecycle is in useHotelSearch();
|
||||
* this panel builds the request and applies events.
|
||||
*/
|
||||
import { ref, computed, onMounted } from "vue";
|
||||
import SharedFields from "./SharedFields.vue";
|
||||
@@ -38,18 +31,13 @@ const RANKINGS = [
|
||||
{ key: "minutes", label: "Travel time" },
|
||||
];
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Form state (this panel's own fields; shared ones live in props.form)
|
||||
// ---------------------------------------------------------------------------
|
||||
// ---- Form state (shared fields are in props.form) ----
|
||||
const checkin = ref(nextFriday());
|
||||
const nights = ref(1);
|
||||
const top = ref(20);
|
||||
const rankBy = ref("total");
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Search state (searching/errorMsg/summary/done/elapsed come from the
|
||||
// composable; rows and `cached` are this panel's own)
|
||||
// ---------------------------------------------------------------------------
|
||||
// ---- Search state ----
|
||||
const rows = ref([]);
|
||||
const cached = ref(false);
|
||||
|
||||
@@ -139,9 +127,7 @@ const summaryText = computed(() => {
|
||||
);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Persistence
|
||||
// ---------------------------------------------------------------------------
|
||||
// ---- Persistence ----
|
||||
function saveConfig() {
|
||||
props.form.save({
|
||||
checkin: checkin.value,
|
||||
@@ -160,9 +146,7 @@ function loadConfig() {
|
||||
if (c.checkin && c.checkin >= todayIso()) checkin.value = c.checkin;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Search
|
||||
// ---------------------------------------------------------------------------
|
||||
// ---- Search ----
|
||||
function buildRequest() {
|
||||
return {
|
||||
...props.form.sharedBody(),
|
||||
@@ -173,13 +157,8 @@ function buildRequest() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply one NDJSON event from the search stream.
|
||||
*
|
||||
* Order is `hotels` (room prices for all candidates) -> many `transport`
|
||||
* (one per hotel as its route is priced) -> `done`. Transport events patch the
|
||||
* existing row in place, matched on hotel `code`, so the table fills in
|
||||
* column-by-column instead of being rebuilt — that is what keeps scroll
|
||||
* position and sort order stable while results arrive.
|
||||
* Events: `hotels`, then a `transport` per hotel, then `done`. Rows patch in
|
||||
* place by `code`, keeping scroll and sort stable.
|
||||
*/
|
||||
function applyEvent(ev) {
|
||||
switch (ev.event) {
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
// Form state shared by the "Single stay" and "Cheapest night" panels: where
|
||||
// you start from, who is travelling and how far you are willing to go. Kept
|
||||
// in one reactive object owned by CheapHotels.vue so values survive tab
|
||||
// switches, and persisted under the same localStorage key (and field names)
|
||||
// the page has always used.
|
||||
// Shared hotel form state. The localStorage key and field names must not change.
|
||||
|
||||
import { reactive, ref } from "vue";
|
||||
|
||||
|
||||
@@ -1,10 +1,4 @@
|
||||
// Search lifecycle shared by the "Single stay" and "Cheapest night" panels.
|
||||
//
|
||||
// Both panels run the same routine: reset the result state, start a 1s elapsed
|
||||
// ticker and an AbortController, stream NDJSON events from a Python endpoint,
|
||||
// then tear everything down in a `finally` (and again on unmount, so leaving
|
||||
// the page cancels an in-flight request). Only the events themselves differ,
|
||||
// so each panel supplies its own applyEvent().
|
||||
// Search lifecycle shared by both hotel panels; unmounting aborts the request.
|
||||
|
||||
import { ref, computed, onBeforeUnmount } from "vue";
|
||||
import { runStream } from "./hotelsStream.js";
|
||||
@@ -13,10 +7,8 @@ import { runStream } from "./hotelsStream.js";
|
||||
* @param {object} options
|
||||
* @param {string} options.url NDJSON streaming endpoint to POST to
|
||||
* @param {() => object} options.buildRequest request body for one run
|
||||
* @param {(ev: object) => void} options.applyEvent apply one streamed event.
|
||||
* Called for every event; it is the panel's job to write into
|
||||
* `summary` / `done` / `errorMsg` from the returned object. Declare it
|
||||
* as a hoisted `function` so it can reference that object.
|
||||
* @param {(ev: object) => void} options.applyEvent writes into the returned
|
||||
* object's summary/done/errorMsg, so declare it as a hoisted function.
|
||||
* @param {() => void} [options.onStart] reset panel-local state before a run
|
||||
* @param {string} [options.busyLabel] status chip text while running
|
||||
* @param {string} [options.failMessage] fallback message for a thrown error
|
||||
|
||||
@@ -1,13 +1,5 @@
|
||||
<script setup>
|
||||
/**
|
||||
* Route `/` — the front door, as a box canvas (page key "index") the admin
|
||||
* arranges in the browser like /stp. The fixed bio-and-links page it
|
||||
* replaced is kept as boxes in landingLayout.js, behind the canvas's import
|
||||
* button.
|
||||
*
|
||||
* Statically imported by the router (it is the first paint), but the canvas
|
||||
* is loaded in its own chunk: it brings the box editor with it.
|
||||
*/
|
||||
/** Route `/`: the "index" canvas, loaded in its own chunk (it brings the editor). */
|
||||
import { defineAsyncComponent } from "vue";
|
||||
import { landingLayout } from "./landingLayout";
|
||||
|
||||
|
||||
@@ -1,12 +1,4 @@
|
||||
/**
|
||||
* The pre-canvas landing page (a bio, an about paragraph and a row of links)
|
||||
* redrawn as boxes, for the "Import old landing page" button on its canvas.
|
||||
*
|
||||
* The old page was a 576px column (max-w-xl) centred in the window, 64px
|
||||
* from the top, with 48px between sections. On the 1400px design canvas that
|
||||
* centre is x = 412; the heights are the old sections' rendered heights,
|
||||
* rounded up. Boxes are unframed, as the old page had no frames.
|
||||
*/
|
||||
/** The pre-canvas landing page redrawn as boxes, for the import button. */
|
||||
import { linkHtml } from "@/views/home3/templates";
|
||||
|
||||
const COLUMN = { x: 412, w: 576 };
|
||||
|
||||
Reference in New Issue
Block a user