@appeeky/open-slideshow 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +227 -2
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +9 -0
- package/dist/brand.d.ts +55 -0
- package/dist/brand.js +246 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +261 -0
- package/dist/decks.d.ts +44 -0
- package/dist/decks.js +90 -0
- package/dist/fonts.d.ts +45 -0
- package/dist/fonts.js +243 -0
- package/dist/gallery.d.ts +35 -0
- package/dist/gallery.js +109 -0
- package/dist/images.d.ts +49 -0
- package/dist/images.js +223 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +13 -0
- package/dist/lint.d.ts +33 -0
- package/dist/lint.js +181 -0
- package/dist/mcp.d.ts +3 -0
- package/dist/mcp.js +233 -0
- package/dist/publish.d.ts +100 -0
- package/dist/publish.js +401 -0
- package/dist/render.d.ts +73 -0
- package/dist/render.js +515 -0
- package/dist/schedule.d.ts +19 -0
- package/dist/schedule.js +114 -0
- package/dist/schema.d.ts +1004 -0
- package/dist/schema.js +174 -0
- package/dist/shape.d.ts +31 -0
- package/dist/shape.js +169 -0
- package/dist/skill.d.ts +7 -0
- package/dist/skill.js +17 -0
- package/dist/templates.d.ts +44 -0
- package/dist/templates.js +185 -0
- package/dist/text.d.ts +40 -0
- package/dist/text.js +230 -0
- package/dist/themes.d.ts +43 -0
- package/dist/themes.js +202 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +1 -0
- package/dist/viral.d.ts +12 -0
- package/dist/viral.js +35 -0
- package/dist/workspace.d.ts +80 -0
- package/dist/workspace.js +306 -0
- package/package.json +65 -4
- package/skills/open-slideshow/SKILL.md +52 -0
- package/skills/open-slideshow/references/brand.md +54 -0
- package/skills/open-slideshow/references/channels.md +63 -0
- package/skills/open-slideshow/references/images.md +53 -0
- package/skills/open-slideshow/references/languages.md +41 -0
- package/skills/open-slideshow/references/publishing.md +70 -0
- package/skills/open-slideshow/references/review.md +74 -0
- package/skills/open-slideshow/references/templates.md +59 -0
- package/skills/open-slideshow/references/troubleshooting.md +82 -0
- package/skills/open-slideshow/references/writing.md +76 -0
package/dist/render.js
ADDED
|
@@ -0,0 +1,515 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { mkdirSync, readFileSync, writeFileSync, existsSync, readdirSync, unlinkSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import satori from "satori";
|
|
6
|
+
import { Resvg } from "@resvg/resvg-js";
|
|
7
|
+
import sharp from "sharp";
|
|
8
|
+
import { satoriFonts, missingChars, glyphReport, fontStack, ensureScriptFonts, SCRIPTS, pickFont } from "./fonts.js";
|
|
9
|
+
import { COMPLEX, shaperReady, shapeLine } from "./shape.js";
|
|
10
|
+
import { fit, plainText, upperCase, isRtl } from "./text.js";
|
|
11
|
+
import { SIZES } from "./schema.js";
|
|
12
|
+
import { getTheme, withColors, readableOn, mix } from "./themes.js";
|
|
13
|
+
export const RENDERER_VERSION = "1";
|
|
14
|
+
const el = (type, style, children, extra = {}) => ({
|
|
15
|
+
type,
|
|
16
|
+
props: { style, ...(children === undefined ? {} : { children }), ...extra },
|
|
17
|
+
});
|
|
18
|
+
const div = (style, children) => el("div", { display: "flex", ...style }, children);
|
|
19
|
+
export function frameFor(size) {
|
|
20
|
+
const { width: W, height: H } = SIZES[size];
|
|
21
|
+
// Where TikTok and Instagram draw their own buttons and captions.
|
|
22
|
+
const top = size === "9:16" ? Math.round(H * 0.11) : Math.round(H * 0.07);
|
|
23
|
+
const bottom = size === "9:16" ? Math.round(H * 0.25) : size === "4:5" ? Math.round(H * 0.12) : Math.round(H * 0.09);
|
|
24
|
+
return { W, H, pad: 84, top, bottom };
|
|
25
|
+
}
|
|
26
|
+
function textStyleFor(style, size) {
|
|
27
|
+
if (style === "outline") {
|
|
28
|
+
// A stroke outside the letters, as a ring of hard shadows: a real stroke eats into thin letters.
|
|
29
|
+
const r = Math.max(2, Math.round(size * 0.05));
|
|
30
|
+
const rings = [];
|
|
31
|
+
for (let i = 0; i < 16; i++) {
|
|
32
|
+
const a = (i / 16) * Math.PI * 2;
|
|
33
|
+
rings.push(`${(Math.cos(a) * r).toFixed(1)}px ${(Math.sin(a) * r).toFixed(1)}px 0 #000000`);
|
|
34
|
+
}
|
|
35
|
+
return { textShadow: rings.join(", ") };
|
|
36
|
+
}
|
|
37
|
+
if (style === "shadow")
|
|
38
|
+
return { textShadow: `0 ${Math.round(size * 0.04)}px ${Math.round(size * 0.2)}px rgba(0,0,0,0.6)` };
|
|
39
|
+
return {};
|
|
40
|
+
}
|
|
41
|
+
/** A shaped line (Arabic, Hebrew, Thai, Devanagari) as an SVG image, with the same text style and accent look as other lines. */
|
|
42
|
+
function shapedLineEl(line, b, theme, style, align) {
|
|
43
|
+
const size = b.fitted.size;
|
|
44
|
+
const lineH = Math.round(size * b.line_height);
|
|
45
|
+
const shaped = shapeLine(b.role, line, size, b.locale);
|
|
46
|
+
const primary = pickFont(b.role, "a", b.locale);
|
|
47
|
+
const em = primary?.unitsPerEm ?? 1000;
|
|
48
|
+
const asc = ((primary?.ascender ?? 900) / em) * size;
|
|
49
|
+
const desc = ((primary?.descender ?? -250) / em) * size;
|
|
50
|
+
const baseline = (lineH - (asc - desc)) / 2 + asc;
|
|
51
|
+
const ring = style === "outline" ? Math.max(2, Math.round(size * 0.05)) : 0;
|
|
52
|
+
const boxPad = theme.accent_style === "box" ? Math.round(size * 0.12) : 0;
|
|
53
|
+
const pad = Math.max(ring, boxPad) + (style === "shadow" ? Math.round(size * 0.3) : 0) + 2;
|
|
54
|
+
// Arabic dots and marks reach well above and below the Latin line box: leave room so they are not cut.
|
|
55
|
+
const padY = Math.max(pad, Math.round(size * 0.5));
|
|
56
|
+
const w = Math.ceil(shaped.width) + pad * 2;
|
|
57
|
+
const h = lineH + padY * 2;
|
|
58
|
+
const accent = theme.colors.accent;
|
|
59
|
+
// Glyphs are drawn in font units and scaled down: a stroke width has to be given in font units too.
|
|
60
|
+
const glyph = (g, stroke = 0) => `<path transform="translate(${(g.x + pad).toFixed(2)} ${(baseline + padY + g.dy).toFixed(2)}) scale(${g.scale.toFixed(5)} ${(-g.scale).toFixed(5)})"${stroke ? ` stroke-width="${(stroke / g.scale).toFixed(1)}"` : ""} d="${g.d}"/>`;
|
|
61
|
+
const fillFor = (isAccent) => isAccent ? (theme.accent_style === "color" ? accent : theme.accent_style === "box" ? readableOn(accent) : b.color) : b.color;
|
|
62
|
+
const parts = [];
|
|
63
|
+
if (style === "shadow")
|
|
64
|
+
parts.push(`<defs><filter id="s" x="-20%" y="-50%" width="140%" height="200%"><feDropShadow dx="0" dy="${Math.round(size * 0.04)}" stdDeviation="${Math.round(size * 0.1)}" flood-color="#000" flood-opacity="0.6"/></filter></defs>`);
|
|
65
|
+
const boxes = theme.accent_style === "box"
|
|
66
|
+
? shaped.accentSpans.map((sp) => `<rect x="${sp.x0 + pad - boxPad}" y="${padY}" width="${sp.x1 - sp.x0 + boxPad * 2}" height="${lineH}" rx="${Math.round(size * 0.12)}" fill="${accent}"/>`)
|
|
67
|
+
: theme.accent_style === "underline"
|
|
68
|
+
? shaped.accentSpans.map((sp) => `<rect x="${sp.x0 + pad}" y="${baseline + padY + size * 0.1}" width="${sp.x1 - sp.x0}" height="${Math.max(3, Math.round(size * 0.08))}" fill="${accent}"/>`)
|
|
69
|
+
: [];
|
|
70
|
+
if (ring) {
|
|
71
|
+
const outlined = shaped.glyphs.filter((g) => !(g.accent && theme.accent_style === "box"));
|
|
72
|
+
parts.push(`<g fill="#000" stroke="#000" stroke-linejoin="round">${outlined.map((g) => glyph(g, ring * 2)).join("")}</g>`);
|
|
73
|
+
}
|
|
74
|
+
parts.push(...boxes);
|
|
75
|
+
for (const isAccent of [false, true]) {
|
|
76
|
+
const gs = shaped.glyphs.filter((g) => g.accent === isAccent);
|
|
77
|
+
if (gs.length)
|
|
78
|
+
parts.push(`<g fill="${fillFor(isAccent)}">${gs.map((g) => glyph(g)).join("")}</g>`);
|
|
79
|
+
}
|
|
80
|
+
const body = style === "shadow" ? `${parts[0]}<g filter="url(#s)">${parts.slice(1).join("")}</g>` : parts.join("");
|
|
81
|
+
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">${body}</svg>`;
|
|
82
|
+
const image = el("img", { width: w, height: h, margin: `${-padY}px ${-pad}px` }, undefined, { src: `data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}`, width: w, height: h });
|
|
83
|
+
const justify = align === "center" ? "center" : shaped.rtl ? "flex-end" : "flex-start";
|
|
84
|
+
const row = { justifyContent: justify, alignSelf: "stretch" };
|
|
85
|
+
if (style === "box")
|
|
86
|
+
return div(row, [div({ backgroundColor: theme.colors.card, padding: `0 ${Math.round(size * 0.3)}px`, borderRadius: Math.round(size * 0.2) }, [image])]);
|
|
87
|
+
return div({ ...row, height: lineH, alignItems: "center" }, [image]);
|
|
88
|
+
}
|
|
89
|
+
function lineEl(line, b, theme, style, align) {
|
|
90
|
+
if (shaperReady() && COMPLEX.test(line.map((r) => r.text).join("")))
|
|
91
|
+
return shapedLineEl(line, b, theme, style, align);
|
|
92
|
+
const size = b.fitted.size;
|
|
93
|
+
const accent = theme.colors.accent;
|
|
94
|
+
const rtl = isRtl(line.map((r) => r.text).join(""));
|
|
95
|
+
const runs = line.map((r) => {
|
|
96
|
+
const s = { whiteSpace: "pre", color: b.color };
|
|
97
|
+
if (r.accent) {
|
|
98
|
+
if (theme.accent_style === "color")
|
|
99
|
+
s.color = accent;
|
|
100
|
+
else if (theme.accent_style === "underline") {
|
|
101
|
+
s.borderBottom = `${Math.max(3, Math.round(size * 0.08))}px solid ${accent}`;
|
|
102
|
+
}
|
|
103
|
+
else {
|
|
104
|
+
s.backgroundColor = accent;
|
|
105
|
+
s.color = readableOn(accent);
|
|
106
|
+
s.padding = `0 ${Math.round(size * 0.12)}px`;
|
|
107
|
+
s.borderRadius = Math.round(size * 0.12);
|
|
108
|
+
if (style === "outline")
|
|
109
|
+
s.textShadow = "none";
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return div(s, r.text);
|
|
113
|
+
});
|
|
114
|
+
const base = {
|
|
115
|
+
fontFamily: fontStack(b.role.family, b.locale),
|
|
116
|
+
fontWeight: b.role.weight,
|
|
117
|
+
fontStyle: b.role.italic ? "italic" : "normal",
|
|
118
|
+
fontSize: size,
|
|
119
|
+
lineHeight: b.line_height,
|
|
120
|
+
letterSpacing: b.role.tracking ? `${b.role.tracking}em` : undefined,
|
|
121
|
+
justifyContent: align === "center" ? "center" : rtl ? "flex-end" : "flex-start",
|
|
122
|
+
// Accent runs are separate boxes: a right-to-left line lays them out from the right.
|
|
123
|
+
flexDirection: rtl ? "row-reverse" : "row",
|
|
124
|
+
...textStyleFor(style, size),
|
|
125
|
+
};
|
|
126
|
+
if (style === "box") {
|
|
127
|
+
return div({ justifyContent: align === "center" ? "center" : rtl ? "flex-end" : "flex-start" }, [
|
|
128
|
+
div({ ...base, backgroundColor: theme.colors.card, padding: `0 ${Math.round(size * 0.3)}px`, borderRadius: Math.round(size * 0.2) }, runs),
|
|
129
|
+
]);
|
|
130
|
+
}
|
|
131
|
+
return div(base, runs);
|
|
132
|
+
}
|
|
133
|
+
function blockEl(b, theme, style, align) {
|
|
134
|
+
const lines = b.fitted.lines.map((l) => lineEl(l, b, theme, style, align));
|
|
135
|
+
if (b.marker !== undefined) {
|
|
136
|
+
const size = b.fitted.size;
|
|
137
|
+
const rtl = isRtl(b.fitted.lines.map((l) => l.map((r) => r.text).join("")).join(" "));
|
|
138
|
+
const markerStyle = {
|
|
139
|
+
fontFamily: fontStack(b.role.family, b.locale),
|
|
140
|
+
fontWeight: 800,
|
|
141
|
+
fontSize: size,
|
|
142
|
+
lineHeight: b.line_height,
|
|
143
|
+
color: theme.colors.accent,
|
|
144
|
+
width: Math.round(size * 1.3),
|
|
145
|
+
flexShrink: 0,
|
|
146
|
+
...textStyleFor(style === "box" ? "plain" : style, size),
|
|
147
|
+
};
|
|
148
|
+
const marker = b.marker === "•"
|
|
149
|
+
? div({ width: Math.round(size * 1.3), height: Math.round(size * b.line_height), alignItems: "center", justifyContent: rtl ? "flex-end" : "flex-start", flexShrink: 0 }, [
|
|
150
|
+
div({ width: Math.round(size * 0.32), height: Math.round(size * 0.32), borderRadius: 999, backgroundColor: theme.colors.accent }),
|
|
151
|
+
])
|
|
152
|
+
: div(markerStyle, b.marker);
|
|
153
|
+
return div({ marginTop: b.gap_before, flexDirection: rtl ? "row-reverse" : "row", alignItems: "flex-start" }, [marker, div({ flexDirection: "column", flexGrow: 1 }, lines)]);
|
|
154
|
+
}
|
|
155
|
+
return div({ marginTop: b.gap_before, flexDirection: "column", alignItems: align === "center" ? "center" : "flex-start" }, lines);
|
|
156
|
+
}
|
|
157
|
+
const blocksHeight = (blocks) => blocks.reduce((h, b) => h + b.gap_before + b.fitted.height, 0);
|
|
158
|
+
/** Fits a slide's words into the box: the title gets what is left after the smaller text. */
|
|
159
|
+
function planText(slide, index, tipNumber, theme, box, color, muted, scale) {
|
|
160
|
+
const issues = [];
|
|
161
|
+
const blocks = [];
|
|
162
|
+
const display = theme.display;
|
|
163
|
+
const body = theme.body;
|
|
164
|
+
const serifish = display.family === "Instrument Serif" || display.family === "Anton";
|
|
165
|
+
const titleLh = display.family === "Anton" ? 1.05 : serifish ? 1.0 : 1.12;
|
|
166
|
+
const bodyLh = 1.3;
|
|
167
|
+
const s = (n) => Math.round(n * scale);
|
|
168
|
+
let title = slide.title;
|
|
169
|
+
if (slide.kind === "tip" && title && tipNumber !== undefined)
|
|
170
|
+
title = `${tipNumber}. ${title}`;
|
|
171
|
+
if (slide.kind === "quote" && title)
|
|
172
|
+
title = `“${title}”`;
|
|
173
|
+
const fitBody = (text, max, min, height, kind, gap, role = body, c = color, marker, width = box.width) => ({ role, fitted: fit(role, text, { max, min, width, height, line_height: bodyLh, locale: box.locale }), color: c, line_height: bodyLh, gap_before: gap, kind, marker, locale: box.locale });
|
|
174
|
+
// Smaller text first, at a size that reads; the title then takes the rest of the height.
|
|
175
|
+
const lower = [];
|
|
176
|
+
if (slide.kind === "list" && slide.items?.length) {
|
|
177
|
+
const n = slide.items.length;
|
|
178
|
+
const perItem = (box.height * (title ? 0.62 : 0.95)) / n - s(20);
|
|
179
|
+
slide.items.forEach((item, i) => {
|
|
180
|
+
const marker = slide.list_style === "number" ? `${i + 1}.` : slide.list_style === "check" ? "✓" : "•";
|
|
181
|
+
const markerWidth = Math.round(s(58) * 1.3);
|
|
182
|
+
const role = { ...body, weight: Math.max(body.weight, 600) };
|
|
183
|
+
lower.push(fitBody(item, s(58), s(32), perItem, "item", i === 0 ? s(title ? 40 : 0) : s(18), role, color, missingChars(body, marker).length ? "•" : marker, box.width - markerWidth));
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
if (slide.body) {
|
|
187
|
+
const max = slide.kind === "text" ? s(72) : s(54);
|
|
188
|
+
const min = slide.kind === "text" ? s(36) : s(30);
|
|
189
|
+
lower.push(fitBody(slide.body, max, min, box.height * (title ? 0.42 : 0.95), "body", title || lower.length ? s(28) : 0));
|
|
190
|
+
}
|
|
191
|
+
if (slide.kind === "quote" && slide.author)
|
|
192
|
+
lower.push(fitBody(`— ${slide.author}`, s(42), s(28), s(140), "meta", s(28), body, muted));
|
|
193
|
+
if (title) {
|
|
194
|
+
const isCover = slide.kind === "cover";
|
|
195
|
+
const max = isCover ? s(display.family === "Anton" ? 150 : display.family === "Instrument Serif" ? 136 : 118) : s(display.family === "Anton" ? 130 : display.family === "Instrument Serif" ? 120 : 100);
|
|
196
|
+
const min = isCover ? s(56) : s(46);
|
|
197
|
+
const room = Math.max(box.height - blocksHeight(lower), box.height * 0.3);
|
|
198
|
+
blocks.push({ role: display, fitted: fit(display, title, { max, min, width: box.width, height: room, line_height: titleLh, locale: box.locale }), color, line_height: titleLh, gap_before: 0, kind: "title", locale: box.locale });
|
|
199
|
+
}
|
|
200
|
+
blocks.push(...lower);
|
|
201
|
+
for (const b of blocks) {
|
|
202
|
+
if (b.fitted.overflow)
|
|
203
|
+
issues.push({ slide: index, level: "error", code: "text-overflow", message: `slide ${index + 1}: the ${b.kind} does not fit even at the smallest size; shorten it` });
|
|
204
|
+
else if (b.fitted.broke_word)
|
|
205
|
+
issues.push({ slide: index, level: "warning", code: "word-cut", message: `slide ${index + 1}: a word in the ${b.kind} is too long for one line and is cut` });
|
|
206
|
+
}
|
|
207
|
+
if (blocksHeight(blocks) > box.height + 2)
|
|
208
|
+
issues.push({ slide: index, level: "error", code: "text-overflow", message: `slide ${index + 1}: the text is taller than the slide's safe area; shorten it or split the slide` });
|
|
209
|
+
return { blocks, issues };
|
|
210
|
+
}
|
|
211
|
+
// ---------- images ----------
|
|
212
|
+
async function cropTo(file, w, h, focus) {
|
|
213
|
+
const img = sharp(file, { limitInputPixels: 80_000_000 }).rotate();
|
|
214
|
+
const meta = await sharp(await img.toBuffer()).metadata();
|
|
215
|
+
const iw = meta.width ?? w;
|
|
216
|
+
const ih = meta.height ?? h;
|
|
217
|
+
const scale = Math.max(w / iw, h / ih);
|
|
218
|
+
const sw = Math.ceil(iw * scale);
|
|
219
|
+
const sh = Math.ceil(ih * scale);
|
|
220
|
+
const fx = (focus?.x ?? 50) / 100;
|
|
221
|
+
const fy = (focus?.y ?? 50) / 100;
|
|
222
|
+
const left = Math.min(Math.max(0, Math.round(sw * fx - w / 2)), sw - w);
|
|
223
|
+
const top = Math.min(Math.max(0, Math.round(sh * fy - h / 2)), sh - h);
|
|
224
|
+
const out = await sharp(file, { limitInputPixels: 80_000_000 }).rotate().resize(sw, sh).extract({ left, top, width: w, height: h }).jpeg({ quality: 90 }).toBuffer();
|
|
225
|
+
return `data:image/jpeg;base64,${out.toString("base64")}`;
|
|
226
|
+
}
|
|
227
|
+
function readImage(ctx, path) {
|
|
228
|
+
const cached = ctx.images?.get(path);
|
|
229
|
+
if (cached)
|
|
230
|
+
return cached;
|
|
231
|
+
const buf = readFileSync(path);
|
|
232
|
+
ctx.images?.set(path, buf);
|
|
233
|
+
return buf;
|
|
234
|
+
}
|
|
235
|
+
async function imageEl(ctx, slide, w, h, style = {}) {
|
|
236
|
+
if (!slide.image)
|
|
237
|
+
return null;
|
|
238
|
+
const path = ctx.resolveImage(slide.image);
|
|
239
|
+
if (!path)
|
|
240
|
+
return null;
|
|
241
|
+
const src = await cropTo(readImage(ctx, path), w, h, slide.focus);
|
|
242
|
+
return el("img", { width: w, height: h, ...style }, undefined, { src, width: w, height: h });
|
|
243
|
+
}
|
|
244
|
+
async function iconEl(ctx, size, theme) {
|
|
245
|
+
if (ctx.brand.icon && existsSync(ctx.brand.icon)) {
|
|
246
|
+
const src = await cropTo(readImage(ctx, ctx.brand.icon), size * 2, size * 2);
|
|
247
|
+
return el("img", { width: size, height: size, borderRadius: Math.round(size * 0.225) }, undefined, { src, width: size, height: size });
|
|
248
|
+
}
|
|
249
|
+
const initial = (ctx.brand.name ?? "?").trim().charAt(0).toUpperCase() || "?";
|
|
250
|
+
return div({ width: size, height: size, borderRadius: Math.round(size * 0.225), backgroundColor: theme.colors.accent, alignItems: "center", justifyContent: "center", color: readableOn(theme.colors.accent), fontFamily: fontStack("Inter"), fontWeight: 700, fontSize: Math.round(size * 0.5) }, initial);
|
|
251
|
+
}
|
|
252
|
+
function handleText(ctx) {
|
|
253
|
+
const h = ctx.brand.handle?.trim();
|
|
254
|
+
if (!h)
|
|
255
|
+
return undefined;
|
|
256
|
+
return h.startsWith("@") ? h : `@${h}`;
|
|
257
|
+
}
|
|
258
|
+
async function photoLayout(ctx, a, f) {
|
|
259
|
+
const t = ctx.theme;
|
|
260
|
+
const style = a.slide.text_style ?? a.deck.text_style ?? t.text_style;
|
|
261
|
+
const align = t.align;
|
|
262
|
+
const width = f.W - f.pad * 2;
|
|
263
|
+
const safe = f.H - f.top - f.bottom;
|
|
264
|
+
const plan = planText(a.slide, a.index, a.tipNumber, t, { width, height: safe - (a.slide.kind === "app" ? BADGE_H : 0), locale: ctx.locale }, style === "box" ? t.colors.fg : "#ffffff", style === "box" ? t.colors.muted : "#f0f0f0", 1);
|
|
265
|
+
const issues = [...plan.issues];
|
|
266
|
+
const children = [];
|
|
267
|
+
const img = a.dry ? null : await imageEl(ctx, a.slide, f.W, f.H, { position: "absolute", left: 0, top: 0 });
|
|
268
|
+
if (img)
|
|
269
|
+
children.push(img);
|
|
270
|
+
else {
|
|
271
|
+
if (a.slide.image && !a.dry)
|
|
272
|
+
issues.push({ slide: a.index, level: "error", code: "image-missing", message: `slide ${a.index + 1}: image ${a.slide.image} not found` });
|
|
273
|
+
children.push(div({ position: "absolute", left: 0, top: 0, width: f.W, height: f.H, backgroundImage: `linear-gradient(160deg, ${mix(t.colors.bg, t.colors.accent, 0.35)}, ${t.colors.bg})` }));
|
|
274
|
+
}
|
|
275
|
+
if (t.scrim > 0) {
|
|
276
|
+
const a1 = t.scrim;
|
|
277
|
+
const grad = t.align === "left" ? `linear-gradient(180deg, rgba(0,0,0,${(a1 * 0.25).toFixed(2)}) 0%, rgba(0,0,0,${(a1 * 0.6).toFixed(2)}) 45%, rgba(0,0,0,${a1.toFixed(2)}) 100%)` : `linear-gradient(180deg, rgba(0,0,0,${a1.toFixed(2)}), rgba(0,0,0,${a1.toFixed(2)}))`;
|
|
278
|
+
children.push(div({ position: "absolute", left: 0, top: 0, width: f.W, height: f.H, backgroundImage: grad }));
|
|
279
|
+
}
|
|
280
|
+
const h = blocksHeight(plan.blocks) + (a.slide.kind === "app" ? BADGE_H : 0);
|
|
281
|
+
const pos = a.slide.text_position ?? (a.slide.kind === "cover" ? t.cover_position : t.tip_position);
|
|
282
|
+
const top = Math.min(Math.max(f.top, Math.round((f.H * pos) / 100 - h / 2)), f.H - f.bottom - h);
|
|
283
|
+
children.push(div({ position: "absolute", left: f.pad, top: Math.max(f.top, top), width, flexDirection: "column", alignItems: align === "center" ? "center" : "flex-start" }, [...plan.blocks.map((b) => blockEl(b, t, style, align)), ...(a.slide.kind === "app" ? [await appBadge(ctx, f, t, "dark")] : [])]));
|
|
284
|
+
if (a.deck.show_handle && handleText(ctx))
|
|
285
|
+
children.push(div({ position: "absolute", left: f.pad, top: Math.round(f.top * 0.45), fontFamily: fontStack("Inter"), fontWeight: 600, fontSize: 30, color: "#ffffff", opacity: 0.85, textShadow: "0 2px 8px rgba(0,0,0,0.5)" }, handleText(ctx)));
|
|
286
|
+
return { tree: div({ width: f.W, height: f.H, position: "relative", backgroundColor: t.colors.bg }, children), issues };
|
|
287
|
+
}
|
|
288
|
+
const BADGE_H = 196;
|
|
289
|
+
async function appBadge(ctx, f, t, tone) {
|
|
290
|
+
const icon = await iconEl(ctx, 96, t);
|
|
291
|
+
const name = ctx.brand.name ?? "";
|
|
292
|
+
const bg = tone === "dark" ? "rgba(255,255,255,0.94)" : t.colors.card;
|
|
293
|
+
const fg = tone === "dark" ? "#111111" : t.colors.fg;
|
|
294
|
+
return div({ marginTop: 56, alignItems: "center", justifyContent: t.align === "center" ? "center" : "flex-start" }, [
|
|
295
|
+
div({ alignItems: "center", backgroundColor: bg, borderRadius: 36, padding: "20px 34px 20px 20px" }, [icon, div({ marginLeft: 24, fontFamily: fontStack("Inter"), fontWeight: 700, fontSize: 40, color: fg }, name || "Get the app")]),
|
|
296
|
+
]);
|
|
297
|
+
}
|
|
298
|
+
async function magazineLayout(ctx, a, f) {
|
|
299
|
+
const t = ctx.theme;
|
|
300
|
+
const width = f.W - f.pad * 2;
|
|
301
|
+
const issues = [];
|
|
302
|
+
const children = [];
|
|
303
|
+
const hasImage = !!a.slide.image;
|
|
304
|
+
const header = a.deck.show_handle ? handleText(ctx) ?? ctx.brand.name : undefined;
|
|
305
|
+
if (header)
|
|
306
|
+
children.push(div({ position: "absolute", left: f.pad, top: Math.round(f.top * 0.55), fontFamily: fontStack("Inter"), fontWeight: 600, fontSize: 30, color: t.colors.muted }, header));
|
|
307
|
+
const missing = () => {
|
|
308
|
+
if (a.slide.image && !a.dry)
|
|
309
|
+
issues.push({ slide: a.index, level: "error", code: "image-missing", message: `slide ${a.index + 1}: image ${a.slide.image} not found` });
|
|
310
|
+
};
|
|
311
|
+
if (a.slide.kind === "cover" && hasImage && a.deck.full_cover) {
|
|
312
|
+
// A full photo that fades into the page colour, with the title on the fade.
|
|
313
|
+
const img = a.dry ? null : await imageEl(ctx, a.slide, f.W, f.H, { position: "absolute", left: 0, top: 0 });
|
|
314
|
+
if (img)
|
|
315
|
+
children.unshift(img);
|
|
316
|
+
else
|
|
317
|
+
missing();
|
|
318
|
+
const textRoom = Math.round((f.H - f.top - f.bottom) * 0.5);
|
|
319
|
+
const plan = planText(a.slide, a.index, a.tipNumber, t, { width, height: textRoom, locale: ctx.locale }, t.colors.fg, t.colors.muted, 1);
|
|
320
|
+
issues.push(...plan.issues);
|
|
321
|
+
const h = blocksHeight(plan.blocks);
|
|
322
|
+
const top = f.H - f.bottom - h;
|
|
323
|
+
const fadeStart = Math.max(0, top - 260);
|
|
324
|
+
children.push(div({ position: "absolute", left: 0, top: fadeStart, width: f.W, height: f.H - fadeStart, backgroundImage: `linear-gradient(180deg, ${t.colors.bg}00 0%, ${t.colors.bg}e6 38%, ${t.colors.bg} 60%)` }));
|
|
325
|
+
children.push(div({ position: "absolute", left: f.pad, top, width, flexDirection: "column" }, plan.blocks.map((b) => blockEl(b, t, "plain", "left"))));
|
|
326
|
+
return { tree: div({ width: f.W, height: f.H, position: "relative", backgroundColor: t.colors.bg }, children), issues };
|
|
327
|
+
}
|
|
328
|
+
const safeTop = f.top + (header ? 40 : 0);
|
|
329
|
+
const safe = f.H - safeTop - f.bottom;
|
|
330
|
+
const imageHeight = hasImage ? Math.round(safe * (a.slide.kind === "cover" ? 0.56 : 0.5)) : 0;
|
|
331
|
+
const badge = a.slide.kind === "app" ? BADGE_H : 0;
|
|
332
|
+
const textRoom = (hasImage ? safe - imageHeight - 48 : safe) - badge;
|
|
333
|
+
const plan = planText(a.slide, a.index, a.tipNumber, t, { width, height: textRoom, locale: ctx.locale }, t.colors.fg, t.colors.muted, 1);
|
|
334
|
+
issues.push(...plan.issues);
|
|
335
|
+
const h = blocksHeight(plan.blocks) + badge;
|
|
336
|
+
const textTop = hasImage ? safeTop : Math.round(safeTop + Math.max(0, (safe - h) * (a.slide.kind === "cover" ? 0.42 : 0.3)));
|
|
337
|
+
children.push(div({ position: "absolute", left: f.pad, top: textTop, width, flexDirection: "column" }, [...plan.blocks.map((b) => blockEl(b, t, "plain", "left")), ...(badge ? [await appBadge(ctx, f, t, "page")] : [])]));
|
|
338
|
+
if (hasImage) {
|
|
339
|
+
const imgTop = f.H - f.bottom - imageHeight;
|
|
340
|
+
const img = a.dry ? null : await imageEl(ctx, a.slide, width, imageHeight, { borderRadius: 32 });
|
|
341
|
+
if (img)
|
|
342
|
+
children.push(div({ position: "absolute", left: f.pad, top: imgTop, width, height: imageHeight }, [img]));
|
|
343
|
+
else {
|
|
344
|
+
missing();
|
|
345
|
+
children.push(div({ position: "absolute", left: f.pad, top: imgTop, width, height: imageHeight, borderRadius: 32, backgroundColor: t.colors.card }));
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
return { tree: div({ width: f.W, height: f.H, position: "relative", backgroundColor: t.colors.bg }, children), issues };
|
|
349
|
+
}
|
|
350
|
+
async function plainLayout(ctx, a, f) {
|
|
351
|
+
const t = ctx.theme;
|
|
352
|
+
const width = f.W - f.pad * 2;
|
|
353
|
+
const issues = [];
|
|
354
|
+
const headerH = 120;
|
|
355
|
+
const safe = f.H - f.top - f.bottom - headerH - 40;
|
|
356
|
+
const hasImage = !!a.slide.image;
|
|
357
|
+
const imageHeight = hasImage ? Math.round(safe * 0.45) : 0;
|
|
358
|
+
const plan = planText(a.slide, a.index, a.tipNumber, t, { width, height: safe - (hasImage ? imageHeight + 40 : 0), locale: ctx.locale }, t.colors.fg, t.colors.muted, 1.08);
|
|
359
|
+
issues.push(...plan.issues);
|
|
360
|
+
const header = div({ alignItems: "center", height: headerH }, [
|
|
361
|
+
await iconEl(ctx, 96, t),
|
|
362
|
+
div({ flexDirection: "column", marginLeft: 26 }, [
|
|
363
|
+
div({ fontFamily: fontStack("Inter"), fontWeight: 700, fontSize: 38, color: t.colors.fg }, ctx.brand.name ?? "Your app"),
|
|
364
|
+
...(handleText(ctx) ? [div({ fontFamily: fontStack("Inter"), fontWeight: 400, fontSize: 32, color: t.colors.muted }, handleText(ctx))] : []),
|
|
365
|
+
]),
|
|
366
|
+
]);
|
|
367
|
+
const content = [header, div({ flexDirection: "column", marginTop: 40 }, plan.blocks.map((b) => blockEl(b, t, "plain", "left")))];
|
|
368
|
+
if (hasImage) {
|
|
369
|
+
const img = a.dry ? null : await imageEl(ctx, a.slide, width, imageHeight, { borderRadius: 28 });
|
|
370
|
+
if (img)
|
|
371
|
+
content.push(div({ marginTop: 40, width, height: imageHeight }, [img]));
|
|
372
|
+
else if (!a.dry)
|
|
373
|
+
issues.push({ slide: a.index, level: "error", code: "image-missing", message: `slide ${a.index + 1}: image ${a.slide.image} not found` });
|
|
374
|
+
}
|
|
375
|
+
const total = headerH + 40 + blocksHeight(plan.blocks) + (hasImage ? imageHeight + 40 : 0);
|
|
376
|
+
const top = Math.max(f.top, Math.round(f.top + (f.H - f.top - f.bottom - total) * 0.45));
|
|
377
|
+
return {
|
|
378
|
+
tree: div({ width: f.W, height: f.H, position: "relative", backgroundColor: t.colors.bg }, [div({ position: "absolute", left: f.pad, top, width, flexDirection: "column" }, content)]),
|
|
379
|
+
issues,
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
export function tipNumbers(slides) {
|
|
383
|
+
let n = 0;
|
|
384
|
+
return slides.map((s) => (s.kind === "tip" ? (n = s.number ?? n + 1) : undefined));
|
|
385
|
+
}
|
|
386
|
+
export async function laySlide(ctx, a) {
|
|
387
|
+
const f = frameFor(ctx.size);
|
|
388
|
+
const all = [a.slide.title, a.slide.body, ...(a.slide.items ?? []), a.slide.author, ctx.brand.name, ctx.brand.handle].filter(Boolean).join(" ");
|
|
389
|
+
const failed = await ensureScriptFonts(all, ctx.locale);
|
|
390
|
+
const laid = ctx.theme.design === "photo" ? await photoLayout(ctx, a, f) : ctx.theme.design === "magazine" ? await magazineLayout(ctx, a, f) : await plainLayout(ctx, a, f);
|
|
391
|
+
const text = [a.slide.title, a.slide.body, ...(a.slide.items ?? []), a.slide.author].filter(Boolean).map((s) => plainText(s)).join(" ");
|
|
392
|
+
const roles = [ctx.theme.display, ctx.theme.body];
|
|
393
|
+
const reports = roles.map((r) => glyphReport(r, ctx.theme.display.uppercase && r === ctx.theme.display ? upperCase(text, ctx.locale) : text, ctx.locale));
|
|
394
|
+
const missing = [...new Set(reports.flatMap((r) => r.missing))];
|
|
395
|
+
const fallback = [...new Set(reports.flatMap((r) => r.fallback))];
|
|
396
|
+
if (COMPLEX.test(text) && [...text].some((ch) => /\p{Extended_Pictographic}/u.test(ch)))
|
|
397
|
+
laid.issues.push({ slide: a.index, level: "warning", code: "emoji-shaped", message: `slide ${a.index + 1}: emoji next to Arabic, Hebrew, Thai or Hindi text are not drawn yet; move them to a line of their own or drop them` });
|
|
398
|
+
if (failed.length)
|
|
399
|
+
laid.issues.push({ slide: a.index, level: "error", code: "font-download", message: `slide ${a.index + 1}: the ${failed.map((p) => SCRIPTS[p].label).join(" and ")} font is downloaded once on first use, and that failed (offline?); connect and render again` });
|
|
400
|
+
else if (missing.length)
|
|
401
|
+
laid.issues.push({ slide: a.index, level: "error", code: "missing-glyphs", message: `slide ${a.index + 1}: no font here can draw ${missing.slice(0, 12).join(" ")}; change the text` });
|
|
402
|
+
else if (fallback.length)
|
|
403
|
+
laid.issues.push({ slide: a.index, level: "warning", code: "font-fallback", message: `slide ${a.index + 1}: the theme's font has no ${fallback.slice(0, 12).join(" ")}; those letters are drawn in Inter, a theme with TikTok Sans or Inter looks more even` });
|
|
404
|
+
return laid;
|
|
405
|
+
}
|
|
406
|
+
// ---------- emoji ----------
|
|
407
|
+
function cacheDir() {
|
|
408
|
+
const dir = process.env.OPEN_SLIDESHOW_CACHE ?? join(homedir(), ".cache", "open-slideshow");
|
|
409
|
+
mkdirSync(join(dir, "emoji"), { recursive: true });
|
|
410
|
+
return dir;
|
|
411
|
+
}
|
|
412
|
+
function emojiCode(segment) {
|
|
413
|
+
const cps = [...segment].map((c) => c.codePointAt(0).toString(16));
|
|
414
|
+
// Twemoji names drop FE0F unless the sequence has a ZWJ.
|
|
415
|
+
return (segment.includes("") ? cps : cps.filter((c) => c !== "fe0f")).join("-");
|
|
416
|
+
}
|
|
417
|
+
async function loadEmoji(segment) {
|
|
418
|
+
const code = emojiCode(segment);
|
|
419
|
+
const file = join(cacheDir(), "emoji", `${code}.svg`);
|
|
420
|
+
if (existsSync(file))
|
|
421
|
+
return `data:image/svg+xml;base64,${readFileSync(file).toString("base64")}`;
|
|
422
|
+
if (process.env.OPEN_SLIDESHOW_OFFLINE === "1")
|
|
423
|
+
return "";
|
|
424
|
+
try {
|
|
425
|
+
const res = await fetch(`https://cdn.jsdelivr.net/gh/jdecked/twemoji@15.1.0/assets/svg/${code}.svg`, { signal: AbortSignal.timeout(8000) });
|
|
426
|
+
if (!res.ok)
|
|
427
|
+
return "";
|
|
428
|
+
const svg = Buffer.from(await res.arrayBuffer());
|
|
429
|
+
if (svg.length > 200_000 || !svg.toString("utf8", 0, 200).includes("<svg"))
|
|
430
|
+
return "";
|
|
431
|
+
writeFileSync(file, svg);
|
|
432
|
+
return `data:image/svg+xml;base64,${svg.toString("base64")}`;
|
|
433
|
+
}
|
|
434
|
+
catch {
|
|
435
|
+
return "";
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
// ---------- rasterize ----------
|
|
439
|
+
export async function rasterize(tree, size, quality = 90) {
|
|
440
|
+
const { width, height } = SIZES[size];
|
|
441
|
+
const svg = await satori(tree, {
|
|
442
|
+
width,
|
|
443
|
+
height,
|
|
444
|
+
fonts: satoriFonts(),
|
|
445
|
+
loadAdditionalAsset: async (code, segment) => (code === "emoji" ? loadEmoji(segment) : []),
|
|
446
|
+
});
|
|
447
|
+
const png = new Resvg(svg, { fitTo: { mode: "width", value: width }, font: { loadSystemFonts: false } }).render().asPng();
|
|
448
|
+
return sharp(png).jpeg({ quality, mozjpeg: true }).toBuffer();
|
|
449
|
+
}
|
|
450
|
+
export function themeFor(deck) {
|
|
451
|
+
const base = getTheme(deck.theme);
|
|
452
|
+
if (!base)
|
|
453
|
+
throw new Error(`unknown theme "${deck.theme}"; run themes_list to see them`);
|
|
454
|
+
return withColors(base, deck.colors);
|
|
455
|
+
}
|
|
456
|
+
export function renderHash(deck, ctx) {
|
|
457
|
+
const h = createHash("sha256");
|
|
458
|
+
h.update(RENDERER_VERSION);
|
|
459
|
+
h.update(JSON.stringify({ size: deck.size, theme: ctx.theme, full_cover: deck.full_cover, text_style: deck.text_style, show_handle: deck.show_handle, slides: deck.slides, brand: { n: ctx.brand.name, h: ctx.brand.handle } }));
|
|
460
|
+
const images = [...deck.slides.map((s) => s.image), ctx.brand.icon].filter(Boolean);
|
|
461
|
+
for (const ref of images) {
|
|
462
|
+
const p = ref === ctx.brand.icon ? ref : ctx.resolveImage(ref);
|
|
463
|
+
if (p && existsSync(p))
|
|
464
|
+
h.update(createHash("sha256").update(readFileSync(p)).digest("hex"));
|
|
465
|
+
else
|
|
466
|
+
h.update(`missing:${ref}`);
|
|
467
|
+
}
|
|
468
|
+
return h.digest("hex").slice(0, 16);
|
|
469
|
+
}
|
|
470
|
+
export async function renderDeck(deck, ctx, outDir) {
|
|
471
|
+
mkdirSync(outDir, { recursive: true });
|
|
472
|
+
ctx.images ??= new Map();
|
|
473
|
+
const numbers = tipNumbers(deck.slides);
|
|
474
|
+
const files = [];
|
|
475
|
+
const issues = [];
|
|
476
|
+
const buffers = [];
|
|
477
|
+
for (let i = 0; i < deck.slides.length; i++) {
|
|
478
|
+
const laid = await laySlide(ctx, { deck, slide: deck.slides[i], index: i, tipNumber: numbers[i] });
|
|
479
|
+
issues.push(...laid.issues);
|
|
480
|
+
const jpg = await rasterize(laid.tree, deck.size);
|
|
481
|
+
const name = `${String(i + 1).padStart(2, "0")}.jpg`;
|
|
482
|
+
writeFileSync(join(outDir, name), jpg);
|
|
483
|
+
files.push(name);
|
|
484
|
+
buffers.push(jpg);
|
|
485
|
+
}
|
|
486
|
+
// Renders of slides that no longer exist would be posted by mistake.
|
|
487
|
+
for (const f of readdirSync(outDir))
|
|
488
|
+
if (/^\d{2}\.jpg$/.test(f) && !files.includes(f))
|
|
489
|
+
unlinkSync(join(outDir, f));
|
|
490
|
+
writeFileSync(join(outDir, "sheet.jpg"), await contactSheet(buffers, deck.size));
|
|
491
|
+
return { files, sheet: "sheet.jpg", hash: renderHash(deck, ctx), issues };
|
|
492
|
+
}
|
|
493
|
+
/** All slides side by side in one image, small, for a quick look. */
|
|
494
|
+
export async function contactSheet(slides, size, columns = Math.min(slides.length, 5), labels) {
|
|
495
|
+
const { width, height } = SIZES[size];
|
|
496
|
+
const tw = 300;
|
|
497
|
+
const th = Math.round((height / width) * tw);
|
|
498
|
+
const gap = 16;
|
|
499
|
+
const labelH = labels ? 44 : 0;
|
|
500
|
+
const rows = Math.ceil(slides.length / columns);
|
|
501
|
+
const W = columns * tw + (columns + 1) * gap;
|
|
502
|
+
const H = rows * (th + labelH) + (rows + 1) * gap;
|
|
503
|
+
const composites = await Promise.all(slides.map(async (buf, i) => ({ input: await sharp(buf).resize(tw, th).toBuffer(), left: gap + (i % columns) * (tw + gap), top: gap + Math.floor(i / columns) * (th + labelH + gap) + labelH })));
|
|
504
|
+
if (labels) {
|
|
505
|
+
for (let i = 0; i < labels.length && i < slides.length; i++) {
|
|
506
|
+
const label = await rasterLabel(labels[i], tw, labelH);
|
|
507
|
+
composites.push({ input: label, left: gap + (i % columns) * (tw + gap), top: gap + Math.floor(i / columns) * (th + labelH + gap) });
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
return sharp({ create: { width: W, height: H, channels: 3, background: "#f2f2f2" } }).composite(composites).jpeg({ quality: 85 }).toBuffer();
|
|
511
|
+
}
|
|
512
|
+
async function rasterLabel(text, w, h) {
|
|
513
|
+
const svg = await satori(div({ width: w, height: h, alignItems: "center", fontFamily: fontStack("Inter"), fontWeight: 600, fontSize: 22, color: "#222222" }, text), { width: w, height: h, fonts: satoriFonts() });
|
|
514
|
+
return new Resvg(svg, { font: { loadSystemFonts: false } }).render().asPng();
|
|
515
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { type Channel } from "./schema.js";
|
|
2
|
+
import { type Workspace } from "./workspace.js";
|
|
3
|
+
export interface Slot {
|
|
4
|
+
channel: string;
|
|
5
|
+
/** Post time, ISO with the channel's offset. */
|
|
6
|
+
at: string;
|
|
7
|
+
/** When the deck for it should be ready. */
|
|
8
|
+
prepare_at: string;
|
|
9
|
+
deck?: string;
|
|
10
|
+
note?: string;
|
|
11
|
+
}
|
|
12
|
+
export declare function checkTimezone(tz: string): string;
|
|
13
|
+
export declare function planSlots(ch: Channel, from: Date, days: number): Slot[];
|
|
14
|
+
export declare function readPlan(ws: Workspace): Slot[];
|
|
15
|
+
/** Adds new slots to the saved plan; slots already there keep their deck. Past slots without a deck are dropped. */
|
|
16
|
+
export declare function savePlan(ws: Workspace, fresh: Slot[], now?: Date): Slot[];
|
|
17
|
+
/** Slots that need a deck now. */
|
|
18
|
+
export declare function dueSlots(ws: Workspace, now?: Date): Slot[];
|
|
19
|
+
export declare function assignSlot(ws: Workspace, channel: string, at: string, deck: string): Slot;
|
package/dist/schedule.js
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { DateTime, IANAZone } from "luxon";
|
|
4
|
+
import { DAYS } from "./schema.js";
|
|
5
|
+
import { listDecks, readJson, UserError, writeAtomic } from "./workspace.js";
|
|
6
|
+
/** A repeatable 0–1 number for a key, so the same day always gets the same random time. */
|
|
7
|
+
function seeded(key) {
|
|
8
|
+
return createHash("sha256").update(key).digest().readUInt32BE(0) / 0xffffffff;
|
|
9
|
+
}
|
|
10
|
+
const minutes = (hhmm) => {
|
|
11
|
+
const [h, m] = hhmm.split(":").map(Number);
|
|
12
|
+
return h * 60 + m;
|
|
13
|
+
};
|
|
14
|
+
export function checkTimezone(tz) {
|
|
15
|
+
if (!IANAZone.isValidZone(tz))
|
|
16
|
+
throw new UserError(`unknown time zone "${tz}"; use a name like Europe/Istanbul or America/New_York`);
|
|
17
|
+
return tz;
|
|
18
|
+
}
|
|
19
|
+
/** Local times (minutes after midnight) for one day. */
|
|
20
|
+
function dayTimes(s, key) {
|
|
21
|
+
if (s.mode === "fixed") {
|
|
22
|
+
if (!s.times.length)
|
|
23
|
+
throw new UserError("fixed schedules need times");
|
|
24
|
+
return { times: [...new Set(s.times.map(minutes))].sort((a, b) => a - b) };
|
|
25
|
+
}
|
|
26
|
+
let start = minutes(s.window.start);
|
|
27
|
+
let end = minutes(s.window.end);
|
|
28
|
+
if (end <= start)
|
|
29
|
+
end += 24 * 60; // a window past midnight, e.g. 22:00–01:00
|
|
30
|
+
const span = end - start;
|
|
31
|
+
const need = (s.per_day - 1) * s.min_gap;
|
|
32
|
+
if (need > span) {
|
|
33
|
+
// Cannot keep the gap: spread evenly and say so.
|
|
34
|
+
const step = s.per_day > 1 ? span / (s.per_day - 1) : 0;
|
|
35
|
+
return { times: Array.from({ length: s.per_day }, (_, i) => Math.round(start + i * step)), note: `window too short for ${s.per_day} posts ${s.min_gap} min apart; spread evenly` };
|
|
36
|
+
}
|
|
37
|
+
// Spread the free minutes randomly between the posts, keeping the minimum gap.
|
|
38
|
+
const free = span - need;
|
|
39
|
+
const cuts = Array.from({ length: s.per_day }, (_, i) => seeded(`${key}:${i}`) * free).sort((a, b) => a - b);
|
|
40
|
+
return { times: cuts.map((c, i) => Math.round(start + c + i * s.min_gap)) };
|
|
41
|
+
}
|
|
42
|
+
function prepareAt(at, s) {
|
|
43
|
+
if (s.prepare === "at_post_time")
|
|
44
|
+
return at;
|
|
45
|
+
if (s.prepare === "day_before")
|
|
46
|
+
return at.minus({ days: 1 });
|
|
47
|
+
return at.minus({ hours: s.prepare.hours_before });
|
|
48
|
+
}
|
|
49
|
+
export function planSlots(ch, from, days) {
|
|
50
|
+
const s = ch.schedule;
|
|
51
|
+
const tz = checkTimezone(s.timezone);
|
|
52
|
+
if (days < 1 || days > 62)
|
|
53
|
+
throw new UserError("plan between 1 and 62 days");
|
|
54
|
+
const start = DateTime.fromJSDate(from, { zone: tz }).startOf("day");
|
|
55
|
+
const slots = [];
|
|
56
|
+
for (let d = 0; d < days; d++) {
|
|
57
|
+
const day = start.plus({ days: d });
|
|
58
|
+
const weekday = DAYS[day.weekday % 7];
|
|
59
|
+
if (!s.days.includes(weekday))
|
|
60
|
+
continue;
|
|
61
|
+
const { times, note } = dayTimes(s, `${ch.id}:${day.toISODate()}`);
|
|
62
|
+
for (const t of times) {
|
|
63
|
+
let at = day.plus({ minutes: t });
|
|
64
|
+
// Luxon moves a time that does not exist (spring-forward gap) forward; keep it, but say so.
|
|
65
|
+
const wanted = `${String(Math.floor((t % 1440) / 60)).padStart(2, "0")}:${String(t % 60).padStart(2, "0")}`;
|
|
66
|
+
const dst = t < 1440 && at.toFormat("HH:mm") !== wanted ? `${wanted} does not exist that day (clocks change); moved to ${at.toFormat("HH:mm")}` : undefined;
|
|
67
|
+
at = at.set({ second: 0, millisecond: 0 });
|
|
68
|
+
if (at.toMillis() <= from.getTime())
|
|
69
|
+
continue;
|
|
70
|
+
slots.push({ channel: ch.id, at: at.toISO({ suppressMilliseconds: true }), prepare_at: prepareAt(at, s).toISO({ suppressMilliseconds: true }), ...(note || dst ? { note: [note, dst].filter(Boolean).join("; ") } : {}) });
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return slots;
|
|
74
|
+
}
|
|
75
|
+
const planFile = (ws) => join(ws.state, "plan.json");
|
|
76
|
+
export function readPlan(ws) {
|
|
77
|
+
return readJson(planFile(ws), { slots: [] }).slots;
|
|
78
|
+
}
|
|
79
|
+
/** Adds new slots to the saved plan; slots already there keep their deck. Past slots without a deck are dropped. */
|
|
80
|
+
export function savePlan(ws, fresh, now = new Date()) {
|
|
81
|
+
const old = readPlan(ws);
|
|
82
|
+
const key = (s) => `${s.channel}|${s.at}`;
|
|
83
|
+
const byKey = new Map(old.map((s) => [key(s), s]));
|
|
84
|
+
for (const s of fresh)
|
|
85
|
+
if (!byKey.has(key(s)))
|
|
86
|
+
byKey.set(key(s), s);
|
|
87
|
+
const decks = new Map(listDecks(ws).map((d) => [d.id, d.deck]));
|
|
88
|
+
const kept = [...byKey.values()].filter((s) => {
|
|
89
|
+
if (s.deck && !decks.has(s.deck))
|
|
90
|
+
delete s.deck; // the deck was deleted: the slot is free again
|
|
91
|
+
return s.deck || Date.parse(s.at) > now.getTime();
|
|
92
|
+
});
|
|
93
|
+
kept.sort((a, b) => a.at.localeCompare(b.at));
|
|
94
|
+
writeAtomic(planFile(ws), JSON.stringify({ slots: kept }, null, 2));
|
|
95
|
+
return kept;
|
|
96
|
+
}
|
|
97
|
+
/** Slots that need a deck now. */
|
|
98
|
+
export function dueSlots(ws, now = new Date()) {
|
|
99
|
+
return readPlan(ws).filter((s) => !s.deck && Date.parse(s.prepare_at) <= now.getTime() && Date.parse(s.at) > now.getTime());
|
|
100
|
+
}
|
|
101
|
+
export function assignSlot(ws, channel, at, deck) {
|
|
102
|
+
const slots = readPlan(ws);
|
|
103
|
+
const slot = slots.find((s) => s.channel === channel && s.at === at);
|
|
104
|
+
if (!slot)
|
|
105
|
+
throw new UserError(`no slot for ${channel} at ${at}; run plan first`);
|
|
106
|
+
if (slot.deck && slot.deck !== deck)
|
|
107
|
+
throw new UserError(`slot ${at} already has deck ${slot.deck}`);
|
|
108
|
+
const other = slots.find((s) => s.deck === deck && s !== slot);
|
|
109
|
+
if (other)
|
|
110
|
+
throw new UserError(`deck ${deck} is already in the slot at ${other.at}`);
|
|
111
|
+
slot.deck = deck;
|
|
112
|
+
writeAtomic(planFile(ws), JSON.stringify({ slots }, null, 2));
|
|
113
|
+
return slot;
|
|
114
|
+
}
|