markdown-pdf-export 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/studio/app.mjs ADDED
@@ -0,0 +1,589 @@
1
+ /* Studio page logic. No framework: one state object, one sync() that reflects it. */
2
+ import {
3
+ CHIPS,
4
+ FIRST_LAYOUT,
5
+ LAYOUTS,
6
+ LOGO,
7
+ MARGINS,
8
+ ZONES,
9
+ draftToSettings,
10
+ emptyDraft,
11
+ lookDefaults,
12
+ matchLayout,
13
+ renderText,
14
+ settingsToDraft,
15
+ } from "/model.mjs";
16
+
17
+ const $ = (id) => document.getElementById(id);
18
+
19
+ function el(tag, props = {}, ...children) {
20
+ const node = document.createElement(tag);
21
+ for (const [key, value] of Object.entries(props)) {
22
+ if (key === "class") node.className = value;
23
+ else if (key === "text") node.textContent = value;
24
+ else if (key.startsWith("on")) node.addEventListener(key.slice(2), value);
25
+ else if (value !== false && value !== null && value !== undefined) node.setAttribute(key, value === true ? "" : value);
26
+ }
27
+ node.append(...children.filter((c) => c !== null && c !== undefined));
28
+ return node;
29
+ }
30
+
31
+ // ── token: arrives in the URL fragment, which is never sent to any server ────
32
+ const fromHash = location.hash.slice(1);
33
+ if (fromHash) {
34
+ sessionStorage.setItem("studio-token", fromHash);
35
+ history.replaceState(null, "", location.pathname);
36
+ }
37
+ const TOKEN = sessionStorage.getItem("studio-token") ?? "";
38
+
39
+ async function api(path, { method = "GET", json, body, raw = false } = {}) {
40
+ const headers = { "x-studio-token": TOKEN };
41
+ if (json !== undefined) headers["content-type"] = "application/json";
42
+ const res = await fetch(path, { method, headers, body: json !== undefined ? JSON.stringify(json) : body });
43
+ if (!res.ok) {
44
+ let message = `Request failed (${res.status}).`;
45
+ try {
46
+ message = (await res.json()).error ?? message;
47
+ } catch {
48
+ // keep the generic message
49
+ }
50
+ const error = new Error(message);
51
+ error.status = res.status;
52
+ throw error;
53
+ }
54
+ return raw ? res : res.json();
55
+ }
56
+
57
+ // ── state ───────────────────────────────────────────────────────────────────
58
+ let server = null; // /api/state
59
+ let raw = {}; // settings file content as last loaded or saved
60
+ let draft = emptyDraft();
61
+ let selected = null; // { area: "header" | "footer", zone }
62
+ let savedJson = "";
63
+ let loadedJson = ""; // what the page showed on arrival (nothing to lose until it differs)
64
+ const thumbs = new Map(); // image path → object URL of the file just uploaded
65
+
66
+ const AREA_NAMES = { header: "Top", footer: "Bottom" };
67
+ const SIZE_LABELS = { s: "Small", m: "Medium", l: "Large" };
68
+ const MARGIN_LABELS = { narrow: "Narrow", normal: "Normal", wide: "Wide" };
69
+ const LOOK_LABELS = { clean: "Clean", report: "Report", academic: "Academic", compact: "Compact", technical: "Technical" };
70
+
71
+ const currentSettings = () => draftToSettings(draft, raw, { looks: server.looks });
72
+ const isDirty = () => JSON.stringify(currentSettings()) !== savedJson;
73
+
74
+ function change(mutate) {
75
+ mutate();
76
+ sync();
77
+ schedulePreview();
78
+ }
79
+
80
+ // ── build once ──────────────────────────────────────────────────────────────
81
+ function segmented(host, options, get, set) {
82
+ host.replaceChildren(
83
+ ...options.map(([value, label, style]) => {
84
+ const b = el("button", { type: "button", role: "radio", "data-value": value, text: label, onclick: () => change(() => set(value)) });
85
+ if (style) b.style.fontFamily = style;
86
+ return b;
87
+ }),
88
+ );
89
+ host._sync = () => {
90
+ for (const b of host.children) b.setAttribute("aria-checked", String(b.dataset.value === get()));
91
+ };
92
+ }
93
+
94
+ function build() {
95
+ // page style gallery
96
+ $("looks").replaceChildren(
97
+ ...Object.entries(server.looks).map(([name, def]) =>
98
+ el(
99
+ "button",
100
+ { type: "button", class: "look", role: "radio", "data-value": name, title: def.description, onclick: () => change(() => Object.assign(draft, { look: name }, lookDefaults(name, server.looks))) },
101
+ el("span", { class: `thumb ${name}` }, el("i", { class: "h" }), el("i"), el("i", { class: "w80" }), el("i", { class: "code" }), el("i"), el("i", { class: "w55" })),
102
+ el("span", { text: LOOK_LABELS[name] ?? name }),
103
+ ),
104
+ ),
105
+ );
106
+
107
+ // Two font choices: body text and titles. "From the page style" writes nothing.
108
+ for (const [id, key] of [["font", "font"], ["heading-font", "heading_font"]]) {
109
+ const names = Object.keys(server.fonts).filter((n) => n !== "system" || draft[key] === "system");
110
+ const options = [
111
+ el("option", { value: "look", text: "From the page style" }),
112
+ ...names.map((n) => {
113
+ const o = el("option", { value: n, text: server.fontLabels[n] ?? n });
114
+ o.style.fontFamily = server.fonts[n];
115
+ return o;
116
+ }),
117
+ ];
118
+ if (draft[key] === "custom") options.push(el("option", { value: "custom", text: "From your file" }));
119
+ $(id).replaceChildren(...options);
120
+ $(id).addEventListener("change", (e) => change(() => (draft[key] = e.target.value)));
121
+ }
122
+
123
+ $("format").replaceChildren(...server.pageFormats.map((f) => el("option", { value: f, text: f })));
124
+ $("format").addEventListener("change", (e) => change(() => (draft.page_format = e.target.value)));
125
+
126
+ const themes = [...server.codeThemes];
127
+ if (!themes.some((t) => t.file === draft.highlight)) {
128
+ themes.push({ file: draft.highlight, label: `${draft.highlight.replace(/\.css$/, "")} (from file)` });
129
+ }
130
+ $("highlight").replaceChildren(...themes.map((t) => el("option", { value: t.file, text: t.label })));
131
+ $("highlight").addEventListener("change", (e) => change(() => (draft.highlight = e.target.value)));
132
+ segmented($("orientation"), [["portrait", "Portrait"], ["landscape", "Landscape"]], () => draft.orientation, (v) => (draft.orientation = v));
133
+
134
+ const margins = Object.entries(MARGIN_LABELS);
135
+ if (draft.margin === "custom") margins.push(["custom", "From file"]);
136
+ segmented($("margin"), margins, () => draft.margin, (v) => (draft.margin = v));
137
+
138
+ $("layouts").replaceChildren(
139
+ ...LAYOUTS.map((l) =>
140
+ el("button", {
141
+ type: "button",
142
+ "data-value": l.id,
143
+ text: l.label,
144
+ onclick: () =>
145
+ change(() => {
146
+ draft.header = l.header();
147
+ draft.footer = l.footer();
148
+ selected = l.id === "letterhead" ? { area: "header", zone: "left" } : null;
149
+ }),
150
+ }),
151
+ ),
152
+ );
153
+
154
+ $("line-header").addEventListener("change", (e) => change(() => (draft.header.line = e.target.checked)));
155
+ $("line-footer").addEventListener("change", (e) => change(() => (draft.footer.line = e.target.checked)));
156
+ segmented($("size"), Object.entries(SIZE_LABELS), () => draft.text_size, (v) => (draft.text_size = v));
157
+ $("color").addEventListener("input", (e) => change(() => (draft.color = e.target.value)));
158
+
159
+ $("save").addEventListener("click", save);
160
+ $("save-path").textContent = `\u200E${server.displayPath}`; // keep the path left-to-right inside the rtl ellipsis
161
+ $("save-path").title = server.settingsPath;
162
+
163
+ $("editors-open").addEventListener("click", openEditors);
164
+ $("editors-close").addEventListener("click", () => $("editors").close());
165
+
166
+ addEventListener("beforeunload", (e) => {
167
+ if (isDirty() && JSON.stringify(currentSettings()) !== loadedJson) e.preventDefault();
168
+ });
169
+ addEventListener("keydown", (e) => {
170
+ if ((e.metaKey || e.ctrlKey) && e.key === "s") {
171
+ e.preventDefault();
172
+ save();
173
+ }
174
+ });
175
+ }
176
+
177
+ // ── sync: reflect state into the page ───────────────────────────────────────
178
+ function slotButton(areaName, zone) {
179
+ const slot = draft[areaName][zone];
180
+ const isSelected = selected?.area === areaName && selected.zone === zone;
181
+ const filled = (slot.kind === "text" && slot.text.trim()) || (slot.kind === "image" && slot.image);
182
+ const text = !filled
183
+ ? slot.kind === "image"
184
+ ? "Add logo"
185
+ : "+"
186
+ : slot.kind === "image"
187
+ ? "Logo"
188
+ : renderText(slot.text, { title: "Quarterly report", author: "Alex Morgan", filename: server.preview.name });
189
+ const button = el("button", {
190
+ type: "button",
191
+ class: `slot ${zone} ${filled ? "filled" : "empty"}`,
192
+ "aria-pressed": String(isSelected),
193
+ "aria-label": `${AREA_NAMES[areaName]} ${zone}: ${filled ? text : "empty"}`,
194
+ text,
195
+ onclick: () => {
196
+ selected = { area: areaName, zone };
197
+ sync();
198
+ $("slot-editor").querySelector("input[type=text]")?.focus();
199
+ },
200
+ });
201
+ button.style.color = filled ? draft.color : "";
202
+ const thumb = slot.kind === "image" ? thumbs.get(slot.image) : null;
203
+ if (thumb) button.replaceChildren(el("img", { src: thumb, alt: "Logo" }));
204
+ button.addEventListener("dragover", (e) => {
205
+ e.preventDefault();
206
+ button.classList.add("drop");
207
+ });
208
+ button.addEventListener("dragleave", () => button.classList.remove("drop"));
209
+ button.addEventListener("drop", (e) => {
210
+ e.preventDefault();
211
+ button.classList.remove("drop");
212
+ const file = e.dataTransfer?.files?.[0];
213
+ if (file) uploadLogo(file, areaName, zone);
214
+ });
215
+ return button;
216
+ }
217
+
218
+ function syncBand(areaName) {
219
+ const band = $(`band-${areaName}`);
220
+ const area = draft[areaName];
221
+ band.className = `band ${area.line ? (areaName === "header" ? "lined-below" : "lined-above") : ""}`;
222
+ if (area.custom) {
223
+ band.replaceChildren(
224
+ el("div", { class: "slot locked", text: `Your file has a hand-written ${areaName}. Studio keeps it as it is.` }),
225
+ );
226
+ return;
227
+ }
228
+ band.replaceChildren(...ZONES.map((zone) => slotButton(areaName, zone)));
229
+ }
230
+
231
+ /** Logo size slider: percent of the standard 12 mm, within a range that still fits a header. */
232
+ function sizeRow(slot) {
233
+ const output = el("output", { text: `${slot.size}%` });
234
+ const input = el("input", {
235
+ type: "range",
236
+ min: LOGO.min,
237
+ max: LOGO.max,
238
+ step: LOGO.step,
239
+ value: slot.size,
240
+ "aria-label": "Logo size",
241
+ oninput: (e) => {
242
+ output.textContent = `${e.target.value}%`;
243
+ change(() => (slot.size = Number(e.target.value)));
244
+ },
245
+ });
246
+ return el("div", { class: "size-row" }, el("span", { class: "label", text: "Size" }), input, output);
247
+ }
248
+
249
+ let editorKey = "";
250
+ function syncSlotEditor() {
251
+ const host = $("slot-editor");
252
+ if (!selected || draft[selected.area].custom) {
253
+ editorKey = "";
254
+ host.replaceChildren(el("p", { class: "empty-note", text: "Click a spot on the page above to put text or a logo there." }));
255
+ return;
256
+ }
257
+ const { area: areaName, zone } = selected;
258
+ const slot = draft[areaName][zone];
259
+ const key = `${areaName}.${zone}.${slot.kind === "image" ? `image:${slot.image}` : "text"}`;
260
+ if (key === editorKey) return; // keep the input (and the caret) while typing
261
+ editorKey = key;
262
+
263
+ const title = el("div", { class: "title" }, el("span", { text: `${AREA_NAMES[areaName]} ${zone}` }));
264
+ const picker = el("input", { type: "file", accept: ".svg,.png,.jpg,.jpeg,image/*", hidden: true, onchange: (e) => e.target.files[0] && uploadLogo(e.target.files[0], areaName, zone) });
265
+
266
+ if (slot.kind === "image") {
267
+ const preview = thumbs.get(slot.image);
268
+ host.replaceChildren(
269
+ title,
270
+ picker,
271
+ el(
272
+ "div",
273
+ { class: "logo-row" },
274
+ preview ? el("img", { src: preview, alt: "" }) : null,
275
+ el("span", { class: "name", text: slot.image || "No logo chosen yet. Drop an image here or choose a file." }),
276
+ el("button", { type: "button", class: "btn small", text: slot.image ? "Replace" : "Choose file", onclick: () => picker.click() }),
277
+ el("button", {
278
+ type: "button",
279
+ class: "btn small quiet",
280
+ text: "Use text",
281
+ onclick: () => change(() => (draft[areaName][zone] = { kind: "text", text: "", image: "", size: 100 })),
282
+ }),
283
+ ),
284
+ slot.image ? sizeRow(slot) : null,
285
+ );
286
+ return;
287
+ }
288
+
289
+ const input = el("input", {
290
+ type: "text",
291
+ value: slot.text,
292
+ placeholder: "Type here, or pick something below",
293
+ "aria-label": `${AREA_NAMES[areaName]} ${zone} text`,
294
+ oninput: (e) =>
295
+ change(() => {
296
+ const text = e.target.value;
297
+ draft[areaName][zone] = { kind: text.trim() ? "text" : "none", text, image: "", size: 100 };
298
+ }),
299
+ });
300
+ const insert = (snippet) => {
301
+ const start = input.selectionStart ?? input.value.length;
302
+ const end = input.selectionEnd ?? start;
303
+ input.value = input.value.slice(0, start) + snippet + input.value.slice(end);
304
+ input.setSelectionRange(start + snippet.length, start + snippet.length);
305
+ input.dispatchEvent(new Event("input"));
306
+ input.focus();
307
+ };
308
+ host.replaceChildren(
309
+ title,
310
+ picker,
311
+ input,
312
+ el(
313
+ "div",
314
+ { class: "chips" },
315
+ ...CHIPS.map((c) => el("button", { type: "button", class: "chip", text: c.label, title: `Inserts ${c.insert}`, onclick: () => insert(c.insert) })),
316
+ el("button", { type: "button", class: "chip logo", text: "Logo…", onclick: () => picker.click() }),
317
+ ),
318
+ );
319
+ }
320
+
321
+ function syncNotices() {
322
+ const notices = [];
323
+ if (server.fileError) {
324
+ notices.push(
325
+ el("div", { class: "notice bad" }, el("strong", { text: "Your settings file could not be read. " }), `${server.fileError} Saving replaces it; the old file is kept as a .bak copy.`),
326
+ );
327
+ }
328
+ if (server.envOverride) {
329
+ notices.push(
330
+ el("div", { class: "notice" }, "MARKDOWN_PDF_SETTINGS is set on this computer, so exports use that instead of the file Studio saves."),
331
+ );
332
+ }
333
+ for (const areaName of ["header", "footer"]) {
334
+ if (!draft[areaName].custom) continue;
335
+ notices.push(
336
+ el(
337
+ "div",
338
+ { class: "notice" },
339
+ `The ${areaName} in your file was written by hand with options Studio does not show. It stays untouched.`,
340
+ el("br"),
341
+ el("button", {
342
+ type: "button",
343
+ class: "btn small",
344
+ text: `Replace the ${areaName} with a simple one`,
345
+ onclick: () => change(() => (draft[areaName] = emptyDraft()[areaName])),
346
+ }),
347
+ ),
348
+ );
349
+ }
350
+ $("notices").replaceChildren(...notices);
351
+ }
352
+
353
+ function sync() {
354
+ for (const b of $("looks").children) b.setAttribute("aria-checked", String(b.dataset.value === draft.look));
355
+ for (const id of ["orientation", "margin", "size"]) $(id)._sync();
356
+ for (const [id, key] of [["font", "font"], ["heading-font", "heading_font"]]) {
357
+ $(id).value = draft[key];
358
+ $(id).style.fontFamily = server.fonts[draft[key]] ?? ""; // the control shows its own choice
359
+ }
360
+ $("format").value = draft.page_format;
361
+ $("highlight").value = draft.highlight;
362
+ // The diagram's side padding follows the margins, so text and rules sit where they will print.
363
+ const side = MARGINS[draft.margin] ?? 15;
364
+ $("sheet").style.setProperty("--side", `${Math.round(side * 0.95)}px`);
365
+ const layout = matchLayout(draft);
366
+ for (const b of $("layouts").children) b.setAttribute("aria-pressed", String(b.dataset.value === layout));
367
+
368
+ const stack = server.fonts[draft.font];
369
+ $("sheet").style.fontFamily = stack ?? "";
370
+ syncBand("header");
371
+ syncBand("footer");
372
+ syncSlotEditor();
373
+ syncNotices();
374
+
375
+ $("line-header").checked = draft.header.line;
376
+ $("line-footer").checked = draft.footer.line;
377
+ $("line-header").disabled = draft.header.custom;
378
+ $("line-footer").disabled = draft.footer.custom;
379
+ $("color").value = draft.color;
380
+
381
+ const state = $("save-state");
382
+ if (isDirty()) {
383
+ state.textContent = server.exists ? "Changes not saved" : "Not saved yet";
384
+ state.className = "dirty";
385
+ $("save").disabled = false;
386
+ } else {
387
+ state.textContent = "Saved";
388
+ state.className = "saved";
389
+ $("save").disabled = true;
390
+ }
391
+ }
392
+
393
+ // ── preview ─────────────────────────────────────────────────────────────────
394
+ let previewTimer = null;
395
+ let previewRun = 0;
396
+ let frontFrame = $("frame-a");
397
+ let backFrame = $("frame-b");
398
+ let frontUrl = null;
399
+
400
+ function schedulePreview() {
401
+ clearTimeout(previewTimer);
402
+ previewTimer = setTimeout(drawPreview, 350);
403
+ }
404
+
405
+ async function drawPreview() {
406
+ const run = ++previewRun;
407
+ const status = $("status");
408
+ status.textContent = "Drawing the page…";
409
+ status.className = "status busy";
410
+ try {
411
+ const res = await api("/api/preview", { method: "POST", json: { settings: currentSettings() }, raw: true });
412
+ const blob = await res.blob();
413
+ if (run !== previewRun) return;
414
+ const url = URL.createObjectURL(blob);
415
+ const incoming = backFrame;
416
+ const swap = () => {
417
+ if (run !== previewRun || incoming === frontFrame) return;
418
+ incoming.classList.remove("back");
419
+ incoming.removeAttribute("tabindex");
420
+ frontFrame.classList.add("back");
421
+ frontFrame.setAttribute("tabindex", "-1");
422
+ if (frontUrl) URL.revokeObjectURL(frontUrl);
423
+ frontUrl = url;
424
+ [frontFrame, backFrame] = [incoming, frontFrame];
425
+ };
426
+ incoming.addEventListener("load", swap, { once: true });
427
+ setTimeout(swap, 900); // some PDF viewers never fire load
428
+ incoming.src = `${url}#toolbar=0&navpanes=0&view=Fit`;
429
+ $("problem").hidden = true;
430
+ const seconds = (Number(res.headers.get("x-render-ms")) / 1000).toFixed(1);
431
+ status.textContent = `This is the real PDF of ${server.preview.sample ? "a sample document" : server.preview.name}, drawn in ${seconds} s.`;
432
+ status.className = "status";
433
+ } catch (error) {
434
+ if (run !== previewRun || error.status === 409) return;
435
+ const box = $("problem");
436
+ box.replaceChildren(el("strong", { text: "The page could not be drawn" }), error.message);
437
+ box.hidden = false;
438
+ status.textContent = "Showing the last page that worked.";
439
+ status.className = "status";
440
+ }
441
+ }
442
+
443
+ // ── actions ─────────────────────────────────────────────────────────────────
444
+ async function uploadLogo(file, areaName, zone) {
445
+ try {
446
+ const { path } = await api(`/api/logo?name=${encodeURIComponent(file.name)}`, { method: "POST", body: file });
447
+ thumbs.set(path, URL.createObjectURL(file));
448
+ change(() => {
449
+ const before = draft[areaName][zone];
450
+ draft[areaName][zone] = { kind: "image", text: "", image: path, size: before.kind === "image" ? before.size : 100 };
451
+ selected = { area: areaName, zone };
452
+ });
453
+ } catch (error) {
454
+ const box = $("problem");
455
+ box.replaceChildren(el("strong", { text: "That logo could not be used" }), error.message);
456
+ box.hidden = false;
457
+ }
458
+ }
459
+
460
+ async function save() {
461
+ if (!isDirty()) return;
462
+ const button = $("save");
463
+ button.disabled = true;
464
+ try {
465
+ const settings = currentSettings();
466
+ const { removed = [] } = await api("/api/save", { method: "POST", json: { settings } });
467
+ if (removed.length) {
468
+ $("status").textContent =
469
+ removed.length === 1 ? `Saved. Removed the logo no longer used (${removed[0]}).` : `Saved. Removed ${removed.length} logos no longer used.`;
470
+ }
471
+ raw = settings;
472
+ savedJson = JSON.stringify(settings);
473
+ server.exists = true;
474
+ server.fileError = null;
475
+ sync();
476
+ } catch (error) {
477
+ button.disabled = false;
478
+ const box = $("problem");
479
+ box.replaceChildren(el("strong", { text: "Saving did not work" }), error.message);
480
+ box.hidden = false;
481
+ }
482
+ }
483
+
484
+ async function openEditors() {
485
+ const dialog = $("editors");
486
+ const list = $("editors-list");
487
+ list.replaceChildren(el("p", { class: "hint", text: "Looking for your editors…" }));
488
+ dialog.showModal();
489
+ let editors;
490
+ try {
491
+ editors = await api("/api/editors");
492
+ } catch (error) {
493
+ list.replaceChildren(el("div", { class: "notice bad", text: error.message }));
494
+ return;
495
+ }
496
+
497
+ const card = (editor) =>
498
+ el(
499
+ "div",
500
+ { class: "editor" },
501
+ el("h3", { text: editor.name }, editor.detected ? el("small", { text: "found on this computer" }) : null),
502
+ ...editor.items.map((item, index) => {
503
+ const result = el("div", { class: "result", role: "status" });
504
+ const copy = el("button", {
505
+ type: "button",
506
+ class: "btn small",
507
+ text: "Copy",
508
+ onclick: async () => {
509
+ await navigator.clipboard.writeText(item.snippet);
510
+ copy.textContent = "Copied";
511
+ setTimeout(() => (copy.textContent = "Copy"), 1500);
512
+ },
513
+ });
514
+ const auto =
515
+ item.write === "print"
516
+ ? null
517
+ : el("button", {
518
+ type: "button",
519
+ class: "btn small primary",
520
+ text: "Do it for me",
521
+ onclick: async () => {
522
+ auto.disabled = true;
523
+ try {
524
+ const { done, message } = await api("/api/editors/apply", { method: "POST", json: { id: editor.id, index } });
525
+ result.textContent = done ? `Done: ${message}` : message;
526
+ result.className = `result ${done ? "" : "bad"}`;
527
+ auto.disabled = done;
528
+ } catch (error) {
529
+ result.textContent = error.message;
530
+ result.className = "result bad";
531
+ auto.disabled = false;
532
+ }
533
+ },
534
+ });
535
+ return el(
536
+ "div",
537
+ { class: "step" },
538
+ el("div", { class: "step-head" }, el("span", { text: item.label }), el("span", { class: "actions" }, copy, auto)),
539
+ item.file ? el("div", { class: "step-file", text: item.write === "print" ? `Paste into ${item.file}` : item.file }) : null,
540
+ el("pre", { text: item.snippet }),
541
+ result,
542
+ );
543
+ }),
544
+ );
545
+
546
+ const found = editors.filter((e) => e.detected);
547
+ const others = editors.filter((e) => !e.detected);
548
+ const nodes = (found.length ? found : others).map(card);
549
+ if (found.length && others.length) {
550
+ nodes.push(el("details", { class: "others" }, el("summary", { text: "Other editors" }), ...others.map(card)));
551
+ }
552
+ list.replaceChildren(...nodes);
553
+ }
554
+
555
+ // ── start ───────────────────────────────────────────────────────────────────
556
+ async function start() {
557
+ try {
558
+ server = await api("/api/state");
559
+ } catch (error) {
560
+ document.body.replaceChildren(
561
+ el(
562
+ "div",
563
+ { class: "problem" },
564
+ el("strong", { text: "Studio is not connected" }),
565
+ error.status === 401
566
+ ? "Open Studio from the link printed in your terminal. Each launch has its own private link."
567
+ : "The Studio program is no longer running. Start it again with: markdown-pdf-export studio",
568
+ ),
569
+ );
570
+ return;
571
+ }
572
+ raw = server.raw;
573
+ draft = settingsToDraft(raw, { looks: server.looks, templates: server.templates });
574
+ if (!server.exists) {
575
+ // Nothing saved yet: propose a sensible page instead of a bare one.
576
+ const first = LAYOUTS.find((l) => l.id === FIRST_LAYOUT);
577
+ draft.header = first.header();
578
+ draft.footer = first.footer();
579
+ }
580
+ // A file Studio would rewrite differently counts as unsaved only after a change.
581
+ loadedJson = JSON.stringify(currentSettings());
582
+ savedJson = server.exists && !server.fileError ? loadedJson : "";
583
+ build();
584
+ sync();
585
+ drawPreview();
586
+ setInterval(() => api("/api/ping", { method: "POST" }).catch(() => {}), 30000);
587
+ }
588
+
589
+ start();