Add scheduled and event-driven printing with a new web UI
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:
+591
@@ -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,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user