@hypersocial/decks-cli 0.9.22 → 0.9.24

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.
Files changed (88) hide show
  1. package/package.json +1 -1
  2. package/skills/hyperdecks/SKILL.md +113 -67
  3. package/skills/hyperdecks/chat.md +11 -8
  4. package/skills/hyperdecks/terminal.md +82 -0
  5. package/src/bars.mjs +268 -0
  6. package/src/brand.mjs +51 -8
  7. package/src/check.mjs +311 -15
  8. package/src/checkRules.mjs +616 -27
  9. package/src/commands.mjs +157 -28
  10. package/src/deckSlug.mjs +41 -0
  11. package/src/export-video.mjs +75 -5
  12. package/src/files.mjs +35 -0
  13. package/src/frame-clock.mjs +6 -2
  14. package/src/guide.mjs +91 -13
  15. package/src/hosted.mjs +18 -8
  16. package/src/iconAliasNames.mjs +70 -0
  17. package/src/iconChoice.mjs +97 -0
  18. package/src/iconSets.mjs +89 -0
  19. package/src/iconSlots.mjs +48 -0
  20. package/src/icons.mjs +285 -45
  21. package/src/iconsCli.mjs +76 -0
  22. package/src/layoutRoutes.mjs +92 -0
  23. package/src/layouts.mjs +4 -4
  24. package/src/mediaPreviews.mjs +3 -1
  25. package/src/narrate.mjs +31 -4
  26. package/src/opening.mjs +9 -3
  27. package/src/ops.mjs +49 -0
  28. package/src/photosGuide.mjs +47 -0
  29. package/src/picturesGuide.mjs +53 -0
  30. package/src/play.mjs +3 -2
  31. package/src/presenter.mjs +3 -1
  32. package/src/preview-moment.mjs +10 -2
  33. package/src/release.mjs +13 -5
  34. package/src/runtime.mjs +9 -2
  35. package/src/scaffold.mjs +73 -13
  36. package/src/source.mjs +86 -14
  37. package/src/stockMedia.mjs +299 -0
  38. package/src/themeCli.mjs +41 -0
  39. package/src/themes.mjs +345 -0
  40. package/templates/icons/material.LICENSE +202 -0
  41. package/templates/icons/material.json.gz +0 -0
  42. package/templates/icons/phosphor.LICENSE +21 -0
  43. package/templates/icons/phosphor.json.gz +0 -0
  44. package/templates/icons/tabler.LICENSE +21 -0
  45. package/templates/icons/tabler.json.gz +0 -0
  46. package/templates/layouts/_deck.html +177 -36
  47. package/templates/layouts/bento.html +75 -0
  48. package/templates/layouts/chart.html +6 -4
  49. package/templates/layouts/closer.html +10 -3
  50. package/templates/layouts/compare.html +13 -4
  51. package/templates/layouts/cover-band.html +10 -8
  52. package/templates/layouts/cover-frame.html +9 -7
  53. package/templates/layouts/cover-poster.html +8 -5
  54. package/templates/layouts/cover-split.html +7 -6
  55. package/templates/layouts/cover-type.html +1 -0
  56. package/templates/layouts/features.html +9 -7
  57. package/templates/layouts/funnel.html +60 -0
  58. package/templates/layouts/hero.html +40 -22
  59. package/templates/layouts/lanes.html +63 -0
  60. package/templates/layouts/loop.html +81 -0
  61. package/templates/layouts/number.html +2 -1
  62. package/templates/layouts/phone-stage.html +68 -0
  63. package/templates/layouts/phones.html +1 -0
  64. package/templates/layouts/picture-full.html +48 -0
  65. package/templates/layouts/portrait.html +45 -0
  66. package/templates/layouts/product.html +7 -6
  67. package/templates/layouts/quote.html +2 -1
  68. package/templates/layouts/rail.html +71 -0
  69. package/templates/layouts/scorecard.html +70 -0
  70. package/templates/layouts/screens.html +85 -0
  71. package/templates/layouts/sentence.html +39 -0
  72. package/templates/layouts/split.html +22 -7
  73. package/templates/layouts/spotlight.html +77 -0
  74. package/templates/layouts/stack.html +83 -0
  75. package/templates/layouts/staircase.html +76 -0
  76. package/templates/layouts/strike.html +46 -0
  77. package/templates/layouts/tap-through.html +73 -0
  78. package/templates/layouts/team.html +3 -2
  79. package/templates/layouts/timeline.html +16 -6
  80. package/templates/layouts/two-bars.html +53 -0
  81. package/templates/layouts/two-by-two.html +71 -0
  82. package/templates/layouts/video-beats.html +66 -0
  83. package/templates/layouts/video-full.html +62 -0
  84. package/templates/layouts/wall.html +81 -0
  85. package/templates/layouts/zoom.html +144 -0
  86. package/templates/narrated-deck.html +12 -7
  87. package/templates/script.md +2 -2
  88. /package/templates/icons/{LICENSE → lucide.LICENSE} +0 -0
