feat: design system, layout e componenti di base

- token, font self-hosted (Fraunces e Inter, sottoinsieme latin) con preload
- BaseLayout con head completo (SEO, Open Graph, favicon) e JSON-LD dello studio
- intestazione con barra superiore, navigazione e sottomenu servizi accessibili
- menu mobile con dialog modale e alternativa senza JavaScript
- footer con P.IVA, recapiti, servizi, orari e link legali
- componenti: Logo, Icon (Lucide inline), Hero, card servizio, scheda
  professionista, badge abilitazione, card sede, mappa click-to-load,
  modulo di contatto, banda CTA, breadcrumb, intestazioni di sezione
- generate-icons.mjs: marchio, favicon, apple-touch-icon e immagine OG
- collection dei servizi e dei link utili con schemi Zod

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016zJ9ZWGKvoKoxYwbmnRKdJ
This commit is contained in:
Claude committed 2026-10-15 22:15:18 +00:00
1 parent b740fee017
commit 6ad49a6bcf
58 files changed
+5077 -16

No files matched your search

+261 -2
View File
@@ -1,2 +1,261 @@
// Segnaposto della fase 0: l'implementazione completa arriva nelle fasi successive (vedi DECISIONS.md).
console.log('scripts/generate-icons.mjs: non ancora implementato (fase 0).');
#!/usr/bin/env node
/**
* Genera il marchio e le icone del sito a partire dai font self-hosted (Fraunces, Inter):
*
* src/assets/logo-mark.svg marchio su fondo chiaro (quadrato navy, «G» bianca, dettaglio oro)
* src/assets/logo-mark-dark.svg marchio su fondo scuro (quadrato oro, «G» navy)
* src/assets/logo.svg marchio + logotipo «Studio Grasso / TRIBUTARIO E SOCIETARIO»
* src/assets/logo-dark.svg variante per fondi scuri
* public/favicon.svg favicon vettoriale (= logo-mark.svg)
* public/favicon.ico 16, 32 e 48 px (PNG incapsulati in ICO)
* public/apple-touch-icon.png 180 × 180 px
* public/og-default.png 1200 × 630 px (anteprima per i social)
*
* I testi sono convertiti in tracciati vettoriali (opentype.js): i file non dipendono da font
* installati sul sistema e il risultato è identico su ogni macchina. Le immagini raster sono
* prodotte con sharp. Uso: `npm run icons` (i file generati vanno committati).
*/
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import opentype from 'opentype.js';
import sharp from 'sharp';
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const out = (p) => resolve(root, p);
// Colori: stessi valori di src/styles/tokens.css
const C = {
navy900: '#0b1f33',
navy800: '#0f2a44',
navy700: '#163a5c',
gold500: '#b8902e',
gold300: '#e3c878',
ink600: '#4f5b66',
white: '#ffffff',
};
async function loadFont(pkg, file) {
const buf = await readFile(out(`node_modules/${pkg}/files/${file}`));
return opentype.parse(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength));
}
const fraunces600 = await loadFont('@fontsource/fraunces', 'fraunces-latin-600-normal.woff');
const fraunces500 = await loadFont('@fontsource/fraunces', 'fraunces-latin-500-normal.woff');
const inter600 = await loadFont('@fontsource/inter', 'inter-latin-600-normal.woff');
const inter500 = await loadFont('@fontsource/inter', 'inter-latin-500-normal.woff');
const round = (n) => Math.round(n * 100) / 100;
/** Serializza i comandi di un tracciato (toPathData di opentype.js produce NaN in alcuni casi). */
function toD(path) {
const n = (v) => {
if (!Number.isFinite(v)) throw new Error(`Coordinata non valida nel tracciato: ${v}`);
return String(round(v));
};
return path.commands
.map((c) => {
switch (c.type) {
case 'M':
case 'L':
return `${c.type}${n(c.x)} ${n(c.y)}`;
case 'Q':
return `Q${n(c.x1)} ${n(c.y1)} ${n(c.x)} ${n(c.y)}`;
case 'C':
return `C${n(c.x1)} ${n(c.y1)} ${n(c.x2)} ${n(c.y2)} ${n(c.x)} ${n(c.y)}`;
case 'Z':
return 'Z';
default:
throw new Error(`Comando di tracciato sconosciuto: ${c.type}`);
}
})
.join('');
}
/**
* Impaginazione semplice glifo per glifo (cmap + crenatura), senza sostituzioni OpenType:
* il motore di shaping di opentype.js non supporta tutte le tabelle GSUB di questi font, e per
* testi brevi in alfabeto latino le sostituzioni non servono. `letterSpacing` è in em.
*/
function layout(font, text, x, y, size, letterSpacing = 0) {
const scale = size / font.unitsPerEm;
const glyphs = [...text].map((ch) => font.charToGlyph(ch));
const kerning = font.position?.getKerningTables?.('latn');
let d = '';
let cx = x;
glyphs.forEach((glyph, i) => {
d += toD(glyph.getPath(cx, y, size));
cx += glyph.advanceWidth * scale;
if (i < glyphs.length - 1) {
const next = glyphs[i + 1];
const k = kerning
? font.position.getKerningValue(kerning, glyph.index, next.index)
: font.getKerningValue(glyph, next);
cx += (k || 0) * scale + letterSpacing * size;
}
});
return { d, width: cx - x };
}
/** Testo → tracciato SVG. `x` è il bordo sinistro, `y` la linea di base. */
const textPath = (font, text, x, y, size, ls = 0) => layout(font, text, x, y, size, ls).d;
const textWidth = (font, text, size, ls = 0) => layout(font, text, 0, 0, size, ls).width;
/** «G» centrata otticamente in un quadrato di lato `box`. */
function markGlyph(box, size) {
const glyph = fraunces600.charToGlyph('G');
const bb = glyph.getPath(0, 0, size).getBoundingBox();
const x = (box - (bb.x2 - bb.x1)) / 2 - bb.x1;
const y = (box - (bb.y2 - bb.y1)) / 2 - bb.y1;
return toD(glyph.getPath(round(x), round(y), size));
}
/** Marchio 44 × 44 (proporzioni del brief §6.3: raggio 10, «G» Fraunces, quadratino oro). */
function markSvg({ dark = false, standalone = true } = {}) {
const bg = dark ? C.gold500 : C.navy800;
const fg = dark ? C.navy900 : C.white;
const dot = dark
? ''
: `<rect class="logo-mark__dot" x="30" y="30" width="8" height="8" rx="2" fill="${C.gold500}"/>`;
const ns = standalone ? ' xmlns="http://www.w3.org/2000/svg"' : '';
return (
`<svg${ns} viewBox="0 0 44 44" width="44" height="44">` +
`<rect class="logo-mark__bg" width="44" height="44" rx="10" fill="${bg}"/>` +
`<path class="logo-mark__glyph" d="${markGlyph(44, 21)}" fill="${fg}"/>` +
dot +
`</svg>`
);
}
/** Logo completo: marchio + nome + sottotitolo, testi convertiti in tracciati. */
function logoSvg({ dark = false } = {}) {
const nameColor = dark ? C.white : C.navy900;
const tagColor = dark ? 'rgba(255,255,255,0.7)' : C.ink600;
const nameSize = 21.6; // 1.35rem
const tagSize = 10.4; // 0.65rem
const nameX = 44 + 12.8;
const nameW = textWidth(fraunces600, 'Studio Grasso', nameSize, -0.01);
const tagW = textWidth(inter600, 'TRIBUTARIO E SOCIETARIO', tagSize, 0.16);
const width = Math.ceil(nameX + Math.max(nameW, tagW) + 2);
const mark = markSvg({ dark, standalone: false }).replace(
'<svg viewBox="0 0 44 44" width="44" height="44">',
'<svg x="0" y="0" viewBox="0 0 44 44" width="44" height="44">',
);
return (
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} 44" width="${width}" height="44" role="img" aria-label="Studio Grasso — Tributario e Societario">` +
mark +
`<path d="${textPath(fraunces600, 'Studio Grasso', nameX, 21, nameSize, -0.01)}" fill="${nameColor}"/>` +
`<path d="${textPath(inter600, 'TRIBUTARIO E SOCIETARIO', nameX, 37, tagSize, 0.16)}" fill="${tagColor}"/>` +
`</svg>`
);
}
/** Icona quadrata per Apple (fondo pieno: iOS applica da sé gli angoli arrotondati). */
function appleTouchSvg() {
return (
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 180 180" width="180" height="180">` +
`<rect width="180" height="180" fill="${C.navy800}"/>` +
`<path d="${markGlyph(180, 100)}" fill="${C.white}"/>` +
`<rect x="122" y="122" width="26" height="26" rx="6" fill="${C.gold500}"/>` +
`</svg>`
);
}
/** Immagine Open Graph 1200 × 630: fondo navy, logo, payoff e città. */
function ogSvg() {
const W = 1200;
const H = 630;
const left = 96;
const markSize = 96;
const scale = markSize / 44;
const nameSize = 52;
const tagSize = 20;
const textX = left + markSize + 32;
const payoff = 'Consulenza fiscale e tributaria';
const payoffSize = 64;
const cities = 'Montegrosso d’Asti · Asti';
const citiesSize = 30;
const mark =
`<g transform="translate(${left} 150) scale(${round(scale)})">` +
`<rect width="44" height="44" rx="10" fill="${C.gold500}"/>` +
`<path d="${markGlyph(44, 21)}" fill="${C.navy900}"/>` +
`</g>`;
return (
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${W} ${H}" width="${W}" height="${H}">` +
`<rect width="${W}" height="${H}" fill="${C.navy900}"/>` +
`<circle cx="1080" cy="40" r="250" fill="none" stroke="${C.gold500}" stroke-opacity="0.22" stroke-width="70"/>` +
`<rect x="${left}" y="${H - 96}" width="72" height="4" fill="${C.gold500}"/>` +
mark +
`<path d="${textPath(fraunces600, 'Studio Grasso', textX, 205, nameSize, -0.01)}" fill="${C.white}"/>` +
`<path d="${textPath(inter600, 'TRIBUTARIO E SOCIETARIO', textX, 240, tagSize, 0.16)}" fill="rgba(255,255,255,0.7)"/>` +
`<path d="${textPath(fraunces500, payoff, left, 390, payoffSize, -0.01)}" fill="${C.white}"/>` +
`<path d="${textPath(inter500, cities, left, 450, citiesSize)}" fill="${C.gold300}"/>` +
`</svg>`
);
}
/** File ICO con immagini PNG incapsulate (supportato da tutti i browser attuali). */
function buildIco(pngs) {
const header = Buffer.alloc(6);
header.writeUInt16LE(0, 0);
header.writeUInt16LE(1, 2);
header.writeUInt16LE(pngs.length, 4);
const entries = [];
let offset = 6 + 16 * pngs.length;
for (const { size, data } of pngs) {
const e = Buffer.alloc(16);
e.writeUInt8(size >= 256 ? 0 : size, 0);
e.writeUInt8(size >= 256 ? 0 : size, 1);
e.writeUInt8(0, 2);
e.writeUInt8(0, 3);
e.writeUInt16LE(1, 4);
e.writeUInt16LE(32, 6);
e.writeUInt32LE(data.length, 8);
e.writeUInt32LE(offset, 12);
offset += data.length;
entries.push(e);
}
return Buffer.concat([header, ...entries, ...pngs.map((p) => p.data)]);
}
const png = (svg, size) =>
sharp(Buffer.from(svg), { density: 72 * Math.max(1, size / 44) })
.resize(size, size)
.png({ compressionLevel: 9 })
.toBuffer();
await mkdir(out('src/assets'), { recursive: true });
await mkdir(out('public'), { recursive: true });
const mark = markSvg();
const files = {
'src/assets/logo-mark.svg': mark,
'src/assets/logo-mark-dark.svg': markSvg({ dark: true }),
'src/assets/logo.svg': logoSvg(),
'src/assets/logo-dark.svg': logoSvg({ dark: true }),
'public/favicon.svg': mark,
};
for (const [file, svg] of Object.entries(files)) {
await writeFile(out(file), svg + '\n');
}
const icoImages = [];
for (const size of [16, 32, 48]) icoImages.push({ size, data: await png(mark, size) });
await writeFile(out('public/favicon.ico'), buildIco(icoImages));
await sharp(Buffer.from(appleTouchSvg()))
.png({ compressionLevel: 9 })
.toFile(out('public/apple-touch-icon.png'));
await sharp(Buffer.from(ogSvg()), { density: 72 })
.png({ compressionLevel: 9 })
.toFile(out('public/og-default.png'));
console.log('Icone generate:');
for (const f of [
...Object.keys(files),
'public/favicon.ico',
'public/apple-touch-icon.png',
'public/og-default.png',
]) {
console.log(` ${f}`);
}
+41
View File
@@ -0,0 +1,41 @@
/**
* Elenco delle pagine del sito letto dalla sitemap generata in dist/ (nessuna lista da tenere
* allineata a mano), più le pagine escluse dalla sitemap (404 e conferma del modulo).
*/
import { existsSync, readFileSync, readdirSync } from 'node:fs';
import { resolve } from 'node:path';
export function readSitemapPaths(distDir) {
const index = resolve(distDir, 'sitemap-index.xml');
if (!existsSync(index)) {
throw new Error(`Sitemap non trovata in ${index}: esegui prima \`npm run build\`.`);
}
const locs = (xml) => [...xml.matchAll(/<loc>([^<]+)<\/loc>/g)].map((m) => m[1].trim());
const paths = [];
for (const sitemapUrl of locs(readFileSync(index, 'utf8'))) {
const file = resolve(distDir, new URL(sitemapUrl).pathname.replace(/^\//, ''));
for (const url of locs(readFileSync(file, 'utf8'))) paths.push(new URL(url).pathname);
}
return [...new Set(paths)].sort();
}
/** Pagine generate ma escluse dalla sitemap per scelta (noindex). */
export const EXTRA_PAGES = ['/404.html', '/contatti/grazie/'];
/** Tutti i file HTML presenti in dist/ (percorsi relativi). */
export function listHtmlFiles(distDir, dir = '') {
const out = [];
for (const entry of readdirSync(resolve(distDir, dir), { withFileTypes: true })) {
const rel = dir ? `${dir}/${entry.name}` : entry.name;
if (entry.isDirectory()) out.push(...listHtmlFiles(distDir, rel));
else if (entry.name.endsWith('.html')) out.push(rel);
}
return out.sort();
}
/** Da file HTML a percorso URL: «studio/index.html» → «/studio/». */
export function fileToPath(rel) {
if (rel === 'index.html') return '/';
if (rel.endsWith('/index.html')) return `/${rel.slice(0, -'index.html'.length)}`;
return `/${rel}`;
}
+66
View File
@@ -0,0 +1,66 @@
/**
* Avvia `astro preview` su una porta libera e restituisce l'URL base e una funzione di stop.
* Usato dagli script che devono navigare il sito compilato (link, screenshot).
*/
import { spawn } from 'node:child_process';
import { existsSync } from 'node:fs';
import { createServer } from 'node:net';
import { resolve } from 'node:path';
export const root = resolve(import.meta.dirname, '..', '..');
async function freePort(preferred) {
const tryPort = (port) =>
new Promise((ok) => {
const srv = createServer();
srv.once('error', () => ok(null));
srv.listen(port, '127.0.0.1', () => srv.close(() => ok(port)));
});
return (await tryPort(preferred)) ?? (await tryPort(0));
}
export async function startPreview({ port = 4322 } = {}) {
if (!existsSync(resolve(root, 'dist', 'index.html'))) {
throw new Error('Cartella dist/ assente: esegui prima `npm run build`.');
}
const p = await freePort(port);
const astroBin = resolve(root, 'node_modules', 'astro', 'bin', 'astro.mjs');
const child = spawn(
process.execPath,
[astroBin, 'preview', '--host', '127.0.0.1', '--port', String(p)],
{
cwd: root,
stdio: ['ignore', 'pipe', 'pipe'],
env: { ...process.env, ASTRO_TELEMETRY_DISABLED: '1' },
},
);
let output = '';
child.stdout.on('data', (d) => (output += d));
child.stderr.on('data', (d) => (output += d));
const base = `http://127.0.0.1:${p}`;
const deadline = Date.now() + 30_000;
for (;;) {
try {
const res = await fetch(`${base}/`);
if (res.ok) break;
} catch {
// server non ancora pronto
}
if (child.exitCode !== null || Date.now() > deadline) {
child.kill();
throw new Error(`Impossibile avviare astro preview:\n${output}`);
}
await new Promise((r) => setTimeout(r, 250));
}
return {
base,
stop: () =>
new Promise((ok) => {
if (child.exitCode !== null) return ok();
child.once('exit', () => ok());
child.kill('SIGTERM');
}),
};
}
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env node
/**
* Screenshot a pagina intera di tutte le pagine del sito (desktop 1440 px e mobile 390 px) in
* docs/screenshots/. Richiede `npm run build`. Uso: `node scripts/screenshots.mjs [--out dir]`.
*/
import { mkdir } from 'node:fs/promises';
import { resolve } from 'node:path';
import { chromium } from 'playwright';
import { EXTRA_PAGES, readSitemapPaths } from './lib/pages.mjs';
import { root, startPreview } from './lib/preview-server.mjs';
const outArg = process.argv.indexOf('--out');
const outDir = resolve(root, outArg > -1 ? process.argv[outArg + 1] : 'docs/screenshots');
const only = process.argv.includes('--only')
? process.argv[process.argv.indexOf('--only') + 1]
: null;
const viewports = [
{ name: 'desktop', width: 1440, height: 900, isMobile: false },
{ name: 'mobile', width: 390, height: 844, isMobile: true },
];
const slug = (path) =>
path === '/'
? 'home'
: path
.replace(/^\/|\/$/g, '')
.replace(/\.html$/, '')
.replace(/\//g, '--');
const paths = [...readSitemapPaths(resolve(root, 'dist')), ...EXTRA_PAGES].filter(
(p) => !only || p === only,
);
await mkdir(outDir, { recursive: true });
const server = await startPreview();
const browser = await chromium.launch();
try {
for (const vp of viewports) {
const context = await browser.newContext({
viewport: { width: vp.width, height: vp.height },
deviceScaleFactor: 1,
isMobile: vp.isMobile,
hasTouch: vp.isMobile,
locale: 'it-IT',
reducedMotion: 'reduce',
});
const page = await context.newPage();
for (const path of paths) {
await page.goto(server.base + path, { waitUntil: 'networkidle' });
await page.evaluate(() => document.fonts.ready);
const file = resolve(outDir, `${slug(path)}-${vp.name}.png`);
await page.screenshot({ path: file, fullPage: true });
console.log(` ${vp.name.padEnd(7)} ${path} → ${file.replace(root + '/', '')}`);
}
await context.close();
}
} finally {
await browser.close();
await server.stop();
}