Add scheduled and event-driven printing with a new web UI
CI / test (3.10) (push) Successful in 1m20s
CI / test (3.12) (push) Successful in 1m49s
CI / test (3.13) (push) Successful in 1m5s

The web server now runs a scheduler over schedules kept in SQLite
(~/.local/share/receipt-maker, outside the clone). A schedule is a
trigger, a receipt made of blocks, and options:

- Triggers: once, recurring (rrule-based, DST-safe), sun times,
  reminders before calendar (ICS) events, RSS/JSON watchers, webhooks
  with per-schedule secrets.
- Blocks, rendered fresh as one job: templated notes ({date},
  {days_until:..}, rotating {choice}, trigger vars), QR, saved images,
  random image, calendar agenda, feed headlines, dividers.
- Rules: quiet hours (hold/skip/ignore), daily cap, pause, catch-up
  window for missed runs (never replayed), retries on connect failure
  only; a mid-job drop (new PrinterDropped) is never resent.

receipt.py renders through composable Blocks (render_note/image/qr are
wrappers, output unchanged). Print history persists, with Print again.
The page moves to web/ with Print (note/image/QR + paper preview),
Schedules (presets, editor with live preview and next runs), History
and Settings tabs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-23 23:58:26 +01:00
co-authored by Claude Opus 5.5
parent fa99c3076c
commit ba92f1fbda
29 changed files with 5433 additions and 294 deletions
+90
View File
@@ -0,0 +1,90 @@
// Talking to the server: every call is relative, so the /receipt/ prefix nginx adds keeps working.
function detailText(detail) {
if (!Array.isArray(detail)) return detail;
// Pydantic errors: say where, minus the "body" prefix and union tags.
const tags = ["body", "once", "recurring", "sun", "calendar", "watch", "webhook", "note", "qr",
"image", "random_image", "agenda", "headlines", "divider"];
return detail.map((d) => {
const where = (d.loc || [])
.filter((p) => !tags.includes(p) && !/[[(]/.test(String(p)))
.map((p) => (typeof p === "number" ? `#${p + 1}` : p.replaceAll("_", " ")));
const msg = String(d.msg || "").replace(/^Value error, /, "");
return where.length ? `${where.join(" › ")}: ${msg}` : msg;
}).join("; ");
}
export async function call(path, init = {}) {
init.headers = Object.assign({"X-Requested-With": "receipt"}, init.headers || {});
let res;
try {
res = await fetch(path, init);
} catch (e) {
return {ok: false, status: 0, text: "Network error: " + e.message, body: {}};
}
let body = {};
try { body = await res.json(); } catch (e) { /* nginx pages aren't JSON */ }
if (!("ok" in body) && !("detail" in body)) {
// Not from this server: nginx's offline page, or its login redirect.
const offline = [502, 503, 504].includes(res.status);
return {ok: false, status: res.status, body,
text: offline ? "The printer machine is offline."
: "Signed out? Reload the page and sign in."};
}
return {ok: res.ok && body.ok !== false, status: res.status, body,
text: body.output || detailText(body.detail) || res.statusText};
}
export const get = (path) => call(path);
const withJson = (method) => (path, data) => call(path, {
method, headers: {"Content-Type": "application/json"},
body: data === undefined ? undefined : JSON.stringify(data),
});
export const post = withJson("POST");
export const put = withJson("PUT");
export const del = withJson("DELETE");
// POST something that queues a print, then long-poll the job until it finishes.
// onUpdate(text) reports progress; resolves {ok, text}.
export async function printJob(request, onUpdate = () => {}) {
onUpdate("Sending…");
let r = await request();
let job = null;
while (r.ok && r.body.job && !["done", "failed"].includes(r.body.job.state)) {
job = r.body.job;
onUpdate(job.state === "queued" ? "Queued…" : "Printing…");
r = await call(`api/jobs/${job.id}?wait=20`);
}
if (r.ok && r.body.skipped) return {ok: true, text: r.body.skipped};
if (!r.ok || !r.body.job) {
return {ok: false, text: r.text + (job && r.status === 0 ? " (the job may still print)" : "")};
}
return {ok: r.body.job.state === "done", text: r.body.job.message};
}
// Lists the editor and settings share; refreshed whenever they change.
export const cache = {sources: null, assets: null, settings: null};
export async function sources(refresh = false) {
if (refresh || !cache.sources) {
const r = await get("api/sources");
cache.sources = r.ok ? r.body.sources : [];
}
return cache.sources;
}
export async function assets(refresh = false) {
if (refresh || !cache.assets) {
const r = await get("api/assets");
cache.assets = r.ok ? r.body.assets : [];
}
return cache.assets;
}
export async function settings(refresh = false) {
if (refresh || !cache.settings) {
const r = await get("api/settings");
cache.settings = r.ok ? r.body : {settings: {}, timezones: []};
}
return cache.settings;
}
+270
View File
@@ -0,0 +1,270 @@
:root {
--bg: #f6f5f2; --card: #fff; --text: #1d1d1b; --muted: #6b6a66;
--border: #dcdad4; --accent: #2f5bd3; --accent-soft: #e6ecfb; --ok: #1f7a3a; --err: #b42318;
--warn: #9a5b00; --field: #fbfaf8; --shadow: 0 1px 2px rgb(0 0 0 / 6%);
--mono: ui-monospace, "SF Mono", "DejaVu Sans Mono", Menlo, monospace;
color-scheme: light;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #161615; --card: #20201e; --text: #ecebe7; --muted: #9c9a94;
--border: #3a3936; --accent: #7a9cff; --accent-soft: #263257; --ok: #5cc27c; --err: #ff7a6b;
--warn: #e8a94a; --field: #1a1a19; --shadow: none;
color-scheme: dark;
}
}
* { box-sizing: border-box; }
body {
margin: 0; background: var(--bg); color: var(--text);
font: 15px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif;
}
a { color: var(--accent); }
h1 { font-size: 1.25rem; margin: 0; }
h2 { font-size: 1.05rem; margin: 0 0 12px; display: flex; align-items: center; gap: 8px; }
h3 { font-size: .95rem; margin: 0 0 10px; }
.small { font-size: .85rem; }
.muted { color: var(--muted); }
.ok { color: var(--ok); }
.err { color: var(--err); }
.warn { color: var(--warn); }
.spacer { flex: 1; }
.indent { margin-left: 24px; }
[hidden] { display: none !important; }
/* --- frame --- */
header.top, nav.tabs, main { max-width: 1040px; margin: 0 auto; padding-left: 16px;
padding-right: 16px; }
header.top { display: flex; align-items: center; justify-content: space-between; gap: 12px;
padding-top: 20px; padding-bottom: 8px; }
nav.tabs { display: flex; gap: 4px; border-bottom: 1px solid var(--border); overflow-x: auto; }
nav.tabs a {
padding: 8px 14px; color: var(--muted); text-decoration: none; border-bottom: 2px solid
transparent; margin-bottom: -1px; white-space: nowrap; font-weight: 500;
}
nav.tabs a.on { color: var(--text); border-bottom-color: var(--accent); }
main { padding-top: 18px; padding-bottom: 60px; display: grid; gap: 16px; }
main[aria-busy] { opacity: .6; }
.card {
background: var(--card); border: 1px solid var(--border); border-radius: 10px; padding: 16px;
box-shadow: var(--shadow); min-width: 0;
}
.card.flush { padding: 0; }
.toolbar { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.toolbar h2 { margin: 0; }
.split { display: grid; grid-template-columns: minmax(0, 1fr) 340px; gap: 16px;
align-items: start; }
.grid2 { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
@media (max-width: 820px) {
.split, .grid2 { grid-template-columns: minmax(0, 1fr); }
}
.preview-col h3 { margin: 4px 0 8px; }
.sticky { position: sticky; top: 12px; }
@media (max-width: 820px) { .sticky { position: static; } }
/* --- controls --- */
button, .button {
display: inline-flex; align-items: center; gap: 6px; padding: 7px 14px;
border: 1px solid var(--border); border-radius: 6px; background: var(--card);
color: var(--text); font: inherit; font-weight: 500; cursor: pointer; text-decoration: none;
}
button:hover, .button:hover { border-color: var(--muted); }
button:disabled { opacity: .5; cursor: default; }
button.primary { background: var(--accent); border-color: var(--accent); color: #fff;
font-weight: 600; }
@media (prefers-color-scheme: dark) { button.primary { color: #10131c; } }
button.ghost, .button.ghost { background: none; }
button.small, .button.small { padding: 3px 9px; font-size: .85rem; }
button.danger, .danger { color: var(--err); }
textarea, input[type=text], input[type=url], input[type=number], input[type=time],
input[type=date], input[type=datetime-local], input:not([type]), select {
padding: 7px 9px; border: 1px solid var(--border); border-radius: 6px;
background: var(--field); color: var(--text); font: inherit; min-width: 0; max-width: 100%;
}
textarea { width: 100%; min-height: 110px; font-family: var(--mono); font-size: .9rem;
resize: vertical; }
input.narrow { width: 90px; }
input.grow { flex: 1; min-width: 200px; }
input.name { font-size: 1.15rem; font-weight: 600; width: 100%; }
:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
.field { display: flex; flex-direction: column; gap: 4px; margin-top: 10px; min-width: 0; }
.field > input[type=text], .field > input:not([type]), .field > input[type=url] { width: 100%; }
.field .caption { font-size: .82rem; color: var(--muted); font-weight: 500; }
.hint { color: var(--muted); font-size: .8rem; }
.check { display: inline-flex; align-items: center; gap: 4px; cursor: pointer; }
.inline { display: inline-flex; align-items: center; gap: 6px; }
.row { display: flex; align-items: center; justify-content: space-between; gap: 10px;
margin-top: 10px; flex-wrap: wrap; }
.row.start { justify-content: flex-start; align-items: end; }
.row.end { justify-content: flex-end; }
.row.center { justify-content: center; }
.row.start > .field { margin-top: 0; }
.row.mid { align-items: center; }
.stack { display: grid; gap: 8px; margin-top: 10px; }
input.switch {
appearance: none; width: 38px; height: 22px; border-radius: 999px; background: var(--border);
position: relative; cursor: pointer; flex: none; margin: 0; transition: background .15s;
}
input.switch::after {
content: ""; position: absolute; top: 3px; left: 3px; width: 16px; height: 16px;
border-radius: 50%; background: #fff; transition: transform .15s;
}
input.switch:checked { background: var(--ok); }
input.switch:checked::after { transform: translateX(16px); }
.segmented { display: inline-flex; flex-wrap: wrap; border: 1px solid var(--border);
border-radius: 8px; padding: 2px; gap: 2px; background: var(--field); }
.segmented button { border: 0; background: none; padding: 5px 12px; color: var(--muted); }
.segmented button.on { background: var(--card); color: var(--text); box-shadow: var(--shadow);
outline: 1px solid var(--border); }
.chips { display: flex; flex-wrap: wrap; gap: 6px; }
.chip { padding: 3px 10px; border-radius: 999px; font-size: .85rem; font-weight: 500; }
.chip.on { background: var(--accent-soft); border-color: var(--accent); color: var(--accent); }
.chip.small { padding: 1px 8px; font-family: var(--mono); font-size: .78rem; }
.vars { display: flex; flex-wrap: wrap; gap: 5px; align-items: center; margin-top: 6px; }
.pill {
font-size: .85rem; padding: 3px 10px; border-radius: 999px; border: 1px solid var(--border);
color: var(--muted); background: none; cursor: pointer; font-weight: 400;
}
.pill.ok { color: var(--ok); border-color: var(--ok); }
.pill.err { color: var(--err); border-color: var(--err); }
.badge { display: inline-block; font-size: .75rem; font-weight: 600; padding: 1px 8px;
border-radius: 999px; background: var(--field); border: 1px solid var(--border);
color: var(--muted); white-space: nowrap; }
.badge.ok { color: var(--ok); border-color: currentColor; }
.badge.err { color: var(--err); border-color: currentColor; }
.badge.warn { color: var(--warn); border-color: currentColor; }
#toast {
position: fixed; left: 50%; bottom: 20px; transform: translate(-50%, 20px); opacity: 0;
background: var(--text); color: var(--bg); padding: 9px 16px; border-radius: 8px;
pointer-events: none; transition: all .2s; max-width: calc(100vw - 32px); z-index: 20;
}
#toast.show { opacity: 1; transform: translate(-50%, 0); }
#toast.err { background: var(--err); color: #fff; }
/* --- print tab --- */
.drop {
display: block; border: 2px dashed var(--border); border-radius: 8px; padding: 22px 16px;
text-align: center; color: var(--muted); cursor: pointer; margin: 12px 0 8px;
}
.drop.over { border-color: var(--accent); color: var(--accent); }
form > input[type=text] { width: 100%; }
.status { margin: 12px 0 0; font-family: var(--mono); font-size: .85rem; white-space: pre-wrap; }
.status.ok { color: var(--ok); }
.status.err { color: var(--err); }
.card .segmented { margin-bottom: 12px; }
/* --- paper preview --- */
.paper-wrap { display: grid; gap: 8px; }
.paper {
background: #fff; color: #161616; padding: 14px 12px 20px; margin: 0 auto 8px; width: 100%;
max-width: 330px; position: relative; box-shadow: 0 1px 4px rgb(0 0 0 / 15%);
border-radius: 2px 2px 0 0;
}
.paper::after { /* the torn edge */
content: ""; position: absolute; left: 0; right: 0; bottom: -7px; height: 8px;
background: linear-gradient(-45deg, transparent 5px, #fff 0) 0 0 / 10px 8px repeat-x,
linear-gradient(45deg, transparent 5px, #fff 0) 0 0 / 10px 8px repeat-x;
}
.paper-strip { container-type: inline-size; min-height: 60px; }
.paper .t {
margin: 0; font-family: var(--mono); white-space: pre-wrap; overflow-wrap: anywhere;
font-size: calc(100cqw / 48 / .615); line-height: 1.25;
}
.paper .t.s2 { font-size: calc(100cqw / 24 / .615); }
.paper .t.s3 { font-size: calc(100cqw / 16 / .615); }
.paper .t.b { font-weight: 700; }
.paper .t.c { text-align: center; }
.paper .t.placeholder { color: #888; font-family: system-ui, sans-serif; font-size: .85rem;
text-align: center; padding: 20px 0; }
.paper img { display: block; width: 100%; image-rendering: pixelated; margin: 4px 0; }
.paper-wrap.error .paper .placeholder { color: var(--err); }
.paper-meta { text-align: center; font-size: .82rem; }
.paper-meta .warn { margin-top: 2px; }
/* --- schedules --- */
.cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 12px; }
.schedule { display: flex; flex-direction: column; gap: 6px; }
.schedule.off { opacity: .65; }
.card-head { display: flex; align-items: center; gap: 10px; }
.card-head .title { font-weight: 600; color: var(--text); text-decoration: none; flex: 1;
overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.card-head .title:hover { text-decoration: underline; }
.icon { display: inline-grid; place-items: center; width: 30px; height: 30px; flex: none;
border-radius: 8px; background: var(--accent-soft); color: var(--accent); font-size: 1rem; }
.schedule .summary { margin: 0; }
.schedule .meta { margin: 0; display: flex; gap: 8px; flex-wrap: wrap; align-items: center;
font-size: .85rem; color: var(--muted); }
.schedule .meta .last { flex-basis: 100%; }
.actions { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; margin-top: auto;
padding-top: 6px; }
.coming:empty { display: none; }
.coming h3 { margin: 0 0 6px; }
.timeline { display: flex; gap: 8px; overflow-x: auto; padding-bottom: 4px; }
.timeline .tick { display: grid; padding: 6px 12px; border: 1px solid var(--border);
border-radius: 8px; background: var(--card); text-decoration: none; color: var(--text);
min-width: 110px; font-size: .85rem; }
.timeline .tick span { color: var(--muted); white-space: nowrap; overflow: hidden;
text-overflow: ellipsis; max-width: 160px; }
.empty { text-align: center; padding: 20px 0; }
.presets { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 10px; text-align: left; }
.preset { display: grid; grid-template-columns: auto 1fr; gap: 2px 10px; align-items: start;
padding: 12px; text-align: left; font-weight: 400; }
.preset .icon { grid-row: span 2; }
dialog.sheet { border: 1px solid var(--border); border-radius: 12px; background: var(--bg);
color: var(--text); width: min(760px, calc(100vw - 32px)); padding: 16px; }
dialog.sheet::backdrop { background: rgb(0 0 0 / 40%); }
dialog.sheet .toolbar { margin-bottom: 12px; justify-content: space-between; }
/* --- editor --- */
.back { text-decoration: none; }
.editor-head { display: grid; gap: 6px; }
.editor-head .meta { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; }
.editor { display: grid; gap: 16px; min-width: 0; }
.step { display: inline-grid; place-items: center; width: 22px; height: 22px; border-radius: 50%;
background: var(--accent); color: #fff; font-size: .75rem; }
@media (prefers-color-scheme: dark) { .step { color: #10131c; } }
.trigger-form { margin-top: 4px; }
.trigger-info { margin-top: 14px; padding-top: 12px; border-top: 1px dashed var(--border); }
.trigger-info:empty { display: none; }
.trigger-info .summary { margin: 0; font-weight: 600; }
.next-runs { margin: 6px 0 0; padding-left: 18px; font-size: .88rem; }
.times { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
.time { display: inline-flex; align-items: center; gap: 2px; }
.blocks { display: grid; gap: 10px; }
.block { border: 1px solid var(--border); border-radius: 8px; padding: 10px 12px;
background: var(--field); }
.block-head { display: flex; align-items: center; gap: 4px; }
.block-head strong { font-size: .9rem; }
.add-block { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
details { margin-top: 10px; }
details > summary { cursor: pointer; color: var(--muted); font-size: .9rem; }
details > summary h2 { display: inline-flex; margin: 0; color: var(--text); }
.copyable { display: flex; gap: 6px; align-items: center; min-width: 0; }
.copyable code, pre.code { font-family: var(--mono); font-size: .8rem; background: var(--field);
border: 1px solid var(--border); border-radius: 6px; padding: 5px 8px; overflow-x: auto;
white-space: nowrap; min-width: 0; }
pre.code { white-space: pre; margin: 8px 0; }
.editor-bar { position: sticky; top: 0; z-index: 5; background: var(--bg);
padding: 8px 0; margin: -8px 0 0; border-bottom: 1px solid transparent; }
.editor-bar .actions { margin: 0; padding: 0; }
/* --- history and settings --- */
.history .run { display: grid; grid-template-columns: 130px 1fr auto; gap: 12px;
padding: 10px 16px; border-bottom: 1px solid var(--border); align-items: center; }
.history .run:last-child { border-bottom: 0; }
.history .when { color: var(--muted); font-size: .85rem; }
.history .empty { padding: 16px; }
@media (max-width: 600px) {
.history .run { grid-template-columns: 1fr auto; }
.history .when { grid-column: 1 / -1; }
}
.list-row { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 8px 0;
border-bottom: 1px solid var(--border); }
.list-row code { overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
max-width: 260px; }
.add-source { margin-top: 12px; }
+54
View File
@@ -0,0 +1,54 @@
// Hash router and the printer status pill.
import {get} from "./api.js";
import {$} from "./dom.js";
import {editorView} from "./editor.js";
import {historyView} from "./history.js";
import {printView} from "./print.js";
import {schedulesView} from "./schedules.js";
import {settingsView} from "./settings.js";
const view = $("#view");
let current = null; // what the active view returned: a cleanup function or {canLeave}
let currentHash = location.hash;
async function route() {
const hash = location.hash || "#print";
if (current?.canLeave && hash !== currentHash && !current.canLeave()) {
history.replaceState(null, "", currentHash); // stay put
return;
}
if (typeof current === "function") current();
current = null;
currentHash = hash;
const [tab, arg] = hash.slice(1).split("/");
document.querySelectorAll("nav.tabs a").forEach((a) =>
a.classList.toggle("on", a.getAttribute("href") === `#${tab}`));
view.setAttribute("aria-busy", "true");
if (tab === "schedules" && arg) current = await editorView(view, arg);
else if (tab === "schedules") current = await schedulesView(view);
else if (tab === "history") current = await historyView(view, arg);
else if (tab === "settings") current = await settingsView(view);
else current = printView(view);
view.removeAttribute("aria-busy");
window.scrollTo(0, 0);
}
window.addEventListener("hashchange", route);
window.addEventListener("beforeunload", (e) => {
if (current?.isDirty?.()) e.preventDefault();
});
async function checkStatus() {
const pill = $("#status");
pill.textContent = "checking…";
pill.className = "pill";
const r = await get("api/status");
pill.textContent = r.body.busy ? "printer busy" : r.ok ? "printer ready" : "printer offline";
pill.className = `pill ${r.ok ? "ok" : "err"}`;
pill.title = r.text;
}
$("#status").addEventListener("click", checkStatus);
checkStatus();
route();
+154
View File
@@ -0,0 +1,154 @@
// Small DOM and formatting helpers shared by the tabs.
export const $ = (selector, root = document) => root.querySelector(selector);
// h("button", {class: "x", onclick: fn}, "text", child) -> element
export function h(tag, props, ...children) {
const el = document.createElement(tag);
for (const [key, value] of Object.entries(props || {})) {
if (value === null || value === undefined || value === false) continue;
if (key.startsWith("on")) el.addEventListener(key.slice(2), value);
else if (key === "class") el.className = value;
else if (key === "dataset") Object.assign(el.dataset, value);
else if (key === "style") el.style.cssText = value;
else if (key === "value") el.value = value; // a textarea has no value attribute
else if (key in el && typeof value !== "string") el[key] = value;
else el.setAttribute(key, value === true ? "" : value);
}
append(el, children);
return el;
}
function append(el, children) {
for (const child of children.flat(Infinity)) {
if (child === null || child === undefined || child === false) continue;
el.append(child instanceof Node ? child : String(child));
}
}
export function clear(el, ...children) {
el.replaceChildren();
append(el, children);
return el;
}
let toastTimer = null;
export function toast(text, kind = "") {
const el = $("#toast");
el.textContent = text;
el.className = `show ${kind}`;
clearTimeout(toastTimer);
toastTimer = setTimeout(() => { el.className = ""; }, kind === "err" ? 6000 : 3000);
}
export function debounce(fn, ms) {
let timer = null;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
}
export const DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
export const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct",
"Nov", "Dec"];
export function fmtTime(iso) {
if (!iso) return "";
const d = new Date(iso);
const today = new Date();
const time = d.toLocaleTimeString([], {hour: "2-digit", minute: "2-digit"});
if (d.toDateString() === today.toDateString()) return `Today ${time}`;
const tomorrow = new Date(today); tomorrow.setDate(today.getDate() + 1);
if (d.toDateString() === tomorrow.toDateString()) return `Tomorrow ${time}`;
const opts = {weekday: "short", day: "numeric", month: "short"};
if (d.getFullYear() !== today.getFullYear()) opts.year = "numeric";
return `${d.toLocaleDateString([], opts)} ${time}`;
}
export function relative(iso) {
if (!iso) return "";
const minutes = Math.round((new Date(iso) - Date.now()) / 60000);
const abs = Math.abs(minutes);
let text;
if (abs < 1) return "now";
if (abs < 60) text = `${abs} min`;
else if (abs < 60 * 36) text = `${Math.round(abs / 60)} h`;
else text = `${Math.round(abs / 1440)} days`;
return minutes > 0 ? `in ${text}` : `${text} ago`;
}
// A <label> wrapping a control, with the caption above it.
export function labelled(caption, control, hint) {
return h("label", {class: "field"}, h("span", {class: "caption"}, caption), control,
hint ? h("small", {class: "hint"}, hint) : null);
}
// A checkbox bound to obj[key].
export function checkbox(obj, key, caption, onchange) {
const input = h("input", {type: "checkbox", checked: !!obj[key], onchange: () => {
obj[key] = input.checked; onchange && onchange();
}});
return h("label", {class: "check"}, input, " ", caption);
}
// Text / number / time / date input bound to obj[key].
export function input(obj, key, props = {}, onchange) {
const type = props.type || "text";
const parse = props.parse || (type === "number"
? (v) => (v === "" ? null : Number(v)) : (v) => v);
const el = h(props.multiline ? "textarea" : "input", {
...props, type: props.multiline ? null : type, multiline: null, parse: null,
value: obj[key] ?? "",
oninput: () => { obj[key] = parse(el.value); onchange && onchange(); },
});
return el;
}
// <select> bound to obj[key]; options are [value, label] pairs.
export function select(obj, key, options, onchange, parse = (v) => v) {
const el = h("select", {onchange: () => { obj[key] = parse(el.value); onchange && onchange(); }},
options.map(([value, label]) => h("option", {value: String(value)}, label)));
el.value = String(obj[key] ?? "");
return el;
}
// Toggle chips for a list of numbers (weekdays).
export function chips(list, labels, onchange) {
return h("div", {class: "chips"}, labels.map((label, i) => {
const chip = h("button", {type: "button", class: list.includes(i) ? "chip on" : "chip",
"aria-pressed": String(list.includes(i)),
onclick: () => {
const at = list.indexOf(i);
if (at >= 0) list.splice(at, 1); else { list.push(i); list.sort((a, b) => a - b); }
chip.classList.toggle("on", at < 0);
chip.setAttribute("aria-pressed", String(at < 0));
onchange && onchange();
}}, label);
return chip;
}));
}
// Segmented control: one of options [value, label].
export function segmented(current, options, onpick) {
return h("div", {class: "segmented", role: "tablist"}, options.map(([value, label]) =>
h("button", {type: "button", role: "tab", class: value === current ? "on" : "",
"aria-selected": String(value === current),
onclick: () => onpick(value)}, label)));
}
// Insert text at the cursor of an input/textarea and fire its input event.
export function insertAtCursor(el, text) {
const start = el.selectionStart ?? el.value.length;
const end = el.selectionEnd ?? el.value.length;
el.value = el.value.slice(0, start) + text + el.value.slice(end);
el.selectionStart = el.selectionEnd = start + text.length;
el.focus();
el.dispatchEvent(new Event("input"));
}
export function localDateTimeValue(date) {
const pad = (n) => String(n).padStart(2, "0");
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T` +
`${pad(date.getHours())}:${pad(date.getMinutes())}`;
}
+591
View File
@@ -0,0 +1,591 @@
// Schedule editor: When (trigger), What (blocks), Options, with a live receipt preview.
import {assets, call, del, get, post, printJob, put, settings, sources} from "./api.js";
import {
DAYS, MONTHS, checkbox, chips, clear, debounce, fmtTime, h, input, insertAtCursor, labelled,
relative, segmented, select, toast,
} from "./dom.js";
import {paper} from "./paper.js";
import {OPTIONS, blockDefaults, triggerDefaults} from "./presets.js";
import {STATUS_LABELS, pending} from "./schedules.js";
const TRIGGER_TYPES = [["once", "Once"], ["recurring", "Repeat"], ["sun", "Sun"],
["calendar", "Calendar"], ["watch", "Feed / URL"], ["webhook", "Webhook"]];
const BLOCK_TYPES = [["note", "Note"], ["qr", "QR code"], ["image", "Image"],
["agenda", "Agenda"], ["headlines", "Headlines"],
["random_image", "Random image"], ["divider", "Divider"]];
const BLOCK_NAMES = Object.fromEntries(BLOCK_TYPES);
const POSITIONS = [["1", "first"], ["2", "second"], ["3", "third"], ["4", "fourth"],
["-1", "last"]];
const FREQ_UNITS = {daily: "day", weekly: "week", monthly: "month", yearly: "year"};
// Variables offered as chips, by trigger type (and for every trigger).
const VARS = {
common: ["{date}", "{time}", "{weekday}", "{date:%d/%m/%Y}", "{days_until:12-25}"],
calendar: ["{event.title}", "{event.start}", "{event.end}", "{event.location}",
"{event.minutes}"],
watch_rss: ["{item.title}", "{item.link}", "{item.summary}", "{item.source}"],
watch_json: ["{value}", "{old_value}"],
webhook: ["{payload.text}", "{payload.title}"],
};
function hhmm(t) { return (t || "").slice(0, 5); }
function freshDraft() {
return {name: "", enabled: true, trigger: triggerDefaults("recurring"),
blocks: [blockDefaults("note")], options: {...OPTIONS}};
}
function normalise(spec) {
// Server times come back as HH:MM:SS; the inputs want HH:MM.
const t = spec.trigger;
if (t.type === "recurring") t.times = t.times.map(hhmm);
if (t.type === "once") t.at = (t.at || "").slice(0, 16);
return spec;
}
export async function editorView(view, id) {
let saved = null;
let draft;
let secret = null;
if (id === "new") {
draft = pending.draft || freshDraft();
pending.draft = null;
} else {
const r = await get(`api/schedules/${id}`);
if (!r.ok) return clear(view, h("p", {class: "err"}, r.text));
saved = r.body.schedule;
draft = {name: saved.name, enabled: saved.enabled, ...normalise(structuredClone(saved.spec))};
}
const [srcs, imgs, conf] = await Promise.all([sources(), assets(), settings()]);
let dirty = id === "new";
const preview = paper();
const triggerBox = h("div");
const triggerInfo = h("div", {class: "trigger-info"});
const blocksBox = h("div", {class: "blocks"});
const optionsBox = h("div");
const hookBox = h("div");
const headerStatus = h("div", {class: "meta"});
const saveButton = h("button", {class: "primary", onclick: () => save()}, "Save");
const testButton = h("button", {onclick: () => testPrint()}, "Test print");
let lastFocused = null; // the text field variable chips insert into
function changed() {
dirty = true;
saveButton.textContent = "Save";
refreshPreview();
}
// --- preview + next runs ---
const refreshPreview = debounce(async () => {
const blank = (b) => b.type === "note" && !b.text.trim() && !b.choices.length;
if (draft.blocks.every(blank)) {
refreshTrigger();
return preview.empty("Write something to print.");
}
const r = await post("api/preview", {blocks: draft.blocks, trigger: draft.trigger,
schedule_id: saved?.id || null});
r.ok ? preview.show(r.body) : preview.error(r.text);
refreshTrigger();
}, 500);
let triggerSeq = 0;
async function refreshTrigger() {
const seq = ++triggerSeq;
if (draft.trigger.type === "watch" && !draft.trigger.url.trim()) {
return clear(triggerInfo, h("p", {class: "muted small"}, "Enter the address to watch."));
}
const r = await post("api/triggers/preview", {trigger: draft.trigger});
if (seq !== triggerSeq) return;
if (!r.ok) return clear(triggerInfo, h("p", {class: "err small"}, r.text));
const {summary, next, error} = r.body;
clear(triggerInfo,
h("p", {class: "summary"}, summary),
error ? h("p", {class: "err small"}, error) : null,
next.length ? h("ul", {class: "next-runs"}, next.map((t) =>
h("li", {}, fmtTime(t), h("span", {class: "muted"}, ` · ${relative(t)}`)))) :
!error && ["once", "recurring", "sun"].includes(draft.trigger.type)
? h("p", {class: "warn small"}, "This never runs again.") : null);
}
// --- When ---
function renderTrigger() {
const t = draft.trigger;
const form = {once: onceForm, recurring: recurringForm, sun: sunForm,
calendar: calendarForm, watch: watchForm, webhook: webhookForm}[t.type](t);
clear(triggerBox,
segmented(t.type, TRIGGER_TYPES, (type) => {
if (type === draft.trigger.type) return;
draft.trigger = triggerDefaults(type, srcs);
renderTrigger(); renderBlocks(); changed();
}),
h("div", {class: "trigger-form"}, form));
renderHook();
}
function onceForm(t) {
return labelled("Date and time", input(t, "at", {type: "datetime-local"}, changed),
`In ${conf.settings.timezone}.`);
}
function recurringForm(t) {
const box = h("div");
const rerender = () => { clear(box, inner()); changed(); };
function inner() {
const unit = FREQ_UNITS[t.freq];
const parts = [
h("div", {class: "row start mid"}, h("span", {}, "Every"),
input(t, "interval", {type: "number", min: 1, max: 365, class: "narrow",
parse: (v) => Math.max(1, Number(v) || 1)}, changed),
select(t, "freq", [["daily", `day${t.interval > 1 ? "s" : ""}`],
["weekly", `week${t.interval > 1 ? "s" : ""}`],
["monthly", `month${t.interval > 1 ? "s" : ""}`],
["yearly", `year${t.interval > 1 ? "s" : ""}`]], () => {
t.weekdays = []; t.setpos = null; t.monthday = null; t.month = null; rerender();
})),
];
if (t.freq === "daily" || t.freq === "weekly") {
parts.push(labelled(t.freq === "daily" ? "Only on (none = every day)" : "On",
h("div", {}, chips(t.weekdays, DAYS, changed),
t.freq === "daily" ? h("div", {class: "row start"},
h("button", {type: "button", class: "ghost small", onclick: () => {
t.weekdays.splice(0, 7, 0, 1, 2, 3, 4); rerender();
}}, "Weekdays"),
h("button", {type: "button", class: "ghost small", onclick: () => {
t.weekdays.splice(0, 7, 5, 6); rerender();
}}, "Weekends")) : null)));
} else {
const byWeekday = t.setpos !== null && t.setpos !== undefined;
const mode = h("div", {class: "stack"},
h("label", {class: "check"}, h("input", {type: "radio", name: "monthmode",
checked: !byWeekday, onchange: () => { t.setpos = null; t.weekdays = []; rerender(); }}),
" On day ",
select(t, "monthday", [["", "(start date's)"],
...Array.from({length: 31}, (_, i) => [i + 1, String(i + 1)]), ["-1", "last"]],
changed, (v) => (v === "" ? null : Number(v)))),
h("label", {class: "check"}, h("input", {type: "radio", name: "monthmode",
checked: byWeekday, onchange: () => {
t.setpos = 1; t.monthday = null; if (!t.weekdays.length) t.weekdays.push(0);
rerender();
}}), " On the ",
select(t, "setpos", POSITIONS, changed, (v) => Number(v))),
byWeekday ? h("div", {class: "indent"}, chips(t.weekdays, DAYS, changed),
h("button", {type: "button", class: "ghost small", onclick: () => {
t.weekdays.splice(0, 7, 0, 1, 2, 3, 4); rerender();
}}, "Any weekday")) : null);
parts.push(mode);
if (t.freq === "yearly") {
parts.push(labelled("Month", select(t, "month",
[["", "(start date's)"], ...MONTHS.map((m, i) => [i + 1, m])], changed,
(v) => (v === "" ? null : Number(v)))));
}
}
parts.push(labelled("At", h("div", {class: "times"},
t.times.map((time, i) => h("span", {class: "time"},
h("input", {type: "time", value: time, oninput: (e) => {
t.times[i] = e.target.value; changed();
}}),
t.times.length > 1 ? h("button", {type: "button", class: "ghost small",
"aria-label": "Remove time", onclick: () => { t.times.splice(i, 1); rerender(); }},
"×") : null)),
t.times.length < 24 ? h("button", {type: "button", class: "ghost small", onclick: () => {
t.times.push("12:00"); rerender();
}}, "+ time") : null)));
parts.push(h("div", {class: "row start"},
labelled("Starting", input(t, "start", {type: "date", parse: (v) => v || null}, changed),
t.interval > 1 ? `Counts every ${t.interval} ${unit}s from here.` : null),
labelled("Until (optional)", input(t, "until", {type: "date",
parse: (v) => v || null}, changed))));
parts.push(h("details", {open: !!t.rrule},
h("summary", {}, "Advanced: custom rule"),
labelled("RRULE", input(t, "rrule", {placeholder: "FREQ=MONTHLY;BYDAY=-1FR",
parse: (v) => v || null}, changed),
"An iCalendar RRULE. It replaces the settings above; the times still apply.")));
return parts;
}
clear(box, inner());
return box;
}
function sunForm(t) {
const direction = {value: t.offset_minutes < 0 ? "before" : "after"};
const minutes = {value: Math.abs(t.offset_minutes)};
const apply = () => {
t.offset_minutes = (direction.value === "before" ? -1 : 1) * (Number(minutes.value) || 0);
changed();
};
return h("div", {},
conf.settings.location ? null
: h("p", {class: "warn"}, "Sun times need a location. ",
h("a", {href: "#settings"}, "Set one in Settings.")),
h("div", {class: "row start mid"},
input(minutes, "value", {type: "number", min: 0, max: 720, class: "narrow"}, apply),
h("span", {}, "min"),
select(direction, "value", [["before", "before"], ["after", "after"]], apply),
select(t, "event", [["dawn", "dawn"], ["sunrise", "sunrise"], ["noon", "solar noon"],
["sunset", "sunset"], ["dusk", "dusk"]], changed)),
labelled("On", chips(t.weekdays, DAYS, changed)));
}
function sourceOptions(kind) {
return srcs.filter((s) => s.kind === kind).map((s) => [s.id, s.name]);
}
function noSources(kind) {
return h("p", {class: "warn"}, `No saved ${kind === "ics" ? "calendars" : "feeds"} yet. `,
h("a", {href: "#settings"}, "Add one in Settings."));
}
function calendarForm(t) {
const options = sourceOptions("ics");
if (!options.length) return noSources("ics");
if (!t.source_id) t.source_id = options[0][0];
return h("div", {},
labelled("Calendar", select(t, "source_id", options, changed)),
h("div", {class: "row start"},
labelled("Minutes before", input(t, "minutes_before", {type: "number", min: 0,
max: 10080, class: "narrow", parse: (v) => Number(v) || 0}, changed)),
labelled("Only titles containing", input(t, "contains", {placeholder: "(any)"},
changed))),
checkbox(t, "include_all_day", "Include all-day events", changed));
}
function watchForm(t) {
const result = h("p", {class: "small muted"});
const box = h("div");
const rerender = () => { clear(box, inner()); changed(); };
function inner() {
return [
segmented(t.kind, [["rss", "RSS / Atom feed"], ["json", "JSON value"]], (kind) => {
t.kind = kind; rerender(); renderBlocks();
}),
labelled("URL", input(t, "url", {type: "url", placeholder: "https://…"}, changed)),
t.kind === "json" ? h("div", {class: "row start"},
labelled("Path", input(t, "path", {placeholder: "data.price"}, changed),
"Dotted path; numbers index lists (items.0.price)."),
labelled("Print when it", select(t, "condition", [["changed", "changes"],
["above", "goes above"], ["below", "goes below"]], rerender)),
t.condition !== "changed" ? labelled("Threshold", input(t, "threshold",
{type: "number", step: "any", class: "narrow"}, changed)) : null) : null,
h("div", {class: "row start"},
labelled("Check every (min)", input(t, "every_minutes", {type: "number", min: 5,
max: 1440, class: "narrow", parse: (v) => Number(v) || 30}, changed)),
t.kind === "rss" ? labelled("Items per receipt", input(t, "max_items",
{type: "number", min: 1, max: 10, class: "narrow", parse: (v) => Number(v) || 1},
changed)) : null),
h("div", {class: "row start"},
h("button", {type: "button", onclick: async () => {
result.textContent = "Checking…";
const r = await post("api/watch/test", t);
result.textContent = r.text;
result.className = `small ${r.ok ? "ok" : "err"}`;
}}, "Try it"), result),
h("p", {class: "muted small"}, t.kind === "rss"
? "The first check only notes what's there; after that, new items print."
: "The first check only notes the value; after that, changes print."),
];
}
clear(box, inner());
return box;
}
function webhookForm(t) {
return h("div", {},
labelled("Most prints per hour", input(t, "per_hour", {type: "number", min: 1, max: 120,
class: "narrow", parse: (v) => Number(v) || 1}, changed)),
hookBox);
}
function renderHook() {
if (draft.trigger.type !== "webhook") return;
if (!saved || saved.spec.trigger.type !== "webhook") {
return clear(hookBox, h("p", {class: "muted"}, "Save to get this webhook's URL and secret."));
}
const base = new URL(".", location.href).href;
const url = `${base}${saved.hook_path}`;
const copy = (text) => () => navigator.clipboard.writeText(text).then(() => toast("Copied."));
const example = `curl -X POST '${url}' \\\n -H 'X-Hook-Secret: ${secret || "<secret>"}' \\\n` +
` -H 'Content-Type: application/json' \\\n -d '{"text": "Hello"}'`;
clear(hookBox,
labelled("URL", h("div", {class: "copyable"}, h("code", {}, url),
h("button", {type: "button", class: "ghost small", onclick: copy(url)},
"Copy"))),
secret
? labelled("Secret (shown once: copy it now)",
h("div", {class: "copyable"}, h("code", {}, secret),
h("button", {type: "button", class: "ghost small", onclick: copy(secret)},
"Copy")))
: h("p", {class: "muted small"},
saved.has_secret ? "The secret was shown when it was made. " : "No secret yet. ",
h("button", {type: "button", class: "ghost small", onclick: async () => {
if (saved.has_secret && !confirm("Make a new secret? The old one stops working.")) {
return;
}
const r = await post(`api/schedules/${saved.id}/secret`);
if (!r.ok) return toast(r.text, "err");
saved = r.body.schedule; secret = r.body.schedule.secret; renderHook();
}}, saved.has_secret ? "Make a new secret" : "Make a secret")),
h("details", {}, h("summary", {}, "Example"), h("pre", {class: "code"}, example),
h("p", {class: "muted small"},
"Send the secret as X-Hook-Secret or ?key=. JSON fields become {payload.…}; a " +
"plain-text body is {payload.text}. Over Tailscale, or from anywhere once nginx " +
"forwards /receipt/hook/.")));
}
// --- What ---
function varChips() {
const t = draft.trigger;
const extra = t.type === "watch" ? VARS[`watch_${t.kind}`] : VARS[t.type] || [];
return h("div", {class: "vars"}, h("span", {class: "muted small"}, "Insert:"),
[...extra, ...VARS.common].map((v) => h("button", {type: "button", class: "chip small",
onmousedown: (e) => e.preventDefault(), // keep the field's cursor
onclick: () => { if (lastFocused) insertAtCursor(lastFocused, v); }}, v)));
}
function track(el) {
el.addEventListener("focus", () => (lastFocused = el));
return el;
}
function renderBlocks() {
clear(blocksBox,
draft.blocks.map((block, i) => blockCard(block, i)),
h("div", {class: "add-block"}, h("span", {class: "muted small"}, "Add:"),
BLOCK_TYPES.map(([type, label]) => h("button", {type: "button", class: "ghost small",
onclick: () => {
draft.blocks.push(blockDefaults(type, srcs)); renderBlocks(); changed();
}}, `+ ${label}`))));
}
function blockCard(block, i) {
const move = (delta) => () => {
const [b] = draft.blocks.splice(i, 1);
draft.blocks.splice(i + delta, 0, b);
renderBlocks(); changed();
};
const form = {note: noteBlock, qr: qrBlock, image: imageBlock, agenda: agendaBlock,
headlines: headlinesBlock}[block.type];
return h("div", {class: "block"},
h("div", {class: "block-head"},
h("strong", {}, BLOCK_NAMES[block.type]),
h("span", {class: "spacer"}),
h("button", {type: "button", class: "ghost small", disabled: i === 0,
"aria-label": "Move up", onclick: move(-1)}, "↑"),
h("button", {type: "button", class: "ghost small", disabled: i === draft.blocks.length - 1,
"aria-label": "Move down", onclick: move(1)}, "↓"),
h("button", {type: "button", class: "ghost small", disabled: draft.blocks.length === 1,
"aria-label": "Remove", onclick: () => {
draft.blocks.splice(i, 1); renderBlocks(); changed();
}}, "×")),
form ? form(block) : block.type === "random_image"
? h("p", {class: "muted small"}, "A random image from /bant/, downloaded when it prints.")
: null);
}
function noteBlock(b) {
const choices = {text: b.choices.join("\n")};
return h("div", {},
track(input(b, "text", {multiline: true, rows: 4, maxlength: 4000,
placeholder: b.choices.length ? "{choice}" : "Text; variables like {date} fill in when it prints"},
changed)),
varChips(),
h("div", {class: "row start"},
labelled("Size", select(b, "size", [[1, "Normal"], [2, "Large"], [3, "Huge"]], changed,
Number)),
checkbox(b, "bold", "Bold", changed),
checkbox(b, "center", "Centered", changed),
checkbox(b, "timestamp", "Date/time header", changed)),
h("details", {open: b.choices.length > 0},
h("summary", {}, "Pick from a list ({choice})"),
labelled("One item per line", input(choices, "text", {multiline: true, rows: 4},
() => { b.choices = choices.text.split("\n").filter((c) => c.trim()); changed(); })),
labelled("Pick", select(b, "pick", [["sequential", "In order, one per print"],
["random", "At random"]], changed))));
}
function qrBlock(b) {
return h("div", {},
labelled("Text or link", track(input(b, "content", {placeholder: "https://…"}, changed))),
labelled("Caption", track(input(b, "caption", {}, changed))),
varChips());
}
function imageBlock(b) {
const picker = h("div");
const draw = () => clear(picker,
imgs.length ? select(b, "asset_id", [["", "(choose an image)"],
...imgs.map((a) => [a.id, a.name])], changed)
: h("span", {class: "muted small"}, "No saved images yet."),
h("label", {class: "button ghost small"}, "Upload…",
h("input", {type: "file", accept: "image/*", hidden: true, onchange: async (e) => {
const file = e.target.files[0];
if (!file) return;
const data = new FormData();
data.append("file", file, file.name || "image.png");
const r = await call("api/assets", {method: "POST", body: data});
if (!r.ok) return toast(r.text, "err");
imgs.splice(0, imgs.length, ...await assets(true));
b.asset_id = r.body.asset.id;
draw(); changed();
}})));
draw();
return h("div", {},
labelled("Image", picker),
labelled("Caption", track(input(b, "caption", {}, changed))), varChips());
}
function sourceChecks(b, kind) {
const options = sourceOptions(kind);
if (!options.length) return noSources(kind);
return h("div", {class: "chips"}, options.map(([sid, name]) => {
const on = b.source_ids.includes(sid);
const chip = h("button", {type: "button", class: on ? "chip on" : "chip", onclick: () => {
const at = b.source_ids.indexOf(sid);
if (at >= 0) b.source_ids.splice(at, 1); else b.source_ids.push(sid);
chip.classList.toggle("on", at < 0); changed();
}}, name);
return chip;
}));
}
function agendaBlock(b) {
return h("div", {},
labelled("Calendars", sourceChecks(b, "ics")),
h("div", {class: "row start"},
labelled("From", select(b, "start_day", [[0, "Today"], [1, "Tomorrow"],
...[2, 3, 4, 5, 6, 7].map((n) => [n, `In ${n} days`])], changed, Number)),
labelled("For", select(b, "days", [1, 2, 3, 4, 5, 6, 7].map((n) =>
[n, n === 1 ? "1 day" : `${n} days`]), changed, Number)),
labelled("Heading", input(b, "title", {placeholder: "(automatic)"}, changed))),
checkbox(b, "include_all_day", "Include all-day events", changed));
}
function headlinesBlock(b) {
return h("div", {},
labelled("Feeds", sourceChecks(b, "rss")),
h("div", {class: "row start"},
labelled("Items per feed", input(b, "count", {type: "number", min: 1, max: 20,
class: "narrow", parse: (v) => Number(v) || 1}, changed)),
labelled("Heading", input(b, "title", {placeholder: "(feed name)"}, changed))),
h("div", {class: "row start"},
checkbox(b, "only_new", "Only items not printed before", changed),
checkbox(b, "qr_first", "QR code for the top item", changed)));
}
// --- Options ---
function renderOptions() {
const o = draft.options;
clear(optionsBox,
labelled("During quiet hours", select(o, "quiet", [
["hold", "Wait, and print when they end"], ["skip", "Skip it"],
["ignore", "Print anyway"]], changed),
conf.settings.quiet_start
? `Quiet hours are ${hhmm(conf.settings.quiet_start)}–${hhmm(conf.settings.quiet_end)}.`
: h("span", {}, "No quiet hours are set. ", h("a", {href: "#settings"}, "Settings"))),
checkbox(o, "skip_if_empty", "Skip when the agenda/headlines have nothing in them",
changed),
h("div", {class: "row start"},
labelled("Catch up if late by up to (min)", input(o, "catch_up_minutes",
{type: "number", min: 0, max: 1440, class: "narrow", parse: (v) => Number(v) || 0},
changed), "After a restart; anything later is logged as missed."),
labelled("Retries if the printer is off", input(o, "retries", {type: "number", min: 0,
max: 10, class: "narrow", parse: (v) => Number(v) || 0}, changed),
"5 minutes apart.")));
}
// --- actions ---
async function save() {
if (!draft.name.trim()) { nameInput.focus(); return toast("Give it a name.", "err"); }
saveButton.disabled = true;
const r = saved ? await put(`api/schedules/${saved.id}`, draft)
: await post("api/schedules", draft);
saveButton.disabled = false;
if (!r.ok) return toast(r.text, "err");
const isNew = !saved;
saved = r.body.schedule;
secret = saved.secret || secret;
draft = {name: saved.name, enabled: saved.enabled,
...normalise(structuredClone(saved.spec))};
dirty = false;
saveButton.textContent = "Saved";
toast("Saved.");
if (isNew) history.replaceState(null, "", `#schedules/${saved.id}`);
renderAll();
}
async function testPrint() {
if (dirty || !saved) {
await save();
if (dirty || !saved) return;
}
testButton.disabled = true;
const result = await printJob(() => post(`api/schedules/${saved.id}/run`),
(text) => (testButton.textContent = text));
testButton.disabled = false;
testButton.textContent = "Test print";
toast(result.text, result.ok ? "" : "err");
}
async function remove() {
if (!saved) { dirty = false; location.hash = "#schedules"; return; }
if (!confirm(`Delete "${saved.name}"?`)) return;
const r = await del(`api/schedules/${saved.id}`);
if (!r.ok) return toast(r.text, "err");
dirty = false;
location.hash = "#schedules";
}
const nameInput = h("input", {type: "text", class: "name", maxlength: 100,
placeholder: "Name this schedule", oninput: () => { draft.name = nameInput.value; changed(); }});
const enabled = h("input", {type: "checkbox", class: "switch", onchange: () => {
draft.enabled = enabled.checked; changed();
}});
function renderAll() {
nameInput.value = draft.name;
enabled.checked = draft.enabled;
clear(headerStatus, saved?.last_status
? [h("span", {class: "badge"}, STATUS_LABELS[saved.last_status] || saved.last_status),
" ", h("span", {class: "muted small"}, saved.last_message || ""),
saved.last_run_at ? h("span", {class: "muted small"}, ` · ${fmtTime(saved.last_run_at)}`)
: null,
" ", h("a", {class: "small", href: `#history/${saved.id}`}, "History")]
: null);
renderTrigger(); renderBlocks(); renderOptions(); refreshPreview();
}
clear(view,
h("div", {class: "toolbar editor-bar"},
h("a", {href: "#schedules", class: "back"}, "← Schedules"),
h("span", {class: "spacer"}),
h("label", {class: "check"}, enabled, " On"),
h("div", {class: "actions"},
h("button", {class: "danger ghost", onclick: remove}, saved ? "Delete" : "Discard"),
testButton, saveButton)),
h("div", {class: "editor-head"}, nameInput, headerStatus),
h("div", {class: "split"},
h("div", {class: "editor"},
h("section", {class: "card"}, h("h2", {}, h("span", {class: "step"}, "1"), "When"),
triggerBox, triggerInfo),
h("section", {class: "card"}, h("h2", {}, h("span", {class: "step"}, "2"), "What it prints"),
blocksBox),
h("section", {class: "card"}, h("details", {},
h("summary", {}, h("h2", {}, h("span", {class: "step"}, "3"), "Options")), optionsBox))),
h("aside", {class: "preview-col sticky"},
h("h3", {class: "muted small"}, "Preview"),
preview.root)));
renderAll();
if (id === "new") nameInput.focus();
// Leaving with unsaved changes: the router asks this before switching views.
return {
canLeave: () => !dirty || confirm("Leave without saving your changes?"),
isDirty: () => dirty,
};
}
+69
View File
@@ -0,0 +1,69 @@
// History tab: everything printed, skipped or missed, newest first.
import {get, post, printJob} from "./api.js";
import {clear, fmtTime, h, select, toast} from "./dom.js";
import {STATUS_LABELS} from "./schedules.js";
const SOURCE_LABELS = {manual: "Printed by hand", schedule: "Scheduled", calendar: "Calendar",
watch: "Watcher", webhook: "Webhook", test: "Test print"};
const STATE_CLASS = {done: "ok", failed: "err", missed: "warn", skipped: "warn"};
const PAGE = 50;
export async function historyView(view, scheduleId) {
const filters = {state: "", schedule_id: scheduleId || ""};
const list = h("div", {class: "history"});
const more = h("button", {class: "ghost", hidden: true}, "Older");
let oldest = null;
const schedules = await get("api/schedules");
const scheduleOptions = [["", "All schedules and prints"],
...(schedules.ok ? schedules.body.schedules.map((s) => [s.id, s.name]) : [])];
async function load(reset) {
if (reset) { clear(list); oldest = null; }
const params = new URLSearchParams({limit: String(PAGE)});
if (filters.state) params.set("state", filters.state);
if (filters.schedule_id) params.set("schedule_id", filters.schedule_id);
if (oldest) params.set("before", oldest);
const r = await get(`api/runs?${params}`);
if (!r.ok) return list.append(h("p", {class: "err"}, r.text));
const runs = r.body.runs;
if (!runs.length && !oldest) list.append(h("p", {class: "muted empty"}, "Nothing yet."));
runs.forEach((run) => list.append(row(run)));
oldest = runs.length ? runs[runs.length - 1].created_at : oldest;
more.hidden = runs.length < PAGE;
}
function row(run) {
const again = run.has_payload ? h("button", {class: "ghost small", onclick: async () => {
const result = await printJob(() => post(`api/runs/${run.id}/reprint`),
(text) => (again.textContent = text));
again.textContent = "Print again";
toast(result.text, result.ok ? "" : "err");
if (result.ok) load(true);
}}, "Print again") : null;
const title = run.schedule_id
? h("a", {href: `#schedules/${run.schedule_id}`}, run.name || "Schedule")
: h("span", {}, run.name || run.kind);
return h("div", {class: "run"},
h("div", {class: "when"}, fmtTime(run.created_at)),
h("div", {class: "what"},
h("div", {}, title, " ",
h("span", {class: `badge ${STATE_CLASS[run.state] || ""}`},
STATUS_LABELS[run.state] || run.state)),
h("div", {class: "muted small"}, SOURCE_LABELS[run.source] || run.source,
run.user && !run.user.startsWith("schedule:") ? ` · ${run.user}` : "",
run.message && run.state !== "done" ? ` · ${run.message}` : "")),
again);
}
more.addEventListener("click", () => load(false));
clear(view,
h("div", {class: "toolbar"}, h("h2", {}, "History"), h("span", {class: "spacer"}),
select(filters, "schedule_id", scheduleOptions, () => load(true)),
select(filters, "state", [["", "Any result"], ["done", "Printed"], ["failed", "Failed"],
["skipped", "Skipped"], ["missed", "Missed"]], () => load(true))),
h("section", {class: "card flush"}, list),
h("div", {class: "row center"}, more));
load(true);
}
+24
View File
@@ -0,0 +1,24 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Receipt Printer</title>
<link rel="stylesheet" href="static/app.css">
<script type="module" src="static/app.js"></script>
</head>
<body>
<header class="top">
<h1>Receipt printer</h1>
<button id="status" class="pill" title="Check again">checking…</button>
</header>
<nav class="tabs" aria-label="Sections">
<a href="#print">Print</a>
<a href="#schedules">Schedules</a>
<a href="#history">History</a>
<a href="#settings">Settings</a>
</nav>
<main id="view"></main>
<div id="toast" role="status" aria-live="polite"></div>
</body>
</html>
+35
View File
@@ -0,0 +1,35 @@
// The receipt preview: a strip of thermal paper drawn from /api/preview's parts.
import {h, clear} from "./dom.js";
export function paper() {
const strip = h("div", {class: "paper-strip"});
const meta = h("div", {class: "paper-meta"});
const root = h("div", {class: "paper-wrap"}, h("div", {class: "paper"}, strip), meta);
return {
root,
show(preview) {
clear(strip, preview.parts.map((part) => {
if (part.image) return h("img", {src: part.image, alt: ""});
const cls = ["t", `s${part.size || 1}`, part.bold ? "b" : "", part.center ? "c" : ""];
return h("pre", {class: cls.join(" ")}, part.text);
}));
const length = `${preview.height_mm} mm of paper`;
clear(meta,
h("span", {class: preview.too_long ? "err" : "muted"},
preview.too_long ? `${length}: over the ${preview.max_mm} mm limit` : length),
(preview.warnings || []).map((w) => h("div", {class: "warn"}, w)));
root.classList.remove("error");
},
error(text) {
clear(strip, h("pre", {class: "t s1 placeholder"}, text));
clear(meta);
root.classList.add("error");
},
empty(text) {
clear(strip, h("pre", {class: "t s1 placeholder"}, text));
clear(meta);
root.classList.remove("error");
},
};
}
+163
View File
@@ -0,0 +1,163 @@
// Starting points for new schedules. Source ids are filled with the first saved one that fits.
import {localDateTimeValue} from "./dom.js";
const WEEKDAYS = [0, 1, 2, 3, 4];
const ALL_DAYS = [0, 1, 2, 3, 4, 5, 6];
export const OPTIONS = {quiet: "hold", skip_if_empty: false, catch_up_minutes: 15, retries: 3};
export function recurring(extra = {}) {
return {type: "recurring", freq: "daily", interval: 1, times: ["08:00"], weekdays: [],
monthday: null, setpos: null, month: null, start: null, until: null, rrule: null,
...extra};
}
export function triggerDefaults(type, sources = []) {
const first = (kind) => (sources.find((s) => s.kind === kind) || {}).id || "";
const inAnHour = new Date(Date.now() + 3600e3);
inAnHour.setMinutes(0);
return {
once: () => ({type: "once", at: localDateTimeValue(inAnHour)}),
recurring: () => recurring(),
sun: () => ({type: "sun", event: "sunset", offset_minutes: 0, weekdays: [...ALL_DAYS]}),
calendar: () => ({type: "calendar", source_id: first("ics"), minutes_before: 15,
contains: "", include_all_day: false}),
watch: () => ({type: "watch", kind: "rss", url: "", path: "", condition: "changed",
threshold: null, every_minutes: 30, max_items: 3}),
webhook: () => ({type: "webhook", per_hour: 10}),
}[type]();
}
export function blockDefaults(type, sources = []) {
const ids = (kind) => {
const found = sources.find((s) => s.kind === kind);
return found ? [found.id] : [];
};
return {
note: () => ({type: "note", text: "", size: 1, timestamp: false, bold: false, center: false,
choices: [], pick: "sequential"}),
qr: () => ({type: "qr", content: "", caption: ""}),
image: () => ({type: "image", asset_id: "", caption: ""}),
random_image: () => ({type: "random_image"}),
agenda: () => ({type: "agenda", source_ids: ids("ics"), start_day: 0, days: 1,
include_all_day: true, title: ""}),
headlines: () => ({type: "headlines", source_ids: ids("rss"), count: 5, only_new: false,
qr_first: false, title: ""}),
divider: () => ({type: "divider"}),
}[type]();
}
function note(text, extra = {}) {
return {...blockDefaults("note"), text, ...extra};
}
export const PRESETS = [
{
id: "brief", icon: "☀", title: "Morning brief",
blurb: "Today's date, your calendar and the headlines, every weekday morning.",
make: (sources) => ({
name: "Morning brief",
trigger: recurring({times: ["07:30"], weekdays: [...WEEKDAYS]}),
blocks: [
note("{date:%A %d %B}", {size: 2, bold: true, center: true}),
blockDefaults("agenda", sources),
blockDefaults("divider"),
{...blockDefaults("headlines", sources), title: "Headlines"},
],
options: {...OPTIONS},
}),
},
{
id: "chores", icon: "✓", title: "Chore rotation",
blurb: "A different chore each day, taking turns through your list.",
make: () => ({
name: "Today's chore",
trigger: recurring({times: ["08:00"]}),
blocks: [note("TODAY'S CHORE\n\n{choice}", {size: 2, center: true,
choices: ["Hoover the living room", "Clean the bathroom", "Laundry", "Water the plants",
"Take the bins out", "Change the bed", "Clear out the fridge"]})],
options: {...OPTIONS},
}),
},
{
id: "countdown", icon: "⏳", title: "Countdown",
blurb: "Days left until a date, printed every morning.",
make: () => ({
name: "Christmas countdown",
trigger: recurring({times: ["09:00"]}),
blocks: [note("{days_until:12-25} days\nuntil Christmas", {size: 3, bold: true,
center: true})],
options: {...OPTIONS},
}),
},
{
id: "reminders", icon: "⏰", title: "Event reminders",
blurb: "A slip before each event in a calendar.",
make: (sources) => ({
name: "Event reminders",
trigger: triggerDefaults("calendar", sources),
blocks: [
note("IN {event.minutes} MIN", {bold: true, center: true}),
note("{event.title}", {size: 2, center: true}),
note("{event.start} - {event.end}\n{event.location}", {center: true}),
],
options: {...OPTIONS, quiet: "skip"},
}),
},
{
id: "feed", icon: "✉", title: "New post alert",
blurb: "Prints each new item in an RSS feed, with a QR code to open it.",
make: () => ({
name: "New posts",
trigger: triggerDefaults("watch"),
blocks: [
note("{item.source}", {bold: true}),
note("{item.title}", {size: 2}),
{type: "qr", content: "{item.link}", caption: ""},
],
options: {...OPTIONS},
}),
},
{
id: "price", icon: "↗", title: "Value watch",
blurb: "Watches a number in a JSON API and prints when it crosses a threshold.",
make: () => ({
name: "Price alert",
trigger: {...triggerDefaults("watch"), kind: "json", path: "price", condition: "above",
threshold: 100},
blocks: [note("Now {value} (was {old_value})", {size: 2, center: true})],
options: {...OPTIONS},
}),
},
{
id: "webhook", icon: "⚡", title: "Webhook",
blurb: "Other services (Home Assistant, phone shortcuts) print by calling a URL.",
make: () => ({
name: "Webhook print",
trigger: triggerDefaults("webhook"),
blocks: [note("{payload.title}", {bold: true}), note("{payload.text}", {size: 2})],
options: {...OPTIONS, quiet: "skip"},
}),
},
{
id: "sunset", icon: "☾", title: "Sunset nudge",
blurb: "A note half an hour before sunset.",
make: () => ({
name: "Sunset soon",
trigger: {...triggerDefaults("sun"), event: "sunset", offset_minutes: -30},
blocks: [note("Sunset in 30 minutes.\nGo and look outside.", {size: 2, center: true})],
options: {...OPTIONS},
}),
},
{
id: "blank", icon: "+", title: "Start from scratch",
blurb: "A one-off note, an hour from now.",
make: () => ({
name: "Reminder",
trigger: triggerDefaults("once"),
blocks: [note("")],
options: {...OPTIONS},
}),
},
];
+149
View File
@@ -0,0 +1,149 @@
// Print tab: a note, an image or a QR code, right now, with a live preview.
import {call, post, printJob} from "./api.js";
import {h, clear, debounce, segmented, toast} from "./dom.js";
import {paper} from "./paper.js";
const draft = {mode: "note", text: "", timestamp: false, size: 2, caption: "", qr: "",
qrCaption: "", file: null};
export function printView(view) {
const preview = paper();
const status = h("p", {class: "status muted"}, "Ready.");
const formBox = h("div");
const modes = h("div");
function setStatus(text, cls = "muted") { status.textContent = text; status.className = `status ${cls}`; }
const refreshPreview = debounce(async () => {
if (draft.mode === "image") {
if (!draft.file) return preview.empty("Choose an image to see how it prints.");
const data = new FormData();
data.append("file", draft.file, draft.file.name || "pasted.png");
data.append("message", draft.caption);
const r = await call("api/preview/image", {method: "POST", body: data});
return r.ok ? preview.show(r.body) : preview.error(r.text);
}
let block;
if (draft.mode === "note") {
if (!draft.text.trim()) return preview.empty("Type a note to see how it prints.");
block = {type: "note", text: draft.text, size: draft.size, timestamp: draft.timestamp};
} else {
if (!draft.qr.trim()) return preview.empty("Enter text or a link to encode.");
block = {type: "qr", content: draft.qr, caption: draft.qrCaption};
}
// Plain prints have no template variables: {{ }} keeps braces literal in the preview.
if (block.type === "note") block.text = block.text.replaceAll("{", "{{").replaceAll("}", "}}");
if (block.type === "qr") {
block.content = block.content.replaceAll("{", "{{").replaceAll("}", "}}");
block.caption = block.caption.replaceAll("{", "{{").replaceAll("}", "}}");
}
const r = await post("api/preview", {blocks: [block]});
r.ok ? preview.show(r.body) : preview.error(r.text);
}, 350);
async function send(request, after) {
const buttons = view.querySelectorAll("button.primary");
buttons.forEach((b) => (b.disabled = true));
const result = await printJob(request, (text) => setStatus(text));
buttons.forEach((b) => (b.disabled = false));
setStatus(result.text, result.ok ? "ok" : "err");
if (result.ok) { toast("Printed."); after && after(); }
}
function noteForm() {
const text = h("textarea", {maxlength: 4000, placeholder: "Your note", value: draft.text,
oninput: () => { draft.text = text.value; refreshPreview(); }});
const size = h("select", {onchange: () => { draft.size = Number(size.value); refreshPreview(); }},
h("option", {value: "1"}, "Normal (48 per line)"),
h("option", {value: "2"}, "Large (24 per line)"),
h("option", {value: "3"}, "Huge (16 per line)"));
size.value = String(draft.size);
const stamp = h("input", {type: "checkbox", checked: draft.timestamp,
onchange: () => { draft.timestamp = stamp.checked; refreshPreview(); }});
return h("form", {onsubmit: (e) => {
e.preventDefault();
if (!draft.text.trim()) return setStatus("Type something first.", "err");
send(() => post("api/note", {text: draft.text, timestamp: draft.timestamp, size: draft.size}),
() => { draft.text = ""; text.value = ""; refreshPreview(); });
}},
text,
h("div", {class: "row"},
h("label", {class: "check"}, stamp, " Date/time header"),
h("label", {class: "inline"}, "Size ", size),
h("button", {type: "submit", class: "primary"}, "Print note")));
}
function imageForm() {
const fileInput = h("input", {type: "file", accept: "image/*", hidden: true,
onchange: () => pick(fileInput.files[0])});
const drop = h("label", {class: "drop"}, draft.file ? draft.file.name || "Pasted image"
: "Choose, drop or paste an image");
drop.append(fileInput);
drop.addEventListener("dragover", (e) => { e.preventDefault(); drop.classList.add("over"); });
drop.addEventListener("dragleave", () => drop.classList.remove("over"));
drop.addEventListener("drop", (e) => {
e.preventDefault(); drop.classList.remove("over"); pick(e.dataTransfer.files[0]);
});
function pick(file) {
if (!file || !file.type.startsWith("image/")) return;
draft.file = file;
drop.firstChild.textContent = file.name || "Pasted image";
refreshPreview();
}
view._pick = pick;
const caption = h("input", {type: "text", maxlength: 500, placeholder: "Caption (optional)",
value: draft.caption, oninput: () => { draft.caption = caption.value; refreshPreview(); }});
return h("form", {onsubmit: (e) => {
e.preventDefault();
if (!draft.file) return setStatus("Choose an image first.", "err");
const data = new FormData();
data.append("file", draft.file, draft.file.name || "pasted.png");
data.append("message", draft.caption);
send(() => call("api/image", {method: "POST", body: data}));
}},
drop, caption,
h("div", {class: "row"},
h("span", {class: "muted"}, "Max 16 MB. Printed full width, dithered."),
h("button", {type: "submit", class: "primary"}, "Print image")));
}
function qrForm() {
const content = h("input", {type: "text", maxlength: 2000, placeholder: "https://example.com",
value: draft.qr, oninput: () => { draft.qr = content.value; refreshPreview(); }});
const caption = h("input", {type: "text", maxlength: 500, placeholder: "Caption (optional)",
value: draft.qrCaption,
oninput: () => { draft.qrCaption = caption.value; refreshPreview(); }});
return h("form", {onsubmit: (e) => {
e.preventDefault();
if (!draft.qr.trim()) return setStatus("Enter something to encode.", "err");
send(() => post("api/qr", {content: draft.qr, caption: draft.qrCaption}));
}},
h("label", {class: "field"}, h("span", {class: "caption"}, "Text or link"), content),
h("label", {class: "field"}, h("span", {class: "caption"}, "Caption"), caption),
h("div", {class: "row end"}, h("button", {type: "submit", class: "primary"}, "Print QR code")));
}
function render() {
clear(modes, segmented(draft.mode, [["note", "Note"], ["image", "Image"], ["qr", "QR code"]],
(mode) => { draft.mode = mode; render(); }));
clear(formBox, {note: noteForm, image: imageForm, qr: qrForm}[draft.mode]());
refreshPreview();
}
// Pasting an image anywhere on this tab picks it.
const onPaste = (e) => {
const item = [...(e.clipboardData?.items || [])].find((i) => i.type.startsWith("image/"));
if (!item) return;
if (draft.mode !== "image") { draft.mode = "image"; render(); }
view._pick(item.getAsFile());
};
document.addEventListener("paste", onPaste);
clear(view,
h("div", {class: "split"},
h("section", {class: "card"}, h("h2", {}, "Print now"), modes, formBox, status),
h("aside", {class: "preview-col"}, h("h3", {class: "muted small"}, "Preview"), preview.root)));
render();
return () => document.removeEventListener("paste", onPaste);
}
+126
View File
@@ -0,0 +1,126 @@
// Schedules tab: what's coming up, every schedule as a card, and the preset picker.
import {get, post, del, printJob, sources} from "./api.js";
import {h, clear, fmtTime, relative, toast} from "./dom.js";
import {PRESETS} from "./presets.js";
export const STATUS_LABELS = {
queued: "Queued", printing: "Printing", done: "Printed", failed: "Failed",
skipped: "Skipped", missed: "Missed", error: "Problem", retrying: "Retrying",
held: "Held", watching: "Watching", finished: "Finished",
};
const STATUS_CLASS = {done: "ok", watching: "ok", failed: "err", error: "err", missed: "warn",
skipped: "warn", retrying: "warn", held: "warn"};
export const TRIGGER_ICONS = {once: "◷", recurring: "↻", sun: "☀", calendar: "▦", watch: "◉",
webhook: "⚡"};
// Set by the editor so a preset or a duplicate opens pre-filled.
export const pending = {draft: null};
export async function schedulesView(view) {
const list = h("div", {class: "cards"});
const coming = h("div", {class: "coming"});
clear(view,
h("div", {class: "toolbar"},
h("h2", {}, "Schedules"),
h("button", {class: "primary", onclick: () => showPresets(view)}, "New schedule")),
coming, list);
const [r, up] = await Promise.all([get("api/schedules"), get("api/upcoming?hours=24")]);
if (!r.ok) return clear(list, h("p", {class: "err"}, r.text));
const schedules = r.body.schedules;
if (up.ok && up.body.upcoming.length) {
clear(coming, h("h3", {class: "small muted"}, "Next 24 hours"),
h("div", {class: "timeline"}, up.body.upcoming.slice(0, 12).map((u) =>
h("a", {class: "tick", href: `#schedules/${u.schedule_id}`},
h("strong", {}, new Date(u.at).toLocaleTimeString([], {hour: "2-digit",
minute: "2-digit"})),
h("span", {}, u.name)))));
}
if (!schedules.length) {
clear(list, h("div", {class: "empty"},
h("p", {}, "Nothing scheduled yet. Pick a starting point:"), presetGrid()));
return;
}
clear(list, schedules.map((s) => card(s, () => schedulesView(view))));
}
function card(s, reload) {
const type = s.spec?.trigger?.type;
const toggle = h("input", {type: "checkbox", class: "switch", checked: s.enabled,
"aria-label": s.enabled ? "Turn off" : "Turn on",
onchange: async () => {
const r = await post(`api/schedules/${s.id}/toggle`, {enabled: toggle.checked});
if (!r.ok) { toggle.checked = !toggle.checked; return toast(r.text, "err"); }
toast(toggle.checked ? `${s.name} is on.` : `${s.name} is off.`);
reload();
}});
const next = s.enabled && s.next_run_at
? `Next: ${fmtTime(s.next_run_at)} (${relative(s.next_run_at)})`
: s.enabled ? (type === "webhook" ? "Waits for its webhook" : "") : "Off";
const status = s.last_status
? h("span", {class: `badge ${STATUS_CLASS[s.last_status] || ""}`,
title: s.last_message || ""}, STATUS_LABELS[s.last_status] || s.last_status)
: null;
const busy = h("span", {class: "muted small"});
async function testPrint() {
const result = await printJob(() => post(`api/schedules/${s.id}/run`),
(text) => (busy.textContent = text));
busy.textContent = "";
toast(result.text, result.ok ? "" : "err");
}
async function duplicate() {
const r = await post(`api/schedules/${s.id}/duplicate`);
if (!r.ok) return toast(r.text, "err");
location.hash = `#schedules/${r.body.schedule.id}`;
}
async function remove() {
if (!confirm(`Delete "${s.name}"?`)) return;
const r = await del(`api/schedules/${s.id}`);
if (!r.ok) return toast(r.text, "err");
toast("Deleted.");
reload();
}
return h("article", {class: `card schedule ${s.enabled ? "" : "off"}`},
h("div", {class: "card-head"},
h("span", {class: "icon", "aria-hidden": "true"}, TRIGGER_ICONS[type] || "?"),
h("a", {class: "title", href: `#schedules/${s.id}`}, s.name),
toggle),
h("p", {class: "summary"}, s.summary),
h("p", {class: "meta"}, next ? h("span", {}, next) : null, status,
s.last_message && s.last_status !== "done"
? h("span", {class: "muted small last"}, s.last_message) : null),
h("div", {class: "actions"},
h("a", {class: "button small", href: `#schedules/${s.id}`}, "Edit"),
h("button", {class: "small", onclick: testPrint}, "Test print"),
h("button", {class: "ghost small", onclick: duplicate}, "Duplicate"),
h("button", {class: "danger ghost small", onclick: remove}, "Delete"),
busy));
}
function presetGrid() {
return h("div", {class: "presets"}, PRESETS.map((p) =>
h("button", {class: "preset", onclick: async () => {
pending.draft = p.make(await sources());
location.hash = "#schedules/new";
}},
h("span", {class: "icon", "aria-hidden": "true"}, p.icon),
h("strong", {}, p.title),
h("span", {class: "muted small"}, p.blurb))));
}
function showPresets(view) {
const dialog = h("dialog", {class: "sheet", onclose: () => dialog.remove()},
h("div", {class: "toolbar"}, h("h2", {}, "New schedule"),
h("button", {class: "ghost", onclick: () => dialog.close()}, "Close")),
presetGrid());
view.append(dialog);
dialog.showModal();
}
+173
View File
@@ -0,0 +1,173 @@
// Settings tab: time zone and location, quiet hours, limits, pause, saved sources and images.
import {assets, call, del, post, put, settings, sources} from "./api.js";
import {checkbox, clear, h, input, labelled, select, toast} from "./dom.js";
export async function settingsView(view) {
const conf = await settings(true);
const s = structuredClone(conf.settings);
const quiet = {on: !!s.quiet_start, start: (s.quiet_start || "22:00").slice(0, 5),
end: (s.quiet_end || "07:00").slice(0, 5)};
const loc = {latitude: s.location?.latitude ?? "", longitude: s.location?.longitude ?? "",
name: s.location?.name ?? ""};
const sourcesBox = h("div");
const assetsBox = h("div");
async function save() {
const body = {
timezone: s.timezone,
location: loc.latitude === "" || loc.longitude === "" || loc.latitude === null
? null : {latitude: Number(loc.latitude), longitude: Number(loc.longitude),
name: loc.name || ""},
quiet_start: quiet.on ? quiet.start : null,
quiet_end: quiet.on ? quiet.end : null,
daily_cap: Number(s.daily_cap) || 0,
paused: !!s.paused,
paused_until: s.paused && s.paused_until ? s.paused_until : null,
};
const r = await put("api/settings", body);
if (!r.ok) return toast(r.text, "err");
await settings(true);
toast("Settings saved.");
}
const latInput = input(loc, "latitude", {type: "number", step: "any", class: "narrow",
placeholder: "51.5"});
const lonInput = input(loc, "longitude", {type: "number", step: "any", class: "narrow",
placeholder: "-0.12"});
const locate = h("button", {type: "button", class: "ghost small", onclick: () => {
if (!navigator.geolocation) return toast("This browser can't share its location.", "err");
locate.textContent = "Locating…";
navigator.geolocation.getCurrentPosition((pos) => {
loc.latitude = Number(pos.coords.latitude.toFixed(4));
loc.longitude = Number(pos.coords.longitude.toFixed(4));
latInput.value = loc.latitude; lonInput.value = loc.longitude;
locate.textContent = "Use my location";
}, (err) => { locate.textContent = "Use my location"; toast(err.message, "err"); });
}}, "Use my location");
const tzList = h("datalist", {id: "tz-list"}, conf.timezones.map((z) => h("option", {value: z})));
const pauseUntil = labelled("Until (optional)", input(s, "paused_until", {type: "date",
parse: (v) => v || null}), "Printing resumes at the start of that day.");
clear(view,
h("div", {class: "toolbar"}, h("h2", {}, "Settings"), h("span", {class: "spacer"}),
h("button", {class: "primary", onclick: save}, "Save settings")),
h("div", {class: "grid2"},
h("section", {class: "card"},
h("h3", {}, "Time and place"),
labelled("Time zone", input(s, "timezone", {list: "tz-list"}), null), tzList,
labelled("Location (for sunrise and sunset)",
h("div", {class: "row start"}, latInput, lonInput, locate)),
labelled("Place name", input(loc, "name", {placeholder: "(optional)"}))),
h("section", {class: "card"},
h("h3", {}, "Automatic printing"),
checkbox(quiet, "on", "Quiet hours"),
h("div", {class: "row start indent"},
input(quiet, "start", {type: "time"}), h("span", {}, "to"),
input(quiet, "end", {type: "time"})),
h("p", {class: "muted small"}, "Each schedule chooses whether to wait, skip or print anyway."),
labelled("Most automatic prints per day", input(s, "daily_cap", {type: "number", min: 0,
max: 1000, class: "narrow"}), "0 for no limit. Prints by hand don't count."),
checkbox(s, "paused", "Pause all schedules (holiday mode)"),
pauseUntil)),
h("section", {class: "card"},
h("h3", {}, "Calendars and feeds"),
h("p", {class: "muted small"},
"Saved once, used by agenda and headline blocks and calendar reminders. For Google " +
"Calendar, use the calendar's secret address in iCal format."),
sourcesBox),
h("section", {class: "card"}, h("h3", {}, "Images for schedules"), assetsBox));
renderSources(sourcesBox);
renderAssets(assetsBox);
}
function mask(url) {
try {
const u = new URL(url);
return `${u.protocol}//${u.host}${u.pathname.length > 1 ? "/…" : ""}`;
} catch (e) { return url; }
}
async function renderSources(box) {
const list = await sources(true);
const draft = {name: "", kind: "ics", url: ""};
const result = h("span", {class: "small muted"});
async function test(body, out) {
out.textContent = "Checking…";
const r = await post("api/sources/test", body);
out.textContent = r.text;
out.className = `small ${r.ok ? "ok" : "err"}`;
}
function item(source) {
const out = h("span", {class: "small muted"});
return h("div", {class: "list-row"},
h("span", {class: "badge"}, source.kind === "ics" ? "Calendar" : "Feed"),
h("strong", {}, source.name),
h("code", {class: "muted small", title: "The full address is hidden"}, mask(source.url)),
h("span", {class: "spacer"}),
out,
h("button", {class: "ghost small", onclick: () => test(
{name: source.name, kind: source.kind, url: source.url}, out)}, "Test"),
h("button", {class: "ghost small", onclick: async () => {
const url = prompt(`New address for ${source.name}:`, "");
if (!url) return;
const r = await put(`api/sources/${source.id}`, {...source, url, id: undefined,
created_at: undefined});
if (!r.ok) return toast(r.text, "err");
renderSources(box);
}}, "Change URL"),
h("button", {class: "ghost small danger", onclick: async () => {
if (!confirm(`Delete ${source.name}?`)) return;
const r = await del(`api/sources/${source.id}`);
if (!r.ok) return toast(r.text, "err");
renderSources(box);
}}, "Delete"));
}
clear(box,
list.length ? list.map(item) : h("p", {class: "muted"}, "None yet."),
h("form", {class: "add-source", onsubmit: async (e) => {
e.preventDefault();
const r = await post("api/sources", draft);
if (!r.ok) return toast(r.text, "err");
toast(`Added ${draft.name}.`);
renderSources(box);
}},
h("div", {class: "row start"},
select(draft, "kind", [["ics", "Calendar (ICS)"], ["rss", "Feed (RSS/Atom)"]]),
input(draft, "name", {placeholder: "Name", required: true, maxlength: 100}),
input(draft, "url", {placeholder: "https://… or webcal://…", required: true,
class: "grow"})),
h("div", {class: "row start"},
h("button", {type: "button", class: "ghost", onclick: () => test(draft, result)}, "Test"),
h("button", {type: "submit"}, "Add"), result)));
}
async function renderAssets(box) {
const list = await assets(true);
clear(box,
list.length ? list.map((a) => h("div", {class: "list-row"},
h("strong", {}, a.name), h("span", {class: "muted small"}, `${Math.ceil(a.size / 1024)} KB`),
h("span", {class: "spacer"}),
h("button", {class: "ghost small danger", onclick: async () => {
if (!confirm(`Delete ${a.name}?`)) return;
const r = await del(`api/assets/${a.id}`);
if (!r.ok) return toast(r.text, "err");
renderAssets(box);
}}, "Delete")))
: h("p", {class: "muted"}, "None yet. Upload one from an image block in a schedule, or here."),
h("label", {class: "button ghost"}, "Upload image…",
h("input", {type: "file", accept: "image/*", hidden: true, onchange: async (e) => {
const file = e.target.files[0];
if (!file) return;
const data = new FormData();
data.append("file", file, file.name || "image.png");
const r = await call("api/assets", {method: "POST", body: data});
if (!r.ok) return toast(r.text, "err");
renderAssets(box);
}})));
}