Give the job tracker stores and fix the admin route guard

createCrudStore captures the places store's pattern and now backs
places, job applications and job references. JobApplications.vue no
longer calls gql() itself and is split into the applications table, the
references table and the add form, with the status vocabulary in
jobStatus.js.

api.js is a thin REST client that turns failures into an ApiError
carrying the backend's message; the admin views and Listening.vue use it
in place of raw axios and fetch.

The router guard waited on the home query's loaded flag, which is never
set when that query fails, so /admin and /cv/jobs could hang. It now
awaits a standalone me query owned by the auth store, and homeData gains
a settled flag for widgets that only need to know the fetch finished.

The Vite proxy targets are configurable through VITE_PROXY_*, and
build:js runs the Vite build without wasm-pack.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-12 14:39:19 +01:00
co-authored by Claude Opus 5.5
parent 71344a1f8d
commit d3f722d077
26 changed files with 1176 additions and 681 deletions
+76
View File
@@ -0,0 +1,76 @@
/**
* The REST half of the API client, beside graphql.js: a thin axios wrapper for
* the Go backend's JSON endpoints under /api (file uploads, admin tooling,
* OAuth starts — everything backend/README.md lists as "not GraphQL").
*
* It does two things a bare axios call does not:
* - prefixes `/api`, so callers name the route (`api.get("/admin/logs")`);
* - turns a failure into an ApiError whose `message` is the backend's
* `{"error": "..."}` body when there is one. Every handler reports errors
* in that shape, and each view used to dig it out of `err.response` itself.
*
* Resolves to the parsed response body, not the axios response.
*
* Auth is the same HTTP-only cookies graphql.js relies on; nothing here handles
* tokens.
*
* NOT for: the Python service's NDJSON streams (views/hotels/hotelsStream.js
* reads those incrementally with fetch) or the `/radio/stream` HEAD probe —
* neither is under /api nor answers with this error shape.
*/
import axios from "axios";
export class ApiError extends Error {
/**
* @param {string} message
* @param {number|undefined} status HTTP status; undefined when no response
* arrived at all (network down, backend restarting)
* @param {*} data the parsed error body, if any
*/
constructor(message, status, data) {
super(message);
this.name = "ApiError";
this.status = status;
this.data = data;
}
}
/**
* @param {string} method
* @param {string} path route below /api, with its leading slash
* @param {object} [options]
* @param {*} [options.body] JSON-serialisable body, or a FormData for
* multipart uploads (axios sets the boundary itself)
* @param {string} [options.fallback] message to use when the backend sent no
* `error` string — callers pass the sentence their UI shows
* Any other option (`headers`, `params`, `onUploadProgress`, `signal`, …) is
* handed to axios unchanged.
*/
async function request(method, path, { body, fallback, ...config } = {}) {
try {
const res = await axios.request({
method,
url: `/api${path}`,
data: body,
...config,
});
return res.data;
} catch (err) {
const data = err.response?.data;
const serverMessage = typeof data?.error === "string" ? data.error : "";
throw new ApiError(
serverMessage || fallback || err.message,
err.response?.status,
data,
);
}
}
export const api = {
get: (path, options) => request("get", path, options),
delete: (path, options) => request("delete", path, options),
post: (path, body, options) => request("post", path, { ...options, body }),
put: (path, body, options) => request("put", path, { ...options, body }),
patch: (path, body, options) => request("patch", path, { ...options, body }),
};
+5 -2
View File
@@ -2,6 +2,9 @@
/**
* Sidebar widget showing the most recent Gitea action, read straight from
* homeData.gitFeed (the backend proxies and caches the Gitea API).
*
* The loading state keys off `settled` rather than `loaded` so a failed home
* query ends in "No activity found." instead of loading forever.
*/
import { useHomeDataStore } from "@/stores/homeData";
import { storeToRefs } from "pinia";
@@ -9,14 +12,14 @@ import Header from "@/components/text/Header.vue";
import Link from "@/components/text/Link.vue";
const homeData = useHomeDataStore();
const { gitFeed: feed, loaded } = storeToRefs(homeData);
const { gitFeed: feed, settled } = storeToRefs(homeData);
</script>
<template>
<div class="flex flex-col text-center min-h-0 h-full overflow-x-hidden">
<Header class="text-left">Commits</Header>
<div v-if="!loaded" class="flex-1 overflow-y-auto">
<div v-if="!settled" class="flex-1 overflow-y-auto">
<p>Loading latest activity...</p>
</div>
+13 -23
View File
@@ -13,11 +13,9 @@
*/
import { createRouter, createWebHistory } from "vue-router";
import { watch } from "vue";
import DefaultLayout from "@/layouts/DefaultLayout.vue";
import CVLayout from "@/layouts/CVLayout.vue";
import Landing from "@/views/landing/Landing.vue";
import { useHomeDataStore } from "@/stores/homeData";
import { useAuthStore } from "@/stores/auth";
const router = createRouter({
@@ -120,29 +118,21 @@ const router = createRouter({
// Guard for routes marked `meta: { requiresAdmin: true }`.
//
// The admin flag comes from homeData's `me` field, which arrives asynchronously.
// Navigating straight to /admin on a cold load would otherwise read an empty
// user and bounce a legitimate admin to the login page, so the guard first
// blocks on homeData.loaded. The watcher is self-stopping: `stop()` is called
// from inside the callback before resolving, so the promise settles exactly
// once and the watcher does not leak across navigations.
// The admin flag arrives asynchronously, so navigating straight to /admin on a
// cold load would otherwise read an empty user and bounce a legitimate admin to
// the login page. The guard therefore awaits auth.ensureLoaded(), which issues
// a standalone `me` query unless the user is already known.
//
// It deliberately does not wait on the home query (stores/homeData.js): that
// one fans out to Spotify, Steam and Gitea, and a guard that waited on it hung
// forever when it failed. ensureLoaded() always settles — a failed `me` reads
// as "not signed in" — and `user` is re-read on every navigation, so a login or
// logout during the session is honoured.
router.beforeEach(async (to) => {
if (!to.meta.requiresAdmin) return;
const homeData = useHomeDataStore();
if (!homeData.loaded) {
await new Promise((resolve) => {
const stop = watch(
() => homeData.loaded,
(val) => {
if (val) {
stop();
resolve();
}
},
);
});
}
if (!useAuthStore().user.admin)
const auth = useAuthStore();
await auth.ensureLoaded();
if (!auth.user.admin)
return { path: "/admin/login", query: { redirect: to.fullPath } };
});
+73 -20
View File
@@ -1,10 +1,18 @@
/**
* Current user + login/logout mutations.
*
* `user` is populated two ways: mirrored from homeData.me (the shared home query
* also returns the session user), and set directly by logIn()/refreshToken().
* The watch is `immediate` so a store created after homeData has already loaded
* still picks up the user.
* `user` is populated three ways:
* - ensureLoaded(): a standalone `me` query, fired at most once per page load.
* The router guard awaits it, and so does the login page.
* - adoptSession(): stores/homeData.js hands over the `me` it got back from
* the home query, so the /stp page never needs the standalone query.
* - logIn() / refreshToken() / logOut(), which set it directly.
*
* This store deliberately does NOT import homeData. It used to mirror
* homeData.me with a watch, which meant that merely asking "who is signed in?"
* instantiated homeData and so fired the nine-field home query — Spotify, Steam
* and Gitea upstreams included — and the guard then had to wait on it. The
* dependency now points the other way: homeData pushes `me` in here.
*
* The JWTs themselves are never visible here — the backend sets access_token and
* refresh_token as HTTP-only cookies, so `loggedIn` is inferred purely from
@@ -12,28 +20,66 @@
*/
import { defineStore } from "pinia";
import { computed, ref, watch } from "vue";
import { computed, ref } from "vue";
import { gql } from "@/graphql";
import { useHomeDataStore } from "@/stores/homeData";
export const useAuthStore = defineStore("auth", () => {
const user = ref({});
const loggedIn = computed(() => !!user.value.username);
const homeData = useHomeDataStore();
// Mirror the `me` field from the shared home query. `immediate` so a store
// created after homeData loaded still sees the user. Only overwrite on a
// truthy `me` — a logged-out response is null and must not clobber a user
// that logIn() just set.
watch(
() => homeData.me,
(me) => {
if (me) {
user.value = me;
}
},
{ immediate: true },
);
// True once something has answered "who is signed in?" — the `me` query,
// the home query, or a login/logout. Until then an empty `user` means
// "unknown", not "signed out", which is the distinction the guard needs.
const resolved = ref(false);
// Bumped by every login/logout/refresh. A `me` answer that was requested
// before the bump describes the previous session, so it is dropped rather
// than allowed to sign a logged-out user back in (or the reverse).
let epoch = 0;
let pending = null;
function markSessionChanged() {
epoch++;
resolved.value = true;
}
/**
* Apply a `me` answer that was requested when the session was at
* `requestedAt` (a value from sessionEpoch()). Only a truthy `me` overwrites
* `user`: a signed-out answer is null and must not clobber a user that
* logIn() set while the request was in flight.
*/
function adoptSession(me, requestedAt = epoch) {
if (requestedAt !== epoch) return;
if (me) user.value = me;
resolved.value = true;
}
/** Token for adoptSession(): read it before issuing a query that returns `me`. */
function sessionEpoch() {
return epoch;
}
/**
* Resolve once the signed-in user is known, fetching `me` if nothing has
* supplied it yet. NEVER rejects and never hangs: a failed query settles as
* "not signed in", because the router guard awaits this and a navigation
* that never resolves is worse than a bounce to the login page. A failure is
* not remembered, so the next call tries again.
*/
function ensureLoaded() {
if (resolved.value) return Promise.resolve();
if (!pending) {
const requestedAt = epoch;
pending = gql(`query Me { me { id username admin } }`)
.then((data) => adoptSession(data.me, requestedAt))
.catch((err) => console.error("me query failed:", err))
.finally(() => {
pending = null;
});
}
return pending;
}
/** Clear the session cookies server-side, then blank the local user.
* Deliberately clears `user` even if the mutation fails. */
@@ -44,6 +90,7 @@ export const useAuthStore = defineStore("auth", () => {
console.error(err);
}
user.value = {};
markSessionChanged();
}
/** Log in and populate `user`. Swallows errors: on a bad password `user`
@@ -55,6 +102,7 @@ export const useAuthStore = defineStore("auth", () => {
{ input: { username, password } },
);
user.value = data.login.user;
markSessionChanged();
} catch (err) {
console.error(err);
}
@@ -83,6 +131,7 @@ export const useAuthStore = defineStore("auth", () => {
`mutation { refreshToken { user { id username admin } } }`,
);
user.value = data.refreshToken.user;
markSessionChanged();
} catch (err) {
console.log(err);
}
@@ -107,6 +156,10 @@ export const useAuthStore = defineStore("auth", () => {
loggedIn,
ensureLoaded,
adoptSession,
sessionEpoch,
logIn,
refreshToken,
logOut,
+123
View File
@@ -0,0 +1,123 @@
/**
* Factory for the "CRUD store" pattern shared by stores/places.js,
* jobApplications.js and jobAppReferences.js.
*
* Each of those is one GraphQL type with the schema's standard quartet — a list
* query, `create<Type>(input:)`, `update<Type>(id:, input:)` and
* `delete<Type>(id:)` — plus a local array that is patched after each mutation
* instead of being refetched. The operation and input-type names are derived
* from `type` because the schema is consistent about them
* (`Create<Type>Input`, `Update<Type>Input`); a type that breaks the convention
* should not be forced through here.
*
* `fields` is interpolated into every query and mutation so the selection set
* can never drift between them.
*
* Error contract, which callers rely on: fetch() never throws — it records the
* failure on `error` — because it is fired from lifecycle hooks with nothing to
* catch it. create/update/remove DO throw, so the form or row that triggered
* them can show the message and keep the user's typing.
*/
import { defineStore } from "pinia";
import { ref } from "vue";
import { gql } from "@/graphql";
/**
* @param {string} id Pinia store id
* @param {object} options
* @param {string} options.type GraphQL type name, e.g. "Place"
* @param {string} options.list list query field, e.g. "places"
* @param {string} options.fields selection set shared by every operation
* @param {string} [options.itemsKey] name the array is exposed under (defaults
* to `list`); components import it by that name
* @param {"prepend"|"append"} [options.insert] where create() puts the new row
* locally, matching the order the list query returns
* @param {"object"|"boolean"} [options.deleteReturns] what the delete mutation
* returns. An object type needs a selection set and a scalar must not have
* one, so the mutation text differs; the schema has both kinds.
* @param {(ctx: object) => object} [options.extend] extra state/actions merged
* into the store; receives the base members
*/
export function createCrudStore(
id,
{
type,
list,
fields,
itemsKey = list,
insert = "prepend",
deleteReturns = "object",
extend,
},
) {
const deleteSelection = deleteReturns === "object" ? "{ id }" : "";
return defineStore(id, () => {
const items = ref([]);
const loaded = ref(false);
const loading = ref(false);
const error = ref(null);
/** Load the whole list. Records failures on `error` rather than throwing. */
async function fetch() {
loading.value = true;
try {
const data = await gql(`query ${type}List { ${list} { ${fields} } }`);
items.value = data[list] || [];
loaded.value = true;
error.value = null;
} catch (err) {
error.value = err;
} finally {
loading.value = false;
}
}
/** Create a row and add it locally. Throws on failure. */
async function create(input) {
const data = await gql(
`mutation Create${type}($input: Create${type}Input!) {
create${type}(input: $input) { ${fields} }
}`,
{ input },
);
const created = data[`create${type}`];
items.value =
insert === "append"
? [...items.value, created]
: [created, ...items.value];
return created;
}
/** Patch a row and replace it in the local list. Throws on failure. */
async function update(rowId, input) {
const data = await gql(
`mutation Update${type}($id: ID!, $input: Update${type}Input!) {
update${type}(id: $id, input: $input) { ${fields} }
}`,
{ id: rowId, input },
);
const updated = data[`update${type}`];
const idx = items.value.findIndex((item) => item.id === rowId);
if (idx >= 0) items.value[idx] = updated;
return updated;
}
/** Delete a row and drop it from the local list. Throws on failure. */
async function remove(rowId) {
await gql(
`mutation Delete${type}($id: ID!) { delete${type}(id: $id) ${deleteSelection} }`,
{ id: rowId },
);
items.value = items.value.filter((item) => item.id !== rowId);
}
const base = { loaded, loading, error, fetch, create, update, remove };
return {
[itemsKey]: items,
...base,
...(extend ? extend({ items, ...base }) : {}),
};
});
}
+28 -5
View File
@@ -4,22 +4,32 @@
* One GraphQL query fetches everything the /stp widgets need (posts, favorites,
* activities, Spotify, rowing, bookmarks, Gitea feed, Steam, current user) in a
* single round trip, instead of each widget issuing its own request. The
* per-domain stores (posts, favorites, activity, songs, steam, auth) are thin
* views over this one — they `watch` their slice of it rather than fetching.
* per-domain stores (posts, favorites, activity, songs, steam) are thin views
* over this one — they `watch` their slice of it rather than fetching. The
* session user is the exception: `me` is pushed into stores/auth.js, which owns
* it and can also fetch it alone (the router guard does not wait on this query).
*
* fetchAll() is called once at the bottom of the setup function, i.e. the first
* time any component calls useHomeDataStore(). That is why no component has to
* kick off the initial load, and why `loaded` is the flag the router guard waits
* on to know whether `me` has been resolved yet.
* kick off the initial load.
*
* Two flags, because "finished" and "succeeded" are different questions:
* `settled` — a fetch has completed, either way. Wait on / show a spinner
* against THIS; it always becomes true.
* `loaded` — a fetch has succeeded at least once, so the data refs are real.
* Anything that waited on `loaded` alone would wait forever when the query
* fails outright, which is how the router guard used to hang.
*/
import { defineStore } from "pinia";
import { ref } from "vue";
import { gql } from "@/graphql";
import axios from "axios";
import { useAuthStore } from "@/stores/auth";
export const useHomeDataStore = defineStore("homeData", () => {
const loaded = ref(false);
const settled = ref(false);
const error = ref(null);
const me = ref(null);
@@ -36,9 +46,14 @@ export const useHomeDataStore = defineStore("homeData", () => {
/**
* Fetch every home-page dataset in one GraphQL round trip, plus the radio
* liveness probe in parallel. Sets `loaded` on success and `error` on
* failure; never throws. Safe to call again to refresh.
* failure, and `settled` either way; never throws. Safe to call again to
* refresh.
*/
async function fetchAll() {
const auth = useAuthStore();
// Read before the request goes out: if the user logs in or out while it is
// in flight, the `me` it returns is stale and auth will ignore it.
const sessionAt = auth.sessionEpoch();
try {
const [data] = await Promise.all([
gql(`
@@ -65,10 +80,17 @@ export const useHomeDataStore = defineStore("homeData", () => {
gitFeed.value = data.giteaFeed || null;
steamStatus.value = data.steamStatus || null;
me.value = data.me || null;
// The home query already says who is signed in, so hand it to the auth
// store rather than have it issue its own `me` query on this page.
auth.adoptSession(me.value, sessionAt);
loaded.value = true;
// A refresh that works clears the failure a previous one left behind.
error.value = null;
} catch (err) {
console.error("HomeData fetch failed:", err);
error.value = err;
} finally {
settled.value = true;
}
}
@@ -91,6 +113,7 @@ export const useHomeDataStore = defineStore("homeData", () => {
return {
loaded,
settled,
error,
me,
bookmarks,
+21
View File
@@ -0,0 +1,21 @@
/**
* The "Quick Reference" snippets on /cv/jobs (reusable profile/experience text
* to paste into application forms) — CRUD built on createCrudStore().
*
* A separate table from the applications themselves; the two only share a page.
*/
import { createCrudStore } from "@/stores/createCrudStore";
const REF_FIELDS = `id category label value sortOrder createdAt`;
export const useJobAppReferencesStore = createCrudStore("jobAppReferences", {
type: "JobAppReference",
list: "jobAppReferences",
itemsKey: "references",
fields: REF_FIELDS,
// The list comes back in sortOrder/creation order, so new rows go last.
insert: "append",
// deleteJobAppReference returns Boolean!, and errors for an id that is gone.
deleteReturns: "boolean",
});
+39
View File
@@ -0,0 +1,39 @@
/**
* Job applications for the tracker at /cv/jobs — CRUD built on
* createCrudStore(), plus the on-demand posting text.
*
* Admin-only on the server, and only that one page uses it, so nothing fetches
* it until the view mounts.
*/
import { createCrudStore } from "@/stores/createCrudStore";
import { gql } from "@/graphql";
// `description` is deliberately not here: it is the full text of the posting,
// tens of kilobytes a row, and is fetched per row when asked for.
const APP_FIELDS = `id jobTitle company location url status notes appliedAt createdAt updatedAt`;
export const useJobApplicationsStore = createCrudStore("jobApplications", {
type: "JobApplication",
list: "jobApplications",
itemsKey: "applications",
fields: APP_FIELDS,
insert: "prepend",
// deleteJobApplication returns Boolean!, and errors for an id that is gone.
deleteReturns: "boolean",
extend: () => ({
/**
* The captured posting text for one row; `""` when none was saved. Throws
* on failure. Not cached here: the view keeps its own per-visit cache, so
* returning to the page re-reads a posting the userscript may have
* replaced.
*/
async fetchDescription(id) {
const data = await gql(
`query JobDescription($id: ID!) { jobApplication(id: $id) { description } }`,
{ id },
);
return data.jobApplication?.description ?? "";
},
}),
});
+16 -79
View File
@@ -1,17 +1,13 @@
/**
* Places-to-go list (the "Places" tab inside the Collage widget) — full CRUD.
* Places-to-go list (the "Places" tab inside the Collage widget) — full CRUD,
* built on createCrudStore().
*
* Not part of the homeData query because it is sign-in-only; PlacesTable.vue
* fetches it lazily once the user is logged in. PLACE_FIELDS is interpolated into
* every query/mutation so the selection set can never drift between them.
* fetches it lazily once the user is logged in.
*/
import { defineStore } from "pinia";
import { ref } from "vue";
import { gql } from "@/graphql";
import { createCrudStore } from "@/stores/createCrudStore";
// Shared selection set: interpolated into every query and mutation so they can
// never drift apart.
const PLACE_FIELDS = `
id
title
@@ -26,75 +22,16 @@ const PLACE_FIELDS = `
updatedAt
`;
export const usePlacesStore = defineStore("places", () => {
const places = ref([]);
const loaded = ref(false);
const loading = ref(false);
const error = ref(null);
/** Load all places into `places`. Records failures on `error` rather than throwing. */
async function fetch() {
loading.value = true;
try {
const data = await gql(`query Places { places { ${PLACE_FIELDS} } }`);
places.value = data.places || [];
loaded.value = true;
error.value = null;
} catch (err) {
error.value = err;
} finally {
loading.value = false;
}
}
/** Create a place and prepend it locally (newest first). Throws on failure. */
async function create(input) {
const data = await gql(
`mutation CreatePlace($input: CreatePlaceInput!) {
createPlace(input: $input) { ${PLACE_FIELDS} }
}`,
{ input },
);
places.value = [data.createPlace, ...places.value];
return data.createPlace;
}
/** Patch a place and replace it in the local list. Throws on failure. */
async function update(id, input) {
const data = await gql(
`mutation UpdatePlace($id: ID!, $input: UpdatePlaceInput!) {
updatePlace(id: $id, input: $input) { ${PLACE_FIELDS} }
}`,
{ id, input },
);
const idx = places.value.findIndex((p) => p.id === id);
if (idx >= 0) places.value[idx] = data.updatePlace;
return data.updatePlace;
}
/** Flip a place's `done` flag. */
async function toggleDone(place) {
return update(place.id, { done: !place.done });
}
/** Soft-delete a place and drop it from the local list. */
async function remove(id) {
await gql(
`mutation DeletePlace($id: ID!) { deletePlace(id: $id) { id } }`,
{ id },
);
places.value = places.value.filter((p) => p.id !== id);
}
return {
places,
loaded,
loading,
error,
fetch,
create,
update,
toggleDone,
remove,
};
export const usePlacesStore = createCrudStore("places", {
type: "Place",
list: "places",
fields: PLACE_FIELDS,
// The list query returns newest first, so a new place goes on top.
insert: "prepend",
// deletePlace returns the deleted Place, unlike the job tracker's deletes.
deleteReturns: "object",
extend: ({ update }) => ({
/** Flip a place's `done` flag. */
toggleDone: (place) => update(place.id, { done: !place.done }),
}),
});
+129
View File
@@ -0,0 +1,129 @@
<script setup>
/**
* The "add an application" form on `/cv/jobs`. Rendered only by
* JobApplications.vue; it creates through stores/jobApplications.js, so the new
* row appears in the parent's table without the two having to talk.
*
* Like JobReferences.vue it reports through the parent's single error banner:
* `fail` carries the error, `ok` says a create succeeded.
*
* Its root sits inside the parent's `.ja-root`, which jobs-shared.css relies on.
*/
import { ref } from "vue";
import { useJobApplicationsStore } from "@/stores/jobApplications";
import { STATUS_OPTIONS } from "./jobStatus";
import "./jobs-shared.css";
const emit = defineEmits(["fail", "ok"]);
const store = useJobApplicationsStore();
function today() {
return new Date().toISOString().substring(0, 10);
}
function blankForm() {
return {
jobTitle: "",
company: "",
location: "",
url: "",
status: "applied",
notes: "",
// Logging an application on the day you send it is the common case, so the
// date defaults to today rather than landing null and ageing as unknown.
appliedAt: today(),
};
}
const form = ref(blankForm());
async function createApplication() {
if (!form.value.jobTitle.trim() || !form.value.company.trim()) return;
try {
await store.create({
jobTitle: form.value.jobTitle.trim(),
company: form.value.company.trim(),
status: form.value.status,
location: form.value.location || undefined,
url: form.value.url || undefined,
notes: form.value.notes || undefined,
appliedAt: form.value.appliedAt
? new Date(form.value.appliedAt).toISOString()
: undefined,
});
form.value = blankForm();
emit("ok");
} catch (err) {
// The form is left as typed so the create can be retried.
emit("fail", err);
}
}
</script>
<template>
<form class="ja-form" @submit.prevent="createApplication">
<div class="ja-form-row">
<input
v-model="form.jobTitle"
class="ja-input"
placeholder="Job title *"
required
/>
<input
v-model="form.company"
class="ja-input"
placeholder="Company *"
required
/>
<select v-model="form.status" class="ja-input ja-select">
<option v-for="s in STATUS_OPTIONS" :key="s.value" :value="s.value">
{{ s.label }}
</option>
</select>
</div>
<div class="ja-form-row">
<input
v-model="form.location"
class="ja-input"
placeholder="Location"
/>
<input v-model="form.url" class="ja-input" placeholder="URL" />
<input
v-model="form.appliedAt"
class="ja-input"
type="date"
title="Applied date"
/>
</div>
<div class="ja-form-row">
<textarea
v-model="form.notes"
class="ja-input ja-textarea"
placeholder="Notes"
/>
<button type="submit" class="cv-btn cv-btn-primary">Add</button>
</div>
</form>
</template>
<style scoped>
/* Inputs are styled by jobs-shared.css; buttons are .cv-btn from CVLayout.vue. */
.ja-form {
display: flex;
flex-direction: column;
gap: 0.5rem;
margin-bottom: 1.5rem;
}
.ja-form-row {
display: flex;
gap: 0.5rem;
flex-wrap: wrap;
}
.ja-textarea {
resize: vertical;
min-height: 2.4rem;
}
</style>
+33 -451
View File
@@ -2,8 +2,14 @@
/**
* Route `/cv/jobs` (guarded by `meta.requiresAdmin`) — a private tracker for job
* applications and for the reusable reference snippets that feed the CV copy.
* Two independent CRUD tables over GraphQL; editing is inline via an `editingId`
* plus a scratch copy of the row.
*
* This view owns the page frame, the single error banner and the applications
* table (pipeline bar, filter/sort, inline editing via an `editingId` plus a
* scratch copy of the row). The two other pieces are components beside it:
* JobReferences.vue (the Quick Reference box, a separate table) and
* JobApplicationForm.vue (the add form). Data access is in
* stores/jobApplications.js and stores/jobAppReferences.js; nothing here calls
* gql() directly.
*
* Rows also arrive from two places that are not this page: the email pipeline,
* and the browser userscript in `public/job-capture.user.js`, which the header
@@ -11,63 +17,21 @@
*/
import { ref, computed, onMounted } from "vue";
import { RouterLink } from "vue-router";
import { gql } from "@/graphql";
import { storeToRefs } from "pinia";
import { useJobApplicationsStore } from "@/stores/jobApplications";
import { STATUS_OPTIONS, OPEN_STATUSES } from "./jobStatus";
import JobReferences from "./JobReferences.vue";
import JobApplicationForm from "./JobApplicationForm.vue";
import "./jobs-shared.css";
const applications = ref([]);
const store = useJobApplicationsStore();
const { applications } = storeToRefs(store);
const editingId = ref(null);
const editForm = ref({});
const error = ref("");
/**
* The status vocabulary is the email pipeline's (services.statusOrder), not a
* separate UI list: the pipeline writes these lowercase keys, and a status it
* does not rank switches its forward-only progression guard off for that row.
* Labels are display-only.
*/
const STATUS_OPTIONS = [
// Captured from the browser but not applied to yet. No email produces it.
{ value: "saved", label: "Saved" },
{ value: "applied", label: "Applied" },
{ value: "screening", label: "Screening" },
{ value: "assessment", label: "Assessment" },
{ value: "interviewing", label: "Interviewing" },
{ value: "offer", label: "Offer" },
{ value: "rejected", label: "Rejected" },
{ value: "withdrawn", label: "Withdrawn" },
];
// Statuses still in play — used to decide whether a row is worth chasing.
// "saved" is absent on purpose: nobody owes a reply on a job not applied to.
const OPEN_STATUSES = ["applied", "screening", "assessment", "interviewing"];
const STALE_DAYS = 14;
function today() {
return new Date().toISOString().substring(0, 10);
}
const form = ref({
jobTitle: "",
company: "",
location: "",
url: "",
status: "applied",
notes: "",
// Logging an application on the day you send it is the common case, so the
// date defaults to today rather than landing null and ageing as unknown.
appliedAt: today(),
});
const references = ref([]);
const refForm = ref({ category: "profile", label: "", value: "" });
const editingRefId = ref(null);
const editRefForm = ref({});
const REF_CATEGORIES = ["profile", "experience"];
const REF_FIELDS = `id category label value sortOrder createdAt`;
// `description` is deliberately not here: it is the full text of the posting,
// tens of kilobytes a row, and is fetched per row when asked for.
const APP_FIELDS = `id jobTitle company location url status notes appliedAt createdAt updatedAt`;
// The captured posting text for the one row whose description is open.
// `undefined` in the cache means "not fetched", `""` means "fetched, none saved".
const descriptionId = ref(null);
@@ -88,49 +52,14 @@ function fail(err) {
error.value = String(err?.message ?? err);
}
async function fetchApplications() {
try {
const data = await gql(`query { jobApplications { ${APP_FIELDS} } }`);
applications.value = data.jobApplications;
} catch (err) {
fail(err);
}
function clearError() {
error.value = "";
}
async function createApplication() {
if (!form.value.jobTitle.trim() || !form.value.company.trim()) return;
try {
const input = {
jobTitle: form.value.jobTitle.trim(),
company: form.value.company.trim(),
status: form.value.status,
location: form.value.location || undefined,
url: form.value.url || undefined,
notes: form.value.notes || undefined,
appliedAt: form.value.appliedAt
? new Date(form.value.appliedAt).toISOString()
: undefined,
};
const data = await gql(
`mutation CreateJobApplication($input: CreateJobApplicationInput!) {
createJobApplication(input: $input) { ${APP_FIELDS} }
}`,
{ input },
);
applications.value.unshift(data.createJobApplication);
form.value = {
jobTitle: "",
company: "",
location: "",
url: "",
status: "applied",
notes: "",
appliedAt: today(),
};
error.value = "";
} catch (err) {
fail(err);
}
async function fetchApplications() {
// The store's fetch() records its failure instead of throwing.
await store.fetch();
if (store.error) fail(store.error);
}
function startEdit(app) {
@@ -178,7 +107,7 @@ async function saveEdit(id) {
// "delete this wrong URL" into a silent no-op that re-renders the old
// value. appliedAt has no empty representation, so clearing it is not
// offered — the field stays as it was.
const input = {
await store.update(id, {
jobTitle: editForm.value.jobTitle,
company: editForm.value.company,
status: editForm.value.status,
@@ -188,15 +117,7 @@ async function saveEdit(id) {
appliedAt: editForm.value.appliedAt
? new Date(editForm.value.appliedAt).toISOString()
: undefined,
};
const data = await gql(
`mutation UpdateJobApplication($id: ID!, $input: UpdateJobApplicationInput!) {
updateJobApplication(id: $id, input: $input) { ${APP_FIELDS} }
}`,
{ id, input },
);
const idx = applications.value.findIndex((a) => a.id === id);
if (idx !== -1) applications.value[idx] = data.updateJobApplication;
});
editingId.value = null;
error.value = "";
} catch (err) {
@@ -210,14 +131,7 @@ async function saveEdit(id) {
async function setStatus(app, status) {
if (status === app.status) return;
try {
const data = await gql(
`mutation UpdateJobApplication($id: ID!, $input: UpdateJobApplicationInput!) {
updateJobApplication(id: $id, input: $input) { ${APP_FIELDS} }
}`,
{ id: app.id, input: { status } },
);
const idx = applications.value.findIndex((a) => a.id === app.id);
if (idx !== -1) applications.value[idx] = data.updateJobApplication;
await store.update(app.id, { status });
error.value = "";
} catch (err) {
fail(err);
@@ -232,11 +146,7 @@ async function toggleDescription(app) {
descriptionId.value = app.id;
if (descriptions.value[app.id] !== undefined) return;
try {
const data = await gql(
`query JobDescription($id: ID!) { jobApplication(id: $id) { description } }`,
{ id: app.id },
);
descriptions.value[app.id] = data.jobApplication?.description ?? "";
descriptions.value[app.id] = await store.fetchDescription(app.id);
} catch (err) {
descriptionId.value = null;
fail(err);
@@ -249,11 +159,7 @@ async function deleteApplication(app) {
if (!confirm(`Delete the ${app.jobTitle} application at ${app.company}?`))
return;
try {
await gql(
`mutation DeleteJobApplication($id: ID!) { deleteJobApplication(id: $id) }`,
{ id: app.id },
);
applications.value = applications.value.filter((a) => a.id !== app.id);
await store.remove(app.id);
error.value = "";
} catch (err) {
fail(err);
@@ -297,95 +203,6 @@ function exportCsv() {
URL.revokeObjectURL(url);
}
async function fetchReferences() {
try {
const data = await gql(`query { jobAppReferences { ${REF_FIELDS} } }`);
references.value = data.jobAppReferences;
} catch (err) {
fail(err);
}
}
async function createReference() {
if (!refForm.value.label || !refForm.value.value) return;
try {
const input = {
category: refForm.value.category,
label: refForm.value.label,
value: refForm.value.value,
};
const data = await gql(
`mutation CreateJobAppReference($input: CreateJobAppReferenceInput!) {
createJobAppReference(input: $input) { ${REF_FIELDS} }
}`,
{ input },
);
references.value.push(data.createJobAppReference);
refForm.value = { category: refForm.value.category, label: "", value: "" };
error.value = "";
} catch (err) {
fail(err);
}
}
function startRefEdit(ref) {
editingRefId.value = ref.id;
editRefForm.value = {
category: ref.category,
label: ref.label,
value: ref.value,
};
}
function cancelRefEdit() {
editingRefId.value = null;
editRefForm.value = {};
}
async function saveRefEdit(id) {
try {
const input = {
category: editRefForm.value.category || undefined,
label: editRefForm.value.label || undefined,
value: editRefForm.value.value || undefined,
};
const data = await gql(
`mutation UpdateJobAppReference($id: ID!, $input: UpdateJobAppReferenceInput!) {
updateJobAppReference(id: $id, input: $input) { ${REF_FIELDS} }
}`,
{ id, input },
);
const idx = references.value.findIndex((r) => r.id === id);
if (idx !== -1) references.value[idx] = data.updateJobAppReference;
editingRefId.value = null;
error.value = "";
} catch (err) {
fail(err);
}
}
async function deleteReference(ref) {
if (!confirm(`Delete the reference "${ref.label}"?`)) return;
try {
await gql(
`mutation DeleteJobAppReference($id: ID!) { deleteJobAppReference(id: $id) }`,
{ id: ref.id },
);
references.value = references.value.filter((r) => r.id !== ref.id);
error.value = "";
} catch (err) {
fail(err);
}
}
function refsByCategory(category) {
return references.value.filter((r) => r.category === category);
}
function copyToClipboard(text) {
navigator.clipboard.writeText(text);
}
function statusLabel(status) {
return (
STATUS_OPTIONS.find((s) => s.value === status?.toLowerCase())?.label ??
@@ -465,10 +282,7 @@ function toggleStatusFilter(status) {
statusFilter.value = statusFilter.value === status ? null : status;
}
onMounted(() => {
fetchApplications();
fetchReferences();
});
onMounted(fetchApplications);
</script>
<template>
@@ -506,134 +320,9 @@ onMounted(() => {
<button class="cv-btn cv-btn-sm" @click="error = ''">Dismiss</button>
</div>
<div class="ja-ref-section">
<h3 class="ja-ref-heading">Quick Reference</h3>
<div v-for="cat in REF_CATEGORIES" :key="cat" class="ja-ref-category">
<h4 class="ja-ref-cat-label">{{ cat }}</h4>
<div
v-for="ref in refsByCategory(cat)"
:key="ref.id"
class="ja-ref-item"
>
<template v-if="editingRefId !== ref.id">
<span class="ja-ref-label">{{ ref.label }}</span>
<span class="ja-ref-value" :title="ref.value">{{ ref.value }}</span>
<button
class="cv-btn cv-btn-sm"
@click="copyToClipboard(ref.value)"
title="Copy"
>
Copy
</button>
<button class="cv-btn cv-btn-sm" @click="startRefEdit(ref)">
Edit
</button>
<button
class="cv-btn cv-btn-sm cv-btn-danger"
@click="deleteReference(ref)"
>
Delete
</button>
</template>
<template v-else>
<select
v-model="editRefForm.category"
class="ja-input ja-input-sm ja-select"
>
<option v-for="c in REF_CATEGORIES" :key="c" :value="c">
{{ c }}
</option>
</select>
<input
v-model="editRefForm.label"
class="ja-input ja-input-sm"
placeholder="Label"
/>
<input
v-model="editRefForm.value"
class="ja-input ja-input-sm"
placeholder="Value"
/>
<button
class="cv-btn cv-btn-sm cv-btn-primary"
@click="saveRefEdit(ref.id)"
>
Save
</button>
<button class="cv-btn cv-btn-sm" @click="cancelRefEdit">
Cancel
</button>
</template>
</div>
<p v-if="!refsByCategory(cat).length" class="ja-ref-empty">
No {{ cat }} items yet.
</p>
</div>
<form class="ja-ref-form" @submit.prevent="createReference">
<select v-model="refForm.category" class="ja-input ja-select">
<option v-for="c in REF_CATEGORIES" :key="c" :value="c">
{{ c }}
</option>
</select>
<input
v-model="refForm.label"
class="ja-input"
placeholder="Label *"
required
/>
<input
v-model="refForm.value"
class="ja-input"
placeholder="Value *"
required
/>
<button type="submit" class="cv-btn cv-btn-primary">Add</button>
</form>
</div>
<JobReferences @fail="fail" @ok="clearError" />
<form class="ja-form" @submit.prevent="createApplication">
<div class="ja-form-row">
<input
v-model="form.jobTitle"
class="ja-input"
placeholder="Job title *"
required
/>
<input
v-model="form.company"
class="ja-input"
placeholder="Company *"
required
/>
<select v-model="form.status" class="ja-input ja-select">
<option v-for="s in STATUS_OPTIONS" :key="s.value" :value="s.value">
{{ s.label }}
</option>
</select>
</div>
<div class="ja-form-row">
<input
v-model="form.location"
class="ja-input"
placeholder="Location"
/>
<input v-model="form.url" class="ja-input" placeholder="URL" />
<input
v-model="form.appliedAt"
class="ja-input"
type="date"
title="Applied date"
/>
</div>
<div class="ja-form-row">
<textarea
v-model="form.notes"
class="ja-input ja-textarea"
placeholder="Notes"
/>
<button type="submit" class="cv-btn cv-btn-primary">Add</button>
</div>
</form>
<JobApplicationForm @fail="fail" @ok="clearError" />
<!-- Pipeline bar: counts at a glance, each one a filter toggle. -->
<div class="ja-pipeline" v-if="applications.length">
@@ -835,7 +524,9 @@ onMounted(() => {
</template>
<style scoped>
/* Colours are the paper palette from CVLayout.vue; buttons are .cv-btn from there too. */
/* Colours are the paper palette from CVLayout.vue; buttons are .cv-btn from
there too. The input classes (.ja-input, .ja-input-sm, .ja-select) are in
jobs-shared.css because the child components use them as well. */
.ja-root {
padding: 1.5rem;
border-top: 2px solid var(--color-ink-soft);
@@ -893,51 +584,6 @@ onMounted(() => {
font-size: 0.85rem;
}
/* Forms */
.ja-form {
display: flex;
flex-direction: column;
gap: 0.5rem;
margin-bottom: 1.5rem;
}
.ja-form-row {
display: flex;
gap: 0.5rem;
flex-wrap: wrap;
}
.ja-input {
padding: 0.35rem 0.6rem;
border: 1px solid var(--color-line);
border-radius: 4px;
font-size: 0.85rem;
background: var(--color-paper);
flex: 1;
min-width: 120px;
}
.ja-input:focus {
outline: none;
border-color: var(--color-ink-muted);
}
.ja-select {
cursor: pointer;
}
.ja-textarea {
resize: vertical;
min-height: 2.4rem;
}
.ja-input-sm {
padding: 0.2rem 0.4rem;
font-size: 0.8rem;
width: 100%;
min-width: 0;
}
.ja-edit-notes {
resize: vertical;
min-height: 3.5rem;
@@ -1139,70 +785,6 @@ onMounted(() => {
font-size: 0.9rem;
}
/* Quick-reference box */
.ja-ref-section {
margin-bottom: 1.5rem;
padding: 1rem;
border: 1px solid var(--color-line-soft);
border-radius: 6px;
background: var(--color-paper);
}
.ja-ref-heading {
font-size: 1rem;
font-weight: 600;
margin-bottom: 0.75rem;
color: var(--color-ink-soft);
}
.ja-ref-category {
margin-bottom: 0.75rem;
}
.ja-ref-cat-label {
font-size: 0.85rem;
font-weight: 600;
color: var(--color-ink-muted);
text-transform: capitalize;
margin-bottom: 0.35rem;
}
.ja-ref-item {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.3rem 0;
}
.ja-ref-label {
font-size: 0.85rem;
font-weight: 500;
color: var(--color-ink-soft);
min-width: 80px;
}
.ja-ref-value {
font-size: 0.85rem;
color: var(--color-ink-muted);
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.ja-ref-empty {
font-size: 0.8rem;
color: var(--color-ink-faint);
margin: 0.2rem 0;
}
.ja-ref-form {
display: flex;
gap: 0.5rem;
margin-top: 0.75rem;
flex-wrap: wrap;
}
/* Seven columns plus an action cell will not fit a phone, so the table becomes
stacked cards with the header text carried by each cell's data-label. */
@media (max-width: 640px) {
+250
View File
@@ -0,0 +1,250 @@
<script setup>
/**
* The "Quick Reference" box on `/cv/jobs`: reusable profile/experience snippets
* to copy into application forms, with inline editing. Rendered only by
* JobApplications.vue; data comes from stores/jobAppReferences.js.
*
* It has no error display of its own — the page has one banner, in the parent,
* so failures are emitted as `fail` (with the error) and every successful
* mutation emits `ok` so the parent can clear a stale message.
*
* Its root sits inside the parent's `.ja-root`, which jobs-shared.css relies on.
*/
import { ref, onMounted } from "vue";
import { storeToRefs } from "pinia";
import { useJobAppReferencesStore } from "@/stores/jobAppReferences";
import "./jobs-shared.css";
const emit = defineEmits(["fail", "ok"]);
const store = useJobAppReferencesStore();
const { references } = storeToRefs(store);
const refForm = ref({ category: "profile", label: "", value: "" });
const editingRefId = ref(null);
const editRefForm = ref({});
const REF_CATEGORIES = ["profile", "experience"];
async function fetchReferences() {
// The store's fetch() records its failure instead of throwing.
await store.fetch();
if (store.error) emit("fail", store.error);
}
async function createReference() {
if (!refForm.value.label || !refForm.value.value) return;
try {
await store.create({
category: refForm.value.category,
label: refForm.value.label,
value: refForm.value.value,
});
refForm.value = { category: refForm.value.category, label: "", value: "" };
emit("ok");
} catch (err) {
emit("fail", err);
}
}
function startRefEdit(ref) {
editingRefId.value = ref.id;
editRefForm.value = {
category: ref.category,
label: ref.label,
value: ref.value,
};
}
function cancelRefEdit() {
editingRefId.value = null;
editRefForm.value = {};
}
async function saveRefEdit(id) {
try {
await store.update(id, {
category: editRefForm.value.category || undefined,
label: editRefForm.value.label || undefined,
value: editRefForm.value.value || undefined,
});
editingRefId.value = null;
emit("ok");
} catch (err) {
emit("fail", err);
}
}
async function deleteReference(ref) {
if (!confirm(`Delete the reference "${ref.label}"?`)) return;
try {
await store.remove(ref.id);
emit("ok");
} catch (err) {
emit("fail", err);
}
}
function refsByCategory(category) {
return references.value.filter((r) => r.category === category);
}
function copyToClipboard(text) {
navigator.clipboard.writeText(text);
}
onMounted(fetchReferences);
</script>
<template>
<div class="ja-ref-section">
<h3 class="ja-ref-heading">Quick Reference</h3>
<div v-for="cat in REF_CATEGORIES" :key="cat" class="ja-ref-category">
<h4 class="ja-ref-cat-label">{{ cat }}</h4>
<div
v-for="ref in refsByCategory(cat)"
:key="ref.id"
class="ja-ref-item"
>
<template v-if="editingRefId !== ref.id">
<span class="ja-ref-label">{{ ref.label }}</span>
<span class="ja-ref-value" :title="ref.value">{{ ref.value }}</span>
<button
class="cv-btn cv-btn-sm"
@click="copyToClipboard(ref.value)"
title="Copy"
>
Copy
</button>
<button class="cv-btn cv-btn-sm" @click="startRefEdit(ref)">
Edit
</button>
<button
class="cv-btn cv-btn-sm cv-btn-danger"
@click="deleteReference(ref)"
>
Delete
</button>
</template>
<template v-else>
<select
v-model="editRefForm.category"
class="ja-input ja-input-sm ja-select"
>
<option v-for="c in REF_CATEGORIES" :key="c" :value="c">
{{ c }}
</option>
</select>
<input
v-model="editRefForm.label"
class="ja-input ja-input-sm"
placeholder="Label"
/>
<input
v-model="editRefForm.value"
class="ja-input ja-input-sm"
placeholder="Value"
/>
<button
class="cv-btn cv-btn-sm cv-btn-primary"
@click="saveRefEdit(ref.id)"
>
Save
</button>
<button class="cv-btn cv-btn-sm" @click="cancelRefEdit">
Cancel
</button>
</template>
</div>
<p v-if="!refsByCategory(cat).length" class="ja-ref-empty">
No {{ cat }} items yet.
</p>
</div>
<form class="ja-ref-form" @submit.prevent="createReference">
<select v-model="refForm.category" class="ja-input ja-select">
<option v-for="c in REF_CATEGORIES" :key="c" :value="c">
{{ c }}
</option>
</select>
<input
v-model="refForm.label"
class="ja-input"
placeholder="Label *"
required
/>
<input
v-model="refForm.value"
class="ja-input"
placeholder="Value *"
required
/>
<button type="submit" class="cv-btn cv-btn-primary">Add</button>
</form>
</div>
</template>
<style scoped>
/* Colours are the paper palette from CVLayout.vue; buttons are .cv-btn from
there too, and the inputs are styled by jobs-shared.css. */
.ja-ref-section {
margin-bottom: 1.5rem;
padding: 1rem;
border: 1px solid var(--color-line-soft);
border-radius: 6px;
background: var(--color-paper);
}
.ja-ref-heading {
font-size: 1rem;
font-weight: 600;
margin-bottom: 0.75rem;
color: var(--color-ink-soft);
}
.ja-ref-category {
margin-bottom: 0.75rem;
}
.ja-ref-cat-label {
font-size: 0.85rem;
font-weight: 600;
color: var(--color-ink-muted);
text-transform: capitalize;
margin-bottom: 0.35rem;
}
.ja-ref-item {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.3rem 0;
}
.ja-ref-label {
font-size: 0.85rem;
font-weight: 500;
color: var(--color-ink-soft);
min-width: 80px;
}
.ja-ref-value {
font-size: 0.85rem;
color: var(--color-ink-muted);
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.ja-ref-empty {
font-size: 0.8rem;
color: var(--color-ink-faint);
margin: 0.2rem 0;
}
.ja-ref-form {
display: flex;
gap: 0.5rem;
margin-top: 0.75rem;
flex-wrap: wrap;
}
</style>
+31
View File
@@ -0,0 +1,31 @@
/**
* The job-application status vocabulary, as the tracker at /cv/jobs shows it.
*
* This is a COPY. The source of truth is server-side: `enum JobStatus` in
* backend/graph/schema/job_application.graphql, ranked by `statusOrder` in
* backend/services/email_sync.go (the email pipeline only ever moves a row
* forward through that order). The server rejects any value outside the enum,
* so a status added here alone cannot be saved — add it there first.
*
* There is a third copy in vue/public/job-capture.user.js (STATUS_LABELS). A
* userscript is a single file installed into the browser and cannot import
* modules, so it has to be kept in step by hand.
*
* Values are the lowercase keys that go over the wire; labels are display-only.
*/
export const STATUS_OPTIONS = [
// Captured from the browser but not applied to yet. No email produces it.
{ value: "saved", label: "Saved" },
{ value: "applied", label: "Applied" },
{ value: "screening", label: "Screening" },
{ value: "assessment", label: "Assessment" },
{ value: "interviewing", label: "Interviewing" },
{ value: "offer", label: "Offer" },
{ value: "rejected", label: "Rejected" },
{ value: "withdrawn", label: "Withdrawn" },
];
// Statuses still in play — used to decide whether a row is worth chasing.
// "saved" is absent on purpose: nobody owes a reply on a job not applied to.
export const OPEN_STATUSES = ["applied", "screening", "assessment", "interviewing"];
+39
View File
@@ -0,0 +1,39 @@
/*
* Form controls shared by the job tracker's components (JobApplications.vue and
* the JobReferences / JobApplicationForm components it renders).
*
* These lived in JobApplications.vue's scoped block until the page was split.
* Scoped styles stop at a child component's root element, so the inputs inside
* the children would have lost them; this file is imported by each component
* instead. It is unscoped, so every selector is prefixed with the page's
* `.ja-root` class — which also keeps the specificity at (0,2,0), the same as
* the scoped originals, so they still beat CVLayout's `.cv-layout input`.
*
* Colours are the paper palette from CVLayout.vue.
*/
.ja-root .ja-input {
padding: 0.35rem 0.6rem;
border: 1px solid var(--color-line);
border-radius: 4px;
font-size: 0.85rem;
background: var(--color-paper);
flex: 1;
min-width: 120px;
}
.ja-root .ja-input:focus {
outline: none;
border-color: var(--color-ink-muted);
}
.ja-root .ja-select {
cursor: pointer;
}
.ja-root .ja-input-sm {
padding: 0.2rem 0.4rem;
font-size: 0.8rem;
width: 100%;
min-width: 0;
}
+15 -10
View File
@@ -8,7 +8,7 @@
* the response to generating it, and replacing it needs no restart.
*/
import { ref, onMounted } from "vue";
import axios from "axios";
import { api } from "@/api";
import Button from "@/components/input/Button.vue";
import SecretReveal from "@/components/admin/SecretReveal.vue";
import "./env.css";
@@ -22,11 +22,12 @@ const newToken = ref("");
async function fetchCaptureToken() {
try {
capture.value = (await axios.get("/api/admin/capture-token")).data;
capture.value = await api.get("/admin/capture-token", {
fallback: "Failed to load the capture token state",
});
error.value = "";
} catch (err) {
error.value =
err.response?.data?.error || "Failed to load the capture token state";
error.value = err.message;
}
}
@@ -42,12 +43,14 @@ async function generate() {
return;
busy.value = true;
try {
const res = await axios.post("/api/admin/capture-token");
newToken.value = res.data.token;
capture.value = { set: true, createdAt: res.data.createdAt };
const res = await api.post("/admin/capture-token", undefined, {
fallback: "Failed to generate a token",
});
newToken.value = res.token;
capture.value = { set: true, createdAt: res.createdAt };
error.value = "";
} catch (err) {
error.value = err.response?.data?.error || "Failed to generate a token";
error.value = err.message;
} finally {
busy.value = false;
}
@@ -58,11 +61,13 @@ async function revoke() {
return;
busy.value = true;
try {
capture.value = (await axios.delete("/api/admin/capture-token")).data;
capture.value = await api.delete("/admin/capture-token", {
fallback: "Failed to revoke the token",
});
newToken.value = "";
error.value = "";
} catch (err) {
error.value = err.response?.data?.error || "Failed to revoke the token";
error.value = err.message;
} finally {
busy.value = false;
}
+7 -6
View File
@@ -10,7 +10,7 @@
*/
import Button from "@/components/input/Button.vue";
import { ref } from "vue";
import axios from "axios";
import { api } from "@/api";
const emit = defineEmits(["done", "cancel"]);
@@ -34,19 +34,20 @@ async function submit() {
const formData = new FormData();
formData.append("image", file);
try {
const res = await axios.post("/api/rowing", formData, {
const res = await api.post("/rowing", formData, {
headers: { "Content-Type": "multipart/form-data" },
fallback: "Upload failed",
});
// Time comes back as a Go time.Duration, i.e. nanoseconds.
const mins = Math.floor(res.data.Time / 1e9 / 60);
const secs = String(Math.floor((res.data.Time / 1e9) % 60)).padStart(
const mins = Math.floor(res.Time / 1e9 / 60);
const secs = String(Math.floor((res.Time / 1e9) % 60)).padStart(
2,
"0",
);
results.value[i].status = `${res.data.Distance}m in ${mins}:${secs}`;
results.value[i].status = `${res.Distance}m in ${mins}:${secs}`;
results.value[i].ok = true;
} catch (err) {
results.value[i].status = err.response?.data?.error || "Upload failed";
results.value[i].status = err.message;
results.value[i].ok = false;
}
}),
+6 -4
View File
@@ -10,7 +10,7 @@
* onMounted, which is the desired "refresh on tab change" behaviour.
*/
import { ref, onMounted, computed } from "vue";
import axios from "axios";
import { api } from "@/api";
import Button from "@/components/input/Button.vue";
const lines = ref([]);
@@ -20,11 +20,13 @@ const loadingLogs = ref(false);
async function fetchLogs() {
loadingLogs.value = true;
try {
const res = await axios.get("/api/admin/logs");
lines.value = res.data.lines;
const res = await api.get("/admin/logs", {
fallback: "Failed to load logs",
});
lines.value = res.lines;
logsError.value = "";
} catch (err) {
logsError.value = err.response?.data?.error || "Failed to load logs";
logsError.value = err.message;
} finally {
loadingLogs.value = false;
}
+20 -20
View File
@@ -16,7 +16,7 @@
* once from the response that created it.
*/
import { ref, reactive, computed, onMounted, onUnmounted } from "vue";
import axios from "axios";
import { api } from "@/api";
import Button from "@/components/input/Button.vue";
import SecretReveal from "@/components/admin/SecretReveal.vue";
import CaptureToken from "./CaptureToken.vue";
@@ -54,13 +54,15 @@ function resetDrafts() {
async function fetchEnv() {
try {
const res = await axios.get("/api/admin/env");
groups.value = res.data.groups;
status.value = res.data.status;
const res = await api.get("/admin/env", {
fallback: "Failed to load the environment",
});
groups.value = res.groups;
status.value = res.status;
error.value = "";
resetDrafts();
} catch (err) {
error.value = err.response?.data?.error || "Failed to load the environment";
error.value = err.message;
} finally {
loading.value = false;
}
@@ -137,19 +139,18 @@ async function apply() {
applying.value = true;
outcome.value = null;
try {
const res = await axios.put("/api/admin/env", body);
revealed.value = res.data.generated || {};
status.value = res.data.status;
awaitedId.value = res.data.status.id;
const res = await api.put("/admin/env", body, {
fallback: "Failed to queue the change",
});
revealed.value = res.generated || {};
status.value = res.status;
awaitedId.value = res.status.id;
// Staged secrets have been sent; do not keep them in the inputs.
resetDrafts();
startPolling();
} catch (err) {
applying.value = false;
outcome.value = {
ok: false,
text: err.response?.data?.error || "Failed to queue the change",
};
outcome.value = { ok: false, text: err.message };
}
}
@@ -165,12 +166,12 @@ function stopPolling() {
async function poll() {
let next;
try {
next = (await axios.get("/api/admin/env/status")).data;
next = await api.get("/admin/env/status");
} catch (err) {
// 401/403 after an apply means the change invalidated this session
// (rotating BACKEND_SECRET does). Anything else is the backend
// restarting, which is the apply working.
if ([401, 403].includes(err.response?.status)) {
if ([401, 403].includes(err.status)) {
stopPolling();
applying.value = false;
outcome.value = {
@@ -200,15 +201,14 @@ async function poll() {
async function cancelPending() {
try {
status.value = (await axios.delete("/api/admin/env/pending")).data;
status.value = await api.delete("/admin/env/pending", {
fallback: "Failed to withdraw the change",
});
stopPolling();
applying.value = false;
outcome.value = { ok: true, text: "Pending change withdrawn. Nothing was applied." };
} catch (err) {
outcome.value = {
ok: false,
text: err.response?.data?.error || "Failed to withdraw the change",
};
outcome.value = { ok: false, text: err.message };
}
}
+5
View File
@@ -17,6 +17,11 @@ 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.
auth.ensureLoaded();
const router = useRouter();
const route = useRoute();
const username = ref("");
+8 -9
View File
@@ -5,7 +5,7 @@
*/
import Button from "@/components/input/Button.vue";
import { ref, onMounted } from "vue";
import axios from "axios";
import { api } from "@/api";
const songs = ref([]);
const files = ref([]);
@@ -14,8 +14,8 @@ const loading = ref(false);
async function fetchSongs() {
try {
const res = await axios.get("/api/radio/songs");
songs.value = res.data.songs;
const res = await api.get("/radio/songs");
songs.value = res.songs;
} catch (err) {
console.error(err);
}
@@ -39,13 +39,14 @@ async function upload() {
const formData = new FormData();
formData.append("file", file);
try {
await axios.post("/api/radio/upload", formData, {
await api.post("/radio/upload", formData, {
headers: { "Content-Type": "multipart/form-data" },
fallback: "Upload failed",
});
results.value[i].status = "Uploaded";
results.value[i].ok = true;
} catch (err) {
results.value[i].status = err.response?.data?.error || "Upload failed";
results.value[i].status = err.message;
results.value[i].ok = false;
}
}),
@@ -58,7 +59,7 @@ async function upload() {
async function deleteSong(name) {
try {
await axios.delete(`/api/radio/songs/${encodeURIComponent(name)}`);
await api.delete(`/radio/songs/${encodeURIComponent(name)}`);
await fetchSongs();
} catch (err) {
console.error(err);
@@ -68,9 +69,7 @@ async function deleteSong(name) {
async function toggleSong(song) {
const action = song.disabled ? "enable" : "disable";
try {
await axios.patch(
`/api/radio/songs/${encodeURIComponent(song.name)}/${action}`,
);
await api.patch(`/radio/songs/${encodeURIComponent(song.name)}/${action}`);
await fetchSongs();
} catch (err) {
console.error(err);
+4 -2
View File
@@ -27,12 +27,14 @@ const CreateRowing = defineAsyncComponent(
);
const store = useHomeDataStore();
const { loaded, error, rowingSessions } = storeToRefs(store);
const { settled, error, rowingSessions } = storeToRefs(store);
const showCreate = ref(false);
// slice() first: reverse() mutates in place and would reorder the store's array.
const rows = computed(() => rowingSessions.value.slice().reverse());
const loading = computed(() => !loaded.value);
// `settled`, not `loaded`: a home query that fails never sets `loaded`, and the
// error branch below would be unreachable behind a permanent spinner.
const loading = computed(() => !settled.value);
const metric = ref("distance");
const hovered = ref(null);
+2 -3
View File
@@ -10,6 +10,7 @@ import { computed, onMounted } from "vue";
import { useSongsStore } from "@/stores/songs";
import { useAuthStore } from "@/stores/auth";
import { useRotation } from "@/js/useRotation";
import { api } from "@/api";
const ROTATE_MS = 5000;
const REFRESH_MS = 120000;
@@ -38,9 +39,7 @@ const showReconnect = computed(
// stays as it was.
async function reconnect() {
try {
const res = await fetch("/api/spotify/auth");
if (!res.ok) return;
const { url } = await res.json();
const { url } = await api.get("/spotify/auth");
window.location.href = url;
} catch (err) {
console.error("Cannot start Spotify re-authentication", err);
+5 -4
View File
@@ -1,9 +1,10 @@
<script setup>
/**
* Steam widget on /stp: online status plus a rotation through recent games
* (5s rotation, 5-minute re-poll, both from useRotation()). `loaded` comes from
* (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".
* show" — and, unlike `loaded`, it also turns true when the fetch fails, so the
* widget cannot sit on "Loading..." forever.
*/
import { computed } from "vue";
import { storeToRefs } from "pinia";
@@ -18,7 +19,7 @@ const REFRESH_MS = 5 * 60 * 1000;
const steamStore = useSteamStore();
const { steamStatus } = storeToRefs(steamStore);
const homeData = useHomeDataStore();
const { loaded } = storeToRefs(homeData);
const { settled } = storeToRefs(homeData);
const { idx, next: nextGame } = useRotation(
() => steamStatus.value.recentGames,
@@ -47,7 +48,7 @@ function formatHours(minutes) {
</span>
</Header>
<div v-if="!loaded" class="p-2 text-sm">Loading...</div>
<div v-if="!settled" class="p-2 text-sm">Loading...</div>
<div v-else-if="game" class="game-container">
<Transition name="fade">