designpaca/research/composition-practice-2026-10-26/build.mjs

113 lines
8.5 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 고정한 문구·서체·색·판형에서 세 구도를 만들고 인쇄용 PDF와 원본 SVG를 남긴다.
import fs from 'node:fs/promises';
import path from 'node:path';
import { createRequire } from 'node:module';
import { pathToFileURL } from 'node:url';
const root = process.cwd();
const out = path.join(root, 'outputs/composition-practice-20261026');
const delivery = path.join(out, 'deliverables');
const require = createRequire(path.join(root, 'apps/site/package.json'));
const puppeteer = await import(pathToFileURL(require.resolve('puppeteer-core')).href);
const sharp = require('sharp');
await fs.mkdir(delivery, { recursive: true });
await fs.mkdir(path.join(out, 'review'), { recursive: true });
const serif = (await fs.readFile(path.join(out, 'fonts/serif.woff2'))).toString('base64');
const sans = (await fs.readFile(path.join(out, 'fonts/sans.woff2'))).toString('base64');
const paper = '#f6f3eb';
const ink = '#182431';
const css = `@font-face{font-family:StudySerif;src:url(data:font/woff2;base64,${serif}) format('woff2');font-weight:500}
@font-face{font-family:StudySans;src:url(data:font/woff2;base64,${sans}) format('woff2');font-weight:500}
text{font-family:StudySans;font-weight:500;fill:${ink}}.serif{font-family:StudySerif}`;
const esc = value => String(value).replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('"', '&quot;');
const t = (text, x, y, size, options = {}) => `<text data-copy="${esc(text)}" x="${x}" y="${y}" font-size="${size}" text-anchor="${options.anchor ?? 'start'}" class="${options.serif ? 'serif' : ''}">${esc(text)}</text>`;
const line = (x1, y, x2) => `<line x1="${x1}" y1="${y}" x2="${x2}" y2="${y}" stroke="${ink}" stroke-width="1.5"/>`;
const meta = () => t('가상 행사 · 조판 실습', 58, 1130, 14);
const desc = (x, y, anchor = 'start') => t('늦은 시간까지 열어 두는,', x, y, 26, { anchor }) + t('함께 읽는 자리.', x, y + 38, 26, { anchor });
const variants = [
{
id: 'A', name: '일정 중심',
body: t('밤의 독서실', 58, 180, 84, { serif: true }) + desc(58, 260)
+ line(58, 432, 782) + t('11월 14일', 58, 505, 40)
+ t('18:00–24:00', 52, 660, 128) + t('중앙도서관 2층', 58, 745, 36)
+ line(58, 812, 782) + t('사전 신청 없이 참여', 58, 906, 28) + meta(),
},
{
id: 'B', name: '표제 중심',
body: t('밤의', 49, 290, 180, { serif: true }) + t('독서실', 49, 500, 180, { serif: true })
+ desc(58, 620) + line(58, 734, 782)
+ t('11월 14일', 782, 812, 30, { anchor: 'end' })
+ t('18:00–24:00', 782, 867, 36, { anchor: 'end' })
+ t('중앙도서관 2층', 782, 927, 30, { anchor: 'end' })
+ t('사전 신청 없이 참여', 58, 1030, 28) + meta(),
},
{
id: 'C', name: '중앙축',
body: t('밤의', 420, 330, 100, { serif: true, anchor: 'middle' })
+ t('독서실', 420, 500, 144, { serif: true, anchor: 'middle' })
+ desc(420, 624, 'middle') + line(370, 740, 470)
+ t('11월 14일', 420, 812, 34, { anchor: 'middle' })
+ t('18:00–24:00', 420, 875, 44, { anchor: 'middle' })
+ t('중앙도서관 2층', 420, 936, 30, { anchor: 'middle' })
+ t('사전 신청 없이 참여', 420, 1032, 28, { anchor: 'middle' }) + meta(),
},
];
const svg = body => `<svg xmlns="http://www.w3.org/2000/svg" width="297mm" height="420mm" viewBox="0 0 840 1188"><style>${css}</style><rect width="840" height="1188" fill="${paper}"/>${body}</svg>`;
const documents = variants.map(v => ({ ...v, source: svg(v.body) }));
for (const v of documents) await fs.writeFile(path.join(delivery, `poster-${v.id}.svg`), v.source);
const html = `<!doctype html><html lang="ko"><meta charset="utf-8"><title>밤의 독서실 - 조판 비교</title><style>@page{size:297mm 420mm;margin:0}html,body{margin:0;padding:0}section{width:297mm;height:420mm;break-after:page}section:last-child{break-after:auto}svg{display:block;width:297mm;height:420mm}</style>${documents.map(v => `<section>${v.source}</section>`).join('')}</html>`;
await fs.writeFile(path.join(out, 'print.html'), html);
const browser = await puppeteer.default.launch({ executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe', headless: true });
const reports = [];
try {
const page = await browser.newPage();
await page.setViewport({ width: 840, height: 1188, deviceScaleFactor: 1 });
for (const v of documents) {
await page.goto(pathToFileURL(path.join(delivery, `poster-${v.id}.svg`)).href);
await page.evaluate(() => document.fonts.ready);
const report = await page.evaluate(() => {
const ctx = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas').getContext('2d');
const texts = [...document.querySelectorAll('text')].map(el => {
const b = el.getBBox();
const style = getComputedStyle(el);
ctx.font = `${style.fontWeight} ${style.fontSize} ${style.fontFamily}`;
const m = ctx.measureText(el.textContent);
const anchor = el.getAttribute('text-anchor');
const start = Number(el.getAttribute('x')) - (anchor === 'middle' ? m.width / 2 : anchor === 'end' ? m.width : 0);
// getBBox에는 이 서체의 큰 상하 여유가 포함된다. 실제 글리프 경계와 함께 기록한다.
return { text: el.textContent, x: start - m.actualBoundingBoxLeft,
y: Number(el.getAttribute('y')) - m.actualBoundingBoxAscent,
width: m.actualBoundingBoxLeft + m.actualBoundingBoxRight,
height: m.actualBoundingBoxAscent + m.actualBoundingBoxDescent,
typographicBox: { x: b.x, y: b.y, width: b.width, height: b.height } };
});
const outside = texts.filter(b => b.x < 28 || b.y < 28 || b.x + b.width > 812 || b.y + b.height > 1160);
const overlaps = [];
for (let i = 0; i < texts.length; i++) for (let j = i + 1; j < texts.length; j++) {
const a = texts[i], b = texts[j];
if (Math.min(a.x+a.width,b.x+b.width)-Math.max(a.x,b.x)>1 && Math.min(a.y+a.height,b.y+b.height)-Math.max(a.y,b.y)>1) overlaps.push([a.text,b.text]);
}
return { texts, outside, overlaps, fontFaces: [...document.fonts].map(f => ({family:f.family,status:f.status})) };
});
reports.push({ id: v.id, ...report });
// SVG의 물리 크기를 캡처 픽셀과 일치시킨다. PDF의 A3 물리 크기는 별도 인쇄 문서가 유지한다.
await page.evaluate(() => { const s=document.querySelector('svg');s.setAttribute('width','840');s.setAttribute('height','1188'); });
await page.screenshot({ path: path.join(delivery, `poster-${v.id}.png`) });
}
if (reports.some(r => r.outside.length || r.overlaps.length || r.fontFaces.some(f => f.status !== 'loaded'))) throw new Error(JSON.stringify(reports));
await page.goto(pathToFileURL(path.join(out, 'print.html')).href);
await page.evaluate(() => document.fonts.ready);
await page.pdf({ path: path.join(delivery, 'composition-study.pdf'), preferCSSPageSize: true, printBackground: true, displayHeaderFooter: false });
const leading = `<svg xmlns="http://www.w3.org/2000/svg" width="840" height="320"><style>${css}</style><rect width="840" height="320" fill="${paper}"/>${t('28',58,62,20)}${t('44',440,62,20)}${t('늦은 시간까지 열어 두는,',58,155,28)}${t('함께 읽는 자리.',58,183,28)}${t('늦은 시간까지 열어 두는,',440,155,28)}${t('함께 읽는 자리.',440,199,28)}</svg>`;
await fs.writeFile(path.join(delivery, 'leading-study.svg'), leading);
await page.goto(pathToFileURL(path.join(delivery, 'leading-study.svg')).href);
await page.evaluate(() => document.fonts.ready);
await page.setViewport({ width: 840, height: 320, deviceScaleFactor: 1 });
await page.screenshot({ path: path.join(delivery, 'leading-study.png') });
} finally { await browser.close(); }
await fs.writeFile(path.join(out, 'review/svg-geometry.json'), JSON.stringify(reports, null, 2));
const tiles = await Promise.all(documents.map(async v => sharp(path.join(delivery, `poster-${v.id}.png`)).resize({ width: 480 }).png().toBuffer()));
const labels = Buffer.from(`<svg xmlns="http://www.w3.org/2000/svg" width="1520" height="810">${documents.map((v,i)=>`<text x="${20+i*500}" y="42" font-family="Arial" font-size="23" fill="${ink}">${v.id}</text>`).join('')}</svg>`);
const overview = await sharp({ create: { width: 1520, height: 810, channels: 3, background: '#e4e4e0' } }).composite([...tiles.map((input,i)=>({input,left:20+i*500,top:65})),{input:labels,left:0,top:0}]).png().toBuffer();
await fs.writeFile(path.join(delivery, 'overview.png'), overview);
console.log(JSON.stringify({ posters: 3, geometry: 'passed', fonts: 'embedded subsets', output: delivery }));