Pull pipeline/ from boilerplate a80ad8a: cadence picker, queue badge, label refresh

The schedule cadence is a picker, the add row is behind a button and off
here, a running-jobs chip with Kill and Stop run sits in every header, and
a declared schedule's label is refreshed at startup.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
WolfandClaude Fable 5.1 committed 2026-09-28 16:22:46 +02:00
1 parent cebe62ddc9
commit 3a240e51df
16 files changed
+828 -167

No files matched your search

+477 -38
View File
@@ -2,10 +2,13 @@
*
* <script type="module" src="/_jobs/jobs.js"></script>
* <desk-jobs></desk-jobs>
* <desk-queue href="/jobs"></desk-queue>
*
* That is the whole of it. The element finds `/ws/jobs` itself, shows what is
* running with a progress bar and a Kill button each, says how many are
* waiting, and reconnects when the server restarts under you.
* That is the whole of it. `<desk-jobs>` finds `/ws/jobs` itself, shows what
* is running with a progress bar and a Kill button each, says how many are
* waiting, and reconnects when the server restarts under you. `<desk-queue>`
* is the same socket as a chip for a top bar, with the list in a popover;
* see its own comment further down.
*
* One file, and the styles are in it rather than beside it, because the
* shadow root scopes them anyway and a second file is a second route, a
@@ -32,6 +35,9 @@
* common reason and the less confusing thing to be wrong about.
* idle="hide" with nothing running or queued, take up no space. The
* default, since a chip that is always there is furniture.
* idle="show" stay, and say "Nothing running." — for a page with a
* heading over the element, which reads as broken over an
* empty panel.
*/
const CSS = `
@@ -89,6 +95,7 @@ button:hover { color: var(--desk-jobs-error); }
button[disabled] { opacity: .4; cursor: default; }
.offline { color: var(--desk-jobs-error); }
.idle { color: var(--desk-jobs-dim); }
/* A finger: Kill is a thumb's height. Sizes only; the layout is the width
* query below, and neither reads the other. */
@@ -115,24 +122,29 @@ const LONGEST_WAIT = 30000;
* really is gone and the strip is quietly showing state from a minute ago. */
const QUIET_ABOUT_IT_FOR = 4000;
class DeskJobs extends HTMLElement {
#root;
/** The socket half of both elements: connecting, backing off, the probe, and
* the snapshot as it last arrived. Each element holds its own connection, as
* `<desk-schedules>` does; sharing one between elements on a page would be a
* registry of subscribers to save a socket the broadcaster does not notice.
* A subclass draws `state` in `render()`. */
class Follower extends HTMLElement {
root;
state = { running: [], queued: [], recent: [], cascades: [] };
offline = false;
killing = new Set();
#socket = null;
#wait = FIRST_WAIT;
#timer = null;
#state = { running: [], queued: [], recent: [] };
#offline = false;
#killing = new Set();
constructor() {
constructor(css) {
super();
this.#root = this.attachShadow({ mode: "open" });
this.root = this.attachShadow({ mode: "open" });
const style = document.createElement("style");
style.textContent = CSS;
this.#root.append(style, document.createElement("div"));
style.textContent = css;
this.root.append(style, document.createElement("div"));
}
connectedCallback() { this.#connect(); this.#render(); }
connectedCallback() { this.#connect(); this.render(); }
disconnectedCallback() {
clearTimeout(this.#timer);
@@ -140,15 +152,20 @@ class DeskJobs extends HTMLElement {
this.#socket = null;
}
get #base() { return this.getAttribute("base") ?? ""; }
get base() { return this.getAttribute("base") ?? ""; }
/** Whether a notice on the socket is raised as `desk-jobs:notice`. */
get raisesNotices() { return true; }
get #socketUrl() {
const given = this.getAttribute("socket");
if (given) return given;
const scheme = location.protocol === "https:" ? "wss" : "ws";
return `${scheme}://${location.host}${this.#base}/ws/jobs`;
return `${scheme}://${location.host}${this.base}/ws/jobs`;
}
render() {}
#connect() {
let socket;
try {
@@ -161,17 +178,17 @@ class DeskJobs extends HTMLElement {
socket.onopen = () => {
this.#wait = FIRST_WAIT;
this.#offline = false;
this.#render();
this.offline = false;
this.render();
};
socket.onmessage = (event) => {
let message;
try { message = JSON.parse(event.data); } catch { return; }
if (message.type === "jobs") {
const { type, ...state } = message;
this.#state = state;
this.#render();
} else if (message.type === "notice") {
this.state = state;
this.render();
} else if (message.type === "notice" && this.raisesNotices) {
// The app's to word. Composed, so a listener on `document` hears it
// through the shadow boundary.
this.dispatchEvent(new CustomEvent("desk-jobs:notice", {
@@ -193,53 +210,64 @@ class DeskJobs extends HTMLElement {
const probe = this.getAttribute("probe");
if (!probe) return;
try {
const answer = await fetch(this.#base + probe, { credentials: "same-origin" });
const answer = await fetch(this.base + probe, { credentials: "same-origin" });
if (answer.status === 401 || answer.status === 403) {
this.dispatchEvent(new CustomEvent("desk-jobs:signed-out", {
bubbles: true, composed: true,
}));
}
} catch { /* offline; the strip says so below */ }
} catch { /* offline; the element says so below */ }
}
#reconnect() {
if (this.#wait >= QUIET_ABOUT_IT_FOR) {
this.#offline = true;
this.#render();
this.offline = true;
this.render();
}
clearTimeout(this.#timer);
this.#timer = setTimeout(() => this.#connect(), this.#wait);
this.#wait = Math.min(this.#wait * 2, LONGEST_WAIT);
}
async #kill(id) {
this.#killing.add(id);
this.#render();
async kill(id) {
this.killing.add(id);
this.render();
try {
await fetch(`${this.#base}/api/jobs/${id}/cancel`,
await fetch(`${this.base}/api/jobs/${id}/cancel`,
{ method: "POST", credentials: "same-origin" });
} finally {
// The socket reports the actual ending — a running job stops at its next
// checkpoint, so the button going quiet is the whole of what happens here.
this.#killing.delete(id);
this.killing.delete(id);
}
}
}
#render() {
const { running = [], queued = [] } = this.#state;
const strip = this.#root.lastElementChild;
this.hidden = this.getAttribute("idle") !== "show"
&& !running.length && !queued.length && !this.#offline;
class DeskJobs extends Follower {
constructor() { super(CSS); }
render() {
const { running = [], queued = [] } = this.state;
const strip = this.root.lastElementChild;
const idle = !running.length && !queued.length && !this.offline;
const show = this.getAttribute("idle") === "show";
this.hidden = idle && !show;
strip.className = "strip";
strip.replaceChildren();
if (this.#offline) {
if (this.offline) {
const said = document.createElement("div");
said.className = "offline";
said.textContent = "Not connected — what you see here may be out of date.";
strip.append(said);
}
if (idle && show) {
const said = document.createElement("div");
said.className = "idle";
said.textContent = "Nothing running.";
strip.append(said);
}
for (const job of running) {
strip.append(this.#row(job));
@@ -263,8 +291,8 @@ class DeskJobs extends HTMLElement {
const kill = document.createElement("button");
kill.textContent = "Kill";
kill.disabled = this.#killing.has(job.id) || job.cancel_requested;
kill.addEventListener("click", () => this.#kill(job.id));
kill.disabled = this.killing.has(job.id) || job.cancel_requested;
kill.addEventListener("click", () => this.kill(job.id));
row.append(kill);
if (job.message) {
@@ -285,8 +313,419 @@ class DeskJobs extends HTMLElement {
}
}
/* <desk-queue>: the queue as a chip for a top bar, after newsdesk's queue
* light.
*
* <desk-queue href="/jobs"></desk-queue>
*
* The chip is a dot, how many jobs are running, and the first one's label and
* progress: "Embedding roles, 6 of 6, +2 waiting". Its message is the chip's
* tooltip, since a sentence does not fit in a top bar. Grey and "Idle" when
* nothing runs, a red dot and "Offline" when the socket is down. Pressing it opens a popover that is the queue as
* the queue holds it: one line per running or queued job with its message,
* done/total, how long it has been at it, and Kill; one line per live cascade
* with Stop run; and, with `href`, a link to the app's full page. Anywhere
* else, or Escape, closes it.
*
* Colours are the `--desk-jobs-*` properties read with fallbacks rather than
* set on `:host` as `<desk-jobs>` sets them, so a theme on `:root` or on an
* ancestor reaches it, and with none at all the chip takes the colour and
* font of the bar it sits in.
*
* Notices on the socket are not re-raised: this sits on every page, next to a
* `<desk-jobs>` on some of them, and one failure would toast twice.
*
* Attributes, all optional:
* href="/jobs" a link at the foot of the popover. Its text is the
* element's content, "All runs" when it has none.
* idle="hide" with nothing running or queued, take up no space. The
* default is a grey chip, because a light that disappears
* cannot say the queue is idle.
* base, socket, probe
* as for `<desk-jobs>`.
*/
const QUEUE_CSS = `
:host {
display: inline-block;
position: relative;
font: inherit;
color: inherit;
}
:host([hidden]) { display: none; }
[hidden] { display: none !important; }
.chip {
display: inline-flex;
align-items: center;
gap: .4em;
max-width: 22rem;
font: inherit;
font-size: .85em;
font-variant-numeric: tabular-nums;
color: var(--desk-jobs-dim, currentColor);
background: none;
border: 1px solid color-mix(in srgb, currentColor 30%, transparent);
border-radius: 999px;
padding: .2em .7em;
cursor: pointer;
}
.chip.busy { color: var(--desk-jobs-fg, currentColor); }
.chip:focus-visible { outline: 2px solid var(--desk-jobs-accent, #4c8dff); outline-offset: 1px; }
.dot {
flex: none;
width: .55em;
height: .55em;
border-radius: 50%;
background: currentColor;
opacity: .45;
}
.chip.busy .dot {
background: var(--desk-jobs-accent, #4c8dff);
opacity: 1;
animation: beat 1.4s ease-in-out infinite;
}
.chip.offline .dot { background: var(--desk-jobs-error, #d33); opacity: 1; animation: none; }
@keyframes beat { 50% { opacity: .35; } }
@media (prefers-reduced-motion: reduce) { .chip.busy .dot { animation: none; } }
.chip .what { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.chip .what:empty, .n:empty, .n.one { display: none; }
.pop {
position: absolute;
top: calc(100% + 6px);
right: 0;
z-index: 20;
min-width: 22rem;
max-width: min(30rem, 90vw);
max-height: 60vh;
overflow: auto;
box-sizing: border-box;
padding: 6px;
text-align: left;
font-family: var(--desk-jobs-font, inherit);
font-size: 13px;
font-weight: normal;
color: var(--desk-jobs-fg, CanvasText);
background: var(--desk-jobs-bg, Canvas);
border: 1px solid color-mix(in srgb, var(--desk-jobs-fg, CanvasText) 15%, transparent);
border-radius: var(--desk-jobs-radius, 10px);
box-shadow: 0 .5rem 1.5rem rgba(0, 0, 0, .18);
}
/* A process list: the label, what it says, how far, how long, and Kill. The
* digits line up so the one line at 5:20 among lines at 0:0x is the one to
* look at. Queued lines are faint; they are not being run. */
.line, .run {
display: flex;
align-items: center;
gap: 8px;
padding: 4px 6px;
}
.line + .line, .run + .run { border-top: 1px dashed color-mix(in srgb, var(--desk-jobs-fg, CanvasText) 15%, transparent); }
.line.queued, .line.waiting { color: var(--desk-jobs-dim, GrayText); }
.line .what, .run .what { font-weight: 600; white-space: nowrap; }
.line.queued .what { font-weight: 400; }
.said { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis;
white-space: nowrap; color: var(--desk-jobs-dim, GrayText); }
.pct, .age { font-variant-numeric: tabular-nums; white-space: nowrap;
color: var(--desk-jobs-dim, GrayText); }
.age { min-width: 2.6em; text-align: right; }
.heading { padding: 8px 6px 2px; font-size: 11px; font-weight: 600;
color: var(--desk-jobs-dim, GrayText); }
.idle, .offline { padding: 6px; color: var(--desk-jobs-dim, GrayText); }
.offline { color: var(--desk-jobs-error, #d33); }
.all { display: block; padding: 8px 6px 4px; color: var(--desk-jobs-accent, LinkText); }
.pop button {
flex: none;
font: inherit;
color: var(--desk-jobs-dim, GrayText);
background: none;
border: 1px solid currentColor;
border-radius: 6px;
padding: 1px 8px;
cursor: pointer;
}
.pop button:hover:not([disabled]) { color: var(--desk-jobs-error, #d33); }
.pop button[disabled] { opacity: .4; cursor: default; }
@media (pointer: coarse) {
.chip { min-height: 2.5rem; }
.pop button { min-height: 2.5rem; padding: 4px 12px; }
}
/* A phone: the bar has no room for a sentence, so the chip is the dot and
* the count, and the popover spans the screen under the bar. Its top is set
* from the chip's position when it opens. */
@media (max-width: 40rem) {
.chip .what { display: none; }
.n.one { display: inline; }
.pop {
position: fixed;
top: var(--desk-queue-top, 3.5rem);
left: .5rem;
right: .5rem;
min-width: 0;
max-width: none;
}
}
`;
/** How long, as a player writes it: 0:04, 5:20, 1:02:07. */
function clock(seconds) {
const total = Math.max(0, Math.round(seconds || 0));
const h = Math.floor(total / 3600), m = Math.floor((total % 3600) / 60), s = total % 60;
const mm = h ? String(m).padStart(2, "0") : String(m);
return (h ? `${h}:` : "") + `${mm}:${String(s).padStart(2, "0")}`;
}
const age = (stamp) => stamp ? clock((Date.now() - new Date(stamp)) / 1000) : "";
/** A running job with nothing left to count: the bar reaches its total well
* before the handler returns, and "12 of 12" for a minute reads as stuck. */
const finishing = (job) => job.state === "running" && job.total > 0 && job.done >= job.total;
const progress = (job) => !job.total ? "" : finishing(job) ? "finishing"
: `${job.done} of ${job.total}`;
/** Keep the rows, write the numbers into them. The snapshot arrives four
* times a second while anything runs, and a list rebuilt that often takes
* the Kill button out from under the pointer on its way to it. Keyed by the
* server's id, so "the same row" means the same job. */
function sync(parent, entries, make, fill) {
const had = new Map();
for (const el of parent.children) had.set(el.dataset.key, el);
let last = null;
for (const [key, item] of entries) {
let el = had.get(String(key));
if (el) had.delete(String(key));
else { el = make(item); el.dataset.key = String(key); }
fill(el, item);
const at = last ? last.nextElementSibling : parent.firstElementChild;
if (el !== at) parent.insertBefore(el, at);
last = el;
}
for (const el of had.values()) el.remove();
}
function span(className) {
const el = document.createElement("span");
el.className = className;
return el;
}
const tally = (t) => t.done + t.failed + t.cancelled + t.running + t.queued;
class DeskQueue extends Follower {
#open = false;
#ticker = null;
#stopping = new Set();
#chip;
#pop;
static get observedAttributes() { return ["href", "idle"]; }
constructor() {
super(QUEUE_CSS);
const host = this.root.lastElementChild;
this.#chip = document.createElement("button");
this.#chip.type = "button";
this.#chip.className = "chip";
this.#chip.setAttribute("aria-haspopup", "true");
this.#chip.setAttribute("aria-expanded", "false");
this.#chip.append(span("dot"), span("n"), span("what"));
this.#chip.addEventListener("click", () => this.#toggle());
this.#pop = document.createElement("div");
this.#pop.className = "pop";
this.#pop.hidden = true;
const offline = document.createElement("div");
offline.className = "offline";
offline.textContent = "Not connected — this may be out of date.";
const lines = document.createElement("div");
lines.className = "lines";
const heading = document.createElement("div");
heading.className = "heading";
heading.textContent = "Runs";
const runs = document.createElement("div");
runs.className = "runs";
const all = document.createElement("a");
all.className = "all";
const slot = document.createElement("slot");
slot.textContent = "All runs";
all.append(slot);
this.#pop.append(offline, lines, heading, runs, all);
host.append(this.#chip, this.#pop);
}
get raisesNotices() { return false; }
connectedCallback() {
super.connectedCallback();
document.addEventListener("click", this.#outside);
document.addEventListener("keydown", this.#escape);
}
disconnectedCallback() {
super.disconnectedCallback();
document.removeEventListener("click", this.#outside);
document.removeEventListener("keydown", this.#escape);
clearInterval(this.#ticker);
this.#ticker = null;
}
attributeChangedCallback() { this.render(); }
// Arrow functions, so that the same function is added and removed.
#outside = (e) => {
if (this.#open && !e.composedPath().includes(this)) this.#toggle(false);
};
#escape = (e) => {
if (e.key !== "Escape" || !this.#open) return;
this.#toggle(false);
this.#chip.focus();
};
#toggle(open = !this.#open) {
this.#open = open;
if (open) {
this.style.setProperty("--desk-queue-top",
`${this.#chip.getBoundingClientRect().bottom + 6}px`);
}
this.render();
}
async #stop(id) {
this.#stopping.add(id);
this.render();
try {
await fetch(`${this.base}/api/cascades/${id}/cancel`,
{ method: "POST", credentials: "same-origin" });
} finally {
this.#stopping.delete(id);
}
}
render() {
if (!this.#chip) return; // an attribute, before the constructor ran
const { running = [], queued = [] } = this.state;
const idle = !running.length && !queued.length;
this.hidden = this.getAttribute("idle") === "hide" && idle && !this.offline;
const chip = this.#chip;
chip.classList.toggle("busy", running.length > 0);
chip.classList.toggle("offline", this.offline);
const n = chip.querySelector(".n");
n.textContent = running.length || "";
n.classList.toggle("one", running.length === 1);
const first = running[0];
const parts = first ? [first.label || first.kind, progress(first)] : [];
if (queued.length) parts.push(first ? `+${queued.length} waiting` : `${queued.length} waiting`);
// Said in a word as well as a colour: a grey dot alone reads as a switch.
if (!parts.length) parts.push(this.offline ? "Offline" : "Idle");
chip.querySelector(".what").textContent = parts.filter(Boolean).join(", ");
chip.title = this.offline ? "Not connected"
: first ? [first.label || first.kind, first.message].filter(Boolean).join(": ")
: queued.length ? `${queued.length} waiting` : "Nothing running";
chip.setAttribute("aria-expanded", String(this.#open));
this.#pop.hidden = !this.#open;
if (!this.#open) {
clearInterval(this.#ticker);
this.#ticker = null;
return;
}
this.#drawPop(running, queued);
// The ages are the one column no push carries: a job that has said
// nothing for five minutes is the one whose age you want.
this.#ticker ??= setInterval(() => {
for (const el of this.#pop.querySelectorAll(".age")) el.textContent = age(el.dataset.since);
}, 1000);
}
#drawPop(running, queued) {
const pop = this.#pop;
pop.querySelector(".offline").hidden = !this.offline;
const jobs = [...running, ...queued];
sync(pop.querySelector(".lines"),
jobs.length ? jobs.map((j) => [j.id, j]) : [["idle", null]],
(j) => j ? this.#line() : Object.assign(document.createElement("div"),
{ className: "idle", textContent: "Nothing running." }),
(el, j) => { if (j) this.#fillLine(el, j); });
// A cascade of one job is that job, and its Kill already says Stop.
const live = (this.state.cascades || []).filter((c) =>
c.tasks.some((t) => t.running || t.queued)
&& !(c.tasks.length === 1 && tally(c.tasks[0]) <= 1));
pop.querySelector(".heading").hidden = !live.length;
sync(pop.querySelector(".runs"), live.map((c) => [c.id, c]),
() => this.#run(), (el, c) => this.#fillRun(el, c));
const all = pop.querySelector(".all");
const href = this.getAttribute("href");
all.hidden = !href;
if (href) all.href = href;
}
#line() {
const el = document.createElement("div");
el.className = "line";
const kill = document.createElement("button");
kill.type = "button";
kill.textContent = "Kill";
kill.addEventListener("click", () => this.kill(Number(el.dataset.key)));
el.append(span("what"), span("said"), span("pct"), span("age"), kill);
return el;
}
#fillLine(el, job) {
// Running: since it started. Queued: since it was asked for, which is how
// long it has waited behind the others.
const running = job.state === "running";
const since = running ? job.started_at : job.created_at;
el.className = `line ${job.state}${job.waiting ? " waiting" : ""}`;
el.title = `${running ? "running" : "waiting"} since ${since || "?"}`
+ (job.waiting && job.error ? ` — last try: ${job.error}` : "");
el.querySelector(".what").textContent = job.label || job.kind;
el.querySelector(".said").textContent = job.message || "";
el.querySelector(".pct").textContent = progress(job);
const when = el.querySelector(".age");
when.dataset.since = since || "";
when.textContent = age(since);
el.querySelector("button").disabled = this.killing.has(job.id) || !!job.cancel_requested;
}
#run() {
const el = document.createElement("div");
el.className = "run";
const stop = document.createElement("button");
stop.type = "button";
stop.textContent = "Stop run";
stop.addEventListener("click", () => this.#stop(Number(el.dataset.key)));
el.append(span("what"), span("said"), stop);
return el;
}
#fillRun(el, cascade) {
const tasks = cascade.tasks;
const done = tasks.reduce((sum, t) => sum + t.done, 0);
const total = tasks.reduce((sum, t) => sum + tally(t), 0);
const now = tasks.find((t) => t.running || t.queued);
el.querySelector(".what").textContent = cascade.name || `run ${cascade.id}`;
el.querySelector(".said").textContent =
[now && (now.label || now.name), `${done} of ${total} done`].filter(Boolean).join(", ");
el.querySelector("button").disabled = this.#stopping.has(cascade.id);
}
}
if (!customElements.get("desk-jobs")) {
customElements.define("desk-jobs", DeskJobs);
}
if (!customElements.get("desk-queue")) {
customElements.define("desk-queue", DeskQueue);
}
export { DeskJobs };
export { DeskJobs, DeskQueue };
+221 -72
View File
@@ -4,9 +4,16 @@
* <desk-schedules></desk-schedules>
*
* A row per schedule — name, kind, cadence, on or off, next run, last run and
* how that job ended — plus Run now, Delete, and a row at the bottom for
* adding one. The kinds come from `/api/jobs/kinds`, so a new `@job` is a new
* option here without this file being touched.
* how that job ended — plus Run now, Delete, and an "Add a schedule" button
* that opens a row for adding one. The kinds come from `/api/jobs/kinds`, so a
* new `@job` is a new option here without this file being touched.
*
* The cadence is picked, not typed: Every / Daily at / Weekly on, then an
* interval, a time or a day and a time. The picker spells the same canonical
* string the server parses (`every 6h`, `daily at 06:00`, `weekly mon 07:00`),
* so the grammar and the API are unchanged and the server's 422 is still the
* backstop. A stored cadence that is not a preset, such as `every 50m`, is
* added to the options rather than lost.
*
* It reads `/ws/jobs` for `schedules` messages, so a row edited in another tab
* redraws in this one, and a firing moves the times without anybody polling.
@@ -30,6 +37,8 @@
* Attributes, all optional:
* base="/api" prefix for the HTTP calls, if the router is mounted deeper
* socket="..." the socket's URL, if it is not `/ws/jobs` on this origin
* add="off" no way to add a schedule, for an app whose schedules are
* all declared in code. Editing and deleting stay.
*/
const CSS = `
@@ -72,10 +81,7 @@ td.actions { text-align: right; white-space: nowrap; }
.off { opacity: .55; }
.bad { color: var(--desk-jobs-error); }
/* The cadence is edited in place: a box that looks like text until you are in
* it, because a table of eight input fields reads as a form to fill in rather
* than as a list of what is running. */
input.cadence, input.text {
input.text {
font: inherit;
color: inherit;
background: none;
@@ -84,11 +90,10 @@ input.cadence, input.text {
padding: 1px 4px;
min-width: 9em;
}
input.cadence:hover { border-color: color-mix(in srgb, var(--desk-jobs-fg) 20%, transparent); }
input:focus { outline: none; border-color: var(--desk-jobs-accent); }
input:focus, select:focus { outline: none; border-color: var(--desk-jobs-accent); }
input::placeholder { color: var(--desk-jobs-dim); }
select {
select, input.time {
font: inherit;
color: inherit;
background: var(--desk-jobs-bg);
@@ -97,6 +102,15 @@ select {
padding: 1px 4px;
}
/* The cadence is edited in place: in a row its controls look like text until
* hovered, because a table of twenty dropdowns reads as a form to fill in
* rather than as a list of what is running. The add row keeps its borders. */
.picker { display: inline-flex; flex-wrap: wrap; gap: 4px; align-items: baseline; }
tr:not(.adder) .picker > * { border-color: transparent; }
tr:not(.adder) .picker > *:hover { border-color: color-mix(in srgb, var(--desk-jobs-fg) 20%, transparent); }
tr:not(.adder) .picker > *:focus { border-color: var(--desk-jobs-accent); }
button.open { margin: 8px 0 0; }
button {
font: inherit;
color: var(--desk-jobs-dim);
@@ -166,12 +180,12 @@ button[disabled] { opacity: .4; cursor: default; }
display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 4px;
}
td.actions button { margin: 0; }
/* A box that looks like text until hovered has nothing to hover with.
* box-sizing: border-box, because the base rule's padding and border are
* content-box -- width: 100% of a border-box cell plus that padding and
* border is wider than the cell, which is exactly the sliver this media
* query exists to not reintroduce. */
input.cadence { border-color: color-mix(in srgb, var(--desk-jobs-fg) 20%, transparent); min-width: 0; width: 100%; box-sizing: border-box; }
/* A control that looks like text until hovered has nothing to hover with.
* The picker's controls share the cell and wrap rather than overflow it:
* min-width: 0, because a select's natural width is its longest option. */
tr:not(.adder) .picker > * { border-color: color-mix(in srgb, var(--desk-jobs-fg) 20%, transparent); }
.picker { display: flex; }
.picker > * { flex: 1 1 auto; min-width: 0; }
/* The add row: label over field, each field the width of the card. */
tr.adder { grid-template-columns: 1fr; }
tr.adder td { grid-column: 1; }
@@ -182,7 +196,10 @@ button[disabled] { opacity: .4; cursor: default; }
color: var(--desk-jobs-dim);
font-weight: 600;
}
tr.adder input, tr.adder select {
/* box-sizing: border-box, because the base rule's padding and border are
* content-box -- width: 100% of a border-box cell plus that padding and
* border is wider than the cell. */
tr.adder td > input, tr.adder td > select {
width: 100%; min-width: 0; box-sizing: border-box;
border-color: color-mix(in srgb, var(--desk-jobs-fg) 20%, transparent);
}
@@ -194,12 +211,125 @@ button[disabled] { opacity: .4; cursor: default; }
const FIRST_WAIT = 500;
const LONGEST_WAIT = 30000;
/** The grammar, in the one place a person is asked to use it. Two of the five
* as the placeholder, because a box wide enough for all five is a box wide
* enough to unbalance the row it is in — and all five on hover, which is also
* what the server's refusal says if they get it wrong anyway. */
const FORMS = "every 15m · every 6h · every 2d · daily at 06:00 · weekly mon 07:00";
const HINT = "every 15m · daily at 06:00";
/** The intervals offered under Every, shortest first. `every 15m` is the
* shortest worth offering: the queue looks for due schedules every thirty
* seconds, but nothing a small app schedules wants to run more often. */
const INTERVALS = ["15m", "30m", "1h", "2h", "3h", "6h", "12h", "1d", "2d", "7d"];
const UNITS = { m: ["minute", 60], h: ["hour", 3600], d: ["day", 86400] };
/** Short names as `pipeline/schedule.py` stores them, long ones as shown. */
const DAYS = [["mon", "Monday"], ["tue", "Tuesday"], ["wed", "Wednesday"],
["thu", "Thursday"], ["fri", "Friday"], ["sat", "Saturday"],
["sun", "Sunday"]];
/** What a new schedule starts as, and what a form switched to starts with. */
const START = { form: "every", every: "1h", day: "mon", time: "06:00" };
/** A stored cadence, taken apart for the picker. The server stores only the
* canonical spelling, so this reads that and nothing looser; anything else
* (a row edited by hand) comes back `null` and is shown as it is. */
function parse(cadence) {
const said = String(cadence || "").trim().toLowerCase();
let m = said.match(/^every (\d+)([mhd])$/);
if (m) return { ...START, form: "every", every: `${Number(m[1])}${m[2]}` };
m = said.match(/^daily at (\d{2}:\d{2})$/);
if (m) return { ...START, form: "daily", time: m[1] };
m = said.match(/^weekly (mon|tue|wed|thu|fri|sat|sun) (\d{2}:\d{2})$/);
if (m) return { ...START, form: "weekly", day: m[1], time: m[2] };
return null;
}
/** The picker's state as the canonical string the server accepts. */
function spell(p) {
if (p.form === "daily") return `daily at ${p.time}`;
if (p.form === "weekly") return `weekly ${p.day} ${p.time}`;
return `every ${p.every}`;
}
/** `6h` as "6 hours", and its length, for ordering an extra option. */
function interval(text) {
const [, n, unit] = text.match(/^(\d+)([mhd])$/);
const [word, seconds] = UNITS[unit];
return { label: `${n} ${word}${n === "1" ? "" : "s"}`, seconds: Number(n) * seconds };
}
function choice(options, selected, label) {
const select = document.createElement("select");
select.setAttribute("aria-label", label);
for (const [value, text] of options) {
const option = document.createElement("option");
option.value = value;
option.textContent = text;
option.selected = value === selected;
select.append(option);
}
return select;
}
/** The cadence picker: a form, then what that form needs. `pick` is handed
* the canonical string each time a complete one is chosen.
*
* `lazy` is for a stored row, where each pick is a PATCH: the time is then
* taken on blur or Enter rather than on `change`, which a time input raises
* per segment typed — a save and a redraw between the hour and the minute. */
function picker(cadence, { disabled = false, lazy = false, pick }) {
const known = parse(cadence);
const p = known || { ...START };
const wrap = document.createElement("span");
wrap.className = "picker";
const form = choice([["every", "Every"], ["daily", "Daily at"], ["weekly", "Weekly on"]],
known ? p.form : "", "Cadence");
if (!known && cadence) {
// Not a spelling the picker makes: shown as it is, and replaced only when
// somebody picks something else.
const stored = document.createElement("option");
stored.value = "";
stored.textContent = cadence;
stored.selected = true;
form.prepend(stored);
}
const offered = INTERVALS.includes(p.every) ? INTERVALS
: [...INTERVALS, p.every].sort((a, b) => interval(a).seconds - interval(b).seconds);
const every = choice(offered.map((v) => [v, interval(v).label]), p.every, "Interval");
const day = choice(DAYS, p.day, "Day");
const time = document.createElement("input");
time.type = "time";
time.step = 900;
time.className = "time";
time.value = p.time;
time.setAttribute("aria-label", "Time");
const emit = () => pick(spell(p));
const draw = () => {
const parts = { every: [every], daily: [time], weekly: [day, time] }[form.value] || [];
wrap.replaceChildren(form, ...parts);
};
for (const control of [form, every, day, time]) control.disabled = disabled;
form.addEventListener("change", () => {
if (!form.value) return;
p.form = form.value;
draw();
emit();
});
every.addEventListener("change", () => { p.every = every.value; emit(); });
day.addEventListener("change", () => { p.day = day.value; emit(); });
const takeTime = () => {
if (!time.value || time.value === p.time) return;
p.time = time.value;
emit();
};
if (lazy) {
time.addEventListener("blur", takeTime);
time.addEventListener("keydown", (e) => { if (e.key === "Enter") time.blur(); });
} else {
time.addEventListener("change", takeTime);
}
draw();
return wrap;
}
/** A stamp as a person reads it. Today is a time, anything else is a date and
* a time, and "never" is said rather than left blank — an empty cell reads as
@@ -223,6 +353,13 @@ class DeskSchedules extends HTMLElement {
#offline = false;
#busy = new Set();
#loaded = false;
/* The add row: whether it is open, and what is in it. Kept here rather than
* in its inputs because every render rebuilds them, and a push arriving
* mid-typing would otherwise clear what somebody was writing. */
#adding = false;
#draft = { name: "", kind: "", cadence: spell(START) };
static get observedAttributes() { return ["add"]; }
constructor() {
super();
@@ -238,6 +375,10 @@ class DeskSchedules extends HTMLElement {
this.#connect();
}
attributeChangedCallback() {
if (this.isConnected) this.#render();
}
disconnectedCallback() {
clearTimeout(this.#timer);
this.#socket?.close();
@@ -246,6 +387,8 @@ class DeskSchedules extends HTMLElement {
get #base() { return this.getAttribute("base") ?? ""; }
get #canAdd() { return this.getAttribute("add") !== "off"; }
get #socketUrl() {
const given = this.getAttribute("socket");
if (given) return given;
@@ -419,14 +562,26 @@ class DeskSchedules extends HTMLElement {
table.append(this.#head());
const body = document.createElement("tbody");
for (const row of this.#rows) body.append(this.#row(row));
body.append(this.#adder());
if (this.#canAdd && this.#adding) body.append(this.#adder());
table.append(body);
panel.append(table);
if (this.#canAdd && !this.#adding) {
// Closed until asked for. An add row always drawn, with a kind already
// chosen and a cadence filled in, reads as a schedule that exists.
const open = document.createElement("button");
open.className = "open";
open.textContent = "Add a schedule";
open.disabled = this.#loaded && !this.#kinds.length;
if (open.disabled) open.title = "No job is registered to schedule.";
open.addEventListener("click", () => { this.#adding = true; this.#render(); });
panel.append(open);
}
if (this.#loaded && !this.#rows.length) {
const empty = document.createElement("div");
empty.className = "empty";
empty.textContent = "Nothing is scheduled. Add one below.";
empty.textContent = "Nothing is scheduled.";
panel.insertBefore(empty, table);
}
}
@@ -464,23 +619,17 @@ class DeskSchedules extends HTMLElement {
const cadence = document.createElement("td");
cadence.className = "cadence";
cadence.dataset.label = "Cadence";
const box = document.createElement("input");
box.className = "cadence";
box.value = schedule.cadence;
box.title = FORMS;
box.disabled = busy;
const save = () => {
const wanted = box.value.trim();
if (!wanted || wanted === schedule.cadence) {
box.value = schedule.cadence;
return;
}
this.#change(schedule.id, () => this.#ask(`/api/schedules/${schedule.id}`,
{ method: "PATCH", body: { cadence: wanted } }));
};
box.addEventListener("change", save);
box.addEventListener("keydown", (e) => { if (e.key === "Enter") box.blur(); });
cadence.append(box);
cadence.append(picker(schedule.cadence, {
disabled: busy,
lazy: true,
// A refusal redraws the row from what the server holds, so the picker
// goes back to the stored cadence and the 422 goes out as before.
pick: (wanted) => {
if (wanted === schedule.cadence) return;
this.#change(schedule.id, () => this.#ask(`/api/schedules/${schedule.id}`,
{ method: "PATCH", body: { cadence: wanted } }));
},
}));
row.append(cadence);
const onOff = document.createElement("td");
@@ -545,34 +694,29 @@ class DeskSchedules extends HTMLElement {
const row = document.createElement("tr");
row.className = "adder";
const busy = this.#busy.has(0);
const draft = this.#draft;
const name = document.createElement("input");
name.className = "text";
name.placeholder = "optional";
name.value = draft.name;
name.disabled = busy;
name.addEventListener("input", () => { draft.name = name.value; });
row.append(this.#wrap(name, "Name"));
const kind = document.createElement("select");
// Starts on nothing, so that what is added is a choice rather than
// whichever kind sorts first.
const kind = choice([["", this.#kinds.length ? "Choose a job…"
: this.#loaded ? "nothing registered" : "loading…"],
...this.#kinds.map((k) => [k.kind, k.label || k.kind])],
draft.kind, "Kind");
kind.disabled = busy || !this.#kinds.length;
for (const k of this.#kinds) {
const option = document.createElement("option");
option.value = k.kind;
option.textContent = k.label || k.kind;
kind.append(option);
}
if (!this.#kinds.length) {
const none = document.createElement("option");
none.textContent = this.#loaded ? "nothing registered" : "loading…";
kind.append(none);
}
row.append(this.#wrap(kind, "Kind"));
const cadence = document.createElement("input");
cadence.className = "text";
cadence.placeholder = HINT;
cadence.title = FORMS;
cadence.disabled = busy;
row.append(this.#wrap(cadence, "Cadence"));
row.append(this.#wrap(picker(draft.cadence, {
disabled: busy,
pick: (wanted) => { draft.cadence = wanted; },
}), "Cadence"));
row.append(document.createElement("td"), document.createElement("td"),
document.createElement("td"));
@@ -581,26 +725,31 @@ class DeskSchedules extends HTMLElement {
actions.className = "actions";
const add = document.createElement("button");
add.textContent = "Add";
add.disabled = busy;
add.disabled = busy || !draft.kind;
kind.addEventListener("change", () => {
draft.kind = kind.value;
add.disabled = busy || !draft.kind;
});
const submit = () => {
if (!kind.value) return;
if (!draft.kind) return;
this.#change(0, async () => {
await this.#ask("/api/schedules", {
method: "POST",
body: { name: name.value.trim(), kind: kind.value,
cadence: cadence.value.trim() },
body: { name: draft.name.trim(), kind: draft.kind, cadence: draft.cadence },
});
// Cleared only on success, so a refused cadence is still there to be
// corrected rather than retyped from memory.
name.value = "";
cadence.value = "";
// Closed and cleared only on success, so a refusal leaves what was
// chosen there to be corrected rather than chosen again.
this.#adding = false;
this.#draft = { name: "", kind: "", cadence: spell(START) };
});
};
add.addEventListener("click", submit);
for (const box of [name, cadence]) {
box.addEventListener("keydown", (e) => { if (e.key === "Enter") submit(); });
}
actions.append(add);
name.addEventListener("keydown", (e) => { if (e.key === "Enter") submit(); });
const cancel = document.createElement("button");
cancel.textContent = "Cancel";
cancel.disabled = busy;
cancel.addEventListener("click", () => { this.#adding = false; this.#render(); });
actions.append(add, cancel);
row.append(actions);
return row;
}