@jonandev/longbeard 0.11.2 → 0.12.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.
Files changed (93) hide show
  1. package/AGENTS.md +3 -4
  2. package/CHANGELOG.md +67 -0
  3. package/README.md +63 -43
  4. package/beard.json +113 -26
  5. package/bin/long-beard.js +172 -36
  6. package/package.json +1 -1
  7. package/skills/design/SKILL.md +51 -126
  8. package/skills/design-brief/SKILL.md +146 -0
  9. package/skills/design-brief/references/graphic.md +59 -0
  10. package/skills/design-check/SKILL.md +27 -11
  11. package/skills/design-check/references/design-rules.md +21 -7
  12. package/skills/design-check/scripts/capture.mjs +121 -37
  13. package/skills/design-check/scripts/contrast.mjs +23 -9
  14. package/skills/design-check/scripts/rules.mjs +613 -0
  15. package/skills/design-check/scripts/screen-contrast.mjs +428 -0
  16. package/skills/design-check/scripts/tokens.mjs +346 -0
  17. package/skills/design-content/SKILL.md +118 -0
  18. package/skills/design-content/scripts/contact-sheet.mjs +259 -0
  19. package/skills/design-content/scripts/pictures.mjs +197 -0
  20. package/skills/design-direction/SKILL.md +115 -200
  21. package/skills/design-direction/references/controls.md +58 -0
  22. package/skills/{design → design-direction}/references/design-rules.md +21 -7
  23. package/skills/design-direction/references/five-second.md +47 -0
  24. package/skills/design-direction/references/full-build.md +19 -0
  25. package/skills/design-direction/references/graphic.md +35 -0
  26. package/skills/design-direction/references/grid.md +114 -0
  27. package/skills/design-direction/references/library.md +75 -0
  28. package/skills/design-direction/references/screen-template.html +233 -0
  29. package/skills/design-direction/references/subject.md +33 -0
  30. package/skills/design-direction/scripts/capture.mjs +121 -37
  31. package/skills/design-direction/scripts/contact-sheet.mjs +18 -7
  32. package/skills/design-direction/scripts/fonts.mjs +276 -0
  33. package/skills/design-direction/scripts/layout-diff.mjs +118 -0
  34. package/skills/design-direction/scripts/measure.mjs +1728 -0
  35. package/skills/design-direction/scripts/moodboard.mjs +123 -32
  36. package/skills/design-direction/scripts/picture-cast.mjs +270 -0
  37. package/skills/design-direction/scripts/pictures.mjs +197 -0
  38. package/skills/design-direction/scripts/screen-contrast.mjs +428 -0
  39. package/skills/design-direction/scripts/sheet.mjs +67 -0
  40. package/skills/design-direction/scripts/subject-colours.mjs +410 -0
  41. package/skills/design-families/SKILL.md +138 -0
  42. package/skills/design-families/scripts/contact-sheet.mjs +259 -0
  43. package/skills/design-families/scripts/families.mjs +606 -0
  44. package/skills/design-families/scripts/measure.mjs +1728 -0
  45. package/skills/design-families/scripts/moodboard.mjs +467 -0
  46. package/skills/design-families/scripts/tag.mjs +289 -0
  47. package/skills/design-figma/SKILL.md +69 -0
  48. package/skills/design-figma/references/graphic.md +26 -0
  49. package/skills/design-identity/SKILL.md +134 -0
  50. package/skills/design-identity/references/graphic.md +8 -0
  51. package/skills/design-identity/references/identity-board.html +140 -0
  52. package/skills/{design → design-identity}/scripts/capture.mjs +121 -37
  53. package/skills/design-identity/scripts/colours.mjs +213 -0
  54. package/skills/design-identity/scripts/contrast.mjs +41 -0
  55. package/skills/design-identity/scripts/fonts.mjs +276 -0
  56. package/skills/design-identity/scripts/measure.mjs +1728 -0
  57. package/skills/design-identity/scripts/sheet.mjs +67 -0
  58. package/skills/design-identity/scripts/subject-colours.mjs +410 -0
  59. package/skills/design-moodboard/SKILL.md +184 -0
  60. package/skills/design-moodboard/references/graphic.md +25 -0
  61. package/skills/{design-direction → design-moodboard}/references/sources.md +17 -11
  62. package/skills/design-moodboard/scripts/capture.mjs +893 -0
  63. package/skills/design-moodboard/scripts/contact-sheet.mjs +259 -0
  64. package/skills/design-moodboard/scripts/crops.mjs +256 -0
  65. package/skills/design-moodboard/scripts/dribbble-cards.mjs +418 -0
  66. package/skills/design-moodboard/scripts/families.mjs +606 -0
  67. package/skills/design-moodboard/scripts/group.mjs +221 -0
  68. package/skills/design-moodboard/scripts/measure.mjs +1728 -0
  69. package/skills/design-moodboard/scripts/moodboard.mjs +467 -0
  70. package/skills/{design-direction → design-moodboard}/scripts/picker.mjs +121 -20
  71. package/skills/design-moodboard/scripts/pictures.mjs +197 -0
  72. package/skills/design-moodboard/scripts/tag.mjs +289 -0
  73. package/skills/design-prototype/SKILL.md +149 -0
  74. package/skills/design-prototype/references/design-md-template.md +82 -0
  75. package/skills/design-prototype/references/design-rules.md +203 -0
  76. package/skills/design-prototype/references/five-second.md +47 -0
  77. package/skills/design-prototype/references/graphic.md +27 -0
  78. package/skills/design-prototype/scripts/capture.mjs +893 -0
  79. package/skills/design-prototype/scripts/contrast.mjs +41 -0
  80. package/skills/design-prototype/scripts/links.mjs +308 -0
  81. package/skills/design-prototype/scripts/pictures.mjs +197 -0
  82. package/skills/design-prototype/scripts/rules.mjs +613 -0
  83. package/skills/design-prototype/scripts/screen-contrast.mjs +428 -0
  84. package/skills/design-prototype/scripts/sheet.mjs +67 -0
  85. package/skills/design-prototype/scripts/tokens.mjs +346 -0
  86. package/skills/design-wordmark/SKILL.md +65 -0
  87. package/skills/design-wordmark/scripts/capture.mjs +893 -0
  88. package/skills/design-wordmark/scripts/sheet.mjs +67 -0
  89. package/skills/idea/SKILL.md +13 -7
  90. package/skills/idea/references/graphic.md +64 -0
  91. package/skills/design/references/design-md-template.md +0 -58
  92. package/skills/design/scripts/contrast.mjs +0 -27
  93. package/skills/design-direction/scripts/dribbble-cards.mjs +0 -356
