Penpot design workflow: baseline export, importer plugin, tokens
Mirror to Gitea / mirror (push) Skipped
Mirror to Gitea / mirror (push) Skipped
- tools/penpot/capture.mjs captures every page at 390 and 1440 px as editable layers (text, boxes, images) grouped by section - tools/penpot/plugin: Penpot plugin that rebuilds the captures as native boards; serve.py hosts it locally; preview.html shows the result - tools/penpot/tokens.mjs exports colours and fonts as design tokens - design/README.md documents the design -> hand-off -> code loop
This commit is contained in:
263 files changed
+1054
-1
No files matched your search
@@ -0,0 +1,211 @@
|
||||
/**
|
||||
* Capture the built site as a layer list Penpot can rebuild (see plugin/).
|
||||
*
|
||||
* npm run build && node dist/server/entry.mjs & # site on :4321
|
||||
* node tools/penpot/capture.mjs [http://127.0.0.1:4321]
|
||||
*
|
||||
* Writes design/baseline/<page>-<mobile|desktop>.json plus image crops.
|
||||
* Each board is a flat, paint-ordered list of:
|
||||
* rect — boxes with a background colour and/or border
|
||||
* image — photos, canvases, SVGs, background images (cropped from a text-free screenshot)
|
||||
* text — real text with font, size, weight, colour, alignment
|
||||
* grouped by top-level section (header, each <section>, footer).
|
||||
*/
|
||||
import { chromium } from 'playwright';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const BASE = process.argv[2] || 'http://127.0.0.1:4321';
|
||||
const OUT = path.resolve('design/baseline');
|
||||
const PAGES = ['/', '/work', '/work/usmt-dash', '/blog', '/blog/building-this-site', '/music', '/models', '/about', '/contact'];
|
||||
// Decorative pieces kept as flat pictures (rotated text, generated art).
|
||||
const RASTER = ['.badge', '.ticker', '.barcode-wrap', '.burst', '.sparkle', '.sticker', '.lcd', '.board', '.led', '.osd', '.stamp', '.postmark', '.spiral', '.bars', '.wave', '.ascii-canvas'];
|
||||
const VIEWPORTS = { mobile: { width: 390, height: 844 }, desktop: { width: 1440, height: 900 } };
|
||||
|
||||
fs.rmSync(OUT, { recursive: true, force: true });
|
||||
fs.mkdirSync(path.join(OUT, 'img'), { recursive: true });
|
||||
|
||||
const browser = await chromium.launch({ args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'] });
|
||||
const index = [];
|
||||
|
||||
for (const [vpName, vp] of Object.entries(VIEWPORTS)) {
|
||||
const ctx = await browser.newContext({ viewport: vp, deviceScaleFactor: 1, reducedMotion: 'reduce' });
|
||||
const page = await ctx.newPage();
|
||||
for (const route of PAGES) {
|
||||
const slug = (route === '/' ? 'home' : route.slice(1).replaceAll('/', '-')) + '-' + vpName;
|
||||
await page.goto(BASE + route, { waitUntil: 'networkidle' });
|
||||
await page.waitForTimeout(1500);
|
||||
|
||||
const data = await page.evaluate((RASTER) => {
|
||||
const px = (v) => parseFloat(v) || 0;
|
||||
const toHex = (c) => {
|
||||
const m = c.match(/rgba?\(([^)]+)\)/);
|
||||
if (!m) return null;
|
||||
const [r, g, b, a = 1] = m[1].split(/[ ,/]+/).filter(Boolean).map(Number);
|
||||
if (a === 0) return null;
|
||||
return { color: '#' + [r, g, b].map((n) => Math.round(n).toString(16).padStart(2, '0')).join(''), opacity: +(+a).toFixed(3) };
|
||||
};
|
||||
const visible = (el, r) => {
|
||||
const s = getComputedStyle(el);
|
||||
return r.width > 1 && r.height > 1 && s.visibility !== 'hidden' && s.display !== 'none' && +s.opacity > 0.02;
|
||||
};
|
||||
const isInline = (el) => /^(inline|contents)/.test(getComputedStyle(el).display) && !['IMG', 'CANVAS', 'SVG', 'svg', 'VIDEO'].includes(el.tagName);
|
||||
const scrollY = window.scrollY;
|
||||
const box = (r) => ({ x: Math.round(r.left), y: Math.round(r.top + scrollY), w: Math.round(r.width), h: Math.round(r.height) });
|
||||
|
||||
const sections = [...document.querySelectorAll('body > header, main > *, body > footer')].filter((s) => s.getBoundingClientRect().height > 2);
|
||||
const out = [];
|
||||
sections.forEach((sec, si) => {
|
||||
const label = sec.getAttribute('aria-label') || sec.className.toString().split(' ').find((c) => c && !c.startsWith('astro')) || sec.tagName.toLowerCase();
|
||||
const layers = [];
|
||||
const walk = (el) => {
|
||||
if (el.closest('[hidden], .staggered-menu-panel, .sm-prelayers')) return;
|
||||
const r = el.getBoundingClientRect();
|
||||
const s = getComputedStyle(el);
|
||||
if (!visible(el, r)) return;
|
||||
const tag = el.tagName.toUpperCase();
|
||||
|
||||
// decorative pieces: flat picture including their text
|
||||
if (RASTER.some((sel) => el.matches(sel))) {
|
||||
layers.push({ type: 'image', withText: true, name: el.className.toString().split(' ').find((c) => c && !c.startsWith('astro')) || tag.toLowerCase(), ...box(r) });
|
||||
return;
|
||||
}
|
||||
// images
|
||||
const bgImg = s.backgroundImage.includes('url(');
|
||||
if (['IMG', 'CANVAS', 'SVG', 'VIDEO', 'PICTURE'].includes(tag) || (bgImg && el.children.length === 0 && !el.textContent.trim())) {
|
||||
layers.push({ type: 'image', name: el.getAttribute('alt') || el.className?.baseVal || el.className || tag.toLowerCase(), ...box(r) });
|
||||
return;
|
||||
}
|
||||
|
||||
// boxes
|
||||
const bg = toHex(s.backgroundColor);
|
||||
const bw = px(s.borderTopWidth);
|
||||
const border = bw > 0 && s.borderTopStyle !== 'none' ? toHex(s.borderTopColor) : null;
|
||||
if (bg || border || bgImg) {
|
||||
layers.push({
|
||||
type: bgImg && !bg ? 'image' : 'rect',
|
||||
name: (el.className.toString().split(' ').find((c) => c && !c.startsWith('astro')) || tag.toLowerCase()),
|
||||
...box(r),
|
||||
fill: bg,
|
||||
stroke: border ? { ...border, width: bw } : null,
|
||||
radius: Math.min(px(s.borderTopLeftRadius), r.height / 2, r.width / 2),
|
||||
shadow: s.boxShadow !== 'none' ? s.boxShadow : null,
|
||||
rotation: 0,
|
||||
});
|
||||
}
|
||||
|
||||
// text: a block whose children are all inline/text becomes one text layer
|
||||
const kids = [...el.childNodes];
|
||||
const hasText = kids.some((n) => n.nodeType === 3 && n.textContent.trim());
|
||||
const allInline = [...el.children].every(isInline);
|
||||
const textStyle = (cs) => {
|
||||
const stroke = parseFloat(cs.webkitTextStrokeWidth) || 0;
|
||||
return {
|
||||
stroke: stroke > 0 ? { ...(toHex(cs.webkitTextStrokeColor) || { color: '#000000', opacity: 1 }), width: stroke } : null,
|
||||
shadow: cs.textShadow !== 'none' ? cs.textShadow : null,
|
||||
};
|
||||
};
|
||||
if (hasText && allInline && !isInline(el)) {
|
||||
el.querySelectorAll('*').forEach((k) => {
|
||||
const ks = getComputedStyle(k);
|
||||
const kb = toHex(ks.backgroundColor);
|
||||
const kg = ks.backgroundImage.includes('gradient');
|
||||
if ((kb || kg) && k.getBoundingClientRect().width > 1) {
|
||||
for (const cr of k.getClientRects()) layers.push({ type: kb ? 'rect' : 'image', name: 'highlight', ...box(cr), fill: kb, radius: 0 });
|
||||
}
|
||||
});
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(el);
|
||||
const tr = range.getBoundingClientRect();
|
||||
const color = toHex(s.color) || (s.webkitTextFillColor && toHex(s.webkitTextFillColor)) || { color: '#000000', opacity: 1 };
|
||||
layers.push({
|
||||
type: 'text',
|
||||
name: el.innerText.trim().slice(0, 40),
|
||||
...box(tr.width ? tr : r),
|
||||
text: el.innerText.trim(),
|
||||
font: s.fontFamily.split(',')[0].replace(/["']/g, '').replace(/ Variable$/, '').trim(),
|
||||
size: px(s.fontSize),
|
||||
weight: s.fontWeight,
|
||||
italic: s.fontStyle === 'italic',
|
||||
lineHeight: s.lineHeight === 'normal' ? 1.2 : +(px(s.lineHeight) / px(s.fontSize)).toFixed(3),
|
||||
letterSpacing: s.letterSpacing === 'normal' ? 0 : px(s.letterSpacing),
|
||||
transform: s.textTransform === 'none' ? null : s.textTransform,
|
||||
align: ['center', 'right', 'justify'].includes(s.textAlign) ? s.textAlign : 'left',
|
||||
color: color.color,
|
||||
opacity: color.opacity,
|
||||
...textStyle(s),
|
||||
});
|
||||
return; // inline children are part of this text
|
||||
}
|
||||
// loose text next to block children (flex/grid items, absolutely placed badges…)
|
||||
if (hasText) {
|
||||
for (const n of kids) {
|
||||
if (n.nodeType !== 3 || !n.textContent.trim()) continue;
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(n);
|
||||
const tr = range.getBoundingClientRect();
|
||||
if (tr.width < 1) continue;
|
||||
const color = toHex(s.color) || { color: '#000000', opacity: 1 };
|
||||
layers.push({
|
||||
type: 'text', name: n.textContent.trim().slice(0, 40), ...box(tr), text: n.textContent.trim(),
|
||||
font: s.fontFamily.split(',')[0].replace(/["']/g, '').replace(/ Variable$/, '').trim(),
|
||||
size: px(s.fontSize), weight: s.fontWeight, italic: s.fontStyle === 'italic',
|
||||
lineHeight: s.lineHeight === 'normal' ? 1.2 : +(px(s.lineHeight) / px(s.fontSize)).toFixed(3),
|
||||
letterSpacing: s.letterSpacing === 'normal' ? 0 : px(s.letterSpacing),
|
||||
transform: s.textTransform === 'none' ? null : s.textTransform, align: 'left',
|
||||
color: color.color, opacity: color.opacity, ...textStyle(s),
|
||||
});
|
||||
}
|
||||
}
|
||||
for (const c of el.children) walk(c);
|
||||
};
|
||||
walk(sec);
|
||||
out.push({ name: `${String(si + 1).padStart(2, '0')} ${label}`, ...box(sec.getBoundingClientRect()), layers });
|
||||
});
|
||||
const html = document.documentElement;
|
||||
return {
|
||||
width: html.clientWidth,
|
||||
height: Math.ceil(document.documentElement.scrollHeight),
|
||||
background: toHex(getComputedStyle(document.body).backgroundColor)?.color || '#ffffff',
|
||||
sections: out,
|
||||
};
|
||||
}, RASTER);
|
||||
|
||||
// reference (with text): used for decorative crops and for comparison
|
||||
const refPath = path.join(OUT, 'img', `${slug}__reference.png`);
|
||||
await page.screenshot({ path: refPath, fullPage: true });
|
||||
// text-free screenshot for image crops
|
||||
await page.addStyleTag({ content: '*{-webkit-text-fill-color:transparent!important;text-shadow:none!important;-webkit-text-stroke-width:0!important;text-decoration-color:transparent!important} body::before,body::after{display:none!important}' });
|
||||
await page.waitForTimeout(200);
|
||||
const shotPath = path.join(OUT, 'img', `${slug}__full.png`);
|
||||
await page.screenshot({ path: shotPath, fullPage: true });
|
||||
const { default: sharp } = await import('sharp');
|
||||
const full = sharp(shotPath);
|
||||
const meta = await full.metadata();
|
||||
let n = 0;
|
||||
for (const sec of data.sections) {
|
||||
for (const l of sec.layers) {
|
||||
if (l.type !== 'image') continue;
|
||||
const x = Math.max(0, l.x), y = Math.max(0, l.y);
|
||||
const w = Math.min(l.w, meta.width - x), h = Math.min(l.h, meta.height - y);
|
||||
if (w < 2 || h < 2) { l.skip = true; continue; }
|
||||
const file = `${slug}-${++n}.jpg`;
|
||||
await sharp(l.withText ? refPath : shotPath).extract({ left: x, top: y, width: w, height: h }).jpeg({ quality: 86 }).toFile(path.join(OUT, 'img', file));
|
||||
Object.assign(l, { x, y, w, h, src: `img/${file}` });
|
||||
}
|
||||
sec.layers = sec.layers.filter((l) => !l.skip);
|
||||
}
|
||||
fs.rmSync(shotPath);
|
||||
await sharp(refPath).jpeg({ quality: 80 }).toFile(path.join(OUT, 'img', `${slug}__reference.jpg`));
|
||||
fs.rmSync(refPath);
|
||||
|
||||
const board = { name: `${route === '/' ? 'Home' : route} — ${vpName} ${vp.width}`, slug, viewport: vpName, route, ...data, reference: `img/${slug}__reference.jpg` };
|
||||
fs.writeFileSync(path.join(OUT, `${slug}.json`), JSON.stringify(board));
|
||||
const count = data.sections.reduce((a, s) => a + s.layers.length, 0);
|
||||
index.push({ slug, name: board.name, file: `${slug}.json`, layers: count });
|
||||
console.log(`${slug}: ${data.sections.length} sections, ${count} layers`);
|
||||
}
|
||||
await ctx.close();
|
||||
}
|
||||
fs.writeFileSync(path.join(OUT, 'index.json'), JSON.stringify(index, null, 1));
|
||||
await browser.close();
|
||||
Reference in new issue
Block a user