@jonandev/longbeard 0.5.2 → 0.8.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.
@@ -5,6 +5,9 @@
5
5
  // node capture.mjs <url> --out .design/refs/name.jpg
6
6
  // node capture.mjs <url> --out .design/refs/name.jpg --review /tmp/name-review.jpg
7
7
  // node capture.mjs <url> --out .design/refs/name.jpg --clip x,y,w,h
8
+ // node capture.mjs <url> --out .design/refs/name.jpg --clip-selector "main"
9
+ // node capture.mjs file:///abs/path/moodboard.html --out /tmp/moodboard.jpg
10
+ // node capture.mjs file:///abs/path/shot.jpg --out .design/refs/name.jpg --clip x,y,w,h
8
11
  import { spawn, execSync } from "node:child_process";
9
12
  import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
10
13
  import { tmpdir } from "node:os";
@@ -22,12 +25,17 @@ const url = args[0];
22
25
  const outArg = flag("out", "") || "";
23
26
  const reviewArg = flag("review", "") || "";
24
27
  const clipArg = flag("clip", "") || "";
25
- if (!url || !/^https?:\/\//.test(url) || !outArg) {
28
+ const clipSelector = flag("clip-selector", "") || "";
29
+ if (!url || !/^(https?|file):\/\//.test(url) || !outArg) {
26
30
  console.error(
27
- "usage: node capture.mjs <https://url> --out .design/refs/name.jpg [--review /tmp/name-review.jpg] [--clip x,y,w,h]",
31
+ 'usage: node capture.mjs <https://url | file:///path> --out .design/refs/name.jpg [--review /tmp/name-review.jpg] [--clip x,y,w,h | --clip-selector "css"]',
28
32
  );
29
33
  process.exit(2);
30
34
  }
35
+ if (clipArg && clipSelector) {
36
+ console.error("pass --clip or --clip-selector, not both");
37
+ process.exit(2);
38
+ }
31
39
 
32
40
  function projectRoot() {
33
41
  try {
@@ -193,7 +201,14 @@ await page("Emulation.setDeviceMetricsOverride", {
193
201
  deviceScaleFactor: 1,
194
202
  mobile: false,
195
203
  });
196
- await page("Page.navigate", { url }, 40000);
204
+ // Chrome centres an image file and shrinks it to the window. A page that holds
205
+ // it at full size from 0,0 makes --clip x,y,w,h the image's own pixels.
206
+ let target = url;
207
+ if (/^file:\/\/.*\.(png|jpe?g|webp|gif)$/i.test(url)) {
208
+ target = `file://${join(dir, "image.html")}`;
209
+ writeFileSync(join(dir, "image.html"), `<!doctype html><body style="margin:0;background:#000"><img src="${url.replace(/"/g, "%22")}" style="display:block">`);
210
+ }
211
+ await page("Page.navigate", { url: target }, 40000);
197
212
  await sleep(2500);
198
213
 
199
214
  const beforeHref = (
@@ -295,25 +310,59 @@ await page("Runtime.evaluate", {
295
310
  });
296
311
  await sleep(400);
297
312
 
313
+ // --clip-selector takes the element's box in document coordinates, measured
314
+ // after the unstick pass so the numbers match what the capture sees.
315
+ let selected = null;
316
+ if (clipSelector) {
317
+ const { result } = await page("Runtime.evaluate", {
318
+ expression: `(() => {
319
+ const el = document.querySelector(${JSON.stringify(clipSelector)});
320
+ if (!el) return null;
321
+ const r = el.getBoundingClientRect();
322
+ return {
323
+ x: Math.max(0, Math.round(r.left + window.scrollX)),
324
+ y: Math.max(0, Math.round(r.top + window.scrollY)),
325
+ width: Math.round(r.width),
326
+ height: Math.round(r.height),
327
+ };
328
+ })()`,
329
+ returnByValue: true,
330
+ });
331
+ selected = result?.value || null;
332
+ if (!selected) {
333
+ console.error(`no element matches ${clipSelector}`);
334
+ drop();
335
+ process.exit(1);
336
+ }
337
+ if (selected.width < 1 || selected.height < 1) {
338
+ console.error(`${clipSelector} has no box (width ${selected.width}, height ${selected.height})`);
339
+ drop();
340
+ process.exit(1);
341
+ }
342
+ }
343
+
298
344
  const metrics = await page("Page.getLayoutMetrics");
299
345
  const size = metrics.cssContentSize || metrics.contentSize;
300
346
  const fullWidth = Math.max(1, Math.ceil(size.width || 1440));
301
347
  const fullHeight = Math.max(1, Math.min(Math.ceil(size.height || 900), 14000));
302
- const shotClip = clip
348
+ const clipBox = clip || (selected ? { ...selected, scale: 1 } : null);
349
+ const shotClip = clipBox
303
350
  ? {
304
- x: Math.min(clip.x, fullWidth - 1),
305
- y: Math.min(clip.y, fullHeight - 1),
306
- width: Math.min(clip.width, fullWidth - Math.min(clip.x, fullWidth - 1)),
307
- height: Math.min(clip.height, fullHeight - Math.min(clip.y, fullHeight - 1)),
351
+ x: Math.min(clipBox.x, fullWidth - 1),
352
+ y: Math.min(clipBox.y, fullHeight - 1),
353
+ width: Math.min(clipBox.width, fullWidth - Math.min(clipBox.x, fullWidth - 1)),
354
+ height: Math.min(clipBox.height, fullHeight - Math.min(clipBox.y, fullHeight - 1)),
308
355
  scale: 1,
309
356
  }
310
357
  : { x: 0, y: 0, width: fullWidth, height: fullHeight, scale: 1 };
311
358
 
359
+ // The file is what its name says, so a reader that trusts the extension is right.
360
+ const format = /\.png$/i.test(out) ? "png" : /\.webp$/i.test(out) ? "webp" : "jpeg";
312
361
  const { data } = await page(
313
362
  "Page.captureScreenshot",
314
363
  {
315
- format: "jpeg",
316
- quality: 70,
364
+ format,
365
+ ...(format === "png" ? {} : { quality: 70 }),
317
366
  captureBeyondViewport: true,
318
367
  clip: shotClip,
319
368
  },
@@ -330,7 +379,7 @@ if (reviewOut) {
330
379
  const reviewHtml = `<!doctype html><meta charset=utf-8>
331
380
  <canvas id=c></canvas>
332
381
  <script>
333
- const src = "data:image/jpeg;base64,${data}";
382
+ const src = "data:image/${format};base64,${data}";
334
383
  const img = new Image();
335
384
  img.onload = () => {
336
385
  const colH = 2800;
@@ -372,7 +421,7 @@ img.src = src;
372
421
  const { data: reviewData } = await page(
373
422
  "Page.captureScreenshot",
374
423
  {
375
- format: "jpeg",
424
+ format: /\.png$/i.test(reviewOut) ? "png" : "jpeg",
376
425
  quality: 75,
377
426
  clip: { x: 0, y: 0, width: sizeResult.value.w, height: sizeResult.value.h, scale: 1 },
378
427
  captureBeyondViewport: true,
@@ -37,9 +37,10 @@ const lines = readFileSync(tsvPath, "utf8")
37
37
  .map((l) => l.trim())
38
38
  .filter(Boolean)
39
39
  .map((l) => {
40
- const tab = l.indexOf("\t");
41
- if (tab === -1) return { label: l, url: l };
42
- return { label: l.slice(0, tab).trim(), url: l.slice(tab + 1).trim() };
40
+ // label\timageURL, and any columns after that (a listing URL) are ignored.
41
+ const cols = l.split("\t").map((c) => c.trim());
42
+ if (cols.length === 1) return { label: l, url: l };
43
+ return { label: cols[0], url: cols[1] };
43
44
  })
44
45
  .filter((r) => /^https?:\/\//i.test(r.url));
45
46
 
@@ -1,8 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
  // List Dribbble search/popular cards from a listing URL.
3
- // Headless Chrome; prints TSV: id-slug\tviews\timageURL\ttitle
3
+ // Headless Chrome; prints TSV: id-slug\tlikes\tviews\timageURL\ttitle
4
+ // Counts come from the card's own stat elements. A column it cannot read
5
+ // stays empty. It never guesses a count from the title.
6
+ //
7
+ // Off-topic cards (merch, resumes, worksheets, posters) are dropped by slug
8
+ // and title before anything is fetched, and the noise rate goes to stderr.
4
9
  //
5
10
  // node dribbble-cards.mjs "https://dribbble.com/search/shots/popular/product-design?q=writing+app&timeframe=year" --scrolls 4
11
+ // node dribbble-cards.mjs "<url>" --drop "mood,habit" --keep "font,illustration"
6
12
  import { spawn } from "node:child_process";
7
13
  import { existsSync, mkdtempSync, rmSync } from "node:fs";
8
14
  import { tmpdir } from "node:os";
@@ -16,15 +22,52 @@ const flag = (name, def) => {
16
22
  args.splice(i, 2);
17
23
  return v;
18
24
  };
25
+ const has = (name) => {
26
+ const i = args.indexOf(`--${name}`);
27
+ if (i === -1) return false;
28
+ args.splice(i, 1);
29
+ return true;
30
+ };
19
31
  const url = args[0];
20
32
  const scrolls = Math.max(0, Number(flag("scrolls", "3")) || 3);
33
+ const noFilter = has("no-filter");
34
+ const words = (s) =>
35
+ String(s || "")
36
+ .toLowerCase()
37
+ .split(",")
38
+ .map((w) => w.trim())
39
+ .filter(Boolean);
40
+ // The shared negative list. These sell the word, not the form: a search for
41
+ // "writing app" returns tees, CV services and tracing worksheets.
42
+ const OFF_TOPIC = [
43
+ "t-shirt", "tshirt", "tee", "merch", "apparel", "hoodie",
44
+ "resume", "cv", "cover letter", "essay",
45
+ "worksheet", "tracing", "handwriting practice", "alphabet",
46
+ "halloween", "christmas", "valentine",
47
+ "logo", "logotype", "branding", "brand identity", "packaging",
48
+ "poster", "book cover", "sticker", "mockup",
49
+ "chatbot", "mood tracker", "habit tracker",
50
+ // "Editor" on Dribbble is mostly code, video, and photo tools and AI products.
51
+ "video editor", "photo editor", "code editor", "ide",
52
+ "agent", "assistant", "copilot", "generator",
53
+ "dashboard", "saas", "crm",
54
+ ];
55
+ const keep = words(flag("keep", ""));
56
+ const dropWords = [...OFF_TOPIC.filter((w) => !keep.includes(w)), ...words(flag("drop", ""))];
21
57
  if (!url || !/^https?:\/\/(www\.)?dribbble\.com\//i.test(url)) {
22
58
  console.error(
23
- 'usage: node dribbble-cards.mjs "https://dribbble.com/search/..." [--scrolls 4]',
59
+ 'usage: node dribbble-cards.mjs "https://dribbble.com/search/..." [--scrolls 4] [--drop "a,b"] [--keep "a,b"] [--no-filter]',
24
60
  );
25
61
  process.exit(2);
26
62
  }
27
63
 
64
+ // Whole words only, so "ai" does not swallow "detail" and "cv" does not
65
+ // swallow "cvs". A hyphen in a slug counts as a space.
66
+ function offTopic(text) {
67
+ const hay = ` ${String(text).toLowerCase().replace(/[^a-z0-9]+/g, " ").trim()} `;
68
+ return dropWords.find((word) => hay.includes(` ${word.replace(/[^a-z0-9]+/g, " ")} `)) || "";
69
+ }
70
+
28
71
  function findChrome() {
29
72
  const env = process.env.CHROME_PATH;
30
73
  if (env && existsSync(env)) return env;
@@ -169,6 +212,38 @@ const { result } = await page("Runtime.evaluate", {
169
212
  expression: `(() => {
170
213
  const rows = [];
171
214
  const seen = new Set();
215
+ const tidy = (t) => (t || "").replace(/\\s+/g, "");
216
+ const isCount = (t) => /^[\\d][\\d.,]*[kKmM]?$/.test(t);
217
+ const hints = (el) =>
218
+ ["aria-label", "title", "class", "data-type", "data-test"]
219
+ .map((name) => el.getAttribute(name) || "")
220
+ .join(" ");
221
+ // A counter labelled as likes or views: its own text, or the one
222
+ // descendant that is nothing but a count.
223
+ const labelled = (li, word) => {
224
+ const re = new RegExp(word, "i");
225
+ for (const el of li.querySelectorAll("*")) {
226
+ if (!re.test(hints(el))) continue;
227
+ const own = tidy(el.textContent);
228
+ if (isCount(own)) return own;
229
+ for (const kid of el.querySelectorAll("*")) {
230
+ const t = tidy(kid.textContent);
231
+ if (isCount(t)) return t;
232
+ }
233
+ }
234
+ return "";
235
+ };
236
+ // Fallback: leaf elements whose whole text is a count, in DOM order.
237
+ // Dribbble prints likes first, then views. Free text is never read.
238
+ const leafCounts = (li) => {
239
+ const out = [];
240
+ for (const el of li.querySelectorAll("*")) {
241
+ if (el.children.length) continue;
242
+ const t = tidy(el.textContent);
243
+ if (isCount(t)) out.push(t);
244
+ }
245
+ return out;
246
+ };
172
247
  for (const li of document.querySelectorAll("li")) {
173
248
  const a = li.querySelector('a[href*="/shots/"]');
174
249
  if (!a) continue;
@@ -182,11 +257,15 @@ const { result } = await page("Runtime.evaluate", {
182
257
  const imageURL = raw.replace(/\\?.*$/, "");
183
258
  if (!imageURL) continue;
184
259
  seen.add(idSlug);
185
- const text = (li.innerText || "").replace(/\\s+/g, " ");
186
- const vm = text.match(/([\\d.]+\\s*[kKmM]?)\\s*views?/i) || text.match(/([\\d.]+\\s*[kKmM]?)/);
187
- const views = vm ? vm[1].replace(/\\s+/g, "") : "";
260
+ let likes = labelled(li, "like");
261
+ let views = labelled(li, "view");
262
+ if (!likes && !views) {
263
+ const counts = leafCounts(li);
264
+ likes = counts[0] || "";
265
+ views = counts[1] || "";
266
+ }
188
267
  const title = (img.getAttribute("alt") || a.getAttribute("title") || idSlug).replace(/\\t/g, " ").trim();
189
- rows.push([idSlug, views, imageURL, title].join("\\t"));
268
+ rows.push([idSlug, likes, views, imageURL, title].join("\\t"));
190
269
  }
191
270
  return rows.join("\\n");
192
271
  })()`,
@@ -195,10 +274,42 @@ const { result } = await page("Runtime.evaluate", {
195
274
 
196
275
  const tsv = result?.value || "";
197
276
  if (!tsv.trim()) {
198
- console.error("0 cards (empty listing or rate limit — retry once after a pause)");
277
+ console.error(
278
+ "0 cards (empty listing or rate limit — retry after 8s, then after 30s; if it is still 0, record it under the board's drops as `<query>: 0 cards (rate limit?)`)",
279
+ );
280
+ drop();
281
+ process.exit(1);
282
+ }
283
+
284
+ const all = tsv.split("\n").filter(Boolean);
285
+ const reasons = new Map();
286
+ const kept = noFilter
287
+ ? all
288
+ : all.filter((row) => {
289
+ const [idSlug, , , , title = ""] = row.split("\t");
290
+ const word = offTopic(`${idSlug} ${title}`);
291
+ if (!word) return true;
292
+ reasons.set(word, (reasons.get(word) ?? 0) + 1);
293
+ return false;
294
+ });
295
+ const cut = all.length - kept.length;
296
+ if (cut > 0) {
297
+ const top = [...reasons.entries()]
298
+ .sort((a, b) => b[1] - a[1])
299
+ .slice(0, 6)
300
+ .map(([word, n]) => `${word} ${n}`)
301
+ .join(", ");
302
+ // The noise rate belongs under the board's drops. A high one means the
303
+ // query is wrong, not that there is more scrolling to do.
304
+ console.error(
305
+ `${kept.length} of ${all.length} cards kept, ${Math.round((cut / all.length) * 100)}% off-topic (${top})`,
306
+ );
307
+ }
308
+ if (!kept.length) {
309
+ console.error("every card was off-topic — query the form, not the word (add \"ui\", \"screen\", or a category path)");
199
310
  drop();
200
311
  process.exit(1);
201
312
  }
202
- console.log(tsv);
313
+ console.log(kept.join("\n"));
203
314
  drop();
204
315
  process.exit(0);