/* 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 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. * * 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 */ 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); } /* 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 { font: inherit; color: inherit; background: none; border: 1px solid transparent; border-radius: 6px; 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::placeholder { color: var(--desk-jobs-dim); } select { 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; } 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 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; } /* 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; } tr.adder input, tr.adder 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 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"; /** 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; 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(); } disconnectedCallback() { clearTimeout(this.#timer); this.#socket?.close(); this.#socket = null; } get #base() { return this.getAttribute("base") ?? ""; } 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)); body.append(this.#adder()); table.append(body); panel.append(table); if (this.#loaded && !this.#rows.length) { const empty = document.createElement("div"); empty.className = "empty"; empty.textContent = "Nothing is scheduled. Add one below."; 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"; 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); 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 name = document.createElement("input"); name.className = "text"; name.placeholder = "optional"; name.disabled = busy; row.append(this.#wrap(name, "Name")); const kind = document.createElement("select"); 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(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; const submit = () => { if (!kind.value) return; this.#change(0, async () => { await this.#ask("/api/schedules", { method: "POST", body: { name: name.value.trim(), kind: kind.value, cadence: cadence.value.trim() }, }); // Cleared only on success, so a refused cadence is still there to be // corrected rather than retyped from memory. name.value = ""; cadence.value = ""; }); }; add.addEventListener("click", submit); for (const box of [name, cadence]) { box.addEventListener("keydown", (e) => { if (e.key === "Enter") submit(); }); } actions.append(add); 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 };