Skip to content

Curated website design inspiration gallery, open zero-auth MCP server for AI agents, and shareable moodboard lists.

5.2 KB
Raw Blame
import { readFile, writeFile, mkdir } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { join } from "node:path";
import { CATEGORIES, safeWebsite, validateSites } from "./gallery-catalog.mjs";
import {
  launchCaptureBrowser,
  captureStitchedWebsite,
  captureScrollVideo,
  detectScrollMotion,
} from "./capture-lib.mjs";

const args = process.argv.slice(2);
if (args.includes("--help") || !args.length) {
  console.log(`Capture a live website into a tall scrollable screenshot (or smooth-scroll video for scroll-motion sites) and add it to the gallery.

Usage:
  npm run site:capture -- \\
    --url https://example.com \\
    --name "Example" \\
    --category "Design tools" \\
    --description "One crisp sentence about the site." \\
    [--id example] \\
    [--observation "What stood out visually."] \\
    [--tags "Dark,Minimal,Editorial"] \\
    [--credit "Creator or brand"] \\
    [--mode auto|video|stitched] \\
    [--max-height 4200]

Categories: ${CATEGORIES.join(", ")}`);
  process.exit(0);
}

const opt = {};
for (let i = 0; i < args.length; i += 2) {
  if (!args[i].startsWith("--") || args[i + 1] === undefined) {
    throw new Error("Expected --flag value pairs.");
  }
  opt[args[i].slice(2)] = args[i + 1];
}

const parsed = safeWebsite(opt.url || "");
const host = parsed.hostname.replace(/^www\./, "");
const id = (
  opt.id ||
  (opt.name || host.split(".")[0])
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-|-$/g, "")
).slice(0, 80);

if (!opt.name) throw new Error("Missing --name");
if (!CATEGORIES.includes(opt.category)) {
  throw new Error(`Invalid --category. Choose one of: ${CATEGORIES.join(", ")}`);
}

const root = fileURLToPath(new URL("../apps/gallery/", import.meta.url));
const catalogPath = join(root, "sites.json");
const sites = JSON.parse(await readFile(catalogPath, "utf8"));

const normalizedUrl =
  parsed.hostname.replace(/^www\./, "") +
  parsed.pathname.replace(/\/$/, "") +
  parsed.search;

if (
  sites.some((s) => {
    const u = new URL(s.url);
    const n =
      u.hostname.replace(/^www\./, "") + u.pathname.replace(/\/$/, "") + u.search;
    return s.id === id || n === normalizedUrl;
  })
) {
  throw new Error(`Site "${id}" or URL "${parsed.toString()}" is already in the collection.`);
}

const browser = await launchCaptureBrowser();
try {
  const mode = (opt.mode || "auto").toLowerCase();
  let useVideo = mode === "video";
  if (mode === "auto") {
    const probeCtx = await browser.newContext({ viewport: { width: 1440, height: 900 } });
    const probePage = await probeCtx.newPage();
    try {
      await probePage.goto(parsed.toString(), { waitUntil: "domcontentloaded", timeout: 20000 });
      await probePage.waitForLoadState("load", { timeout: 8000 }).catch(() => {});
      await probePage.waitForTimeout(800);
      const motion = await detectScrollMotion(probePage);
      useVideo = motion.isScrollMotion;
      if (useVideo) {
        console.log(
          `Detected scroll-motion layout (sticky=${motion.tallStickyCount}, canvas=${motion.fullCanvasCount}) — recording smooth-scroll video.`,
        );
      }
    } catch {
      useVideo = false;
    } finally {
      await probeCtx.close().catch(() => {});
    }
  }

  console.log(`Capturing ${parsed.toString()} (${useVideo ? "video" : "stitched"}) ...`);
  const result = useVideo
    ? await captureScrollVideo(browser, parsed.toString())
    : await captureStitchedWebsite(browser, parsed.toString(), {
        maxHeight: Number(opt["max-height"] || 4200),
      });

  const today = new Date().toISOString().slice(0, 10);
  const imageRel = `assets/${id}.jpg`;
  await mkdir(join(root, "assets"), { recursive: true });
  await writeFile(join(root, imageRel), result.buffer);

  let videoFields = {};
  if (useVideo && result.videoBuffer) {
    const videoRel = `assets/${id}.mp4`;
    await writeFile(join(root, videoRel), result.videoBuffer);
    videoFields = { video: videoRel, videoSha256: result.videoSha256 };
  }

  const description = (
    opt.description ||
    `Considered web design from ${opt.name}.`
  ).slice(0, 240);
  const observation = (opt.observation || description).slice(0, 1200);

  const entry = {
    id,
    name: opt.name.trim(),
    url: parsed.toString(),
    category: opt.category,
    tags: (opt.tags || "Curated")
      .split(",")
      .map((t) => t.trim())
      .filter(Boolean)
      .slice(0, 8),
    description,
    observation,
    image: imageRel,
    ...videoFields,
    capturedAt: today,
    viewport: { width: 1440, height: 900 },
    credit: (opt.credit || opt.name).trim(),
    imageDimensions: { width: result.width, height: result.height },
    captureSha256: result.sha256,
    captureMethod: result.captureMethod,
    rank: sites.length,
  };

  sites.push(entry);
  await validateSites(sites, root);
  await writeFile(catalogPath, JSON.stringify(sites, null, 2) + "\n");
  console.log(
    useVideo
      ? `Added ${entry.name} (${entry.id}) — poster ${result.width}×${result.height} + ${(result.videoBytes / 1024).toFixed(0)}KB scroll video. Run npm run verify to rebuild.`
      : `Added ${entry.name} (${entry.id}) — ${result.width}×${result.height} (${result.slices} slices). Run npm run verify to rebuild.`,
  );
} finally {
  await browser.close();
}