Penpot design workflow: baseline export, importer plugin, tokens
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:
Johan Sandoval committed 2026-10-08 19:40:41 +00:00
1 parent 38b5213138
commit bf0d1efa2c
263 files changed
+1054 -1

No files matched your search

+211
View File
@@ -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();
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><circle cx="16" cy="16" r="15" fill="#c60c30" stroke="#141412" stroke-width="2"/><text x="16" y="21" font-family="Arial Black,sans-serif" font-size="13" text-anchor="middle" fill="#fff">yo</text></svg>

After

Width:  |  Height:  |  Size: 262 B

+7
View File
@@ -0,0 +1,7 @@
{
"name": "yoyos.sh baseline importer",
"description": "Rebuilds the captured yoyos.sh pages (phone + desktop) as editable Penpot boards.",
"code": "/plugin.js",
"icon": "/icon.svg",
"permissions": ["content:read", "content:write"]
}
+136
View File
@@ -0,0 +1,136 @@
// @ts-check
/// <reference types="@penpot/plugin-types" />
/**
* yoyos.sh baseline importer — runs inside Penpot.
* The UI (ui.html) fetches captured boards from the local server and posts them here;
* this code turns each layer into a native Penpot rectangle, image or text shape.
*/
penpot.ui.open('yoyos.sh baseline', '/ui.html', { width: 340, height: 520 });
/** @param {string} css e.g. "rgb(20, 20, 18) 6px 6px 0px 0px" */
function parseShadow(css) {
const color = css.match(/rgba?\([^)]+\)/)?.[0];
if (!color) return [];
const nums = css.replace(color, '').trim().split(/\s+/).map(parseFloat);
const [r, g, b, a = 1] = color.replace(/rgba?\(|\)/g, '').split(/[ ,/]+/).filter(Boolean).map(Number);
const hex = '#' + [r, g, b].map((n) => Math.round(n).toString(16).padStart(2, '0')).join('');
return [{ style: 'drop-shadow', offsetX: nums[0] || 0, offsetY: nums[1] || 0, blur: nums[2] || 0, spread: nums[3] || 0, color: { color: hex, opacity: a }, hidden: false }];
}
const fontCache = new Map();
/** @param {string} name */
function findFont(name) {
if (!fontCache.has(name)) {
fontCache.set(name, penpot.fonts.findByName(name) || penpot.fonts.findAllByName(name)[0] || null);
}
return fontCache.get(name);
}
/** @param {any} l @param {number} ox @param {number} oy */
function makeText(l, ox, oy) {
const t = penpot.createText(l.text);
if (!t) return null;
t.name = l.name || 'text';
const font = findFont(l.font);
if (font) {
const variant =
font.variants.find((/** @type {any} */ v) => v.fontWeight === String(l.weight) && v.fontStyle === (l.italic ? 'italic' : 'normal')) ||
font.variants.find((/** @type {any} */ v) => v.fontWeight === String(l.weight)) ||
font.variants[0];
font.applyToText(t, variant);
}
t.fontSize = String(Math.round(l.size * 100) / 100);
t.lineHeight = String(l.lineHeight);
t.letterSpacing = String(l.letterSpacing || 0);
if (l.transform) t.textTransform = l.transform;
t.align = l.align;
t.fills = [{ fillColor: l.color, fillOpacity: l.opacity ?? 1 }];
if (l.stroke) t.strokes = [{ strokeColor: l.stroke.color, strokeOpacity: l.stroke.opacity, strokeWidth: l.stroke.width, strokeAlignment: 'outer', strokeStyle: 'solid' }];
if (l.shadow) t.shadows = /** @type {any} */ (parseShadow(l.shadow));
t.growType = 'fixed';
t.x = ox + l.x;
t.y = oy + l.y;
t.resize(Math.max(l.w + 2, 4), Math.max(l.h, 4));
return t;
}
/** @param {any} l @param {number} ox @param {number} oy */
function makeRect(l, ox, oy) {
const r = penpot.createRectangle();
r.name = l.name || 'box';
r.x = ox + l.x;
r.y = oy + l.y;
r.resize(Math.max(l.w, 1), Math.max(l.h, 1));
r.fills = l.fill ? [{ fillColor: l.fill.color, fillOpacity: l.fill.opacity }] : [];
if (l.stroke) r.strokes = [{ strokeColor: l.stroke.color, strokeOpacity: l.stroke.opacity, strokeWidth: l.stroke.width, strokeAlignment: 'inner', strokeStyle: 'solid' }];
if (l.radius) r.borderRadius = l.radius;
if (l.shadow) r.shadows = /** @type {any} */ (parseShadow(l.shadow));
return r;
}
/** @param {any} l @param {number} ox @param {number} oy @param {Uint8Array} bytes */
async function makeImage(l, ox, oy, bytes) {
const img = await penpot.uploadMediaData(l.name || 'image', bytes, 'image/jpeg');
const r = penpot.createRectangle();
r.name = l.name || 'image';
r.x = ox + l.x;
r.y = oy + l.y;
r.resize(Math.max(l.w, 1), Math.max(l.h, 1));
r.fills = [{ fillOpacity: 1, fillImage: img }];
return r;
}
/** @type {Record<string, number>} */
let nextX = { mobile: 0, desktop: 0 };
/** @param {any} b @param {Record<string, Uint8Array>} images */
async function importBoard(b, images) {
const rowY = b.viewport === 'mobile' ? 0 : 7000;
const ox = nextX[b.viewport];
nextX[b.viewport] += b.width + 200;
const board = penpot.createBoard();
board.name = b.name;
board.x = ox;
board.y = rowY;
board.resize(b.width, b.height);
board.fills = [{ fillColor: b.background, fillOpacity: 1 }];
board.clipContent = true;
let made = 0;
for (const sec of b.sections) {
/** @type {any[]} */
const shapes = [];
for (const l of sec.layers) {
try {
const s =
l.type === 'text' ? makeText(l, ox, rowY) : l.type === 'image' ? (images[l.src] ? await makeImage(l, ox, rowY, images[l.src]) : null) : makeRect(l, ox, rowY);
if (s) {
board.appendChild(s);
shapes.push(s);
made++;
}
} catch (e) {
console.warn('layer failed', l.name, e);
}
}
if (shapes.length > 1) {
const g = penpot.group(shapes);
if (g) g.name = sec.name;
} else if (shapes[0]) shapes[0].name = sec.name;
penpot.ui.sendMessage({ type: 'progress', board: b.name, section: sec.name });
}
return made;
}
penpot.ui.onMessage(async (/** @type {any} */ msg) => {
if (msg.type === 'board') {
try {
const n = await importBoard(msg.board, msg.images);
penpot.ui.sendMessage({ type: 'done', board: msg.board.name, layers: n });
} catch (e) {
penpot.ui.sendMessage({ type: 'error', board: msg.board.name, error: String(e) });
}
}
});
+57
View File
@@ -0,0 +1,57 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Baseline preview</title>
<!-- Same Google Fonts Penpot uses -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Archivo:wdth,wght@62..125,100..900&family=Dela+Gothic+One&family=DotGothic16&family=Doto:wght@100..900&family=IBM+Plex+Mono:wght@400;500&family=IBM+Plex+Sans:wght@100..700&family=Rubik+Mono+One&family=Rubik+Wet+Paint&family=Sedgwick+Ave+Display&family=VT323&display=block" />
<style>
body { margin: 0; background: #2a2a2a; font-family: system-ui; }
#board { position: relative; overflow: hidden; margin: 0 auto; }
#board > * { position: absolute; box-sizing: border-box; }
.t { white-space: pre-wrap; overflow: visible; }
nav { position: fixed; top: 0; right: 0; z-index: 9; background: #000c; padding: 6px; }
nav select { font-size: 13px; }
</style>
</head>
<body>
<nav><select id="pick"></select></nav>
<div id="board"></div>
<script>
// Mirrors plugin.js: rect → div with fill/stroke/radius, image → img, text → absolutely placed text.
const pick = document.getElementById('pick');
const render = async (file) => {
const b = await (await fetch('/baseline/' + file)).json();
const el = document.getElementById('board');
el.style.cssText = `width:${b.width}px;height:${b.height}px;background:${b.background}`;
el.innerHTML = '';
for (const sec of b.sections) for (const l of sec.layers) {
const d = document.createElement(l.type === 'image' ? 'img' : 'div');
d.style.left = l.x + 'px'; d.style.top = l.y + 'px'; d.style.width = (l.type === 'text' ? l.w + 2 : l.w) + 'px'; d.style.height = l.h + 'px';
if (l.type === 'image') d.src = '/baseline/' + l.src;
if (l.type === 'rect') {
if (l.fill) d.style.background = l.fill.color, d.style.opacity = 1;
if (l.fill && l.fill.opacity < 1) d.style.background = l.fill.color + Math.round(l.fill.opacity * 255).toString(16).padStart(2, '0');
if (l.stroke) d.style.border = `${l.stroke.width}px solid ${l.stroke.color}`;
if (l.radius) d.style.borderRadius = l.radius + 'px';
if (l.shadow) d.style.boxShadow = l.shadow;
}
if (l.type === 'text') {
d.className = 't'; d.textContent = l.text;
if (l.stroke) { d.style.webkitTextStroke = `${l.stroke.width}px ${l.stroke.color}`; d.style.paintOrder = 'stroke fill'; }
if (l.shadow) d.style.textShadow = l.shadow;
Object.assign(d.style, { fontFamily: `'${l.font}'`, fontSize: l.size + 'px', fontWeight: l.weight, fontStyle: l.italic ? 'italic' : 'normal',
lineHeight: l.lineHeight, letterSpacing: (l.letterSpacing || 0) + 'px', textTransform: l.transform || 'none', textAlign: l.align, color: l.color, opacity: l.opacity });
}
el.appendChild(d);
}
document.fonts.ready.then(() => document.body.dataset.ready = file);
};
fetch('/baseline/index.json').then((r) => r.json()).then((idx) => {
pick.innerHTML = idx.map((b) => `<option value="${b.file}">${b.name}</option>`).join('');
pick.onchange = () => { location.hash = pick.value; render(pick.value); };
const f = location.hash.slice(1) || idx[0].file; pick.value = f; render(f);
});
</script>
</body>
</html>
+61
View File
@@ -0,0 +1,61 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<style>
body { font: 13px system-ui, sans-serif; margin: 0; padding: 12px; color: #e8e8e8; background: #18181a; }
h1 { font-size: 14px; margin: 0 0 8px; }
label { display: flex; gap: 6px; align-items: center; padding: 3px 0; }
button { margin-top: 10px; width: 100%; padding: 8px; font-weight: 700; border: 0; border-radius: 6px; background: #31efb8; color: #000; cursor: pointer; }
button[disabled] { opacity: .5; }
#log { margin-top: 10px; font: 11px ui-monospace, monospace; white-space: pre-wrap; max-height: 150px; overflow: auto; color: #aaa; }
.row { display: flex; gap: 8px; font-size: 12px; }
.row a { color: #31efb8; cursor: pointer; }
</style>
</head>
<body>
<h1>Import yoyos.sh baseline</h1>
<div class="row"><a id="all">all</a><a id="none">none</a><a id="mob">phone only</a><a id="desk">desktop only</a></div>
<div id="list">Loading boards…</div>
<button id="go" disabled>Import selected</button>
<div id="log"></div>
<script>
const log = (m) => { const el = document.getElementById('log'); el.textContent += m + '\n'; el.scrollTop = 1e9; };
let boards = [];
fetch('/baseline/index.json').then((r) => r.json()).then((idx) => {
boards = idx;
document.getElementById('list').innerHTML = idx.map((b, i) =>
`<label><input type="checkbox" data-i="${i}" checked> ${b.name} <small>(${b.layers})</small></label>`).join('');
document.getElementById('go').disabled = false;
}).catch((e) => log('Could not load /baseline/index.json — is tools/penpot/serve.py running? ' + e));
const boxes = () => [...document.querySelectorAll('input[type=checkbox]')];
document.getElementById('all').onclick = () => boxes().forEach((b) => (b.checked = true));
document.getElementById('none').onclick = () => boxes().forEach((b) => (b.checked = false));
document.getElementById('mob').onclick = () => boxes().forEach((b) => (b.checked = boards[b.dataset.i].slug.endsWith('mobile')));
document.getElementById('desk').onclick = () => boxes().forEach((b) => (b.checked = boards[b.dataset.i].slug.endsWith('desktop')));
let queue = [];
async function next() {
const item = queue.shift();
if (!item) { log('All done.'); document.getElementById('go').disabled = false; return; }
const board = await (await fetch('/baseline/' + item.file)).json();
const images = {};
for (const sec of board.sections) for (const l of sec.layers) {
if (l.type === 'image' && l.src && !images[l.src]) images[l.src] = new Uint8Array(await (await fetch('/baseline/' + l.src)).arrayBuffer());
}
log('Importing ' + board.name + '…');
parent.postMessage({ type: 'board', board, images }, '*');
}
window.addEventListener('message', (e) => {
const m = e.data;
if (m.type === 'done') { log(`✓ ${m.board} (${m.layers} layers)`); next(); }
if (m.type === 'error') { log(`✗ ${m.board}: ${m.error}`); next(); }
});
document.getElementById('go').onclick = () => {
queue = boxes().filter((b) => b.checked).map((b) => boards[b.dataset.i]);
document.getElementById('go').disabled = true;
next();
};
</script>
</body>
</html>
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env python3
"""Serve the Penpot importer plugin + captured baseline locally, with CORS.
python3 tools/penpot/serve.py # then in Penpot: Plugins → install
# http://localhost:4402/manifest.json
"""
import http.server
import os
from pathlib import Path
ROOT = Path(__file__).resolve().parent
REPO = ROOT.parent.parent
PORT = int(os.environ.get('PORT', 4402))
class Handler(http.server.SimpleHTTPRequestHandler):
def translate_path(self, path):
path = path.split('?', 1)[0]
if path.startswith('/baseline/'):
return str(REPO / 'design' / path.lstrip('/'))
return str(ROOT / 'plugin' / path.lstrip('/'))
def end_headers(self):
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Private-Network', 'true')
self.send_header('Cache-Control', 'no-store')
super().end_headers()
def do_OPTIONS(self):
self.send_response(204)
self.send_header('Access-Control-Allow-Methods', 'GET, OPTIONS')
self.send_header('Access-Control-Allow-Headers', '*')
self.end_headers()
if __name__ == '__main__':
print(f'Penpot plugin: http://localhost:{PORT}/manifest.json')
http.server.ThreadingHTTPServer(('127.0.0.1', PORT), Handler).serve_forever()
+30
View File
@@ -0,0 +1,30 @@
/**
* Export src/styles/tokens.css → design/tokens.json (W3C design-token format,
* which Penpot's Tokens panel imports). Colours and font families only.
*
* node tools/penpot/tokens.mjs
*/
import fs from 'node:fs';
const css = fs.readFileSync('src/styles/tokens.css', 'utf8');
const root = css.slice(css.indexOf(':root'), css.indexOf('}', css.indexOf(':root')));
const vars = Object.fromEntries([...root.matchAll(/--([\w-]+):\s*([^;]+);/g)].map((m) => [m[1], m[2].trim()]));
const resolve = (v, seen = 0) => {
const m = v.match(/^var\(--([\w-]+)\)$/);
return m && seen < 5 ? resolve(vars[m[1]] ?? v, seen + 1) : v;
};
const tokens = { color: {}, fontFamily: {} };
for (const [name, raw] of Object.entries(vars)) {
const v = resolve(raw);
if (/^#[0-9a-f]{3,8}$/i.test(v)) {
const [group, ...rest] = name.split('-');
const key = rest.length ? rest.join('-') : 'base';
(tokens.color[group] ??= {})[key] = { $type: 'color', $value: v };
} else if (name.startsWith('ff-')) {
tokens.fontFamily[name.slice(3)] = { $type: 'fontFamilies', $value: v.split(',')[0].replace(/['"]/g, '').replace(/ Variable$/, '').trim() };
}
}
fs.mkdirSync('design', { recursive: true });
fs.writeFileSync('design/tokens.json', JSON.stringify({ 'yoyos.sh': tokens }, null, 2));
console.log(`design/tokens.json: ${Object.values(tokens.color).reduce((a, g) => a + Object.keys(g).length, 0)} colours, ${Object.keys(tokens.fontFamily).length} font families`);