package/src/source.mjs CHANGED
@@ -5,13 +5,14 @@
5
5
  // hyperdecks source push <slug> [dir] [--base-rev N] a folder's files to the draft
6
6
  // hyperdecks check <slug> --hosted
7
7
  // hyperdecks release <slug> --hosted [--to "<name>" [--email e]]... [--qa]
8
- // hyperdecks asset add <slug> <file|url> [--name n]
8
+ // hyperdecks asset add <slug> <file|url> [--name n] [--trim]
9
9
  import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
10
10
  import { tmpdir } from "node:os";
11
11
  import { basename, extname, join, resolve } from "node:path";
12
12
  import { api, client, uploadBytes } from "./runtime.mjs";
13
13
  import { HOSTED_LAYOUT_WHY, MESSAGES } from "./checkRules.mjs";
14
14
  import { withLoadingBlock } from "./loadingBlock.mjs";
15
+ import { TRIMS, barsLine, measureBars, trimFile } from "./bars.mjs";
15
16
  import { SOURCE_FILES, getDeckSource, hostedCheck, hostedRelease, uploadDeckAsset, writeDeckSource } from "./hosted.mjs";
16
17
 
17
18
  export * from "./hosted.mjs";
@@ -114,21 +115,92 @@ export async function sourcePush(pos, opts = {}, { log = (line) => console.log(l
114
115
 
115
116
  const TYPES = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp", ".avif": "image/avif", ".svg": "image/svg+xml", ".mp4": "video/mp4", ".webm": "video/webm", ".woff2": "font/woff2", ".woff": "font/woff", ".mp3": "audio/mpeg", ".m4a": "audio/mp4", ".json": "application/json" };
116
117
 
117
- export async function assetAdd(pos, opts = {}, { log = (line) => console.log(line), cwd = process.cwd() } = {}) {
118
+ // Measured for bars (bars.mjs): pictures ffmpeg reads (not SVG) and clips.
119
+ const MEASURED = /^(image\/(png|jpeg|gif|webp|avif)|video\/)/;
120
+ const MAX_FETCH_BYTES = 25 * 1024 * 1024;
121
+ async function defaultFfmpeg() {
122
+ const { bundledFfmpeg } = await import("./mediaPreviewMake.mjs");
123
+ return bundledFfmpeg();
124
+ }
125
+ async function uploadLocal(opts, { slug, name, bytes, contentType }) {
126
+ const c = await client(opts);
127
+ const storageId = await uploadBytes(c, bytes, contentType);
128
+ return c.mutation(api.assets.saveAsset, { name, storageId, contentType, deckSlug: slug });
129
+ }
130
+ // A URL's bytes for --trim, which crops here (the hosted import takes the URL as it is).
131
+ async function fetchForTrim(url, fetchImpl) {
132
+ const res = await fetchImpl(url, { signal: AbortSignal.timeout(60_000) });
133
+ if (!res.ok) throw new Error(`${url} returned HTTP ${res.status}`);
134
+ const declared = (res.headers.get("content-type") || "").split(";")[0].trim().toLowerCase();
135
+ const byExt = TYPES[extname(new URL(url).pathname).toLowerCase()];
136
+ const contentType = MEASURED.test(declared) ? declared : byExt;
137
+ const bytes = Buffer.from(await res.arrayBuffer());
138
+ if (bytes.byteLength > MAX_FETCH_BYTES) throw new Error(`${url} is over 25 MB`);
139
+ if (!contentType) throw new Error(`${url} is ${declared || "untyped"}; --trim takes a picture or clip`);
140
+ return { bytes, contentType };
141
+ }
142
+
143
+ // asset add <slug> <file|url> [--name n] [--trim]. A picture or clip is measured for bars baked into it
144
+ // (a letterboxed screenshot): past 5% of a side they are printed, and --trim uploads the content box
145
+ // only. Never trimmed without the flag: a designed border is legitimate. A URL without --trim is
146
+ // imported by the server, which reports a PNG's bars itself.
147
+ export async function assetAdd(pos, opts = {}, { log = (line) => console.log(line), cwd = process.cwd(), ffmpeg = defaultFfmpeg, upload = uploadLocal, fetchImpl = fetch } = {}) {
118
148
  const [slug, from] = pos;
119
- if (!slug || !from) throw new Error("usage: asset add <slug> <file|url> [--name <name>]");
149
+ if (!slug || !from) throw new Error("usage: asset add <slug> <file|url> [--name <name>] [--trim]");
150
+ const isUrl = /^https?:\/\//i.test(from);
120
151
  let out;
121
- if (/^https?:\/\//i.test(from)) out = await uploadDeckAsset(opts, { slug, name: opts.name, url: from });
122
- else {
123
- const path = resolve(/*turbopackIgnore: true*/ cwd, from);
124
- const contentType = TYPES[extname(path).toLowerCase()];
125
- if (!contentType) throw new Error(`${from}: asset add takes images, video, audio, fonts and JSON (${Object.keys(TYPES).join(" ")})`);
126
- const c = await client(opts);
127
- const bytes = readFileSync(path);
128
- const storageId = await uploadBytes(c, bytes, contentType);
129
- const saved = await c.mutation(api.assets.saveAsset, { name: String(opts.name || basename(path)), storageId, contentType, deckSlug: slug });
130
- out = { url: saved.url, name: saved.name, contentType, bytes: bytes.byteLength };
152
+ if (isUrl && !opts.trim) {
153
+ out = await uploadDeckAsset(opts, { slug, name: opts.name, url: from });
154
+ const line = barsLine(out.bars);
155
+ if (line) log(`${line}; add --trim to upload it without them`);
156
+ // The server reads a PNG's bars only: say so for the rest rather than imply there are none.
157
+ else if (out.bars == null && MEASURED.test(out.contentType ?? "")) log(`bars: not measured for ${out.contentType} from a URL; add --trim (or add the file from disk) to measure them`);
158
+ } else {
159
+ let bytes, contentType, name = String(opts.name || "");
160
+ if (isUrl) {
161
+ ({ bytes, contentType } = await fetchForTrim(from, fetchImpl));
162
+ if (!name) name = basename(new URL(from).pathname) || "asset";
163
+ } else {
164
+ const path = resolve(/*turbopackIgnore: true*/ cwd, from);
165
+ contentType = TYPES[extname(path).toLowerCase()];
166
+ if (!contentType) throw new Error(`${from}: asset add takes images, video, audio, fonts and JSON (${Object.keys(TYPES).join(" ")})`);
167
+ bytes = readFileSync(path);
168
+ if (!name) name = basename(path);
169
+ }
170
+ let bars = null, trimmed = null, unmeasured = null;
171
+ if (MEASURED.test(contentType)) {
172
+ const temp = mkdtempSync(join(tmpdir(), "hd-bars-"));
173
+ try {
174
+ const ff = await ffmpeg();
175
+ // Named by its type, not by --name, so ffmpeg picks the right reader.
176
+ const input = join(temp, `in${Object.keys(TYPES).find((ext) => TYPES[ext] === contentType) ?? ""}`);
177
+ writeFileSync(input, bytes);
178
+ const video = contentType.startsWith("video/");
179
+ bars = await measureBars(ff, input, { video });
180
+ if (opts.trim && bars.reported) {
181
+ const to = TRIMS[contentType];
182
+ if (!to) throw new Error(`${from}: --trim takes a PNG, JPEG or WebP picture or an MP4 clip; this is ${contentType}`);
183
+ const output = join(temp, `out${to.ext}`);
184
+ const size = await trimFile(ff, input, output, bars.content, { video: !!to.video });
185
+ bytes = readFileSync(output);
186
+ trimmed = { from: { width: bars.width, height: bars.height }, to: size };
187
+ if (to.type !== contentType) { contentType = to.type; if (!opts.name) name = name.replace(/\.[A-Za-z0-9]+$/, "") + to.ext; }
188
+ }
189
+ } catch (e) {
190
+ if (opts.trim) throw e;
191
+ unmeasured = e.message;
192
+ } finally {
193
+ rmSync(temp, { recursive: true, force: true });
194
+ }
195
+ } else if (opts.trim) throw new Error(`${from}: --trim takes a picture or clip, not ${contentType}`);
196
+ const saved = await upload(opts, { slug, name, bytes, contentType });
197
+ out = { url: saved.url, name: saved.name, contentType, bytes: bytes.byteLength, ...(bars ? { bars } : {}), ...(trimmed ? { trimmed } : {}), ...(unmeasured ? { barsUnmeasured: unmeasured } : {}) };
198
+ if (trimmed) log(`trimmed: ${barsLine(bars).slice("bars: ".length)} cut away; uploaded ${trimmed.to.width}x${trimmed.to.height}`);
199
+ else if (bars?.reported) log(`${barsLine(bars)}; add --trim to upload it without them`);
200
+ else if (opts.trim) log("no bars to trim; uploaded as it is");
131
201
  }
132
- log(out.url);
202
+ // The file (or URL) it came from beside its new URL, so uploads in a loop stay told apart.
203
+ out = { ...out, file: from };
204
+ log(`${from} → ${out.url}`);
133
205
  return out;
134
206
  }
@@ -0,0 +1,299 @@
1
+ // Found pictures: Unsplash photos and GIPHY GIFs (convex/stockMedia.ts searches
2
+ // them; check and the player read what this writes). No Node imports: Convex,
3
+ // the CLI, both MCP servers and check share it.
4
+ //
5
+ // Both services' terms say to show their media from their own URLs, not a copy:
6
+ // - Unsplash API Terms s.6: "you must directly use or embed the related image
7
+ // URLs returned by the API"; adding a photo calls its download_location
8
+ // (the download-tracking endpoint) and credits the photographer and Unsplash,
9
+ // with links carrying utm_source and utm_medium=referral.
10
+ // - GIPHY API docs: "Do not cache API responses or media URLs or cache or store
11
+ // copies of GIPHY's media assets" and "Do not strip or modify URLs returned by
12
+ // the API"; "Powered By GIPHY" shows where its content does.
13
+ // So a slide embeds the service's URL (never re-hosted), and a viewer's device
14
+ // loads it from there. The credit sits on the slide (a .hd-credit line, which
15
+ // check requires) and in its data-note; the player hides a picture whose link
16
+ // died (data-hd-stock), and check warns about one.
17
+
18
+ export const UTM = "utm_source=hyperdecks&utm_medium=referral";
19
+ // The long side a photo is asked for at (Unsplash resizes; fit=max never upscales).
20
+ export const PHOTO_LONG_SIDE = 2000;
21
+ export const MAX_RESULTS = 20;
22
+ export const DEFAULT_RESULTS = 10;
23
+ // More than this many GIFs in one deck and check warns (deck_guide topic look).
24
+ export const MAX_DECK_GIFS = 2;
25
+ export const GIF_RATINGS = ["g", "pg"];
26
+ // Search words: what both services accept, kept short (GIPHY's q is at most 50).
27
+ export const MAX_QUERY_CHARS = 50;
28
+
29
+ // The hosts a slide may load found media from, and nothing else new.
30
+ const HOSTS = {
31
+ unsplash: /^images\.unsplash\.com$/,
32
+ giphy: /^(media\d?\.giphy\.com|i\.giphy\.com)$/,
33
+ };
34
+
35
+ // "unsplash", "giphy" or null for any other URL.
36
+ export function stockSource(url) {
37
+ let host;
38
+ try {
39
+ const u = new URL(url);
40
+ if (u.protocol !== "https:") return null;
41
+ host = u.hostname;
42
+ } catch {
43
+ return null;
44
+ }
45
+ for (const [name, re] of Object.entries(HOSTS)) if (re.test(host)) return name;
46
+ return null;
47
+ }
48
+
49
+ export function shapeOf(width, height) {
50
+ if (!(width > 0 && height > 0)) return "unknown";
51
+ const r = width / height;
52
+ return r > 1.1 ? "landscape" : r < 0.9 ? "portrait" : "square";
53
+ }
54
+
55
+ export const escapeHtml = (s) =>
56
+ String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
57
+
58
+ const withParams = (url, params) => `${url}${url.includes("?") ? "&" : "?"}${params}`;
59
+ // Only links to the service itself: a profile or page URL from a response that
60
+ // is not on the service's own https host is dropped, never written into a slide.
61
+ function serviceLink(url, host) {
62
+ try {
63
+ const u = new URL(String(url));
64
+ return u.protocol === "https:" && (u.hostname === host || u.hostname === `www.${host}`) ? u.toString() : null;
65
+ } catch {
66
+ return null;
67
+ }
68
+ }
69
+ const imageUrl = (url, source) => (stockSource(url) === source ? String(url) : null);
70
+
71
+ export function normalizeQuery(query) {
72
+ const q = String(query ?? "").replace(/\s+/g, " ").trim();
73
+ if (!q) throw new Error("say what to search for (a few words)");
74
+ if (q.length > MAX_QUERY_CHARS) throw new Error(`search words must be at most ${MAX_QUERY_CHARS} characters`);
75
+ return q;
76
+ }
77
+
78
+ export function normalizeLimit(limit) {
79
+ if (limit == null || limit === "") return DEFAULT_RESULTS;
80
+ const n = Number(limit);
81
+ if (!Number.isInteger(n) || n < 1 || n > MAX_RESULTS) throw new Error(`limit must be a whole number from 1 to ${MAX_RESULTS}`);
82
+ return n;
83
+ }
84
+
85
+ // ---- Unsplash ---------------------------------------------------------------
86
+
87
+ // One search hit, from an Unsplash photo object: enough to choose by (what it
88
+ // shows, its shape, who took it) and its id for add_photo. null when the
89
+ // response is missing what a slide needs.
90
+ export function photoResult(p) {
91
+ const thumb = imageUrl(p?.urls?.small ?? p?.urls?.thumb, "unsplash");
92
+ if (!p?.id || !thumb || !imageUrl(p?.urls?.raw, "unsplash")) return null;
93
+ const width = Number(p.width) || 0;
94
+ const height = Number(p.height) || 0;
95
+ return {
96
+ id: String(p.id),
97
+ description: String(p.description || p.alt_description || "").trim(),
98
+ width,
99
+ height,
100
+ shape: shapeOf(width, height),
101
+ thumbUrl: thumb,
102
+ photographer: String(p.user?.name || p.user?.username || "an Unsplash photographer"),
103
+ photographerUrl: photographerUrl(p),
104
+ };
105
+ }
106
+
107
+ function photographerUrl(p) {
108
+ const link = serviceLink(p?.user?.links?.html, "unsplash.com") ?? (p?.user?.username ? `https://unsplash.com/@${encodeURIComponent(p.user.username)}` : "https://unsplash.com/");
109
+ return withParams(link, UTM);
110
+ }
111
+
112
+ // A chosen photo, ready for a slide: its URL at about PHOTO_LONG_SIDE on the
113
+ // long side (built on urls.raw, which keeps the ixid the terms require), its
114
+ // size at that scale, the credit and the markup. Throws on a response without
115
+ // a usable image.
116
+ export function photoUse(p) {
117
+ const raw = imageUrl(p?.urls?.raw, "unsplash");
118
+ if (!p?.id || !raw) throw new Error("Unsplash returned no image for that photo");
119
+ const w = Number(p.width) || 0;
120
+ const h = Number(p.height) || 0;
121
+ const portrait = h > w;
122
+ const scale = w && h ? Math.min(1, PHOTO_LONG_SIDE / Math.max(w, h)) : 1;
123
+ const width = w ? Math.round(w * scale) : PHOTO_LONG_SIDE;
124
+ const height = h ? Math.round(h * scale) : Math.round(PHOTO_LONG_SIDE * 0.66);
125
+ const url = withParams(raw, `${portrait ? "h" : "w"}=${PHOTO_LONG_SIDE}&fit=max&q=80&fm=jpg`);
126
+ const photographer = String(p.user?.name || p.user?.username || "an Unsplash photographer");
127
+ const credit = {
128
+ text: `Photo by ${photographer} on Unsplash`,
129
+ photographer,
130
+ photographerUrl: photographerUrl(p),
131
+ unsplashUrl: withParams("https://unsplash.com/", UTM),
132
+ };
133
+ const creditHtml = `Photo by <a href="${escapeHtml(credit.photographerUrl)}" target="_blank" rel="noopener noreferrer">${escapeHtml(photographer)}</a> on <a href="${escapeHtml(credit.unsplashUrl)}" target="_blank" rel="noopener noreferrer">Unsplash</a>`;
134
+ const alt = String(p.alt_description || p.description || "").trim();
135
+ return {
136
+ id: String(p.id),
137
+ url,
138
+ width,
139
+ height,
140
+ shape: shapeOf(width, height),
141
+ alt,
142
+ credit,
143
+ creditHtml,
144
+ note: escapeHtml(credit.text),
145
+ markup: photoTag({ url, alt, width, height }, "pic"),
146
+ creditLine: creditLine(creditHtml),
147
+ };
148
+ }
149
+
150
+ // One credit line a slide: the slide's own child (never inside a picture slot,
151
+ // where it would count in a layout's grid), shown in its top-right corner
152
+ // (player.css). Several found pictures on one slide share it: join their
153
+ // creditHtml with " · " inside the one line.
154
+ export function creditLine(...creditHtmls) {
155
+ return `<p class="hd-credit">${creditHtmls.join(" · ")}</p>`;
156
+ }
157
+
158
+ // ---- GIPHY ------------------------------------------------------------------
159
+
160
+ export function normalizeRating(rating) {
161
+ if (rating == null || rating === "") return "g";
162
+ const r = String(rating).toLowerCase();
163
+ if (!GIF_RATINGS.includes(r)) throw new Error(`rating must be g (the default) or pg; pg only when the person asks for it`);
164
+ return r;
165
+ }
166
+
167
+ // One GIF, from a GIPHY GIF object: what it is, its shape and the markup a
168
+ // slide uses as is (the MP4 rendition in a muted looping <video>, its first
169
+ // frame as the poster, the attribution line). null when it has no MP4.
170
+ export function gifResult(g) {
171
+ const o = g?.images?.original ?? {};
172
+ const mp4 = imageUrl(o.mp4, "giphy");
173
+ const still = imageUrl(g?.images?.original_still?.url, "giphy");
174
+ if (!g?.id || !mp4 || !still) return null;
175
+ const width = Number(o.width) || 0;
176
+ const height = Number(o.height) || 0;
177
+ const title = String(g.title || "").trim();
178
+ const pageUrl = serviceLink(g.url, "giphy.com") ?? "https://giphy.com/";
179
+ const user = String(g.user?.username || g.username || "").trim();
180
+ const creditHtml = `<a href="${escapeHtml(pageUrl)}" target="_blank" rel="noopener noreferrer">GIF${user ? ` by @${escapeHtml(user)}` : ""}</a> · Powered by GIPHY`;
181
+ return {
182
+ id: String(g.id),
183
+ title,
184
+ rating: String(g.rating || ""),
185
+ width,
186
+ height,
187
+ shape: shapeOf(width, height),
188
+ mp4Url: mp4,
189
+ mp4Bytes: Number(o.mp4_size) || null,
190
+ stillUrl: still,
191
+ previewUrl: imageUrl(g?.images?.fixed_width?.url, "giphy") ?? still,
192
+ pageUrl,
193
+ user: user || null,
194
+ creditHtml,
195
+ note: escapeHtml(`GIF${user ? ` by @${user}` : ""} via GIPHY (${pageUrl}). Powered by GIPHY.`),
196
+ markup: gifTag({ mp4Url: mp4, stillUrl: still, width, height, title }, "pic"),
197
+ creditLine: creditLine(creditHtml),
198
+ };
199
+ }
200
+
201
+ // ---- where it goes: one layout's picture slot ---------------------------------
202
+
203
+ // The layouts that take a found photo or GIF, and their slot: the class the
204
+ // layout styles (art on a cover, pic for a photo slot, shot in screens), the id
205
+ // a slot carries for the layout's cues (the slide's id + suffix), and the
206
+ // placeholder the markup replaces. `wide` is the class for a picture wider than
207
+ // `wideOver` (width ÷ height). The rest take a screenshot or a recording.
208
+ const COVER = { cls: "art", replaces: '<div class="art" role="presentation"></div>' };
209
+ export const PICTURE_SLOTS = {
210
+ hero: { ...COVER, wide: "art wide", wideOver: 2 },
211
+ "cover-frame": COVER,
212
+ "cover-split": COVER,
213
+ "cover-band": COVER,
214
+ "cover-poster": COVER,
215
+ split: { cls: "pic", id: "frame", replaces: 'the whole <div class="frame card" id="{slide}-frame">…</div> (the phone card and the placeholder in it)' },
216
+ "picture-full": { cls: "pic", id: "pic", replaces: '<div class="pic" id="{slide}-pic" …></div>' },
217
+ portrait: { cls: "pic", id: "pic", replaces: '<div class="pic" id="{slide}-pic" …></div>' },
218
+ wall: { cls: "pic", id: "p1", replaces: 'the first <div class="pic" id="{slide}-p1" …></div> (the large cell: the strongest photo)', others: 'each other <div class="pic" …></div>' },
219
+ screens: { cls: "shot", wide: "shot wide", wideOver: 1.1, replaces: 'one <div class="shot" …></div> inside a .pane (keep the pictures one shape)' },
220
+ };
221
+ const SLOT_NAMES = Object.keys(PICTURE_SLOTS);
222
+ export const FOR_HINT = `add --for <layout> (${SLOT_NAMES.join(", ")}; layout:slide-id when the slide's id is not the layout's name) for the markup that layout's slot takes`;
223
+
224
+ // `--for` names a layout, a slide made from one by deck new (wall-2: the second
225
+ // wall slide, whose ids start wall-2), or a layout and any slide id
226
+ // (wall:proof, for <section id="proof" class="slide l-wall">). { layout, slide }
227
+ // or a readable error.
228
+ const SLIDE_ID = /^[a-z0-9][a-z0-9_-]{0,63}$/i;
229
+ export function parseSlotTarget(target) {
230
+ const t = String(target ?? "").trim();
231
+ const [name, id] = t.includes(":") ? t.split(/:(.*)/s) : [t, null];
232
+ const lower = name.toLowerCase();
233
+ const layout = SLOT_NAMES.find((n) => lower === n || (id === null && new RegExp(`^${n}-\\d+$`).test(lower)));
234
+ if (!layout) throw new Error(`--for takes a layout with a picture slot: ${SLOT_NAMES.join(", ")} (or a slide id made from one, like wall-2, or layout:slide-id, like wall:proof); "${target}" is not one. Phone, product, zoom and video layouts take a screenshot or a recording, not a found picture`);
235
+ if (id !== null && !SLIDE_ID.test(id)) throw new Error(`--for ${layout}:<slide-id>: the slide id is the slide's own id (letters, digits, - and _); "${id}" is not one`);
236
+ return { layout, slide: id ?? lower };
237
+ }
238
+
239
+ function photoTag(p, cls, id) {
240
+ return `<img class="${cls}" src="${escapeHtml(p.url)}" alt="${escapeHtml(p.alt)}" width="${p.width}" height="${p.height}"${id ? ` id="${escapeHtml(id)}"` : ""} data-hd-stock="unsplash" referrerpolicy="no-referrer">`;
241
+ }
242
+ function gifTag(g, cls, id) {
243
+ return (
244
+ `<video class="${cls}" src="${escapeHtml(g.mp4Url)}" poster="${escapeHtml(g.stillUrl)}"` +
245
+ (g.width && g.height ? ` width="${g.width}" height="${g.height}"` : "") +
246
+ `${id ? ` id="${escapeHtml(id)}"` : ""} muted loop playsinline autoplay preload="auto" data-hd-gif data-hd-stock="giphy"${g.title ? ` aria-label="${escapeHtml(g.title)}"` : ""}></video>`
247
+ );
248
+ }
249
+ const tagFor = (item, cls, id) => (item.mp4Url ? gifTag(item, cls, id) : photoTag(item, cls, id));
250
+
251
+ // A photo (photoUse) or a GIF (gifResult) with its markup made for one layout's
252
+ // slot: markup in the class that slot takes, with the slot's id; slot says what
253
+ // it replaces (and, on a wall, the markup for the other cells).
254
+ export function fitSlot(item, target) {
255
+ const { layout, slide } = parseSlotTarget(target);
256
+ const s = PICTURE_SLOTS[layout];
257
+ const ratio = item.width && item.height ? item.width / item.height : 0;
258
+ const cls = s.wide && ratio > s.wideOver ? s.wide : s.cls;
259
+ const markup = tagFor(item, cls, s.id ? `${slide}-${s.id}` : null);
260
+ const slot = { layout, slide, replaces: s.replaces.replaceAll("{slide}", slide) };
261
+ if (s.others) slot.otherCells = { replaces: s.others, markup: tagFor(item, cls, null) };
262
+ // A wall's cells stand upright by default: a set of landscape or square photos takes its own cells.
263
+ const shape = shapeOf(item.width, item.height);
264
+ if (layout === "wall" && (shape === "landscape" || shape === "square")) slot.cells = `for a set of ${shape} photos write <div class="pics ${shape === "landscape" ? "wide" : "square"}">`;
265
+ return { ...item, markup, slot };
266
+ }
267
+
268
+ // A squarish search often comes back short (few photos on Unsplash are square):
269
+ // say so, and that a landscape one crops to a square slot (the layouts cover).
270
+ export function searchHint({ orientation, limit, count }) {
271
+ if (orientation !== "squarish" || count >= normalizeLimit(limit)) return null;
272
+ return `only ${count} squarish photo${count === 1 ? "" : "s"} for a limit of ${normalizeLimit(limit)}: few photos are square, so search again with orientation landscape (or none); the layouts crop a photo to its slot, so keep the subject near the middle`;
273
+ }
274
+
275
+ // ---- what check reads -------------------------------------------------------
276
+
277
+ // Every Unsplash or GIPHY URL a piece of HTML loads (src, poster, srcset, url()).
278
+ export function stockRefs(html) {
279
+ const raw = [
280
+ ...[...html.matchAll(/\s(?:src|poster)\s*=\s*(?:"([^"]*)"|'([^']*)')/gi)].map((m) => m[1] ?? m[2]),
281
+ ...[...html.matchAll(/\ssrcset\s*=\s*(?:"([^"]*)"|'([^']*)')/gi)].flatMap((m) => (m[1] ?? m[2]).split(",").map((c) => c.trim().split(/\s+/)[0])),
282
+ ...[...html.matchAll(/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)'"\s]+))\s*\)/gi)].map((m) => m[1] ?? m[2] ?? m[3]),
283
+ ];
284
+ const decode = (s) => s.replace(/&amp;/g, "&");
285
+ return [...new Set(raw.map((r) => decode(String(r ?? "").trim())).filter((u) => stockSource(u)))];
286
+ }
287
+
288
+ // The text and links of a slide's credit lines (.hd-credit).
289
+ export function creditLines(html) {
290
+ return [...html.matchAll(/<([a-z][\w-]*)\b[^>]*\bclass\s*=\s*["'][^"']*\bhd-credit\b[^"']*["'][^>]*>([\s\S]*?)<\/\1>/gi)].map((m) => m[2]);
291
+ }
292
+
293
+ export function hasUnsplashCredit(html) {
294
+ return creditLines(html).some((c) => /\bUnsplash\b/.test(c) && /href\s*=\s*["']https:\/\/(?:www\.)?unsplash\.com\/@/i.test(c) && /href\s*=\s*["']https:\/\/(?:www\.)?unsplash\.com\/?\?/i.test(c));
295
+ }
296
+
297
+ export function hasGiphyCredit(html) {
298
+ return creditLines(html).some((c) => /Powered by GIPHY/i.test(c));
299
+ }
@@ -0,0 +1,41 @@
1
+ // hyperdecks theme list | theme set <deck-dir|slug> <theme> [--brand]
2
+ //
3
+ // The built-in themes (themes.mjs). `theme set` swaps a local deck's theme
4
+ // tokens and fonts and gives it the theme's own colours (a named theme wins);
5
+ // --brand puts the saved brand back on top. --no-brand is still accepted, and
6
+ // is the default. A released deck changes only when it is released again.
7
+ import { readFileSync, writeFileSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { THEMES, DEFAULT_THEME, applyTheme, themeOrThrow, themesMarkdown } from "./themes.mjs";
10
+ import { applyBrand, brandAsked, brandForNewDeck, brandWanted, stripBrandLogo } from "./brand.mjs";
11
+ import { resolveDeckDir } from "./check.mjs";
12
+ import * as ops from "./ops.mjs";
13
+
14
+ export function themeList(opts = {}, { log = (line) => console.log(line) } = {}) {
15
+ const list = THEMES.map((t) => ({ id: t.id, name: t.name, for: t.for, default: t.id === DEFAULT_THEME }));
16
+ log(opts.json ? JSON.stringify(list, null, 2) : `${themesMarkdown()}\n\nPick one: deck new … --theme <name>; change a deck's: hyperdecks theme set <deck-dir> <name>.`);
17
+ return list;
18
+ }
19
+
20
+ export async function themeSet(pos, opts = {}, { log = (line) => console.log(line), cwd = process.cwd(), getBrand = () => ops.getBrand(opts) } = {}) {
21
+ const [dirArg, name] = pos;
22
+ if (!dirArg || !name) throw new Error("usage: theme set <deck-dir|slug> <theme> [--brand|--no-brand]");
23
+ const theme = themeOrThrow(name);
24
+ const dir = resolveDeckDir(dirArg, cwd);
25
+ const path = join(dir, "index.html");
26
+ const { brand, readError } = await brandForNewDeck(getBrand, brandWanted(brandAsked(opts), true));
27
+ // The deck may be in the brand's colours now: a brand we cannot read must not be overwritten with the theme's.
28
+ if (readError) throw new Error(`could not read your brand (${readError}); ${dir} is unchanged. Try again, or leave out --brand for the theme's own colours`);
29
+ const html = readFileSync(path, "utf8");
30
+ // Without the brand, a logo it put on before goes too: a named theme has none.
31
+ const out = brand ? applyBrand(applyTheme(html, theme.id), brand) : stripBrandLogo(applyTheme(html, theme.id));
32
+ writeFileSync(path, out);
33
+ const how = brand ? "your brand's colours on top (leave out --brand for the theme's own)" : opts.brand === true ? "the theme's own colours (no brand is saved)" : "the theme's own colours (pass --brand to recolour it in your brand)";
34
+ // A layout deck made before themes has its outlines and corners in literal px: only colours, fonts and titles change.
35
+ const before = /class="slide[^"]*\bl-[a-z]/.test(html) && !/var\(--line\)/.test(html);
36
+ // A logo moved or edited by hand is not one stripBrandLogo knows: say so rather than claim none.
37
+ const leftover = !brand && /<img\b[^>]*class="[^"]*\bbrand-logo\b/.test(out);
38
+ log(`✓ ${dir} is in ${theme.name} now, with ${how}.${leftover ? "\n ⚠ a brand logo <img class=\"brand-logo\"> is still in index.html (it was edited by hand); remove it for the theme's own look." : ""}${before ? "\n ⚠ this deck's CSS predates themes, so its outlines, corners and shadows stay as they are; make it again with deck new --theme to get the theme's shape." : ""}\n A released deck changes when you release it again (hyperdecks release ${dirArg}).`);
39
+ if (theme.transition) log(` ${theme.name} changes slides with a ${theme.transition}: set \`transition: ${theme.transition}\` in script.md's front matter to match.`);
40
+ return { dir, theme: theme.id, brand: !!brand, shapeless: before };
41
+ }