/* The schedule table, on screen, for an app that has not written a UI yet. * * * * * A row per schedule — name, kind, cadence, on or off, next run, last run and * 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. * The socket's opening message is the *job* list, though, so the table is * fetched once on connect: the push says what changed, not what there is. The * job list is read as it goes past as well, for the last column — a schedule * is pushed when it fires, which is before its job has ended, so the state it * ended in can only come from there. * * The same one-file, shadow-root, custom-property shape as ``, and * deliberately the same `--desk-jobs-*` names: an app that themed one element * has themed both, and two schemes for two halves of one page is the thing * nobody wants to maintain. * * Failures are not worded here. A refused change raises `desk-schedules:error` * carrying the server's own `detail` — which the endpoints promise is one * readable sentence — and the app toasts it. Notices arriving on the socket * are re-raised as `desk-jobs:notice`, the same event `` raises, so * an app that listens for one is listening for both. * * 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 = ` :host { --desk-jobs-bg: #16181d; --desk-jobs-fg: #e7e9ee; --desk-jobs-dim: #9aa1ad; --desk-jobs-accent: #4c8dff; --desk-jobs-error: #ff6b6b; --desk-jobs-radius: 10px; --desk-jobs-font: system-ui, -apple-system, "Segoe UI", sans-serif; --desk-jobs-gap: 8px; display: block; font-family: var(--desk-jobs-font); font-size: 13px; color: var(--desk-jobs-fg); } :host([hidden]) { display: none; } .panel { background: var(--desk-jobs-bg); border-radius: var(--desk-jobs-radius); padding: 10px 12px; } table { width: 100%; border-collapse: collapse; } th, td { text-align: left; padding: 6px 8px 6px 0; vertical-align: baseline; border-bottom: 1px solid color-mix(in srgb, var(--desk-jobs-fg) 12%, transparent); } th { color: var(--desk-jobs-dim); font-weight: 600; white-space: nowrap; } tr:last-child > td { border-bottom: 0; } td.actions { text-align: right; white-space: nowrap; } .name { font-weight: 600; } .kind, .when { color: var(--desk-jobs-dim); font-variant-numeric: tabular-nums; } .off { opacity: .55; } .bad { color: var(--desk-jobs-error); } input.text { font: inherit; color: inherit; background: none; border: 1px solid transparent; border-radius: 6px; padding: 1px 4px; min-width: 9em; } input:focus, select:focus { outline: none; border-color: var(--desk-jobs-accent); } input::placeholder { color: var(--desk-jobs-dim); } select, input.time { font: inherit; color: inherit; background: var(--desk-jobs-bg); border: 1px solid color-mix(in srgb, var(--desk-jobs-fg) 20%, transparent); border-radius: 6px; 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); background: none; border: 1px solid currentColor; border-radius: 6px; padding: 1px 8px; margin-left: 6px; cursor: pointer; } button:hover { color: var(--desk-jobs-accent); } button.remove:hover { color: var(--desk-jobs-error); } button[disabled] { opacity: .4; cursor: default; } .state { font-size: 11px; padding: 0 5px; border-radius: 999px; border: 1px solid currentColor; margin-left: 6px; } .state.failed, .state.cancelled { color: var(--desk-jobs-error); } .state.running, .state.queued { color: var(--desk-jobs-accent); } .empty, .offline { color: var(--desk-jobs-dim); padding: 6px 0; } .offline { color: var(--desk-jobs-error); } /* A finger: every control a thumb's height, and no field under 16px, which * is where iOS zooms the page in on focus and never back out. Sizes only; * the layout is the width query below, and neither reads the other. */ @media (pointer: coarse) { button { min-height: 2.5rem; padding: 4px 12px; } input, select { font-size: 16px; padding: 6px 8px; } input[type="checkbox"] { width: 1.4rem; height: 1.4rem; } } /* A phone: seven columns do not fit in 375 pixels, so each row folds to * three lines instead -- name, kind and the switch on top, cadence, next * and last in the middle, the two buttons across the bottom -- and the * header goes, since there is nothing left to label. * * The middle and last columns are sized with minmax(0, ...) rather than * auto: auto sizes a track to its content's natural, unwrapped width, which * for a nowrap cell is the whole string -- so a long kind or timestamp * pushed the name column down to nothing. minmax(0, ...) caps how wide a * track may grow but still lets it shrink to fit, and each of those cells * gets its own ellipsis instead. */ @media (max-width: 40rem) { .panel { padding: 0; } table, tbody { display: block; } thead { display: none; } tr { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 6rem) minmax(0, 5rem); column-gap: 8px; row-gap: 2px; align-items: center; padding: 8px 0; border-bottom: 1px solid color-mix(in srgb, var(--desk-jobs-fg) 12%, transparent); } tr:last-child { border-bottom: 0; } td, th { display: block; padding: 0; border: 0; min-width: 0; } td:empty { display: none; } td.name { grid-column: 1; grid-row: 1; font-size: 14px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } td.kind { grid-column: 2; grid-row: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } td.on { grid-column: 3; grid-row: 1; justify-self: end; } td.cadence { grid-column: 1; grid-row: 2; } td.next { grid-column: 2; grid-row: 2; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } td.last { grid-column: 3; grid-row: 2; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } td.actions { grid-column: 1 / -1; grid-row: 3; justify-self: end; display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 4px; } td.actions button { margin: 0; } /* 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; } tr.adder td[data-label]::before { content: attr(data-label) " "; display: block; font-size: 11px; color: var(--desk-jobs-dim); font-weight: 600; } /* 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); } } `; /** The same backoff as ``: the usual reason a socket closed is the * server restarting under --reload, which comes back inside a second. */ const FIRST_WAIT = 500; const LONGEST_WAIT = 30000; /** 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 * a bug, and "never" is a fact. */ function when(stamp) { if (!stamp) return "never"; const at = new Date(stamp); if (isNaN(at)) return stamp; const today = at.toDateString() === new Date().toDateString(); const clock = at.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); return today ? clock : `${at.toLocaleDateString()} ${clock}`; } class DeskSchedules extends HTMLElement { #root; #socket = null; #wait = FIRST_WAIT; #timer = null; #rows = []; #kinds = []; #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(); this.#root = this.attachShadow({ mode: "open" }); const style = document.createElement("style"); style.textContent = CSS; this.#root.append(style, document.createElement("div")); } connectedCallback() { this.#render(); this.#load(); this.#connect(); } attributeChangedCallback() { if (this.isConnected) this.#render(); } disconnectedCallback() { clearTimeout(this.#timer); this.#socket?.close(); this.#socket = null; } get #base() { return this.getAttribute("base") ?? ""; } get #canAdd() { return this.getAttribute("add") !== "off"; } 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`; } /* -- the server ------------------------------------------------------- */ /** Every call goes through here, so one place raises the event and one * place knows that a refusal carries `{"detail": ""}`. */ async #ask(path, options) { const o = Object.assign({ credentials: "same-origin" }, options); if (o.body !== undefined && typeof o.body !== "string") { o.headers = Object.assign({ "Content-Type": "application/json" }, o.headers); o.body = JSON.stringify(o.body); } let answer; try { answer = await fetch(this.#base + path, o); } catch (e) { this.#failed("Could not reach the server."); throw e; } const text = await answer.text(); let body = null; if (text) { try { body = JSON.parse(text); } catch (e) { body = null; } } if (!answer.ok) { this.#failed((body && body.detail) || `The server answered ${answer.status} and said nothing about why.`); throw new Error(String((body && body.detail) || answer.status)); } return body; } #failed(detail) { // Composed, so a listener on `document` hears it through the shadow // boundary. The wording is the server's; this element has no opinion. this.dispatchEvent(new CustomEvent("desk-schedules:error", { detail: { detail: String(detail) }, bubbles: true, composed: true, })); } async #load() { try { const [rows, kinds] = await Promise.all([ this.#ask("/api/schedules"), this.#ask("/api/jobs/kinds"), ]); this.#rows = rows || []; this.#kinds = kinds || []; } catch (e) { /* already raised */ } finally { this.#loaded = true; this.#render(); } } #connect() { let socket; try { socket = new WebSocket(this.#socketUrl); } catch { this.#reconnect(); return; } this.#socket = socket; socket.onopen = () => { this.#wait = FIRST_WAIT; if (this.#offline) { // Down and back: what changed while we were away came as nothing, so // the list is read again rather than waited for. this.#offline = false; this.#load(); } this.#render(); }; socket.onmessage = (event) => { let message; try { message = JSON.parse(event.data); } catch { return; } if (message.type === "schedules") { this.#rows = message.schedules || []; this.#render(); } else if (message.type === "jobs") { this.#catchUp(message); } else if (message.type === "notice") { this.dispatchEvent(new CustomEvent("desk-jobs:notice", { detail: message, bubbles: true, composed: true, })); } }; socket.onerror = () => socket.close(); socket.onclose = () => { if (this.#socket !== socket) return; // a later connection owns us this.#socket = null; this.#reconnect(); }; } /* The last column says how the last job ended, and the `schedules` message * is pushed when a schedule *fires* — at which point that job has not ended * and the cell reads `running`. Nothing pushes a schedule again when the * job finishes, so without this the table goes on reporting a job as * running long after it is done, which is the one thing this column is for. * * The job list arrives on this same socket four times a second while * anything is going, and it carries the state of every job worth knowing * about, so the answer is already here: take it off the snapshot rather * than ask the server a second time. A job old enough to have left `recent` * keeps whatever it was last seen as; its schedule has fired since, or it * has been on screen for an hour. */ #catchUp(snapshot) { const states = new Map(); for (const list of ["running", "queued", "recent"]) { for (const job of snapshot[list] || []) states.set(job.id, job.state); } let moved = false; for (const row of this.#rows) { const state = states.get(row.last_job_id); if (state && state !== row.last_state) { row.last_state = state; moved = true; } } if (moved) this.#render(); } #reconnect() { if (this.#wait >= 4000) { this.#offline = true; this.#render(); } clearTimeout(this.#timer); this.#timer = setTimeout(() => this.#connect(), this.#wait); this.#wait = Math.min(this.#wait * 2, LONGEST_WAIT); } /* One wrapper for every change: the row is greyed while the request is in * the air, and the new list arrives on the socket rather than being patched * in here — so what is on screen is always what the server holds. */ async #change(id, run) { this.#busy.add(id); this.#render(); try { await run(); } catch (e) { /* already raised */ } finally { this.#busy.delete(id); this.#render(); } } /* -- drawing ---------------------------------------------------------- */ #render() { const panel = this.#root.lastElementChild; panel.className = "panel"; panel.replaceChildren(); if (this.#offline) { const said = document.createElement("div"); said.className = "offline"; said.textContent = "Not connected — what you see here may be out of date."; panel.append(said); } const table = document.createElement("table"); table.append(this.#head()); const body = document.createElement("tbody"); for (const row of this.#rows) body.append(this.#row(row)); 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."; panel.insertBefore(empty, table); } } #head() { const head = document.createElement("thead"); const row = document.createElement("tr"); for (const label of ["Name", "Kind", "Cadence", "On", "Next", "Last", ""]) { const cell = document.createElement("th"); cell.textContent = label; row.append(cell); } head.append(row); return head; } #row(schedule) { const row = document.createElement("tr"); const busy = this.#busy.has(schedule.id); if (!schedule.enabled) row.classList.add("off"); row.append(this.#cell("name", schedule.name)); const kind = this.#cell("kind", schedule.kind, "Kind"); if (schedule.unknown) { // Never fires, and says so rather than sitting there with a next run it // is not going to keep. Deleting it is the only thing left to do. const bad = document.createElement("span"); bad.className = "state bad"; bad.textContent = "unknown kind"; kind.append(bad); } row.append(kind); const cadence = document.createElement("td"); cadence.className = "cadence"; cadence.dataset.label = "Cadence"; 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"); onOff.className = "on"; const toggle = document.createElement("input"); toggle.type = "checkbox"; toggle.checked = !!schedule.enabled; toggle.disabled = busy; toggle.title = schedule.enabled ? "switch this schedule off" : "switch it on"; toggle.addEventListener("change", () => this.#change(schedule.id, () => this.#ask(`/api/schedules/${schedule.id}`, { method: "PATCH", body: { enabled: toggle.checked } }))); onOff.append(toggle); row.append(onOff); row.append(this.#cell("when next", schedule.enabled ? when(schedule.next_run) : "—", "Next")); const last = this.#cell("when last", when(schedule.last_run), "Last"); if (schedule.last_state) { const state = document.createElement("span"); state.className = `state ${schedule.last_state}`; state.textContent = schedule.last_state; last.append(state); } row.append(last); const actions = document.createElement("td"); actions.className = "actions"; const now = document.createElement("button"); now.textContent = "Run now"; now.disabled = busy || schedule.unknown; now.addEventListener("click", () => this.#change(schedule.id, () => this.#ask(`/api/schedules/${schedule.id}/run`, { method: "POST" }))); const remove = document.createElement("button"); remove.className = "remove"; remove.textContent = "Delete"; remove.disabled = busy; remove.addEventListener("click", () => this.#change(schedule.id, () => this.#ask(`/api/schedules/${schedule.id}`, { method: "DELETE" }))); actions.append(now, remove); row.append(actions); return row; } /** `label` is the column's name, which the phone layout writes in front of * the value once the header row is gone. */ #cell(className, text, label) { const cell = document.createElement("td"); cell.className = className; if (label) cell.dataset.label = label; const span = document.createElement("span"); span.textContent = text; cell.append(span); return cell; } /** The add row. In the table rather than in a form above it, because what * is being added is another one of these and the columns already say what * each box is for. */ #adder() { 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")); // 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; row.append(this.#wrap(kind, "Kind")); 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")); const actions = document.createElement("td"); actions.className = "actions"; const add = document.createElement("button"); add.textContent = "Add"; add.disabled = busy || !draft.kind; kind.addEventListener("change", () => { draft.kind = kind.value; add.disabled = busy || !draft.kind; }); const submit = () => { if (!draft.kind) return; this.#change(0, async () => { await this.#ask("/api/schedules", { method: "POST", body: { name: draft.name.trim(), kind: draft.kind, cadence: draft.cadence }, }); // 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); 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; } #wrap(control, label) { const cell = document.createElement("td"); cell.dataset.label = label; cell.append(control); return cell; } } if (!customElements.get("desk-schedules")) { customElements.define("desk-schedules", DeskSchedules); } export { DeskSchedules };