@@ -2,17 +2,27 @@
2
2
  // A picker: a wide pool of candidates from any source, as one page where the
3
3
  // person marks each like or no. It hotlinks each listing's own thumbnail and
4
4
  // saves nothing, so it is a view, not a capture. Their picks come back as
5
- // text they copy into the chat.
5
+ // text they copy into the chat. A liked tile opens a small note, "what you like
6
+ // in it, and why", kept with the mark and copied out beside that pick; no note
7
+ // is fine, and a no needs none.
6
8
  //
7
9
  // The TSV has one row per candidate: title, image, link, source, meta (a
8
10
  // short line such as the designer and likes). Columns after the image may be
9
- // empty. A line starting with # is a comment. Each
10
- // row's id is the round letter and its row number (a1, a2…, b1… in round 2),
11
- // so a pick maps to its line in the TSV. A row with source "seed" starts
12
- // liked; its image may be a path in the project instead of a URL.
11
+ // empty. A line starting with # and holding no tab is a comment: a row always
12
+ // has a tab, since it needs an image, so a title that starts with # is still
13
+ // a row. Each row's id is the round letter and its row number among the rows
14
+ // (a1, a2…, b1… in round 2), so a pick maps to its line in the TSV. A row with
15
+ // source "seed" starts liked; its image may be a path in the project instead
16
+ // of a URL. A row it cannot show is skipped, and stderr says how many and why.
13
17
  //
14
- // node picker.mjs design-exploration/identity/candidates.tsv --out design-exploration/identity/picker.html
15
- // node picker.mjs design-exploration/identity/candidates-2.tsv --round 2 --out design-exploration/identity/picker-2.html
18
+ // --families families.json (from group.mjs) shows the tiles in groups, each
19
+ // headed by its name and size, the biggest first. A row in no group follows,
20
+ // last. Ids and marks are the same with or without it, and without it the
21
+ // page is one grid, as before.
22
+ //
23
+ // node picker.mjs .longbeard/design/moodboard/candidates.tsv --out .longbeard/design/moodboard/picker.html
24
+ // node picker.mjs .longbeard/design/moodboard/candidates.tsv --families .longbeard/design/moodboard/families.json --out .longbeard/design/moodboard/picker.html
25
+ // node picker.mjs .longbeard/design/moodboard/candidates-2.tsv --round 2 --out .longbeard/design/moodboard/picker-2.html
16
26
  import { execSync } from "node:child_process";
17
27
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
18
28
  import { dirname, isAbsolute, relative, resolve } from "node:path";
@@ -24,11 +34,12 @@ const flag = (name) => {
24
34
  };
25
35
  const outArg = flag("out");
26
36
  const roundArg = flag("round") || "1";
37
+ const familiesArg = flag("families");
27
38
  const round = Number(roundArg);
28
39
  const tsvArg = args[0];
29
40
  if (!tsvArg || !outArg || args.length !== 1 || !Number.isInteger(round) || round < 1 || round > 26) {
30
41
  console.error(
31
- "usage: node picker.mjs design-exploration/<slug>/candidates.tsv --out design-exploration/<slug>/picker.html [--round 2]",
42
+ "usage: node picker.mjs .longbeard/design/<step>/candidates.tsv --out .longbeard/design/<step>/picker.html [--round 2] [--families families.json]",
32
43
  );
33
44
  process.exit(2);
34
45
  }
