// @ts-check
///
/**
* 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 }];
}
/** Base64 → bytes without relying on atob (not guaranteed in the plugin sandbox). @param {string} b64 */
function fromBase64(b64) {
const abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
const lut = new Uint8Array(128);
for (let i = 0; i < abc.length; i++) lut[abc.charCodeAt(i)] = i;
const clean = b64.replace(/[^A-Za-z0-9+/]/g, '');
const out = new Uint8Array(Math.floor((clean.length * 3) / 4));
let o = 0;
for (let i = 0; i < clean.length; i += 4) {
const n = (lut[clean.charCodeAt(i)] << 18) | (lut[clean.charCodeAt(i + 1)] << 12) | (lut[clean.charCodeAt(i + 2)] << 6) | lut[clean.charCodeAt(i + 3)];
out[o++] = (n >> 16) & 255;
if (i + 2 < clean.length) out[o++] = (n >> 8) & 255;
if (i + 3 < clean.length) out[o++] = n & 255;
}
return out.subarray(0, o);
}
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 {string} b64 */
async function makeImage(l, ox, oy, b64) {
const img = await penpot.uploadMediaData(String(l.name || 'image').slice(0, 60), fromBase64(b64), '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 }];
// Readback: Penpot sometimes accepts the upload but drops the fill silently.
const got = /** @type {any} */ (r.fills)[0]?.fillImage;
if (!got) throw new Error('fill dropped after upload (uploaded id ' + (img && img.id) + ')');
if (!diag) diag = `first image: id ${got.id}, ${got.width}×${got.height}, ${got.mtype}`;
imagesMade++;
return r;
}
let diag = '';
let imagesMade = 0;
/** @type {Record} */
let nextX = { mobile: 0, desktop: 0 };
/** @param {any} b @param {Record} images */
async function importBoard(b, images) {
/** @type {Record} */
const failed = {};
/** @type {string[]} */
const errors = [];
diag = '';
imagesMade = 0;
const wanted = b.sections.reduce((/** @type {number} */ n, /** @type {any} */ s) => n + s.layers.filter((/** @type {any} */ l) => l.type === 'image').length, 0);
const missing = b.sections.flatMap((/** @type {any} */ s) => s.layers).filter((/** @type {any} */ l) => l.type === 'image' && !images[l.src]).length;
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;
// Full-page screenshot of the real site: hidden + locked, toggle it on to compare/trace.
/** @type {any} */
let refShape = null;
if (images[b.reference]) {
try {
const ref = await makeImage({ name: 'Reference screenshot', x: 0, y: 0, w: b.width, h: b.height }, ox, rowY, images[b.reference]);
board.appendChild(ref);
ref.name = '⧉ Reference screenshot (toggle to compare)';
ref.hidden = true;
ref.blocked = true;
refShape = ref;
} catch (e) {
errors.push('reference: ' + String(e));
}
}
let made = 0;
/** @type {any[]} */
const sections = [];
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) {
failed[l.type] = (failed[l.type] || 0) + 1;
if (errors.length < 5) errors.push(`${l.type} "${String(l.name).slice(0, 30)}": ${String(e)}`);
}
}
/** @type {any} */
let top = shapes[0];
if (shapes.length > 1) {
const g = penpot.group(shapes);
if (g) g.name = sec.name;
top = g;
} else if (shapes[0]) shapes[0].name = sec.name;
// Enforce DOM paint order explicitly (append/group don't guarantee it):
// each later layer goes in front, so backgrounds sit under their content.
for (const s of shapes) s.bringToFront();
if (top) sections.push(top);
penpot.ui.sendMessage({ type: 'progress', board: b.name, section: sec.name });
}
for (const g of sections) g.bringToFront();
if (refShape) refShape.bringToFront();
errors.unshift(`images: ${imagesMade}/${wanted + (images[b.reference] ? 1 : 0)} placed${missing ? `, ${missing} never reached the plugin` : ''}${diag ? ' · ' + diag : ''}`);
return { made, failed, errors };
}
penpot.ui.onMessage(async (/** @type {any} */ msg) => {
if (msg.type === 'board') {
try {
const r = await importBoard(msg.board, msg.images);
penpot.ui.sendMessage({ type: 'done', board: msg.board.name, layers: r.made, failed: r.failed, errors: r.errors });
} catch (e) {
penpot.ui.sendMessage({ type: 'error', board: msg.board.name, error: String(e) });
}
}
});