@@ -61,12 +72,37 @@ const esc = (s) =>
61
72
  .replace(/'/g, "&#39;");
62
73
  const isUrl = (s) => /^https?:\/\//i.test(s);
63
74
 
75
+ // A local path in a src: each part encoded, so # ? % and spaces stay in the name.
76
+ const urlPath = (path) => path.split("/").map(encodeURIComponent).join("/");
77
+
78
+ let comments = 0;
64
79
  const rows = readFileSync(tsvPath, "utf8")
65
80
  .split(/\r?\n/)
66
- .filter((l) => l.trim() && !l.trimStart().startsWith("#"));
81
+ .filter((l) => {
82
+ if (!l.trim()) return false;
83
+ if (l.trimStart().startsWith("#") && !l.includes("\t")) {
84
+ comments++;
85
+ return false;
86
+ }
87
+ return true;
88
+ });
89
+
90
+ let groups = null;
91
+ if (familiesArg) {
92
+ try {
93
+ groups = JSON.parse(readFileSync(resolvePath(familiesArg), "utf8")).families;
94
+ if (!Array.isArray(groups)) throw new Error("no families list");
95
+ } catch (error) {
96
+ console.error(`picker: cannot read families at ${familiesArg}: ${error.message}`);
97
+ process.exit(1);
98
+ }
99
+ }
67
100
 
68
101
  const tiles = [];
102
+ const tileById = new Map();
69
103
  const seenImages = new Set();
104
+ const skipped = new Map();
105
+ const skip = (why) => skipped.set(why, (skipped.get(why) ?? 0) + 1);
70
106
  rows.forEach((line, i) => {
71
107
  const id = `${letter}${i + 1}`;
72
108
  const [title = "", image = "", link = "", source = "", meta = ""] = line.split("\t").map((c) => c.trim());
@@ -75,13 +111,15 @@ rows.forEach((line, i) => {
75
111
  const abs = image ? resolvePath(image) : "";
76
112
  if (!abs || !existsSync(abs)) {
77
113
  console.error(`picker: ${id} has no image (${image || "empty"}), skipped`);
114
+ skip("no image");
78
115
  return;
79
116
  }
80
- src = relative(dirname(outPath), abs).split("\\").join("/");
117
+ src = urlPath(relative(dirname(outPath), abs).split("\\").join("/"));
81
118
  if (!src.startsWith(".")) src = `./${src}`;
82
119
  }
83
120
  if (seenImages.has(src)) {
84
121
  console.error(`picker: ${id} repeats an earlier image, skipped`);
122
+ skip("repeats an earlier image");
85
123
  return;
86
124
  }
87
125
  seenImages.add(src);
@@ -92,14 +130,17 @@ rows.forEach((line, i) => {
92
130
  ? `<a class="name" href="${esc(link)}" title="${esc(name)}" target="_blank" rel="noopener noreferrer">${esc(name)}</a>`
93
131
  : `<span class="name" title="${esc(name)}">${esc(name)}</span>`) +
94
132
  (meta ? `<span class="meta">${esc(meta)}</span>` : "");
95
- tiles.push(`<figure class="tile" data-id="${esc(id)}" data-title="${esc(name)}"${seed ? ' data-seed="1"' : ""}>
133
+ const tile = `<figure class="tile" data-id="${esc(id)}" data-title="${esc(name)}"${seed ? ' data-seed="1"' : ""}>
96
134
  <button type="button" class="frame" aria-pressed="false" aria-label="${esc(`${id} ${name}: mark like, no, or clear`)}">
97
135
  <img src="${esc(src)}" alt="" loading="lazy" referrerpolicy="no-referrer">
98
136
  <span class="id">${esc(id)}</span>${source ? `<span class="src">${esc(source)}</span>` : ""}
99
137
  <span class="mark"></span>
100
138
  </button>
101
139
  <figcaption>${caption}</figcaption>
102
- </figure>`);
140
+ <input class="why" type="text" placeholder="What you like in it, and why (optional)" aria-label="${esc(`${id} ${name}: what you like in it, and why`)}">
141
+ </figure>`;
142
+ tiles.push(tile);
143
+ tileById.set(id, tile);
103
144
  });
104
145
 
105
146
  if (!tiles.length) {
@@ -107,6 +148,48 @@ if (!tiles.length) {
107
148
  process.exit(1);
108
149
  }
109
150
 
151
+ // Without groups, one grid. With them, a section per family, each tile once.
152
+ const grid = (list) => `<div class="grid">
153
+ ${list.join("\n ")}
154
+ </div>`;
155
+ let body = grid(tiles);
156
+ if (groups) {
157
+ const placed = new Set();
158
+ const sections = [];
159
+ const section = (title, ids, stray) => {
160
+ const own = ids.filter((id) => tileById.has(id) && !placed.has(id));
161
+ own.forEach((id) => placed.add(id));
162
+ if (own.length) sections.push(`<section class="group"${stray ? ' data-stray="1"' : ""}>
163
+ <h2>${esc(title)} <span class="n">${own.length}</span> <span class="liked"></span></h2>
164
+ ${grid(own.map((id) => tileById.get(id)))}
165
+ </section>`);
166
+ };
167
+ let k = 0;
168
+ for (const g of groups) {
169
+ if (g.stray) section("Unlike the rest", g.members || [], true);
170
+ else section(String(g.name || "").trim() || `Group ${++k}`, g.members || [], false);
171
+ }
172
+ const rest = [...tileById.keys()].filter((id) => !placed.has(id));
173
+ if (rest.length) {
174
+ section("Not grouped", rest, true);
175
+ console.error(`picker: ${rest.length} rows are in no group`);
176
+ }
177
+ body = sections.join("\n ");
178
+ }
179
+
180
+ const groupCss = ` .group { margin: 0 0 32px; }
181
+ .group h2 { margin: 0 0 12px 2px; font-size: 15px; font-weight: 600; }
182
+ .group h2 .n, .group h2 .liked { font-size: 12px; font-weight: 500; color: var(--muted); margin-left: 6px; }
183
+ .group[hidden] { display: none; }
184
+ `;
185
+ const groupJs = ` for (const g of document.querySelectorAll(".group")) {
186
+ const own = [...g.querySelectorAll(".tile")];
187
+ g.hidden = own.every((t) => t.hidden);
188
+ const n = own.filter((t) => t.dataset.state === "like").length;
189
+ g.querySelector(".liked").textContent = n ? "· " + n + " liked" : "";
190
+ }
191
+ `;
192
+
110
193
  const html = `<!DOCTYPE html>
111
194
  <html lang="en">
112
195
  <head>
@@ -124,11 +207,14 @@ const html = `<!DOCTYPE html>
124
207
  .filters { margin: 0 0 18px 2px; display: flex; gap: 8px; }
125
208
  .filters button { font: inherit; font-size: 13px; padding: 6px 12px; border-radius: 999px; border: 1px solid #c8c8c4; background: var(--paper); color: var(--ink); cursor: pointer; }
126
209
  .filters button[aria-pressed="true"] { background: var(--ink); color: var(--paper); border-color: var(--ink); }
127
- .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 16px; }
210
+ ${groups ? groupCss : ""} .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 16px; }
128
211
  .tile { margin: 0; display: flex; flex-direction: column; background: var(--paper); border-radius: 16px; overflow: hidden; outline: 3px solid transparent; outline-offset: -3px; }
129
212
  .tile[data-state="like"] { outline-color: var(--like); }
130
213
  .tile[data-state="no"] .frame img { opacity: 0.3; filter: grayscale(1); }
131
214
  .tile[hidden] { display: none; }
215
+ .why { display: none; margin: 0 12px 12px; font: inherit; font-size: 13px; padding: 7px 9px; border: 1px solid #c8c8c4; border-radius: 8px; }
216
+ .tile[data-state="like"] .why { display: block; }
217
+ .why:focus-visible { outline: 3px solid #2f6fdb; outline-offset: 2px; }
132
218
  .frame { position: relative; display: block; width: 100%; aspect-ratio: 4 / 3; padding: 0; border: 0; overflow: hidden; background: #141414; cursor: pointer; }
133
219
  .frame:focus-visible { outline: 3px solid #2f6fdb; outline-offset: -3px; }
134
220
  .frame img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
@@ -160,16 +246,14 @@ const html = `<!DOCTYPE html>
160
246
  <body>
161
247
  <main>
162
248
  <h1>Pick, round ${round}</h1>
163
- <p class="how">Click a picture: once for like, twice for no, three times to clear. Leave anything you have no view on. The name opens the source.</p>
249
+ <p class="how">Click a picture: once for like, twice for no, three times to clear. A liked picture opens a note: say what you like in it, and why, if you can. Leave anything you have no view on. The name opens the source.</p>
164
250
  <div class="filters" role="group" aria-label="Show">
165
251
  <button type="button" data-show="all" aria-pressed="true">All</button>
166
252
  <button type="button" data-show="open" aria-pressed="false">Not marked</button>
167
253
  <button type="button" data-show="like" aria-pressed="false">Likes</button>
168
254
  <button type="button" data-show="no" aria-pressed="false">Noes</button>
169
255
  </div>
170
- <div class="grid">
171
- ${tiles.join("\n ")}
172
- </div>
256
+ ${body}
173
257
  </main>
174
258
  <div class="bar">
175
259
  <div class="bar-in">
@@ -188,6 +272,7 @@ const html = `<!DOCTYPE html>
188
272
  let saved = {};
189
273
  try { saved = JSON.parse(localStorage.getItem(key) || "{}"); } catch (e) { saved = {}; }
190
274
  const states = saved.states || {};
275
+ const whys = saved.whys || {};
191
276
  note.value = saved.note || "";
192
277
  // A mark is saved with its title, so a row dropped and the page rebuilt
193
278
  // never moves a mark onto another picture. A cleared seed stays cleared.
@@ -195,14 +280,22 @@ const html = `<!DOCTYPE html>
195
280
  for (const t of tiles) {
196
281
  const s = tag(t) in states ? states[tag(t)] : t.dataset.seed ? "like" : "";
197
282
  if (s) t.dataset.state = s;
283
+ t.querySelector(".why").value = whys[tag(t)] || "";
198
284
  }
199
285
  let show = "all";
200
286
  const short = (s) => (s.length > 48 ? s.slice(0, 47) + "…" : s);
287
+ const why = (t) => t.querySelector(".why").value.trim().replace(/\\s+/g, " ");
201
288
  const list = (state) => tiles.filter((t) => t.dataset.state === state).map((t) => t.dataset.id + " " + short(t.dataset.title));
202
289
  function render() {
203
290
  const like = list("like");
204
291
  const no = list("no");
205
- const lines = ["Picks, round ${round} (${letter})", "like: " + (like.join("; ") || "none"), "no: " + (no.join("; ") || "none")];
292
+ const said = tiles.filter((t) => t.dataset.state === "like" && why(t));
293
+ const lines = ["Picks, round ${round} (${letter})", "like: " + (like.join("; ") || "none")];
294
+ if (said.length) {
295
+ lines.push("like, in their words:");
296
+ for (const t of said) lines.push("- " + t.dataset.id + " " + short(t.dataset.title) + ": " + why(t));
297
+ }
298
+ lines.push("no: " + (no.join("; ") || "none"));
206
299
  if (note.value.trim()) lines.push("note: " + note.value.trim().replace(/\\s+/g, " "));
207
300
  out.value = lines.join("\\n");
208
301
  count.textContent = like.length + " like · " + no.length + " no · " + tiles.length + " shown";
@@ -211,9 +304,11 @@ const html = `<!DOCTYPE html>
211
304
  t.querySelector(".frame").setAttribute("aria-pressed", s ? "true" : "false");
212
305
  t.hidden = !(show === "all" || (show === "open" ? !s : s === show));
213
306
  }
214
- const keep = {};
307
+ ${groups ? groupJs : ""} const keep = {};
215
308
  for (const t of tiles) if (t.dataset.state || t.dataset.seed) keep[tag(t)] = t.dataset.state || "";
216
- try { localStorage.setItem(key, JSON.stringify({ states: keep, note: note.value })); } catch (e) {}
309
+ const keepWhys = {};
310
+ for (const t of tiles) if (why(t)) keepWhys[tag(t)] = t.querySelector(".why").value;
311
+ try { localStorage.setItem(key, JSON.stringify({ states: keep, whys: keepWhys, note: note.value })); } catch (e) {}
217
312
  }
218
313
  const next = { "": "like", like: "no", no: "" };
219
314
  for (const t of tiles) {
@@ -231,6 +326,7 @@ const html = `<!DOCTYPE html>
231
326
  });
232
327
  }
233
328
  note.addEventListener("input", render);
329
+ for (const t of tiles) t.querySelector(".why").addEventListener("input", render);
234
330
  // The text box is the real path: the clipboard API can be refused on a file:// page.
235
331
  document.getElementById("copy").addEventListener("click", async (e) => {
236
332
  out.focus();
@@ -251,4 +347,9 @@ const html = `<!DOCTYPE html>
251
347
  mkdirSync(dirname(outPath), { recursive: true });
252
348
  writeFileSync(outPath, html);
253
349
  console.error(`picker: ${tiles.length} of ${rows.length} rows, ids ${letter}1–${letter}${rows.length}`);
350
+ if (skipped.size) {
351
+ const why = [...skipped].map(([reason, n]) => `${n} ${reason}`).join(", ");
352
+ console.error(`picker: ${rows.length - tiles.length} rows skipped: ${why}`);
353
+ }
354
+ if (comments) console.error(`picker: ${comments} comment line${comments === 1 ? "" : "s"} ignored`);
254
355
  console.log(outArg);
@@ -0,0 +1,197 @@
1
+ #!/usr/bin/env node
2
+ // A few clearly licensed pictures of the product's own subject, from Wikimedia Commons, to design
3
+ // with as stand-ins until the real ones come. It is not a bulk downloader: 4 by default, 12 at most.
4
+ // Only licences that hold in every country are kept: CC0, CC BY and CC BY-SA (any version), and
5
+ // public domain marked as worldwide (read from the file's templates, as the source's own licence
6
+ // name does not tell the two kinds apart). Public domain in one country only ("PD-US", "PD-Russia"),
7
+ // NC, ND, GFDL-only, fair use, unknown, and anything the source flags as restricted or non-free
8
+ // is left out. A licence that asks for credit needs an author to credit: with none, the picture
9
+ // is left out too. Node 22+, no dependencies.
10
+ //
11
+ // node pictures.mjs "sourdough bread" --out .longbeard/design/pictures
12
+ // node pictures.mjs "flour on a wooden bench" --out .longbeard/design/pictures --count 4 --min 1200 --orientation landscape
13
+ //
14
+ // Each picture is saved 1600 wide as <name>.jpg (or .png, .webp) in --out. A picture already
15
+ // credited there is skipped, so running again adds, never duplicates. Each new one gets a row in <out>/credits.tsv:
16
+ // name, file, source, author, licence, licence link, a ready credit line, share-alike (yes or no). The
17
+ // first two columns are what contact-sheet.mjs reads; a credits.tsv from before the last three columns
18
+ // stays readable, its rows just stop at the licence.
19
+ // --count 4 (1 to 12), --min 1200 (the longer side, in pixels), --orientation landscape|portrait|square,
20
+ // --timeout 30 (seconds to wait for each request), --api <url> (the Commons endpoint: for tests)
21
+ // Search the subject, not a mood: "sourdough loaf on a board", not "cosy".
22
+ import { existsSync, mkdirSync, readFileSync, appendFileSync, writeFileSync } from "node:fs";
23
+ import { extname, join } from "node:path";
24
+
25
+ const args = process.argv.slice(2);
26
+ const flag = (name, def = "") => {
27
+ const i = args.indexOf(`--${name}`);
28
+ return i === -1 ? def : (args.splice(i, 2)[1] ?? "");
29
+ };
30
+ const fail = (text) => {
31
+ console.error(`pictures: ${text}`);
32
+ process.exit(2);
33
+ };
34
+ const api = flag("api", "https://commons.wikimedia.org/w/api.php");
35
+ const outArg = flag("out");
36
+ const count = Number(flag("count", "4"));
37
+ const min = Number(flag("min", "1200"));
38
+ const orientation = flag("orientation").toLowerCase();
39
+ const timeout = Number(flag("timeout", "30"));
40
+ const query = args.join(" ").trim();
41
+ if (!query || !outArg || !Number.isInteger(count) || count < 1 || count > 12 || !(min >= 0) || !(timeout > 0) || (orientation && !["landscape", "portrait", "square"].includes(orientation))) {
42
+ console.error(`usage: node pictures.mjs "subject" --out <dir> [--count 4] [--min 1200] [--orientation landscape|portrait|square] [--timeout 30]`);
43
+ process.exit(2);
44
+ }
45
+ const headers = { "User-Agent": "longbeard-pictures (https://github.com/jonanderdev/longbeard)" };
46
+
47
+ // Public domain is not one thing. Commons gives nearly every such file the same short name, "Public
48
+ // domain", whether it is so everywhere or only in one country (a US government photograph, a work
49
+ // old enough in the US alone), so the name cannot tell them apart; the templates on the file page
50
+ // can. A public-domain file is kept only when its page carries a template that says it holds
51
+ // everywhere: the worldwide public-domain mark, or the author's own dedication. The search asks for
52
+ // just these, so a page's list is short, and a page that shows none is left out.
53
+ const WORLDWIDE_PD_TEMPLATES = ["Cc-pd-mark-footer", "PD-self", "PD-author"];
54
+ const WORLDWIDE_PD = /^(public domain|public domain mark|pdm|pd|pd-self|pd-old|pd-old-100(-expired)?|pd-author)$/i;
55
+ // The licence as { name, link, shareAlike, credit } (credit: the licence asks for one), or
56
+ // { reason } when the picture is not one we can design with freely. templates: the names of the
57
+ // worldwide public-domain templates found on the file's page.
58
+ function licence(meta = {}, templates = []) {
59
+ const val = (k) => String(meta[k]?.value ?? "").trim();
60
+ const short = val("LicenseShortName"), code = val("License"), terms = val("UsageTerms"), link = val("LicenseUrl");
61
+ const text = `${short} ${code}`;
62
+ if (!text.trim()) return { reason: "licence" };
63
+ if (val("NonFree") && !/^(false|0|no)$/i.test(val("NonFree"))) return { reason: "restricted" };
64
+ if (val("Restrictions")) return { reason: "restricted" };
65
+ if (/\bNC\b|\bND\b|-nc\b|-nd\b|non-?commercial|no-?deriv|fair use/i.test(`${text} ${terms}`)) return { reason: "licence" };
66
+ if (/\bcc0\b|cc-zero/i.test(text)) {
67
+ return { name: "CC0", link: link || "https://creativecommons.org/publicdomain/zero/1.0/", shareAlike: false, credit: false };
68
+ }
69
+ for (const s of [short, code]) {
70
+ const m = s.match(/^cc[ -]by(?:[ -](sa))?(?:[ -](\d(?:\.\d)?))?(?:[ -]([a-z]{2,3})(?![a-z]))?/i);
71
+ if (m) {
72
+ const version = m[2] ? (m[2].includes(".") ? m[2] : `${m[2]}.0`) : "";
73
+ return {
74
+ // A ported licence keeps its country: "CC BY-SA 3.0 de".
75
+ name: `CC BY${m[1] ? "-SA" : ""}${version ? ` ${version}` : ""}${version && m[3] ? ` ${m[3].toLowerCase()}` : ""}`,
76
+ link: link || (version ? `https://creativecommons.org/licenses/${m[1] ? "by-sa" : "by"}/${version}/` : ""),
77
+ shareAlike: Boolean(m[1]), credit: true,
78
+ };
79
+ }
80
+ }
81
+ if (WORLDWIDE_PD.test(short) || (!short && WORLDWIDE_PD.test(code))) {
82
+ // The terms must not narrow it to a place or a condition, and the page must say it holds everywhere.
83
+ if (/\b(only|united states|u\.?s\.?a?\b|russia|country|countries|jurisdiction|if|except|unless)\b/i.test(terms)) return { reason: "licence" };
84
+ if (!templates.length) return { reason: "licence" };
85
+ return { name: "Public domain", link: /^https?:/i.test(link) ? link : "", shareAlike: false, credit: val("AttributionRequired") === "true" };
86
+ }
87
+ return { reason: "licence" };
88
+ }
89
+ const plain = (html) => String(html ?? "").replace(/<(\w+)[^>]*display:\s*none[^>]*>.*?<\/\1>/gis, " ").replace(/<[^>]*>/g, " ").replace(/&nbsp;/g, " ").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#0?39;/g, "'").replace(/\s+/g, " ").trim();
90
+ // An author we can credit: a name, not "unknown" or an empty field.
91
+ const usable = (author) => author && !/^(unknown|anonymous|anon|not specified|not known|n\/a|none|\?+|-+)( (author|artist|photographer|creator|source))?\.?$/i.test(author);
92
+ const name = (title) => title.replace(/^File:/i, "").replace(/\.[a-z0-9]+$/i, "").replace(/_/g, " ").trim();
93
+ const slug = (title) => name(title).toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60).replace(/-+$/, "") || "picture";
94
+
95
+ const url = new URL(api);
96
+ for (const [k, v] of Object.entries({
97
+ action: "query", format: "json", generator: "search", gsrnamespace: "6", gsrsearch: `${query} filetype:bitmap`,
98
+ gsrlimit: String(Math.min(count * 6, 50)), prop: "imageinfo|templates", iiprop: "url|size|mime|extmetadata", iiurlwidth: "1600",
99
+ tlnamespace: "10", tllimit: "500", tltemplates: WORLDWIDE_PD_TEMPLATES.map((t) => `Template:${t}`).join("|"),
100
+ })) url.searchParams.set(k, v);
101
+
102
+ let data;
103
+ try {
104
+ const res = await fetch(url, { headers, signal: AbortSignal.timeout(timeout * 1000) });
105
+ if (!res.ok) fail(`Commons answered ${res.status} for the search`);
106
+ data = await res.json();
107
+ } catch (e) {
108
+ fail(e.name === "TimeoutError" ? `Commons did not answer the search within ${timeout}s` : `could not reach Commons (${e.cause?.code ?? e.message})`);
109
+ }
110
+ if (data?.error) fail(`Commons said: ${data.error.info ?? data.error.code}`);
111
+ const pages = Object.values(data?.query?.pages ?? {}).sort((a, b) => (a.index ?? 0) - (b.index ?? 0));
112
+
113
+ const left = { licence: 0, restricted: 0, "no author": 0, "too small": 0, orientation: 0, type: 0 };
114
+ const passing = [];
115
+ for (const page of pages) {
116
+ const info = page.imageinfo?.[0];
117
+ if (!info || !["image/jpeg", "image/png", "image/webp"].includes(info.mime)) { left.type++; continue; }
118
+ const { width: w = 0, height: h = 0 } = info;
119
+ if (Math.max(w, h) < min) { left["too small"]++; continue; }
120
+ const shape = w > h * 1.1 ? "landscape" : h > w * 1.1 ? "portrait" : "square";
121
+ if (orientation && shape !== orientation) { left.orientation++; continue; }
122
+ const marks = (page.templates ?? []).map((t) => String(t.title ?? "").replace(/^Template:/i, "")).filter((t) => WORLDWIDE_PD_TEMPLATES.includes(t));
123
+ const lic = licence(info.extmetadata, marks);
124
+ if (lic.reason) { left[lic.reason]++; continue; }
125
+ const author = plain(info.extmetadata?.Artist?.value).slice(0, 200).trim();
126
+ if (lic.credit && !usable(author)) {
127
+ // A licence that asks for credit cannot be met without a name to give it to.
128
+ console.log(`left out ${name(page.title)}: ${lic.name} asks for credit and no author is given`);
129
+ left["no author"]++;
130
+ continue;
131
+ }
132
+ passing.push({ title: page.title, info, licence: lic, author: usable(author) ? author : "unknown" });
133
+ }
134
+
135
+ const why = Object.entries(left).filter(([, n]) => n).map(([k, n]) => `${n} ${k}`).join(", ");
136
+ if (!passing.length) {
137
+ console.error(`pictures: none of ${pages.length} found for "${query}" could be kept${why ? ` (left out: ${why})` : ""}. Try another query: search the subject, not a mood.`);
138
+ process.exit(1);
139
+ }
140
+
141
+ mkdirSync(outArg, { recursive: true });
142
+ const credits = join(outArg, "credits.tsv");
143
+ const HEADER = "# name\tfile\tsource\tauthor\tlicence\tlicence link\tcredit line\tshare-alike\n";
144
+ const OLD_HEADER = "# name\tfile\tsource\tauthor\tlicence\n";
145
+ if (!existsSync(credits)) writeFileSync(credits, HEADER);
146
+ else {
147
+ // A file from before the licence link: the new header over the old rows, which stay as they were.
148
+ const text = readFileSync(credits, "utf8");
149
+ if (text.startsWith(OLD_HEADER)) writeFileSync(credits, HEADER + text.slice(OLD_HEADER.length));
150
+ }
151
+ // Rows already credited: which files are taken, and which Commons pictures are already here. A
152
+ // picture is known by its source page (its name when there is none), never by its file name: two
153
+ // titles can cut down to the same name.
154
+ const rows = readFileSync(credits, "utf8").split("\n").filter((l) => l && !l.startsWith("#")).map((l) => l.split("\t"));
155
+ const listed = new Set(rows.map((r) => r[1]));
156
+ const known = new Map(rows.map((r) => [r[2] || `name:${r[0]}`, r[1]]));
157
+ const clean = (s) => String(s).replace(/[\t\r\n]+/g, " ").trim();
158
+
159
+ let kept = 0, already = 0, broken = 0, shareAlike = 0;
160
+ for (const pic of passing) {
161
+ if (kept >= count) break;
162
+ const src = pic.info.thumburl || pic.info.url;
163
+ let ext = extname(new URL(src).pathname).toLowerCase();
164
+ if (ext === ".jpeg") ext = ".jpg";
165
+ if (![".jpg", ".png", ".webp"].includes(ext)) ext = ".jpg";
166
+ const key = clean(pic.info.descriptionurl ?? "") || `name:${clean(name(pic.title))}`;
167
+ if (known.has(key) && existsSync(known.get(key))) { already++; continue; }
168
+ // A name another picture (or a file of yours) already holds gets -2, -3 …
169
+ let path = join(outArg, `${slug(pic.title)}${ext}`);
170
+ for (let i = 2; existsSync(path) || listed.has(path); i++) path = join(outArg, `${slug(pic.title)}-${i}${ext}`);
171
+ let bytes;
172
+ try {
173
+ const res = await fetch(src, { headers, signal: AbortSignal.timeout(timeout * 1000) });
174
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
175
+ bytes = Buffer.from(await res.arrayBuffer());
176
+ } catch (e) {
177
+ console.error(`pictures: could not download ${pic.title} (${e.name === "TimeoutError" ? `no answer within ${timeout}s` : e.cause?.code ?? e.message}); skipped`);
178
+ broken++;
179
+ continue;
180
+ }
181
+ writeFileSync(path, bytes);
182
+ const lic = pic.licence;
183
+ const line = `"${clean(name(pic.title))}"${pic.author === "unknown" ? "" : ` by ${clean(pic.author)}`}, ${lic.name}${lic.link ? `, ${lic.link}` : ""}`;
184
+ appendFileSync(credits, [name(pic.title), path, pic.info.descriptionurl ?? "", pic.author, lic.name, lic.link, line, lic.shareAlike ? "yes" : "no"].map(clean).join("\t") + "\n");
185
+ if (lic.shareAlike) shareAlike++;
186
+ listed.add(path);
187
+ known.set(key, path);
188
+ kept++;
189
+ console.log(`kept ${path} ${lic.name} ${pic.author}`);
190
+ }
191
+ if (broken && !kept && !already) fail(`no picture could be downloaded from Commons`);
192
+ const notes = [`${kept} kept in ${outArg}`];
193
+ if (already) notes.push(`${already} already there`);
194
+ notes.push(why ? `left out: ${why}` : "none left out");
195
+ if (broken) notes.push(`${broken} failed to download`);
196
+ console.log(`${notes.join("; ")}. Credits in ${credits}.`);
197
+ if (shareAlike) console.log(`share-alike: a cropped or toned version of ${shareAlike === 1 ? "the share-alike picture" : "a share-alike picture"} must carry the same licence. The credit lines are in ${credits}.`);