test: suite completa di §11 e npm run verify verde

- html-validate su tutte le pagine; linkinator su astro preview (link, asset,
  CSS e ancore), con modalità --external per i siti esterni
- e2e Playwright: struttura e metadati di ogni pagina, 404, navigazione,
  sottomenu, menu mobile, ancore del vecchio sito, nessuna richiesta esterna,
  nessun cookie, localStorage vuoto, mappa solo dopo il clic, funzionamento
  senza JavaScript, modulo di contatto
- a11y: axe su tutte le pagine a 1440 e 390 px e negli stati interattivi,
  tastiera (skip link, sottomenu, menu mobile), focus visibile, testo al 200 %,
  reflow a 320 px, movimento ridotto
- check-compliance.mjs: P.IVA, link legali, risorse sicure, segnaposto,
  JSON-LD, sitemap, robots, .htaccess, badge e servizi, uso di
  «commercialista», riferimento L. 4/2013, budget
- fix: punti di interruzione in em, focus ciclico nel menu mobile,
  rel="noopener" sui link esterni del Markdown, numeri di telefono non spezzabili

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:55:46 +00:00
1 parent 8ce77de137
commit 601d13cfaf
40 files changed
+1798 -114

No files matched your search

+43
View File
@@ -219,3 +219,46 @@ Ogni scelta non banale presa durante lo sviluppo (brief §0.4). Formato: data ·
- **Scelta:** in `lighthouserc.cjs` restano errori bloccanti le quattro soglie di §9.3 (Performance ≥ 0.95, Accessibility = 1, Best Practices ≥ 0.95, SEO = 1) e tutti gli audit del preset; sono declassati a `warn` solo: `network-dependency-tree-insight`, `critical-request-chains`, `render-blocking-insight`, `render-blocking-resources`, `uses-http2`, `bf-cache`, `csp-xss`. - **Scelta:** in `lighthouserc.cjs` restano errori bloccanti le quattro soglie di §9.3 (Performance ≥ 0.95, Accessibility = 1, Best Practices ≥ 0.95, SEO = 1) e tutti gli audit del preset; sono declassati a `warn` solo: `network-dependency-tree-insight`, `critical-request-chains`, `render-blocking-insight`, `render-blocking-resources`, `uses-http2`, `bf-cache`, `csp-xss`.
- **Alternative scartate:** togliere il preset (si perderebbero i controlli puntuali). - **Alternative scartate:** togliere il preset (si perderebbero i controlli puntuali).
- **Motivazione:** regole «rumorose» declassate come previsto dal brief (§11.6), senza allentare le soglie. - **Motivazione:** regole «rumorose» declassate come previsto dal brief (§11.6), senza allentare le soglie.
## D-028 — Punti di interruzione in `em` e focus ciclico nel menu mobile
- **Data:** 2026-10-15
- **Contesto:** il test «testo al 200 %» (dimensione del carattere del browser raddoppiata) mostrava scorrimento orizzontale: con i punti di interruzione in px l'intestazione desktop restava attiva anche con testo doppio. Il test del menu mobile mostrava che il `<dialog>` nativo lascia uscire il focus verso l'interfaccia del browser dopo l'ultimo elemento.
- **Scelta:** media query in `em` (960 px → 60em, 640 px → 40em, 1100 px → 68.75em, 420 px → 26.25em) e larghezze fisse in `rem`; nel menu mobile Tab/Maiusc+Tab ciclano tra il primo e l'ultimo elemento.
- **Alternative scartate:** lasciare il comportamento nativo del dialog (accettabile ma meno prevedibile per chi usa la tastiera).
- **Motivazione:** WCAG 1.4.4 (ridimensionamento del testo) e 2.4.3 (ordine del focus) senza eccezioni.
## D-029 — Correzioni ai test durante la fase 6
- **Data:** 2026-10-15
- **Contesto:** §0.6 chiede di spiegare ogni test corretto.
- **Scelta:**
1. `check-compliance.mjs`, controllo «commercialista»: `DomUtils.findAll` restituisce solo elementi, quindi i nodi di testo non venivano esaminati; sostituito con una visita esplicita dei nodi di testo e una divisione in frasi che non spezza «Dott.», «n.», «sez.». Verificato con casi negativi iniettati (frasi errate rilevate, frasi sulla Dott.ssa Giulia Grasso accettate).
2. Test «testo al 200 %»: la prima versione iniettava `html { font-size: 200% }`, che non agisce sulle media query e non corrisponde a nessuna impostazione reale; ora il test usa il protocollo DevTools (`Page.setFontSizes`) come la preferenza «Dimensione carattere» del browser.
3. Test axe con mappa caricata: l'iframe è contenuto di terze parti (nei test una pagina finta): escluso dall'analisi, che resta sul markup del sito.
- **Alternative scartate:** nessuna (i test non sono stati allentati: le soglie restano zero violazioni gravi/critiche).
- **Motivazione:** test corretti che verificano davvero il requisito.
## D-030 — Link esterni nel Markdown e processore Markdown di Astro 7
- **Data:** 2026-10-15
- **Contesto:** in Astro 7 il processore Markdown predefinito (Sätteri) ignora `markdown.rehypePlugins` (deprecato); i link esterni dei testi legali risultavano senza `rel="noopener"` (rilevato da `check-compliance`).
- **Scelta:** l'HTML generato dal Markdown (servizi e testi legali) passa da `src/lib/html.ts`, che aggiunge `rel="noopener"` ai link verso altri domini; i link si aprono nella stessa scheda (§4.7).
- **Alternative scartate:** installare `@astrojs/markdown-remark` solo per un plugin.
- **Motivazione:** nessuna dipendenza in più, comportamento verificato dai test.
## D-031 — Dipendenze di test esplicite
- **Data:** 2026-10-15
- **Contesto:** `@axe-core/playwright` dichiara `playwright-core` come peer e npm installava la 1.64.1 accanto alla 1.56.1 di Playwright (tipi incompatibili); `check-compliance.mjs` usa `htmlparser2`, già presente come dipendenza di linkinator.
- **Scelta:** `playwright-core@1.56.1` e `htmlparser2@12.0.0` dichiarati esplicitamente in `devDependencies`.
- **Alternative scartate:** affidarsi alle dipendenze transitive.
- **Motivazione:** una sola versione di Playwright nel progetto; nessuna dipendenza usata senza essere dichiarata.
## D-032 — Test del modulo con il modulo attivo
- **Data:** 2026-10-15
- **Contesto:** con la configurazione predefinita (`contactForm.mode = 'off'`) i test del modulo (validazione, honeypot, tempo minimo, pagina di conferma) vengono saltati.
- **Scelta:** la variabile d'ambiente `CONTACT_FORM_MODE` (`off`, `php`, `endpoint`) ha la precedenza su `studio.ts`; i test del modulo sono stati eseguiti con `CONTACT_FORM_MODE=php npm run build` seguito da Playwright (tutti verdi, insieme a html-validate, axe e conformità). Il README spiega come ripeterli. L'invio a `/contact.php` è simulato nei test (nessun PHP in `astro preview`).
- **Alternative scartate:** attivare il modulo per impostazione predefinita (moduli rotti su hosting senza PHP, §10.1).
- **Motivazione:** il modulo resta verificato anche se disattivato.
+6 -18
View File
@@ -30,9 +30,11 @@
"eslint-plugin-astro": "3.2.1", "eslint-plugin-astro": "3.2.1",
"globals": "17.13.0", "globals": "17.13.0",
"html-validate": "11.16.2", "html-validate": "11.16.2",
"htmlparser2": "12.0.0",
"linkinator": "8.1.0", "linkinator": "8.1.0",
"opentype.js": "2.0.0", "opentype.js": "2.0.0",
"playwright": "1.56.1", "playwright": "1.56.1",
"playwright-core": "1.56.1",
"prettier": "3.9.10", "prettier": "3.9.10",
"prettier-plugin-astro": "1.1.1", "prettier-plugin-astro": "1.1.1",
"sharp": "0.35.5", "sharp": "0.35.5",
@@ -8151,17 +8153,16 @@
} }
}, },
"node_modules/playwright-core": { "node_modules/playwright-core": {
"version": "1.64.1", "version": "1.56.1",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz", "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.56.1.tgz",
"integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==", "integrity": "sha512-hutraynyn31F+Bifme+Ps9Vq59hKuUCz7H1kDOcBs+2oGguKkWTU50bBWrtz34OUWmIwpBTWDxaRPXrIXkgvmQ==",
"dev": true, "dev": true,
"license": "Apache-2.0", "license": "Apache-2.0",
"peer": true,
"bin": { "bin": {
"playwright-core": "cli.js" "playwright-core": "cli.js"
}, },
"engines": { "engines": {
"node": ">=20" "node": ">=18"
} }
}, },
"node_modules/playwright/node_modules/fsevents": { "node_modules/playwright/node_modules/fsevents": {
@@ -8179,19 +8180,6 @@
"node": "^8.16.0 || ^10.6.0 || >=11.0.0" "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
} }
}, },
"node_modules/playwright/node_modules/playwright-core": {
"version": "1.56.1",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.56.1.tgz",
"integrity": "sha512-hutraynyn31F+Bifme+Ps9Vq59hKuUCz7H1kDOcBs+2oGguKkWTU50bBWrtz34OUWmIwpBTWDxaRPXrIXkgvmQ==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=18"
}
},
"node_modules/postcss": { "node_modules/postcss": {
"version": "8.5.30", "version": "8.5.30",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.30.tgz", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.30.tgz",
+2
View File
@@ -50,9 +50,11 @@
"eslint-plugin-astro": "3.2.1", "eslint-plugin-astro": "3.2.1",
"globals": "17.13.0", "globals": "17.13.0",
"html-validate": "11.16.2", "html-validate": "11.16.2",
"htmlparser2": "12.0.0",
"linkinator": "8.1.0", "linkinator": "8.1.0",
"opentype.js": "2.0.0", "opentype.js": "2.0.0",
"playwright": "1.56.1", "playwright": "1.56.1",
"playwright-core": "1.56.1",
"prettier": "3.9.10", "prettier": "3.9.10",
"prettier-plugin-astro": "1.1.1", "prettier-plugin-astro": "1.1.1",
"sharp": "0.35.5", "sharp": "0.35.5",
+715 -2
View File
@@ -1,2 +1,715 @@
// Segnaposto della fase 0: l'implementazione completa arriva nelle fasi successive (vedi DECISIONS.md). #!/usr/bin/env node
console.log('scripts/check-compliance.mjs: non ancora implementato (fase 0).'); /**
* Controlli di conformità sul sito compilato (brief §11.5). Ogni errore indica COSA non va e
* DOVE (file di dist/). Richiede `npm run build`. Uscita con codice 1 se c'è almeno un errore.
*
* I dati attesi (abilitazioni, servizi, P.IVA, professionisti) sono letti dalle stesse fonti
* del sito: src/data/studio.ts e src/content/servizi/*.md.
*/
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { DomUtils, parseDocument } from 'htmlparser2';
import { fileToPath, listHtmlFiles, readSitemapPaths } from './lib/pages.mjs';
import { root } from './lib/preview-server.mjs';
const dist = resolve(root, 'dist');
const { abilitazioni, professionisti, studio, contactForm } = await import(
resolve(root, 'src/data/studio.ts')
);
const SITE = (process.env.SITE_URL || 'https://www.grassoezio.it').replace(/\/+$/, '');
const PIVA = `P.IVA ${studio.partitaIva}`;
const LEGAL_PAGES = ['/privacy-policy/', '/cookie-policy/', '/note-legali/', '/accessibilita/'];
const NOINDEX_PAGES = ['/404.html', '/contatti/grazie/'];
const BUDGET_HTML_CSS = 120 * 1024;
const BUDGET_JS = 15 * 1024;
const BUDGET_FONTS = 110 * 1024;
const errors = [];
const fail = (where, what) => errors.push(`${where}: ${what}`);
let checks = 0;
const check = (ok, where, what) => {
checks++;
if (!ok) fail(where, what);
return ok;
};
/* ------------------------------------------------------------------ utilità DOM */
const { findAll, findOne, getAttributeValue: attr, textContent, getParent } = DomUtils;
const isTag = (n) => n.type === 'tag' || n.type === 'script' || n.type === 'style';
const all = (doc, pred) => findAll((n) => isTag(n) && pred(n), doc.children);
const byTag = (doc, name) => all(doc, (n) => n.name === name);
const normalize = (s) => s.replace(/\s+/g, ' ').replace(/[’‘]/g, "'").trim();
/** Testo visibile (esclusi script, style, noscript, template). */
function visibleText(node) {
if (node.type === 'text') return node.data;
if (!isTag(node) && node.type !== 'root') return '';
if (['script', 'style', 'noscript', 'template'].includes(node.name)) return '';
return (node.children ?? []).map(visibleText).join(' ');
}
const BLOCKS = new Set([
'p',
'li',
'dd',
'dt',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'td',
'th',
'address',
'figcaption',
'blockquote',
'label',
'button',
'a',
'title',
]);
/** Tutti i nodi di testo del documento (DomUtils.findAll restituisce solo elementi). */
function textNodes(node, out = []) {
for (const child of node.children ?? []) {
if (child.type === 'text') out.push(child);
else textNodes(child, out);
}
return out;
}
/** Divide in frasi senza spezzare abbreviazioni come «Dott.», «Dott.ssa», «n.», «sez.». */
function sentences(text) {
const protectedText = text.replace(
/\b(Dott|Dott\.ssa|Avv|Rag|Sig|n|nn|sez|art|artt|co|lett|par|D\.Lgs|D\.L|L|Reg|ecc|es|tel|p)\./gi,
(m) => m.replace(/\./g, '\u2024'),
);
return protectedText.split(/(?<=[.!?;])\s+/).map((s) => s.replace(/\u2024/g, '.'));
}
function closestBlock(node) {
let n = getParent(node);
while (n && !(isTag(n) && BLOCKS.has(n.name))) n = getParent(n);
return n;
}
function ancestorWithAttr(node, name, value) {
for (let n = getParent(node); n; n = getParent(n)) {
if (isTag(n) && attr(n, name) === value) return n;
}
return null;
}
/* ------------------------------------------------------------------ pagine */
check(existsSync(dist), 'dist/', 'cartella assente: esegui prima `npm run build`');
const htmlFiles = listHtmlFiles(dist);
const pages = htmlFiles.map((file) => {
const html = readFileSync(join(dist, file), 'utf8');
return { file: `dist/${file}`, path: fileToPath(file), html, doc: parseDocument(html) };
});
const byPath = new Map(pages.map((p) => [p.path, p]));
check(pages.length >= 18, 'dist/', `attese almeno 18 pagine HTML, trovate ${pages.length}`);
/* ------------------------------------------------------------------ file obbligatori */
for (const f of [
'.htaccess',
'404.html',
'robots.txt',
'sitemap-index.xml',
'favicon.svg',
'favicon.ico',
]) {
check(existsSync(join(dist, f)), `dist/${f}`, 'file obbligatorio mancante');
}
for (const p of LEGAL_PAGES) {
const page = byPath.get(p);
if (check(Boolean(page), `pagina ${p}`, 'pagina legale mancante')) {
check(byTag(page.doc, 'h1').length === 1, page.file, 'la pagina legale deve avere un <h1>');
}
}
/* ------------------------------------------------------------------ robots e sitemap */
const robots = existsSync(join(dist, 'robots.txt'))
? readFileSync(join(dist, 'robots.txt'), 'utf8')
: '';
check(
robots.includes(`Sitemap: ${SITE}/sitemap-index.xml`),
'dist/robots.txt',
`manca la riga «Sitemap: ${SITE}/sitemap-index.xml»`,
);
check(
/User-agent:\s*\*/i.test(robots) && /Allow:\s*\//i.test(robots),
'dist/robots.txt',
'mancano User-agent/Allow',
);
const sitemapPaths = readSitemapPaths(dist);
const expectedInSitemap = pages
.map((p) => p.path)
.filter((p) => !NOINDEX_PAGES.includes(p))
.sort();
for (const p of expectedInSitemap)
check(sitemapPaths.includes(p), 'sitemap', `manca la pagina ${p}`);
for (const p of sitemapPaths) {
check(expectedInSitemap.includes(p), 'sitemap', `contiene ${p}, che non esiste o è noindex`);
}
for (const p of NOINDEX_PAGES) {
const page = byPath.get(p);
if (check(Boolean(page), `pagina ${p}`, 'pagina mancante')) {
const robotsMeta = findOne(
(n) => n.name === 'meta' && attr(n, 'name') === 'robots',
page.doc.children,
);
check(
/noindex/.test(attr(robotsMeta ?? {}, 'content') ?? ''),
page.file,
'manca <meta name="robots" content="noindex">',
);
}
}
/* ------------------------------------------------------------------ controlli per pagina */
const PLACEHOLDERS = [
/\bTODO\b/,
/lorem/i,
/XXX/,
/\[da\b/i,
/\{\{|\}\}/,
/\bundefined\b/,
/\bnull\b/,
/NaN/,
];
const FORBIDDEN_REFS = [
/fonts\.googleapis\.com/i,
/gstatic/i,
/analytics/i,
/gtag/i,
/\bcdn\./i,
/googletagmanager/i,
];
const COMMERCIALISTA_OK =
/giulia|odcec|ordine dei dottori commercialisti|\bocc\b|organismo di composizione della crisi/i;
const titles = new Map();
const descriptions = new Map();
const year = String(new Date().getFullYear());
for (const page of pages) {
const { doc, file, path, html } = page;
const where = `${file} (${path})`;
// lingua, viewport, titolo, descrizione, canonical
const htmlEl = byTag(doc, 'html')[0];
check(attr(htmlEl ?? {}, 'lang') === 'it', where, 'manca lang="it" su <html>');
const viewport = findOne(
(n) => n.name === 'meta' && attr(n, 'name') === 'viewport',
doc.children,
);
const vp = attr(viewport ?? {}, 'content') ?? '';
check(Boolean(viewport), where, 'manca il meta viewport');
check(
!/user-scalable\s*=\s*(no|0)|maximum-scale/i.test(vp),
where,
`meta viewport che blocca lo zoom: «${vp}»`,
);
const title = normalize(textContent(byTag(doc, 'title')[0] ?? { children: [] }));
check(
title.length > 0 && title.length <= 65,
where,
`titolo vuoto o oltre 65 caratteri: «${title}»`,
);
if (titles.has(title)) fail(where, `titolo duplicato di ${titles.get(title)}: «${title}»`);
titles.set(title, path);
const descEl = findOne(
(n) => n.name === 'meta' && attr(n, 'name') === 'description',
doc.children,
);
const desc = normalize(attr(descEl ?? {}, 'content') ?? '');
check(
desc.length >= 120 && desc.length <= 155,
where,
`descrizione di ${desc.length} caratteri (attesi 120–155)`,
);
if (descriptions.has(desc)) fail(where, `descrizione duplicata di ${descriptions.get(desc)}`);
descriptions.set(desc, path);
if (path !== '/404.html') {
const canonical = findOne(
(n) => n.name === 'link' && attr(n, 'rel') === 'canonical',
doc.children,
);
check(
attr(canonical ?? {}, 'href') === `${SITE}${path}`,
where,
`canonical atteso ${SITE}${path}, trovato ${attr(canonical ?? {}, 'href')}`,
);
}
// un solo h1
check(
byTag(doc, 'h1').length === 1,
where,
`attesa una sola intestazione <h1>, trovate ${byTag(doc, 'h1').length}`,
);
// footer: P.IVA, anno, link legali
const footer = byTag(doc, 'footer')[0];
const footerText = footer ? normalize(visibleText(footer)) : '';
check(footerText.includes(PIVA), where, `il footer non contiene «${PIVA}»`);
check(
footerText.includes(`© ${year}`),
where,
`il footer non contiene «© ${year}» (anno di build)`,
);
for (const legal of ['/privacy-policy/', '/cookie-policy/', '/note-legali/', '/accessibilita/']) {
const found = all(doc, (n) => n.name === 'a' && attr(n, 'href') === legal).length > 0;
check(found, where, `manca il link a ${legal}`);
}
// risorse: niente http://, niente domini vietati, niente iframe statici
for (const el of all(doc, () => true)) {
for (const name of ['src', 'href', 'srcset', 'action', 'data-map-src', 'poster']) {
const v = attr(el, name);
if (v && /^\s*http:\/\//i.test(v))
fail(where, `risorsa o link non sicuro (http://) in <${el.name} ${name}="${v}">`);
}
for (const [name, value] of Object.entries(el.attribs ?? {})) {
if (/^on[a-z]+$/i.test(name))
fail(where, `gestore di evento inline vietato dalla CSP: <${el.name} ${name}="${value}">`);
}
}
for (const re of FORBIDDEN_REFS)
check(!re.test(html), where, `riferimento vietato a ${re.source.replace(/\\/g, '')}`);
check(
byTag(doc, 'iframe').length === 0,
where,
"<iframe> presente nell'HTML statico (la mappa va caricata solo su richiesta)",
);
// script: solo esterni dallo stesso sito o dati JSON-LD
for (const s of byTag(doc, 'script')) {
const type = attr(s, 'type') ?? '';
const src = attr(s, 'src');
if (type === 'application/ld+json') continue;
check(
Boolean(src) && src.startsWith('/'),
where,
`script inline o esterno non ammesso dalla CSP (type="${type}" src="${src ?? ''}")`,
);
}
// immagini con alt e dimensioni
for (const img of byTag(doc, 'img')) {
check(
attr(img, 'alt') !== undefined,
where,
`<img src="${attr(img, 'src')}"> senza attributo alt`,
);
check(
Boolean(attr(img, 'width') && attr(img, 'height')),
where,
`<img src="${attr(img, 'src')}"> senza width/height`,
);
}
// link esterni: rel="noopener", nessun target="_blank" non segnalato
for (const a of byTag(doc, 'a')) {
const href = attr(a, 'href') ?? '';
if (/^https?:\/\//.test(href) && !href.startsWith(SITE)) {
check(
/\bnoopener\b/.test(attr(a, 'rel') ?? ''),
where,
`link esterno senza rel="noopener": ${href}`,
);
}
if (attr(a, 'target') === '_blank') {
check(
/nuova scheda|nuova finestra/i.test(textContent(a)),
where,
`link con target="_blank" senza indicazione per screen reader: ${href}`,
);
}
}
// segnaposto nel testo visibile e negli attributi testuali
const text = visibleText(doc);
const attrText = all(doc, () => true)
.flatMap((el) =>
['alt', 'title', 'aria-label', 'placeholder', 'content', 'value'].map(
(n) => attr(el, n) ?? '',
),
)
.join(' ');
for (const re of PLACEHOLDERS) {
const m = (text + ' ' + attrText).match(re);
check(!m, where, `testo segnaposto «${m?.[0]}» presente nella pagina`);
}
// «commercialista» solo per la Dott.ssa Giulia Grasso, l'ODCEC o l'OCC (controllo per frase)
for (const node of textNodes(doc)) {
if (!/commercialist/i.test(node.data)) continue;
let p = getParent(node);
let skip = false;
for (; p; p = getParent(p))
if (isTag(p) && ['script', 'style', 'noscript'].includes(p.name)) skip = true;
if (skip) continue;
if (ancestorWithAttr(node, 'data-person', 'giulia-grasso')) continue;
const block = closestBlock(node) ?? getParent(node);
const blockText = normalize(visibleText(block));
for (const s of sentences(blockText).filter((x) => /commercialist/i.test(x))) {
check(
COMMERCIALISTA_OK.test(s),
where,
`«commercialista» usato fuori contesto (ammesso solo per la Dott.ssa Giulia Grasso, ODCEC, OCC): «${s}»`,
);
}
}
const lower = normalize(text).toLowerCase();
for (const bad of [
'studio commercialista',
'studio di commercialisti',
'studio di commercialista',
'commercialista ezio',
'ezio grasso, commercialista',
'ezio grasso commercialista',
]) {
check(!lower.includes(bad), where, `dicitura vietata «${bad}»`);
}
// JSON-LD
const ld = byTag(doc, 'script').filter((s) => attr(s, 'type') === 'application/ld+json');
check(ld.length > 0, where, 'nessun dato strutturato JSON-LD');
const nodes = [];
for (const s of ld) {
try {
const data = JSON.parse(textContent(s));
check(
data['@context'] === 'https://schema.org',
where,
'JSON-LD senza @context https://schema.org',
);
for (const item of data['@graph'] ?? [data]) {
check(Boolean(item['@type']), where, 'elemento JSON-LD senza @type');
nodes.push(item);
}
} catch (e) {
fail(where, `JSON-LD non valido: ${e.message}`);
}
}
const org = nodes.find((n) => n['@type'] === 'AccountingService');
if (check(Boolean(org), where, 'JSON-LD: manca AccountingService')) {
for (const k of [
'name',
'url',
'telephone',
'email',
'address',
'location',
'openingHoursSpecification',
'areaServed',
'employee',
'sameAs',
]) {
check(org[k] !== undefined, where, `JSON-LD AccountingService: manca «${k}»`);
}
check(
org.name === `${studio.nome} — ${studio.sottotitolo}`,
where,
`JSON-LD: name atteso «${studio.nome} — ${studio.sottotitolo}»`,
);
check(
org.vatID === `IT${studio.partitaIva}`,
where,
`JSON-LD: vatID atteso IT${studio.partitaIva}`,
);
check(
org.telephone === studio.telefoni[0].display,
where,
'JSON-LD: telefono diverso da studio.ts',
);
check(org.email === studio.email, where, 'JSON-LD: e-mail diversa da studio.ts');
check(
org.address?.['@type'] === 'PostalAddress',
where,
'JSON-LD: address non è un PostalAddress',
);
check(
Array.isArray(org.sameAs) && org.sameAs.length === 0,
where,
'JSON-LD: sameAs deve essere vuoto (nessun social)',
);
const hours = (org.openingHoursSpecification ?? [])
.map((h) => `${h.opens}-${h.closes}`)
.sort()
.join(',');
check(
hours === '09:00-12:30,15:00-18:30',
where,
`JSON-LD: orari attesi 09:00-12:30 e 15:00-18:30, trovati ${hours}`,
);
const people = (org.employee ?? org.founder ?? []).filter((p) => p['@type'] === 'Person');
check(people.length === professionisti.length, where, 'JSON-LD: professionisti mancanti');
for (const p of professionisti) {
const ldp = people.find((x) => x.name === p.nomeSenzaTitolo);
check(
ldp?.jobTitle === p.qualificaPrincipale,
where,
`JSON-LD: jobTitle di ${p.nome} diverso da studio.ts`,
);
}
}
const internal = path !== '/' && path !== '/404.html';
if (internal)
check(
nodes.some((n) => n['@type'] === 'BreadcrumbList'),
where,
'JSON-LD: manca BreadcrumbList',
);
if (/^\/servizi\/[^/]+\/$/.test(path)) {
const service = nodes.find((n) => n['@type'] === 'Service');
if (check(Boolean(service), where, 'JSON-LD: manca Service')) {
for (const k of ['name', 'description', 'provider', 'areaServed'])
check(Boolean(service[k]), where, `JSON-LD Service: manca «${k}»`);
}
}
// budget HTML + CSS (il CSS è incluso nella pagina)
const size = statSync(join(dist, file.replace(/^dist\//, ''))).size;
check(
size <= BUDGET_HTML_CSS,
where,
`HTML+CSS di ${Math.round(size / 1024)} KB oltre il budget di 120 KB`,
);
}
/* ------------------------------------------------------------------ contenuti attesi */
function servicesFromCollection() {
const dir = resolve(root, 'src/content/servizi');
return readdirSync(dir)
.filter((f) => f.endsWith('.md'))
.map((f) => {
const fm = readFileSync(join(dir, f), 'utf8').split('---')[1];
const get = (k) =>
(fm.match(new RegExp(`^${k}:\\s*(.+)$`, 'm'))?.[1] ?? '')
.trim()
.replace(/^['"]|['"]$/g, '');
return {
titolo: get('titolo'),
slug: get('slug'),
anchor: get('anchorLegacy'),
ordine: Number(get('ordine')),
};
})
.sort((a, b) => a.ordine - b.ordine);
}
const servizi = servicesFromCollection();
check(servizi.length === 6, 'src/content/servizi', `attesi 6 servizi, trovati ${servizi.length}`);
const hub = byPath.get('/servizi/');
const home = byPath.get('/');
for (const s of servizi) {
check(
byPath.has(`/servizi/${s.slug}/`),
`servizio «${s.titolo}»`,
`manca la pagina /servizi/${s.slug}/`,
);
if (hub) {
const card = findOne((n) => attr(n, 'id') === s.anchor, hub.doc.children);
check(
Boolean(card),
'dist/servizi/index.html',
`manca la card con id="${s.anchor}" (ancora del vecchio sito)`,
);
check(
attr(card ?? {}, 'data-legacy-href') === `/servizi/${s.slug}/`,
'dist/servizi/index.html',
`la card #${s.anchor} non punta a /servizi/${s.slug}/`,
);
}
if (home) {
const link = all(home.doc, (n) => n.name === 'a' && attr(n, 'href') === `/servizi/${s.slug}/`);
check(link.length > 0, 'dist/index.html', `la home non collega il servizio «${s.titolo}»`);
}
}
for (const [p, label] of [
['/', 'home'],
['/studio/', 'Lo studio'],
]) {
const page = byPath.get(p);
if (!page) continue;
const badges = all(page.doc, (n) => n.name === 'li' && /\bbadge\b/.test(attr(n, 'class') ?? ''));
check(
badges.length === abilitazioni.length,
page.file,
`${label}: attesi ${abilitazioni.length} badge di abilitazione, trovati ${badges.length}`,
);
abilitazioni.forEach((a, i) => {
const t = normalize(visibleText(badges[i] ?? { children: [] }));
check(
t.includes(normalize(a.testo)),
page.file,
`${label}: il badge n. ${i + 1} non corrisponde a studio.ts («${a.testo.slice(0, 60)}…»)`,
);
});
// riferimento L. 4/2013 nella scheda del Dott. Ezio Grasso
const ezio = findOne(
(n) => attr(n, 'data-person') === 'ezio-grasso' && n.name === 'article',
page.doc.children,
);
const et = normalize(visibleText(ezio ?? { children: [] }));
check(
/Legge 14 gennaio 2013, n\. 4/.test(et) && et.includes('1535'),
page.file,
`${label}: la scheda del Dott. Ezio Grasso non riporta il riferimento alla L. 4/2013 e l'iscrizione I.N.T. n. 1535`,
);
}
const note = byPath.get('/note-legali/');
if (note) {
const t = normalize(visibleText(note.doc));
check(
/Legge 14 gennaio 2013, n\. 4/.test(t),
note.file,
'le Note legali non riportano il riferimento alla L. 4/2013',
);
check(t.includes(PIVA.replace('P.IVA ', '')), note.file, 'le Note legali non riportano la P.IVA');
}
// modulo: con mode = off nessun <form>, ma card e-mail con oggetto precompilato
const contatti = byPath.get('/contatti/');
if (contatti) {
const forms = byTag(contatti.doc, 'form');
if (contactForm.mode === 'off') {
check(
forms.length === 0,
contatti.file,
'contactForm.mode = "off" ma la pagina contiene un <form>',
);
const mail = all(
contatti.doc,
(n) =>
n.name === 'a' && (attr(n, 'href') ?? '').startsWith(`mailto:${studio.email}?subject=`),
);
check(mail.length > 0, contatti.file, 'manca il pulsante e-mail con oggetto precompilato');
} else {
check(forms.length === 1, contatti.file, 'modulo di contatto assente');
const trap = all(contatti.doc, (n) => n.name === 'input' && attr(n, 'name') === 'sito_web');
check(
trap.length === 1 && attr(trap[0], 'tabindex') === '-1',
contatti.file,
'campo honeypot assente o raggiungibile da tastiera',
);
check(
all(contatti.doc, (n) => n.name === 'input' && attr(n, 'name') === 'ts').length === 1,
contatti.file,
'campo ts assente',
);
const privacy = all(
contatti.doc,
(n) =>
n.name === 'input' && attr(n, 'name') === 'privacy' && attr(n, 'required') !== undefined,
);
check(privacy.length === 1, contatti.file, 'checkbox privacy obbligatoria assente');
}
}
/* ------------------------------------------------------------------ asset */
const astroDir = join(dist, '_astro');
const assets = existsSync(astroDir) ? readdirSync(astroDir) : [];
const jsBytes = assets
.filter((f) => f.endsWith('.js'))
.reduce((n, f) => n + statSync(join(astroDir, f)).size, 0);
check(
jsBytes <= BUDGET_JS,
'dist/_astro',
`JavaScript totale ${(jsBytes / 1024).toFixed(1)} KB oltre il budget di 15 KB`,
);
for (const f of assets.filter((x) => /\.(js|css)$/.test(x))) {
const src = readFileSync(join(astroDir, f), 'utf8');
for (const re of FORBIDDEN_REFS)
check(
!re.test(src),
`dist/_astro/${f}`,
`riferimento vietato a ${re.source.replace(/\\/g, '')}`,
);
check(!/document\.cookie/.test(src), `dist/_astro/${f}`, 'uso di document.cookie');
check(
!/localStorage/.test(src),
`dist/_astro/${f}`,
'uso di localStorage (solo sessionStorage ammesso)',
);
}
const mapFiles = [];
(function walk(dir) {
for (const e of readdirSync(dir, { withFileTypes: true })) {
if (e.isDirectory()) walk(join(dir, e.name));
else if (e.name.endsWith('.map')) mapFiles.push(join(dir, e.name));
}
})(dist);
check(mapFiles.length === 0, 'dist/', `file .map presenti: ${mapFiles.join(', ')}`);
const preload = home
? all(
home.doc,
(n) => n.name === 'link' && attr(n, 'rel') === 'preload' && attr(n, 'as') === 'font',
)
: [];
check(
preload.length === 2,
'dist/index.html',
`attesi 2 font precaricati, trovati ${preload.length}`,
);
const fontBytes = preload.reduce((n, l) => n + statSync(join(dist, attr(l, 'href'))).size, 0);
check(
fontBytes <= BUDGET_FONTS,
'dist/index.html',
`font principali ${Math.round(fontBytes / 1024)} KB oltre il budget`,
);
/* ------------------------------------------------------------------ .htaccess */
const htaccess = existsSync(join(dist, '.htaccess'))
? readFileSync(join(dist, '.htaccess'), 'utf8')
: '';
for (const [re, what] of [
[/ErrorDocument 404 \/404\.html/, 'ErrorDocument 404 /404.html'],
[
/RedirectMatch 301 \^\/privacy\/\?\$ \/privacy-policy\//,
'redirect /privacy → /privacy-policy/',
],
[
/Content-Security-Policy "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self'; font-src 'self'; frame-src https:\/\/www\.google\.com; form-action 'self'; base-uri 'self'; frame-ancestors 'self'"/,
'Content-Security-Policy di §9.4',
],
[/X-Content-Type-Options "nosniff"/, 'X-Content-Type-Options'],
[/Referrer-Policy "strict-origin-when-cross-origin"/, 'Referrer-Policy'],
[/Permissions-Policy/, 'Permissions-Policy'],
[/X-Frame-Options "SAMEORIGIN"/, 'X-Frame-Options'],
[/#\s*Header always set Strict-Transport-Security/, 'HSTS presente ma commentato'],
[/\\\.map\$/, 'blocco dei file .map'],
]) {
check(re.test(htaccess), 'dist/.htaccess', `manca: ${what}`);
}
/* ------------------------------------------------------------------ esito */
if (errors.length > 0) {
console.error(
`✘ Conformità: ${errors.length} errori su ${checks} controlli (${pages.length} pagine)\n`,
);
for (const e of errors) console.error(` - ${e}`);
process.exit(1);
}
console.log(`✔ Conformità: ${checks} controlli superati su ${pages.length} pagine.`);
+74 -2
View File
@@ -1,2 +1,74 @@
// Segnaposto della fase 0: l'implementazione completa arriva nelle fasi successive (vedi DECISIONS.md). #!/usr/bin/env node
console.log('scripts/check-links.mjs: non ancora implementato (fase 0).'); /**
* Controllo dei link (brief §11.8) con linkinator sul sito servito da `astro preview`.
*
* npm run test:links link interni, immagini, asset, CSS e ancore (#…): bloccante
* npm run test:links -- --external anche i link verso siti esterni (da eseguire prima di un
* rilascio; dipende dalla rete)
*
* Le pagine di partenza sono lette dalla sitemap generata (più 404 e pagina di conferma).
*/
import { resolve } from 'node:path';
import { LinkChecker, LinkState } from 'linkinator';
import { EXTRA_PAGES, readSitemapPaths } from './lib/pages.mjs';
import { root, startPreview } from './lib/preview-server.mjs';
const external = process.argv.includes('--external');
const dist = resolve(root, 'dist');
const seeds = [...readSitemapPaths(dist), ...EXTRA_PAGES];
const server = await startPreview({ port: 4323 });
const base = server.base;
let exitCode = 0;
try {
const checker = new LinkChecker();
const result = await checker.check({
path: seeds.map((p) => base + p),
recurse: true,
concurrency: external ? 4 : 10,
timeout: external ? 20_000 : 10_000,
checkCss: true,
checkFragments: true,
retryErrors: external,
retryErrorsCount: 2,
linksToSkip: async (link) => {
if (link.startsWith(base)) return false;
if (!/^https?:\/\//.test(link)) return true; // mailto:, tel:, data:
return !external;
},
// Alcuni siti istituzionali rifiutano i controlli automatici: segnalati come avviso.
statusCodes: external
? { 401: 'warn', 403: 'warn', 405: 'warn', 429: 'warn', 999: 'warn' }
: {},
});
const checked = result.links.filter((l) => l.state !== LinkState.SKIPPED);
const broken = result.links.filter((l) => l.state === LinkState.BROKEN);
const internal = checked.filter((l) => l.url.startsWith(base));
const outside = checked.filter((l) => !l.url.startsWith(base));
const show = (u) => (u ?? '').replace(base, '');
console.log(
`Link controllati: ${internal.length} interni${external ? `, ${outside.length} esterni` : ''} ` +
`(partenza da ${seeds.length} pagine).`,
);
if (!external)
console.log('Link esterni non controllati: usa `npm run test:links -- --external`.');
if (broken.length > 0) {
exitCode = 1;
console.error(`\n✘ ${broken.length} link non funzionanti:`);
for (const l of broken) {
console.error(
` - ${show(l.url)} (stato ${l.status ?? 'nessuna risposta'}) nella pagina ${show(l.parent)}`,
);
}
} else {
console.log('✔ Nessun link non funzionante.');
}
} finally {
await server.stop();
}
process.exit(exitCode);
+1 -1
View File
@@ -12,7 +12,7 @@ const all = [{ name: 'Home', href: '/' }, ...items];
--- ---
<nav class="breadcrumb" aria-label="Percorso"> <nav class="breadcrumb" aria-label="Percorso">
<ol role="list"> <ol>
{all.map((c, i) => {all.map((c, i) =>
i === all.length - 1 ? ( i === all.length - 1 ? (
<li> <li>
+3 -3
View File
@@ -12,7 +12,7 @@
*/ */
import { contactForm, studio } from '../data/studio'; import { contactForm, studio } from '../data/studio';
import { modulo, scriviEmail } from '../data/testi'; import { modulo, scriviEmail } from '../data/testi';
import { mailtoHref, telHref } from '../lib/format'; import { mailtoHref, telHref, telText } from '../lib/format';
import Icon from './Icon.astro'; import Icon from './Icon.astro';
const mode = contactForm.mode; const mode = contactForm.mode;
@@ -33,7 +33,7 @@ const c = modulo.campi;
{scriviEmail.pulsante} {studio.email} {scriviEmail.pulsante} {studio.email}
</a> </a>
<p class="mail-card__note"> <p class="mail-card__note">
{scriviEmail.nota} <a href={telHref(telefono)}>{telefono.display}</a>. {scriviEmail.nota} <a href={telHref(telefono)}>{telText(telefono)}</a>.
</p> </p>
</div> </div>
) : ( ) : (
@@ -305,7 +305,7 @@ const c = modulo.campi;
gap: 0 var(--space-4); gap: 0 var(--space-4);
} }
@media (max-width: 640px) { @media (max-width: 40em) {
.field__row { .field__row {
grid-template-columns: minmax(0, 1fr); grid-template-columns: minmax(0, 1fr);
} }
+4 -4
View File
@@ -1,7 +1,7 @@
--- ---
/** Riquadri «Le sedi», «Recapiti» e «Orari» (pagine Contatti e Dove siamo). */ /** Riquadri «Le sedi», «Recapiti» e «Orari» (pagine Contatti e Dove siamo). */
import { sedePrincipale, studio } from '../data/studio'; import { sedePrincipale, studio } from '../data/studio';
import { cityLine, hoursLine, mailtoHref, telHref } from '../lib/format'; import { cityLine, hoursLine, mailtoHref, telHref, telText } from '../lib/format';
import Icon from './Icon.astro'; import Icon from './Icon.astro';
interface Props { interface Props {
@@ -46,12 +46,12 @@ const elencoSedi = [sedePrincipale, ...studio.sedi.filter((s) => s.id !== sedePr
<dd> <dd>
{studio.telefoni.map((t) => ( {studio.telefoni.map((t) => (
<span class="info__line"> <span class="info__line">
<a href={telHref(t)}>{t.display}</a> <a href={telHref(t)}>{telText(t)}</a>
</span> </span>
))} ))}
</dd> </dd>
<dt>Fax</dt> <dt>Fax</dt>
<dd>{studio.fax.display}</dd> <dd>{telText(studio.fax)}</dd>
<dt>E-mail</dt> <dt>E-mail</dt>
<dd> <dd>
<a href={mailtoHref(studio.email)}>{studio.email}</a> <a href={mailtoHref(studio.email)}>{studio.email}</a>
@@ -151,7 +151,7 @@ const elencoSedi = [sedePrincipale, ...studio.sedi.filter((s) => s.id !== sedePr
padding-block: 0.15rem; padding-block: 0.15rem;
} }
@media (max-width: 420px) { @media (max-width: 26.25em) {
.info dl { .info dl {
grid-template-columns: minmax(0, 1fr); grid-template-columns: minmax(0, 1fr);
gap: 0.1rem; gap: 0.1rem;
+3 -3
View File
@@ -2,7 +2,7 @@
/** Banda navy di invito all'azione (brief §6.3): titolo, testo, preventivo e telefono. */ /** Banda navy di invito all'azione (brief §6.3): titolo, testo, preventivo e telefono. */
import { studio } from '../data/studio'; import { studio } from '../data/studio';
import { ctaBand } from '../data/testi'; import { ctaBand } from '../data/testi';
import { telHref } from '../lib/format'; import { telHref, telText } from '../lib/format';
import Icon from './Icon.astro'; import Icon from './Icon.astro';
const telefono = studio.telefoni[0]; const telefono = studio.telefoni[0];
@@ -22,7 +22,7 @@ const telefono = studio.telefoni[0];
<a class="btn btn--ghost-light" href={telHref(telefono)}> <a class="btn btn--ghost-light" href={telHref(telefono)}>
<Icon name="phone" size={18} /> <Icon name="phone" size={18} />
<span class="visually-hidden">Telefono</span> <span class="visually-hidden">Telefono</span>
{telefono.display} {telText(telefono)}
</a> </a>
</div> </div>
</div> </div>
@@ -81,7 +81,7 @@ const telefono = studio.telefoni[0];
flex: none; flex: none;
} }
@media (max-width: 960px) { @media (max-width: 60em) {
.cta-band__inner { .cta-band__inner {
flex-direction: column; flex-direction: column;
align-items: flex-start; align-items: flex-start;
+10 -10
View File
@@ -6,7 +6,7 @@
import { navLegale } from '../data/navigazione'; import { navLegale } from '../data/navigazione';
import { denominazione, sedePrincipale, studio } from '../data/studio'; import { denominazione, sedePrincipale, studio } from '../data/studio';
import { buildYear } from '../lib/build'; import { buildYear } from '../lib/build';
import { addressLine, hoursLine, mailtoHref, telHref } from '../lib/format'; import { addressLine, hoursLine, mailtoHref, telHref, telText } from '../lib/format';
import { servizioHref, type Servizio } from '../lib/servizi'; import { servizioHref, type Servizio } from '../lib/servizi';
import Logo from './Logo.astro'; import Logo from './Logo.astro';
@@ -34,7 +34,7 @@ const datiSocietari = [
<div class="footer__studio"> <div class="footer__studio">
<Logo variant="dark" /> <Logo variant="dark" />
<p>{studio.descrizioneBreve}</p> <p>{studio.descrizioneBreve}</p>
<ul role="list"> <ul>
{sedi.map((s) => ( {sedi.map((s) => (
<li>{addressLine(s.indirizzo)}</li> <li>{addressLine(s.indirizzo)}</li>
))} ))}
@@ -43,13 +43,13 @@ const datiSocietari = [
<div> <div>
<h2 class="footer__title">Contatti</h2> <h2 class="footer__title">Contatti</h2>
<ul role="list"> <ul>
{studio.telefoni.map((t) => ( {studio.telefoni.map((t) => (
<li> <li>
Tel. <a href={telHref(t)}>{t.display}</a> Tel. <a href={telHref(t)}>{telText(t)}</a>
</li> </li>
))} ))}
<li>Fax {studio.fax.display}</li> <li>Fax {telText(studio.fax)}</li>
<li> <li>
<a href={mailtoHref(studio.email)}>{studio.email}</a> <a href={mailtoHref(studio.email)}>{studio.email}</a>
</li> </li>
@@ -64,7 +64,7 @@ const datiSocietari = [
<nav class="footer__services" aria-label="Servizi"> <nav class="footer__services" aria-label="Servizi">
<h2 class="footer__title">Servizi</h2> <h2 class="footer__title">Servizi</h2>
<ul role="list"> <ul>
{servizi.map((s) => ( {servizi.map((s) => (
<li> <li>
<a href={servizioHref(s)}>{s.data.titolo}</a> <a href={servizioHref(s)}>{s.data.titolo}</a>
@@ -75,7 +75,7 @@ const datiSocietari = [
<div> <div>
<h2 class="footer__title">Orari</h2> <h2 class="footer__title">Orari</h2>
<ul role="list"> <ul>
<li>{studio.orari.giorniEsteso}</li> <li>{studio.orari.giorniEsteso}</li>
<li>{hoursLine()}</li> <li>{hoursLine()}</li>
<li>{studio.orari.notaAsti}</li> <li>{studio.orari.notaAsti}</li>
@@ -89,7 +89,7 @@ const datiSocietari = [
{datiSocietari.length > 0 && <p>{datiSocietari.join(' — ')}</p>} {datiSocietari.length > 0 && <p>{datiSocietari.join(' — ')}</p>}
</div> </div>
<nav aria-label="Informazioni legali"> <nav aria-label="Informazioni legali">
<ul role="list"> <ul>
{navLegale.map((item) => ( {navLegale.map((item) => (
<li> <li>
<a <a
@@ -201,13 +201,13 @@ const datiSocietari = [
min-height: var(--tap); min-height: var(--tap);
} }
@media (max-width: 960px) { @media (max-width: 60em) {
.footer__grid { .footer__grid {
grid-template-columns: 1fr 1fr; grid-template-columns: 1fr 1fr;
} }
} }
@media (max-width: 640px) { @media (max-width: 40em) {
.footer__grid { .footer__grid {
grid-template-columns: 1fr; grid-template-columns: 1fr;
} }
+5 -5
View File
@@ -5,7 +5,7 @@
* durante lo scorrimento; la barra superiore scorre via. * durante lo scorrimento; la barra superiore scorre via.
*/ */
import { sedePrincipale, studio } from '../data/studio'; import { sedePrincipale, studio } from '../data/studio';
import { mailtoHref, telHref } from '../lib/format'; import { mailtoHref, telHref, telText } from '../lib/format';
import type { Servizio } from '../lib/servizi'; import type { Servizio } from '../lib/servizi';
import Icon from './Icon.astro'; import Icon from './Icon.astro';
import Logo from './Logo.astro'; import Logo from './Logo.astro';
@@ -27,7 +27,7 @@ const short = (s: (typeof sedi)[number]) =>
<header class="site-header"> <header class="site-header">
<div class="topbar"> <div class="topbar">
<div class="container topbar__inner"> <div class="container topbar__inner">
<ul class="topbar__list" role="list" aria-label="Sedi"> <ul class="topbar__list" aria-label="Sedi">
{sedi.map((s) => ( {sedi.map((s) => (
<li> <li>
<Icon name="map-pin" size={14} /> <Icon name="map-pin" size={14} />
@@ -35,10 +35,10 @@ const short = (s: (typeof sedi)[number]) =>
</li> </li>
))} ))}
</ul> </ul>
<ul class="topbar__list" role="list" aria-label="Recapiti"> <ul class="topbar__list" aria-label="Recapiti">
<li> <li>
<Icon name="phone" size={14} /> <Icon name="phone" size={14} />
<a href={telHref(telefono)}>{telefono.display}</a> <a href={telHref(telefono)}>{telText(telefono)}</a>
</li> </li>
<li> <li>
<Icon name="mail" size={14} /> <Icon name="mail" size={14} />
@@ -120,7 +120,7 @@ const short = (s: (typeof sedi)[number]) =>
min-height: var(--header-h); min-height: var(--header-h);
} }
@media (max-width: 960px) { @media (max-width: 60em) {
.site-header { .site-header {
top: 0; top: 0;
} }
+5 -5
View File
@@ -38,7 +38,7 @@ const { eyebrow, titolo, titoloCorsivo, testo, ctaPrimaria, ctaSecondaria, fiduc
{ctaSecondaria.label} {ctaSecondaria.label}
</a> </a>
</div> </div>
<ul class="hero__trust" role="list"> <ul class="hero__trust">
{fiducia.map((voce) => ( {fiducia.map((voce) => (
<li> <li>
<Icon name="circle-check" size={18} /> <Icon name="circle-check" size={18} />
@@ -50,7 +50,7 @@ const { eyebrow, titolo, titoloCorsivo, testo, ctaPrimaria, ctaSecondaria, fiduc
<div class="hero__visual"> <div class="hero__visual">
<div class="hero__blob" aria-hidden="true"></div> <div class="hero__blob" aria-hidden="true"></div>
<div class="hero__ring" aria-hidden="true"></div> <div class="hero__ring" aria-hidden="true"></div>
<ul class="hero__facts" role="list"> <ul class="hero__facts">
{fatti.map((f, i) => ( {fatti.map((f, i) => (
<li class:list={['fact', `fact--${i + 1}`]}> <li class:list={['fact', `fact--${i + 1}`]}>
<span class="fact__icon"> <span class="fact__icon">
@@ -131,7 +131,7 @@ const { eyebrow, titolo, titoloCorsivo, testo, ctaPrimaria, ctaSecondaria, fiduc
.hero__visual { .hero__visual {
position: relative; position: relative;
min-height: 420px; min-height: 26.25rem;
} }
.hero__blob { .hero__blob {
@@ -161,7 +161,7 @@ const { eyebrow, titolo, titoloCorsivo, testo, ctaPrimaria, ctaSecondaria, fiduc
display: flex; display: flex;
gap: var(--space-3); gap: var(--space-3);
align-items: flex-start; align-items: flex-start;
width: 300px; width: 18.75rem;
padding: var(--space-4) var(--space-5); padding: var(--space-4) var(--space-5);
background: var(--white); background: var(--white);
border: 1px solid var(--line); border: 1px solid var(--line);
@@ -215,7 +215,7 @@ const { eyebrow, titolo, titoloCorsivo, testo, ctaPrimaria, ctaSecondaria, fiduc
bottom: 6%; bottom: 6%;
} }
@media (max-width: 960px) { @media (max-width: 60em) {
.hero__inner { .hero__inner {
grid-template-columns: minmax(0, 1fr); grid-template-columns: minmax(0, 1fr);
gap: var(--space-6); gap: var(--space-6);
+10 -5
View File
@@ -7,6 +7,7 @@ import type { MarkdownHeading } from 'astro';
import { getEntry } from 'astro:content'; import { getEntry } from 'astro:content';
import BaseLayout from '../layouts/BaseLayout.astro'; import BaseLayout from '../layouts/BaseLayout.astro';
import { formatDateIt } from '../lib/format'; import { formatDateIt } from '../lib/format';
import { externalLinksNoopener } from '../lib/html';
import { renderLegal } from '../lib/legal'; import { renderLegal } from '../lib/legal';
import PageHead from './PageHead.astro'; import PageHead from './PageHead.astro';
@@ -20,7 +21,11 @@ interface Props {
const { id, dataLabel = 'Ultimo aggiornamento' } = Astro.props; const { id, dataLabel = 'Ultimo aggiornamento' } = Astro.props;
const entry = await getEntry('legali', id); const entry = await getEntry('legali', id);
if (!entry) throw new Error(`Testo legale mancante: src/content/legali/${id}.md`); if (!entry) throw new Error(`Testo legale mancante: src/content/legali/${id}.md`);
const html = renderLegal(entry.rendered?.html ?? '', `src/content/legali/${id}.md`); const siteHost = (Astro.site ?? new URL('https://www.grassoezio.it')).host;
const html = externalLinksNoopener(
renderLegal(entry.rendered?.html ?? '', `src/content/legali/${id}.md`),
siteHost,
);
const allHeadings = (entry.rendered?.metadata?.headings ?? []) as MarkdownHeading[]; const allHeadings = (entry.rendered?.metadata?.headings ?? []) as MarkdownHeading[];
const headings = allHeadings.filter((h) => h.depth === 2); const headings = allHeadings.filter((h) => h.depth === 2);
const path = `/${id}/`; const path = `/${id}/`;
@@ -47,7 +52,7 @@ const updated = entry.data.aggiornato;
<p class="doc-toc__title" id="indice-titolo"> <p class="doc-toc__title" id="indice-titolo">
Indice Indice
</p> </p>
<ol role="list"> <ol>
{headings.map((h) => ( {headings.map((h) => (
<li> <li>
<a href={`#${h.slug}`}>{h.text}</a> <a href={`#${h.slug}`}>{h.text}</a>
@@ -70,7 +75,7 @@ const updated = entry.data.aggiornato;
.doc-layout { .doc-layout {
display: grid; display: grid;
grid-template-columns: 260px minmax(0, 1fr); grid-template-columns: 16.25rem minmax(0, 1fr);
gap: var(--space-8); gap: var(--space-8);
align-items: start; align-items: start;
} }
@@ -161,7 +166,7 @@ const updated = entry.data.aggiornato;
color: var(--ink-600); color: var(--ink-600);
} }
@media (max-width: 960px) { @media (max-width: 60em) {
.doc-layout { .doc-layout {
grid-template-columns: minmax(0, 1fr); grid-template-columns: minmax(0, 1fr);
gap: var(--space-6); gap: var(--space-6);
@@ -172,7 +177,7 @@ const updated = entry.data.aggiornato;
} }
} }
@media (max-width: 420px) { @media (max-width: 26.25em) {
.doc :global(dl.doc-card) { .doc :global(dl.doc-card) {
grid-template-columns: minmax(0, 1fr); grid-template-columns: minmax(0, 1fr);
gap: 0.1rem; gap: 0.1rem;
+5 -5
View File
@@ -7,7 +7,7 @@
*/ */
import { ctaHeader, isCurrentSection, navPrincipale } from '../data/navigazione'; import { ctaHeader, isCurrentSection, navPrincipale } from '../data/navigazione';
import { studio } from '../data/studio'; import { studio } from '../data/studio';
import { mailtoHref, telHref } from '../lib/format'; import { mailtoHref, telHref, telText } from '../lib/format';
import { servizioHref, type Servizio } from '../lib/servizi'; import { servizioHref, type Servizio } from '../lib/servizi';
import Icon from './Icon.astro'; import Icon from './Icon.astro';
import Logo from './Logo.astro'; import Logo from './Logo.astro';
@@ -43,7 +43,7 @@ const telefono = studio.telefoni[0];
</button> </button>
</div> </div>
<nav class="mobile-menu__nav" aria-label="Menu mobile"> <nav class="mobile-menu__nav" aria-label="Menu mobile">
<ul class="mobile-menu__list" role="list"> <ul class="mobile-menu__list">
{navPrincipale.map((item) => {navPrincipale.map((item) =>
item.servizi ? ( item.servizi ? (
<li class="mobile-menu__item"> <li class="mobile-menu__item">
@@ -62,7 +62,7 @@ const telefono = studio.telefoni[0];
<span class="visually-hidden">Sottomenu {item.label}</span> <span class="visually-hidden">Sottomenu {item.label}</span>
</button> </button>
</div> </div>
<ul class="mobile-menu__sub submenu-list" id="menu-mobile-servizi" role="list"> <ul class="mobile-menu__sub submenu-list" id="menu-mobile-servizi">
{servizi.map((s) => ( {servizi.map((s) => (
<li> <li>
<a href={servizioHref(s)} aria-current={current(servizioHref(s))}> <a href={servizioHref(s)} aria-current={current(servizioHref(s))}>
@@ -89,7 +89,7 @@ const telefono = studio.telefoni[0];
</a> </a>
<a class="btn btn--outline btn--block" href={telHref(telefono)}> <a class="btn btn--outline btn--block" href={telHref(telefono)}>
<Icon name="phone" size={18} /> <Icon name="phone" size={18} />
{telefono.display} {telText(telefono)}
</a> </a>
<a class="mobile-menu__mail" href={mailtoHref(studio.email)}> <a class="mobile-menu__mail" href={mailtoHref(studio.email)}>
<Icon name="mail" size={18} /> <Icon name="mail" size={18} />
@@ -118,7 +118,7 @@ const telefono = studio.telefoni[0];
height: 22px; height: 22px;
} }
@media (max-width: 960px) { @media (max-width: 60em) {
.menu-toggle { .menu-toggle {
display: inline-flex; display: inline-flex;
} }
+6 -6
View File
@@ -6,7 +6,7 @@
*/ */
import { ctaHeader, isCurrentSection, navPrincipale } from '../data/navigazione'; import { ctaHeader, isCurrentSection, navPrincipale } from '../data/navigazione';
import { studio } from '../data/studio'; import { studio } from '../data/studio';
import { telHref } from '../lib/format'; import { telHref, telText } from '../lib/format';
import { servizioHref, type Servizio } from '../lib/servizi'; import { servizioHref, type Servizio } from '../lib/servizi';
import Icon from './Icon.astro'; import Icon from './Icon.astro';
@@ -21,7 +21,7 @@ const current = (href: string) =>
--- ---
<nav class="nav" aria-label="Principale"> <nav class="nav" aria-label="Principale">
<ul class="nav__list" role="list"> <ul class="nav__list">
{navPrincipale.map((item) => {navPrincipale.map((item) =>
item.servizi ? ( item.servizi ? (
<li class="nav__item nav__item--has-sub" data-submenu> <li class="nav__item nav__item--has-sub" data-submenu>
@@ -38,7 +38,7 @@ const current = (href: string) =>
<Icon name="chevron-down" size={16} /> <Icon name="chevron-down" size={16} />
<span class="visually-hidden">Sottomenu {item.label}</span> <span class="visually-hidden">Sottomenu {item.label}</span>
</button> </button>
<ul class="nav__sub" id="sottomenu-servizi" role="list"> <ul class="nav__sub" id="sottomenu-servizi">
{servizi.map((s) => ( {servizi.map((s) => (
<li> <li>
<a href={servizioHref(s)} aria-current={current(servizioHref(s))}> <a href={servizioHref(s)} aria-current={current(servizioHref(s))}>
@@ -61,7 +61,7 @@ const current = (href: string) =>
<a class="nav__phone" href={telHref(studio.telefoni[0])}> <a class="nav__phone" href={telHref(studio.telefoni[0])}>
<Icon name="phone" size={16} /> <Icon name="phone" size={16} />
<span class="visually-hidden">Telefono</span> <span class="visually-hidden">Telefono</span>
{studio.telefonoPrincipaleBreve} {telText(studio.telefonoPrincipaleBreve)}
</a> </a>
<a class="btn btn--primary btn--sm" href={ctaHeader.href}> <a class="btn btn--primary btn--sm" href={ctaHeader.href}>
{ctaHeader.label} {ctaHeader.label}
@@ -227,7 +227,7 @@ const current = (href: string) =>
white-space: nowrap; white-space: nowrap;
} }
@media (max-width: 1100px) { @media (max-width: 68.75em) {
.nav { .nav {
gap: var(--space-3); gap: var(--space-3);
} }
@@ -237,7 +237,7 @@ const current = (href: string) =>
} }
} }
@media (max-width: 960px) { @media (max-width: 60em) {
.nav { .nav {
display: none; display: none;
} }
+3 -3
View File
@@ -9,7 +9,7 @@ interface Props {
const { partner } = Astro.props; const { partner } = Astro.props;
--- ---
<ul class="partners" role="list"> <ul class="partners">
{partner.map((p) => ( {partner.map((p) => (
<li class="partner"> <li class="partner">
<Icon name={p.icona} size={22} /> <Icon name={p.icona} size={22} />
@@ -59,13 +59,13 @@ const { partner } = Astro.props;
line-height: 1.45; line-height: 1.45;
} }
@media (max-width: 960px) { @media (max-width: 60em) {
.partners { .partners {
grid-template-columns: repeat(2, minmax(0, 1fr)); grid-template-columns: repeat(2, minmax(0, 1fr));
} }
} }
@media (max-width: 640px) { @media (max-width: 40em) {
.partners { .partners {
grid-template-columns: minmax(0, 1fr); grid-template-columns: minmax(0, 1fr);
} }
+2 -2
View File
@@ -25,7 +25,7 @@ const qualifiche = variant === 'full' ? persona.qualifiche : persona.qualificheS
<div class="person__body"> <div class="person__body">
<Heading class="person__name">{persona.nome}</Heading> <Heading class="person__name">{persona.nome}</Heading>
<p class="person__role">{persona.qualificaPrincipale}</p> <p class="person__role">{persona.qualificaPrincipale}</p>
<ul class="person__list" role="list"> <ul class="person__list">
{qualifiche.map((q) => ( {qualifiche.map((q) => (
<li>{q}</li> <li>{q}</li>
))} ))}
@@ -127,7 +127,7 @@ const qualifiche = variant === 'full' ? persona.qualifiche : persona.qualificheS
overflow-wrap: anywhere; overflow-wrap: anywhere;
} }
@media (max-width: 420px) { @media (max-width: 26.25em) {
.person { .person {
grid-template-columns: minmax(0, 1fr); grid-template-columns: minmax(0, 1fr);
} }
+3 -3
View File
@@ -5,7 +5,7 @@
*/ */
import type { Sede } from '../data/studio'; import type { Sede } from '../data/studio';
import { studio } from '../data/studio'; import { studio } from '../data/studio';
import { cityLine, googleDirectionsUrl, hoursLine, telHref } from '../lib/format'; import { cityLine, googleDirectionsUrl, hoursLine, telHref, telText } from '../lib/format';
import Icon from './Icon.astro'; import Icon from './Icon.astro';
import MapConsent from './MapConsent.astro'; import MapConsent from './MapConsent.astro';
@@ -45,7 +45,7 @@ const telefono = studio.telefoni[0];
<strong>Ricevimento</strong> <strong>Ricevimento</strong>
<span>Su appuntamento</span> <span>Su appuntamento</span>
<span> <span>
Per fissare un appuntamento: tel. <a href={telHref(telefono)}>{telefono.display}</a> Per fissare un appuntamento: tel. <a href={telHref(telefono)}>{telText(telefono)}</a>
</span> </span>
</> </>
) : ( ) : (
@@ -69,7 +69,7 @@ const telefono = studio.telefoni[0];
{variant === 'full' && ( {variant === 'full' && (
<a class="btn btn--primary btn--sm" href={telHref(telefono)}> <a class="btn btn--primary btn--sm" href={telHref(telefono)}>
<Icon name="phone" size={16} /> <Icon name="phone" size={16} />
Chiama<span class="visually-hidden"> lo {telefono.display}</span> Chiama<span class="visually-hidden">{telText(` lo ${telefono.display}`)}</span>
</a> </a>
)} )}
</div> </div>
+10 -3
View File
@@ -29,16 +29,23 @@ Il sito non usa questi dati per identificare o profilare chi lo visita e non uti
### Dati che comunichi allo Studio ### Dati che comunichi allo Studio
Se scrivi allo Studio per e-mail o PEC, o lo contatti per telefono, vengono trattati i dati che comunichi: di norma nome e cognome, indirizzo e-mail o numero di telefono e il contenuto della richiesta.
<!-- se:modulo --> <!-- se:modulo -->
Se usi il modulo della pagina [Contatti](/contatti/) vengono trattati i dati che inserisci: nome e cognome, indirizzo e-mail, numero di telefono, oggetto e testo del messaggio. Il modulo include controlli anti-spam che non usano cookie né servizi di terze parti. Se usi il modulo della pagina [Contatti](/contatti/) vengono trattati i dati che inserisci: nome e cognome, indirizzo e-mail, numero di telefono, oggetto e testo del messaggio. Il modulo include controlli anti-spam che non usano cookie né servizi di terze parti.
<!-- /se:modulo --> <!-- /se:modulo -->
<!-- se:!modulo --> <!-- se:moduloPhp -->
Se scrivi allo Studio per e-mail o PEC, o lo contatti per telefono, vengono trattati i dati che comunichi: di norma nome e cognome, indirizzo e-mail o numero di telefono e il contenuto della richiesta. Le richieste inviate con il modulo non vengono conservate sul server del sito: sono inoltrate alla casella di posta elettronica dello Studio.
<!-- /se:!modulo --> <!-- /se:moduloPhp -->
<!-- se:moduloEsterno -->
Le richieste inviate con il modulo sono trasmesse al fornitore del servizio di gestione dei moduli, che opera come responsabile del trattamento ai sensi dell’art. 28 GDPR, all’interno dell’Unione europea.
<!-- /se:moduloEsterno -->
- **Finalità:** rispondere alla richiesta e gestire i contatti che precedono un eventuale incarico, come la richiesta di un preventivo. - **Finalità:** rispondere alla richiesta e gestire i contatti che precedono un eventuale incarico, come la richiesta di un preventivo.
- **Base giuridica:** esecuzione di misure precontrattuali adottate su tua richiesta (art. 6, par. 1, lett. b, GDPR) e, per quanto non necessario a tale scopo, il tuo consenso (art. 6, par. 1, lett. a, GDPR), che puoi revocare in qualsiasi momento. - **Base giuridica:** esecuzione di misure precontrattuali adottate su tua richiesta (art. 6, par. 1, lett. b, GDPR) e, per quanto non necessario a tale scopo, il tuo consenso (art. 6, par. 1, lett. a, GDPR), che puoi revocare in qualsiasi momento.
+1 -1
View File
@@ -102,7 +102,7 @@ const servizi = await getServizi();
.submenu-list { .submenu-list {
display: block !important; display: block !important;
} }
@media (max-width: 960px) { @media (max-width: 60em) {
.site-header { .site-header {
position: static !important; position: static !important;
} }
+5
View File
@@ -18,6 +18,11 @@ export function telHref(phone: Phone): string {
return `tel:${phone.e164}`; return `tel:${phone.e164}`;
} }
/** Numero da mostrare con spazi non separabili, così non va mai a capo. */
export function telText(phone: Phone | string): string {
return (typeof phone === 'string' ? phone : phone.display).replace(/ /g, '\u00a0');
}
export function mailtoHref(email: string, subject?: string): string { export function mailtoHref(email: string, subject?: string): string {
return subject ? `mailto:${email}?subject=${encodeURIComponent(subject)}` : `mailto:${email}`; return subject ? `mailto:${email}?subject=${encodeURIComponent(subject)}` : `mailto:${email}`;
} }
+26
View File
@@ -0,0 +1,26 @@
/**
* Post-elaborazione dell'HTML generato dal Markdown.
*/
function hostOf(href: string): string | null {
try {
return new URL(href).host;
} catch {
return null;
}
}
/**
* Aggiunge `rel="noopener"` ai link verso altri siti (brief §4.7); i link si aprono nella stessa
* scheda. `siteHost` è l'host del sito (i link interni assoluti restano invariati).
*/
export function externalLinksNoopener(html: string, siteHost: string): string {
return html.replace(
/<a\s+href="(https?:\/\/[^"]+)"([^>]*)>/g,
(match, href: string, rest: string) => {
const host = hostOf(href);
if (!host || host === siteHost || /\brel=/.test(rest)) return match;
return `<a href="${href}" rel="noopener"${rest}>`;
},
);
}
+13 -7
View File
@@ -10,7 +10,7 @@
* restare nessun segnaposto. * restare nessun segnaposto.
*/ */
import { contactForm, denominazione, professionisti, sedePrincipale, studio } from '../data/studio'; import { contactForm, denominazione, professionisti, sedePrincipale, studio } from '../data/studio';
import { addressLine, mailtoHref, telHref } from './format'; import { addressLine, mailtoHref, telHref, telText } from './format';
const esc = (s: string) => const esc = (s: string) =>
s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;'); s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
@@ -44,7 +44,7 @@ function bloccoTitolare(): string {
const [k, ...v] = riga.split(': '); const [k, ...v] = riga.split(': ');
rows.push(v.length ? [k, esc(v.join(': '))] : ['Note', esc(riga)]); rows.push(v.length ? [k, esc(v.join(': '))] : ['Note', esc(riga)]);
} }
rows.push(['Telefono', `<a href="${esc(telHref(telefono))}">${esc(telefono.display)}</a>`]); rows.push(['Telefono', `<a href="${esc(telHref(telefono))}">${esc(telText(telefono))}</a>`]);
rows.push(['E-mail', mailLink(studio.email)]); rows.push(['E-mail', mailLink(studio.email)]);
if (pecStudio) rows.push(['PEC', mailLink(pecStudio.indirizzo)]); if (pecStudio) rows.push(['PEC', mailLink(pecStudio.indirizzo)]);
return `<dl class="doc-card">${rows.map(([k, v]) => `<dt>${k}</dt><dd>${v}</dd>`).join('')}</dl>`; return `<dl class="doc-card">${rows.map(([k, v]) => `<dt>${k}</dt><dd>${v}</dd>`).join('')}</dl>`;
@@ -77,7 +77,7 @@ function tokens(): Record<string, string> {
piva: esc(studio.partitaIva), piva: esc(studio.partitaIva),
email: mailLink(studio.email), email: mailLink(studio.email),
pecStudio: mailLink(studio.pec[0].indirizzo), pecStudio: mailLink(studio.pec[0].indirizzo),
telefono: `<a href="${esc(telHref(studio.telefoni[0]))}">${esc(studio.telefoni[0].display)}</a>`, telefono: `<a href="${esc(telHref(studio.telefoni[0]))}">${esc(telText(studio.telefoni[0]))}</a>`,
fornitoreHosting: f.hosting fornitoreHosting: f.hosting
? `il fornitore del servizio di hosting (${esc(f.hosting)})` ? `il fornitore del servizio di hosting (${esc(f.hosting)})`
: 'il fornitore del servizio di hosting', : 'il fornitore del servizio di hosting',
@@ -96,6 +96,7 @@ function tokens(): Record<string, string> {
function conditions(): Record<string, boolean> { function conditions(): Record<string, boolean> {
return { return {
modulo: contactForm.mode !== 'off', modulo: contactForm.mode !== 'off',
moduloPhp: contactForm.mode === 'php',
moduloEsterno: contactForm.mode === 'endpoint', moduloEsterno: contactForm.mode === 'endpoint',
societa: datiSocietari().length > 0, societa: datiSocietari().length > 0,
hosting: studio.fornitori.hosting !== null, hosting: studio.fornitori.hosting !== null,
@@ -110,10 +111,15 @@ const COND = /<!--\s*se:(!?)([a-zA-Z]+)\s*-->([\s\S]*?)<!--\s*\/se:!?\2\s*-->/g;
export function renderLegal(html: string, source: string): string { export function renderLegal(html: string, source: string): string {
const conds = conditions(); const conds = conditions();
const vals = tokens(); const vals = tokens();
let out = html.replace(COND, (_m, neg: string, name: string, body: string) => { // più passaggi: i blocchi condizionali possono essere annidati
if (!(name in conds)) throw new Error(`${source}: condizione sconosciuta «${name}»`); let out = html;
return conds[name] !== (neg === '!') ? body : ''; for (let previous = ''; previous !== out;) {
}); previous = out;
out = out.replace(COND, (_m, neg: string, name: string, body: string) => {
if (!(name in conds)) throw new Error(`${source}: condizione sconosciuta «${name}»`);
return conds[name] !== (neg === '!') ? body : '';
});
}
out = out.replace(BLOCK_TOKEN, (_m, name: string) => vals[name]); out = out.replace(BLOCK_TOKEN, (_m, name: string) => vals[name]);
out = out.replace(TOKEN, (_m, name: string) => { out = out.replace(TOKEN, (_m, name: string) => {
if (!(name in vals)) throw new Error(`${source}: segnaposto sconosciuto «{{${name}}}»`); if (!(name in vals)) throw new Error(`${source}: segnaposto sconosciuto «{{${name}}}»`);
+1 -1
View File
@@ -11,7 +11,7 @@ import BaseLayout from '../layouts/BaseLayout.astro';
<p class="eyebrow">Errore 404</p> <p class="eyebrow">Errore 404</p>
<h1>{t.titolo}</h1> <h1>{t.titolo}</h1>
<p class="lead">{t.testo}</p> <p class="lead">{t.testo}</p>
<ul class="notfound__links" role="list"> <ul class="notfound__links">
{t.link.map((l) => ( {t.link.map((l) => (
<li> <li>
<a class="btn btn--outline" href={l.href}> <a class="btn btn--outline" href={l.href}>
+1 -1
View File
@@ -66,7 +66,7 @@ const breadcrumbs = [{ name: t.titolo, href: '/contatti/' }];
color: var(--navy-800); color: var(--navy-800);
} }
@media (max-width: 960px) { @media (max-width: 60em) {
.contact-grid { .contact-grid {
grid-template-columns: minmax(0, 1fr); grid-template-columns: minmax(0, 1fr);
gap: var(--space-6); gap: var(--space-6);
+1 -1
View File
@@ -55,7 +55,7 @@ const sedi = [sedePrincipale, ...studio.sedi.filter((s) => s.id !== sedePrincipa
margin-bottom: 0; margin-bottom: 0;
} }
@media (max-width: 960px) { @media (max-width: 60em) {
.recapiti { .recapiti {
grid-template-columns: minmax(0, 1fr); grid-template-columns: minmax(0, 1fr);
gap: var(--space-5); gap: var(--space-5);
+3 -3
View File
@@ -57,7 +57,7 @@ const sedi = [sedePrincipale, ...studio.sedi.filter((s) => s.id !== sedePrincipa
{home.studio.paragrafi.map((p) => ( {home.studio.paragrafi.map((p) => (
<p>{p}</p> <p>{p}</p>
))} ))}
<ul class="chips home-values" role="list" aria-label="I nostri valori"> <ul class="chips home-values" aria-label="I nostri valori">
{valori.map((v) => ( {valori.map((v) => (
<li class="chip">{v.nome}</li> <li class="chip">{v.nome}</li>
))} ))}
@@ -83,7 +83,7 @@ const sedi = [sedePrincipale, ...studio.sedi.filter((s) => s.id !== sedePrincipa
title={home.abilitazioni.titolo} title={home.abilitazioni.titolo}
subtitle={home.abilitazioni.sottotitolo} subtitle={home.abilitazioni.sottotitolo}
/> />
<ul class="grid grid--3 badges" role="list"> <ul class="grid grid--3 badges">
{abilitazioni.map((a) => ( {abilitazioni.map((a) => (
<BadgeAbilitazione <BadgeAbilitazione
testo={a.testo} testo={a.testo}
@@ -143,7 +143,7 @@ const sedi = [sedePrincipale, ...studio.sedi.filter((s) => s.id !== sedePrincipa
list-style: none; list-style: none;
} }
@media (max-width: 960px) { @media (max-width: 60em) {
.split { .split {
grid-template-columns: minmax(0, 1fr); grid-template-columns: minmax(0, 1fr);
gap: var(--space-6); gap: var(--space-6);
+1 -1
View File
@@ -17,7 +17,7 @@ const breadcrumbs = [{ name: t.titolo, href: '/link-utili/' }];
<section class="section" aria-label="Elenco dei link"> <section class="section" aria-label="Elenco dei link">
<div class="container"> <div class="container">
<ul class="grid grid--2 links" role="list"> <ul class="grid grid--2 links">
{links.map((l) => ( {links.map((l) => (
<li class="link-card"> <li class="link-card">
<span class="link-card__icon"> <span class="link-card__icon">
+9 -9
View File
@@ -5,14 +5,14 @@
* successivo. * successivo.
*/ */
import type { GetStaticPaths } from 'astro'; import type { GetStaticPaths } from 'astro';
import { render } from 'astro:content';
import CtaBand from '../../components/CtaBand.astro'; import CtaBand from '../../components/CtaBand.astro';
import Icon from '../../components/Icon.astro'; import Icon from '../../components/Icon.astro';
import PageHead from '../../components/PageHead.astro'; import PageHead from '../../components/PageHead.astro';
import { studio } from '../../data/studio'; import { studio } from '../../data/studio';
import { ctaSidebar } from '../../data/testi'; import { ctaSidebar } from '../../data/testi';
import BaseLayout from '../../layouts/BaseLayout.astro'; import BaseLayout from '../../layouts/BaseLayout.astro';
import { telHref } from '../../lib/format'; import { externalLinksNoopener } from '../../lib/html';
import { telHref, telText } from '../../lib/format';
import { serviceLd } from '../../lib/seo'; import { serviceLd } from '../../lib/seo';
import { getServizi, servizioHref, type Servizio } from '../../lib/servizi'; import { getServizi, servizioHref, type Servizio } from '../../lib/servizi';
@@ -37,7 +37,6 @@ interface Props {
} }
const { servizio, servizi, prev, next } = Astro.props; const { servizio, servizi, prev, next } = Astro.props;
const { Content } = await render(servizio);
const d = servizio.data; const d = servizio.data;
const path = servizioHref(servizio); const path = servizioHref(servizio);
const breadcrumbs = [ const breadcrumbs = [
@@ -45,6 +44,7 @@ const breadcrumbs = [
{ name: d.titolo, href: path }, { name: d.titolo, href: path },
]; ];
const site = Astro.site ?? new URL('https://www.grassoezio.it'); const site = Astro.site ?? new URL('https://www.grassoezio.it');
const contentHtml = externalLinksNoopener(servizio.rendered?.html ?? '', site.host);
const jsonLd = [serviceLd(site, { name: d.titolo, description: d.descrizioneSeo, path })]; const jsonLd = [serviceLd(site, { name: d.titolo, description: d.descrizioneSeo, path })];
const telefono = studio.telefoni[0]; const telefono = studio.telefoni[0];
--- ---
@@ -64,7 +64,7 @@ const telefono = studio.telefoni[0];
<p class="sidenav__title" id="sidenav-titolo"> <p class="sidenav__title" id="sidenav-titolo">
Tutti i servizi Tutti i servizi
</p> </p>
<ul role="list"> <ul>
{servizi.map((s) => ( {servizi.map((s) => (
<li> <li>
<a href={servizioHref(s)} aria-current={s.id === servizio.id ? 'page' : undefined}> <a href={servizioHref(s)} aria-current={s.id === servizio.id ? 'page' : undefined}>
@@ -84,13 +84,13 @@ const telefono = studio.telefoni[0];
<a class="sidenav__tel" href={telHref(telefono)}> <a class="sidenav__tel" href={telHref(telefono)}>
<Icon name="phone" size={18} /> <Icon name="phone" size={18} />
<span class="visually-hidden">Telefono</span> <span class="visually-hidden">Telefono</span>
{telefono.display} {telText(telefono)}
</a> </a>
</div> </div>
</aside> </aside>
<div class="content"> <div class="content">
<Content /> <Fragment set:html={contentHtml} />
<nav class="pager" aria-label="Servizio precedente e successivo"> <nav class="pager" aria-label="Servizio precedente e successivo">
<a href={servizioHref(prev)} rel="prev"> <a href={servizioHref(prev)} rel="prev">
@@ -118,7 +118,7 @@ const telefono = studio.telefoni[0];
<style> <style>
.layout { .layout {
display: grid; display: grid;
grid-template-columns: 280px minmax(0, 1fr); grid-template-columns: 17.5rem minmax(0, 1fr);
gap: var(--space-8); gap: var(--space-8);
align-items: start; align-items: start;
} }
@@ -283,7 +283,7 @@ const telefono = studio.telefoni[0];
text-decoration: underline; text-decoration: underline;
} }
@media (max-width: 960px) { @media (max-width: 60em) {
.layout { .layout {
grid-template-columns: minmax(0, 1fr); grid-template-columns: minmax(0, 1fr);
gap: var(--space-6); gap: var(--space-6);
@@ -295,7 +295,7 @@ const telefono = studio.telefoni[0];
} }
} }
@media (max-width: 640px) { @media (max-width: 40em) {
.pager { .pager {
flex-direction: column; flex-direction: column;
} }
+4 -4
View File
@@ -43,7 +43,7 @@ const breadcrumbs = [{ name: t.titolo, href: '/studio/' }];
<section class="section section--paper" aria-labelledby="studio-valori"> <section class="section section--paper" aria-labelledby="studio-valori">
<div class="container"> <div class="container">
<SectionHead id="studio-valori" eyebrow={t.valori.eyebrow} title={t.valori.titolo} /> <SectionHead id="studio-valori" eyebrow={t.valori.eyebrow} title={t.valori.titolo} />
<ul class="grid grid--4 values" role="list"> <ul class="grid grid--4 values">
{valori.map((v) => ( {valori.map((v) => (
<li class="value"> <li class="value">
<span class="value__icon"> <span class="value__icon">
@@ -80,7 +80,7 @@ const breadcrumbs = [{ name: t.titolo, href: '/studio/' }];
title={t.abilitazioni.titolo} title={t.abilitazioni.titolo}
subtitle={t.abilitazioni.sottotitolo} subtitle={t.abilitazioni.sottotitolo}
/> />
<ul class="grid grid--3 badges" role="list"> <ul class="grid grid--3 badges">
{abilitazioni.map((a) => ( {abilitazioni.map((a) => (
<BadgeAbilitazione <BadgeAbilitazione
testo={a.testo} testo={a.testo}
@@ -105,7 +105,7 @@ const breadcrumbs = [{ name: t.titolo, href: '/studio/' }];
<div class="collab"> <div class="collab">
<h3>{t.partner.collaborazioniTitolo}</h3> <h3>{t.partner.collaborazioniTitolo}</h3>
<p>{t.partner.collaborazioniTesto}</p> <p>{t.partner.collaborazioniTesto}</p>
<ul class="checklist" role="list"> <ul class="checklist">
{collaborazioni.map((c) => ( {collaborazioni.map((c) => (
<li>{c}</li> <li>{c}</li>
))} ))}
@@ -191,7 +191,7 @@ const breadcrumbs = [{ name: t.titolo, href: '/studio/' }];
color: var(--ink-700); color: var(--ink-700);
} }
@media (max-width: 960px) { @media (max-width: 60em) {
.studio-intro { .studio-intro {
grid-template-columns: minmax(0, 1fr); grid-template-columns: minmax(0, 1fr);
gap: var(--space-6); gap: var(--space-6);
+19 -1
View File
@@ -27,13 +27,31 @@ function initMobileMenu(): void {
closeButton?.addEventListener('click', () => dialog.close()); closeButton?.addEventListener('click', () => dialog.close());
// Il focus resta nel menu aperto: Tab dall'ultimo elemento torna al primo e viceversa.
dialog.addEventListener('keydown', (event) => {
if (event.key !== 'Tab') return;
const focusables = Array.from(
dialog.querySelectorAll<HTMLElement>('a[href], button:not([disabled])'),
).filter((el) => el.offsetParent !== null);
if (focusables.length === 0) return;
const first = focusables[0];
const last = focusables[focusables.length - 1];
if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
});
dialog.addEventListener('close', () => { dialog.addEventListener('close', () => {
setExpanded(openButton, false); setExpanded(openButton, false);
openButton.focus(); openButton.focus();
}); });
// Se la finestra diventa larga (rotazione, ridimensionamento) il menu mobile si chiude. // Se la finestra diventa larga (rotazione, ridimensionamento) il menu mobile si chiude.
const desktop = window.matchMedia('(min-width: 960.02px)'); const desktop = window.matchMedia('(min-width: 60.001em)');
desktop.addEventListener('change', (event) => { desktop.addEventListener('change', (event) => {
if (event.matches && dialog.open) dialog.close(); if (event.matches && dialog.open) dialog.close();
}); });
+6 -5
View File
@@ -98,8 +98,9 @@ ol {
padding: 0; padding: 0;
} }
ul[role='list'], /* gli elenchi con una classe sono elementi d'interfaccia: niente punti elenco */
ol[role='list'] { ul[class],
ol[class] {
list-style: none; list-style: none;
} }
@@ -202,14 +203,14 @@ button {
grid-template-columns: repeat(4, minmax(0, 1fr)); grid-template-columns: repeat(4, minmax(0, 1fr));
} }
@media (max-width: 960px) { @media (max-width: 60em) {
.grid--3, .grid--3,
.grid--4 { .grid--4 {
grid-template-columns: repeat(2, minmax(0, 1fr)); grid-template-columns: repeat(2, minmax(0, 1fr));
} }
} }
@media (max-width: 640px) { @media (max-width: 40em) {
.grid--2, .grid--2,
.grid--3, .grid--3,
.grid--4 { .grid--4 {
@@ -389,7 +390,7 @@ button {
center / contain no-repeat; center / contain no-repeat;
} }
@media (max-width: 640px) { @media (max-width: 40em) {
.checklist, .checklist,
.content ul { .content ul {
grid-template-columns: minmax(0, 1fr); grid-template-columns: minmax(0, 1fr);
+77
View File
@@ -0,0 +1,77 @@
/**
* Accessibilità automatica con axe-core (brief §11.3): tutte le pagine (lette dalla sitemap)
* a 1440 e 390 px, più gli stati interattivi (menu mobile e sottomenu aperti, mappa caricata).
* Criterio: zero violazioni «serious» o «critical» (WCAG 2.0/2.1 A e AA e buone pratiche);
* le violazioni minori sono comunque riportate nel messaggio d'errore e nelle annotazioni.
*/
import AxeBuilder from '@axe-core/playwright';
import { expect, test, type Page } from '@playwright/test';
import { ALL_PAGES, stubGoogle } from '../helpers/site';
const VIEWPORTS = [
{ name: 'desktop', width: 1440, height: 900 },
{ name: 'mobile', width: 390, height: 844 },
];
const TAGS = ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'best-practice'];
async function audit(page: Page, where: string, include?: string, exclude?: string) {
let builder = new AxeBuilder({ page }).withTags(TAGS);
if (include) builder = builder.include(include);
if (exclude) builder = builder.exclude(exclude);
const results = await builder.analyze();
const blocking = results.violations.filter(
(v) => v.impact === 'serious' || v.impact === 'critical',
);
const report = results.violations.map(
(v) =>
`[${v.impact}] ${v.id}: ${v.help} — ${v.nodes
.slice(0, 5)
.map((n) => n.target.join(' '))
.join(' | ')}`,
);
if (report.length > 0) {
test.info().annotations.push({ type: 'axe', description: `${where}\n${report.join('\n')}` });
}
expect(blocking, `violazioni gravi di accessibilità in ${where}:\n${report.join('\n')}`).toEqual(
[],
);
}
for (const vp of VIEWPORTS) {
test.describe(`${vp.name} ${vp.width}px`, () => {
test.use({ viewport: { width: vp.width, height: vp.height } });
for (const path of ALL_PAGES) {
test(`axe: ${path}`, async ({ page }) => {
await page.goto(path, { waitUntil: 'networkidle' });
await audit(page, `${path} a ${vp.width}px`);
});
}
});
}
test.describe('stati interattivi', () => {
test('menu mobile aperto con sottomenu', async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 });
await page.goto('/');
await page.locator('[data-menu-open]').click();
await page.locator('#menu-mobile [data-submenu-toggle]').click();
await audit(page, 'menu mobile aperto', '#menu-mobile');
});
test('sottomenu desktop aperto', async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 900 });
await page.goto('/');
await page.locator('.nav [data-submenu-toggle]').click();
await audit(page, 'sottomenu desktop aperto', 'header');
});
test('mappa caricata', async ({ page }) => {
await stubGoogle(page);
await page.goto('/contatti/');
await page.locator('[data-map-load]').first().click();
await expect(page.locator('[data-map-consent] iframe')).toHaveCount(1);
// il contenuto dell'iframe è di Google (terze parti): si verifica solo il nostro markup
await audit(page, 'mappa caricata', '[data-map-consent]', '[data-map-consent] iframe');
});
});
+176
View File
@@ -0,0 +1,176 @@
/**
* Accessibilità da tastiera (brief §9.5, §11.3): link «salta al contenuto», sottomenu e menu
* mobile usabili con la tastiera, focus sempre visibile, testo ridimensionabile, reflow a 320 px.
*/
import { expect, test, type Page } from '@playwright/test';
import { ALL_PAGES } from '../helpers/site';
/** Vero se l'elemento attivo ha un indicatore di focus visibile (outline su sé o su ::after). */
async function focusIsVisible(page: Page): Promise<{ ok: boolean; what: string }> {
return page.evaluate(() => {
const el = document.activeElement as HTMLElement | null;
if (!el || el === document.body) return { ok: false, what: 'nessun elemento con il focus' };
const has = (s: CSSStyleDeclaration) =>
(s.outlineStyle !== 'none' && parseFloat(s.outlineWidth) > 0) ||
(s.boxShadow !== 'none' && s.boxShadow !== '');
const ok = has(getComputedStyle(el)) || has(getComputedStyle(el, '::after'));
const what = `${el.tagName.toLowerCase()}${el.id ? '#' + el.id : ''}.${String(el.className).split(' ')[0]} «${(el.textContent ?? '').trim().slice(0, 40)}»`;
return { ok, what };
});
}
test('il primo Tab porta al link «Vai al contenuto principale»', async ({ page }) => {
await page.goto('/studio/');
await page.keyboard.press('Tab');
const skip = page.locator('.skip-link');
await expect(skip).toBeFocused();
await expect(skip).toBeInViewport();
await expect(skip).toHaveText('Vai al contenuto principale');
await page.keyboard.press('Enter');
await expect(page.locator('main#contenuto')).toBeFocused();
// il Tab successivo prosegue all'interno del contenuto principale
await page.keyboard.press('Tab');
const insideMain = await page.evaluate(
() => document.querySelector('main')?.contains(document.activeElement) ?? false,
);
expect(insideMain, 'dopo il salto il focus prosegue nel contenuto').toBe(true);
});
test('sottomenu desktop: apertura con Invio, navigazione con Tab, chiusura con Esc', async ({
page,
}) => {
await page.setViewportSize({ width: 1440, height: 900 });
await page.goto('/');
const toggle = page.locator('.nav [data-submenu-toggle]');
const submenu = page.locator('#sottomenu-servizi');
// raggiunge il pulsante del sottomenu solo con la tastiera
for (let i = 0; i < 30; i++) {
await page.keyboard.press('Tab');
if (await toggle.evaluate((el) => el === document.activeElement)) break;
}
await expect(toggle).toBeFocused();
await expect(toggle).toHaveAttribute('aria-expanded', 'false');
await page.keyboard.press('Enter');
await expect(toggle).toHaveAttribute('aria-expanded', 'true');
await expect(submenu).toBeVisible();
await page.keyboard.press('Tab');
await expect(submenu.getByRole('link').first()).toBeFocused();
await page.keyboard.press('Escape');
await expect(submenu).toBeHidden();
await expect(toggle).toBeFocused();
await expect(toggle).toHaveAttribute('aria-expanded', 'false');
// uscendo dal sottomenu con Tab il sottomenu si chiude
await page.keyboard.press('Enter');
await expect(submenu).toBeVisible();
for (let i = 0; i < 7; i++) await page.keyboard.press('Tab');
await expect(submenu).toBeHidden();
});
test('menu mobile: apertura con Invio, focus intrappolato nel menu, chiusura con Esc', async ({
page,
}) => {
await page.setViewportSize({ width: 390, height: 844 });
await page.goto('/');
const toggle = page.locator('[data-menu-open]');
const menu = page.locator('#menu-mobile');
for (let i = 0; i < 10; i++) {
await page.keyboard.press('Tab');
if (await toggle.evaluate((el) => el === document.activeElement)) break;
}
await expect(toggle).toBeFocused();
await page.keyboard.press('Enter');
await expect(menu).toBeVisible();
await expect(toggle).toHaveAttribute('aria-expanded', 'true');
await expect(page.locator('[data-menu-close]')).toBeFocused();
for (let i = 0; i < 25; i++) {
await page.keyboard.press('Tab');
const inside = await menu.evaluate((m) => m.contains(document.activeElement));
expect(inside, `il focus resta nel menu aperto (Tab n. ${i + 1})`).toBe(true);
}
// il sottomenu si apre con la tastiera
await page.locator('#menu-mobile [data-submenu-toggle]').focus();
await page.keyboard.press('Enter');
await expect(page.locator('#menu-mobile-servizi')).toBeVisible();
await page.keyboard.press('Escape');
await expect(menu).toBeHidden();
await expect(toggle).toBeFocused();
await expect(toggle).toHaveAttribute('aria-expanded', 'false');
});
for (const path of ['/', '/servizi/', '/contatti/', '/dove-siamo/']) {
test(`focus visibile su ogni elemento raggiungibile con Tab in ${path}`, async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 900 });
await page.goto(path);
const total = await page
.locator('a[href], button:not([disabled]), input, textarea, select, [tabindex="0"]')
.evaluateAll(
(els) =>
els.filter((e) => {
const r = (e as HTMLElement).getBoundingClientRect();
return r.width > 0 && r.height > 0 && (e as HTMLElement).tabIndex >= 0;
}).length,
);
expect(total).toBeGreaterThan(5);
const seen: string[] = [];
for (let i = 0; i < total; i++) {
await page.keyboard.press('Tab');
const { ok, what } = await focusIsVisible(page);
seen.push(what);
expect(ok, `focus non visibile su ${what} (Tab n. ${i + 1}) in ${path}`).toBe(true);
}
});
}
test('testo ingrandito al 200 % dalle impostazioni del browser: nessun contenuto tagliato', async ({
page,
}) => {
await page.setViewportSize({ width: 1280, height: 900 });
// equivale a impostare «Dimensione carattere» a 32 px (il doppio di 16) nelle preferenze
const cdp = await page.context().newCDPSession(page);
await cdp.send('Page.enable');
await cdp.send('Page.setFontSizes', { fontSizes: { standard: 32, fixed: 26 } });
for (const path of ['/', '/servizi/contenzioso-tributario/', '/contatti/', '/note-legali/']) {
await page.goto(path);
const { overflow, fontSize } = await page.evaluate(() => ({
overflow: document.documentElement.scrollWidth - document.documentElement.clientWidth,
fontSize: parseFloat(getComputedStyle(document.body).fontSize),
}));
expect(fontSize, `dimensione del testo raddoppiata in ${path}`).toBeGreaterThanOrEqual(32);
expect(overflow, `scorrimento orizzontale con testo al 200 % in ${path}`).toBeLessThanOrEqual(
0,
);
}
});
test('reflow a 320 px: nessuno scorrimento orizzontale in tutte le pagine', async ({ page }) => {
await page.setViewportSize({ width: 320, height: 640 });
for (const path of ALL_PAGES) {
await page.goto(path);
const overflow = await page.evaluate(
() => document.documentElement.scrollWidth - document.documentElement.clientWidth,
);
expect(overflow, `scorrimento orizzontale a 320 px in ${path}`).toBeLessThanOrEqual(0);
}
});
test('preferenza «riduci movimento»: nessuna transizione', async ({ browser }) => {
const context = await browser.newContext({ reducedMotion: 'reduce' });
const page = await context.newPage();
await page.goto('/');
const duration = await page
.locator('.card')
.first()
.evaluate((el) => getComputedStyle(el).transitionDuration);
expect(
duration.split(',').every((d) => parseFloat(d) <= 0.001),
`durata transizioni con movimento ridotto: ${duration}`,
).toBe(true);
await context.close();
});
+103
View File
@@ -0,0 +1,103 @@
/**
* Modulo di contatto (brief §10.1, §11.4). Con `contactForm.mode = 'off'` (predefinito) si
* verifica la card «Scrivici una e-mail»; con il modulo attivo (CONTACT_FORM_MODE=php o
* endpoint nella build) si verificano validazione, honeypot, tempo minimo e pagina di conferma.
*/
import { expect, test } from '@playwright/test';
test('contatti: modulo oppure card e-mail, a seconda della configurazione', async ({ page }) => {
await page.goto('/contatti/');
const forms = await page.locator('form[data-contact-form]').count();
if (forms === 0) {
const card = page.locator('[data-contact-mode="off"]');
await expect(card).toBeVisible();
await expect(card.getByRole('heading', { name: 'Scrivici una e-mail' })).toBeVisible();
const href = await card.locator('a[href^="mailto:"]').getAttribute('href');
expect(href).toBe(
`mailto:info@studiograssoezio.it?subject=${encodeURIComponent('Richiesta di informazioni dal sito')}`,
);
} else {
await expect(page.locator('form[data-contact-form]')).toBeVisible();
}
});
test.describe('modulo attivo', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/contatti/');
const forms = await page.locator('form[data-contact-form]').count();
test.skip(forms === 0, 'modulo disattivato (contactForm.mode = "off")');
});
test('campi obbligatori, etichette e informativa', async ({ page }) => {
const form = page.locator('form[data-contact-form]');
for (const label of [
'Nome e cognome',
'E-mail',
'Telefono / Cellulare',
'Oggetto',
'Messaggio',
]) {
const field = form.getByLabel(label);
await expect(field, `campo «${label}»`).toBeVisible();
await expect(field, `campo «${label}» obbligatorio`).toHaveAttribute('required', '');
}
const consent = form.locator('input[name="privacy"]');
await expect(consent).toHaveAttribute('required', '');
await expect(form.locator('label[for="cf-privacy"] a')).toHaveAttribute(
'href',
'/privacy-policy/',
);
await expect(form).toContainText('* campo obbligatorio');
});
test('honeypot nascosto e campo ts valorizzato', async ({ page }) => {
const trap = page.locator('input[name="sito_web"]');
await expect(trap).toHaveAttribute('tabindex', '-1');
await expect(trap).not.toBeInViewport();
await expect(page.locator('.contact-form__trap')).toHaveAttribute('aria-hidden', 'true');
const ts = await page.locator('input[name="ts"]').inputValue();
expect(Number(ts), 'timestamp di apertura della pagina').toBeGreaterThan(1_600_000_000_000);
});
test('invio vuoto: errori in italiano accanto ai campi e riepilogo', async ({ page }) => {
await page.getByRole('button', { name: /Invia la richiesta/ }).click();
const summary = page.locator('[data-form-summary]');
await expect(summary).toBeVisible();
await expect(summary).toBeFocused();
await expect(summary).toContainText('Controlla i campi evidenziati');
await expect(page.locator('#cf-nome')).toHaveAttribute('aria-invalid', 'true');
await expect(page.locator('#cf-nome-err')).toHaveText('Compila questo campo.');
await expect(page.locator('#cf-privacy-err')).toContainText('informativa sulla privacy');
await expect(page).toHaveURL('/contatti/');
});
test('e-mail non valida', async ({ page }) => {
await page.locator('#cf-email').fill('non-valida');
await page.locator('#cf-email').blur();
await expect(page.locator('#cf-email-err')).toContainText('indirizzo e-mail valido');
});
test('invio troppo rapido bloccato, poi invio e pagina di conferma', async ({ page }) => {
await page.route('**/contact.php', (route) =>
route.fulfill({ status: 303, headers: { Location: '/contatti/grazie/' } }),
);
await page.locator('#cf-nome').fill('Mario Rossi');
await page.locator('#cf-email').fill('mario.rossi@example.com');
await page.locator('#cf-telefono').fill('+39 0141 000000');
await page.locator('#cf-oggetto').fill('Richiesta di preventivo');
await page
.locator('#cf-messaggio')
.fill('Vorrei un preventivo per la tenuta della contabilità.');
await page.locator('#cf-privacy').check();
// primo invio entro 3 secondi dall'apertura della pagina: bloccato dall'anti-spam
await page.getByRole('button', { name: /Invia la richiesta/ }).click();
await expect(page.locator('[data-form-status]')).toHaveText(/Attendi qualche secondo/);
await expect(page).toHaveURL('/contatti/');
await page.waitForTimeout(3_200);
await page.getByRole('button', { name: /Invia la richiesta/ }).click();
await expect(page).toHaveURL('/contatti/grazie/');
await expect(page.locator('h1')).toHaveText('Richiesta inviata');
});
});
+67
View File
@@ -0,0 +1,67 @@
/**
* Menu mobile a 390 px (brief §5.2): apertura e chiusura, aria-expanded, Esc, focus, sottomenu.
*/
import { expect, test } from '@playwright/test';
import { SERVICE_PAGES } from '../helpers/site';
test.use({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true });
test('il menu mobile si apre e si chiude', async ({ page }) => {
await page.goto('/');
const toggle = page.locator('[data-menu-open]');
const menu = page.locator('#menu-mobile');
await expect(page.getByRole('navigation', { name: 'Principale' })).toBeHidden();
await expect(toggle).toBeVisible();
await expect(toggle).toHaveAttribute('aria-controls', 'menu-mobile');
await expect(toggle).toHaveAttribute('aria-expanded', 'false');
await expect(menu).toBeHidden();
await toggle.click();
await expect(menu).toBeVisible();
await expect(toggle).toHaveAttribute('aria-expanded', 'true');
await expect(page.locator('[data-menu-close]')).toBeFocused();
for (const label of ['Lo studio', 'Servizi', 'Contatti', 'Dove siamo', 'Link utili']) {
await expect(menu.getByRole('link', { name: label, exact: true })).toBeVisible();
}
await expect(menu.locator('a[href^="tel:"]')).toBeVisible();
await page.locator('[data-menu-close]').click();
await expect(menu).toBeHidden();
await expect(toggle).toHaveAttribute('aria-expanded', 'false');
await expect(toggle).toBeFocused();
});
test('il menu mobile si chiude con Esc', async ({ page }) => {
await page.goto('/');
const toggle = page.locator('[data-menu-open]');
await toggle.click();
await expect(page.locator('#menu-mobile')).toBeVisible();
await page.keyboard.press('Escape');
await expect(page.locator('#menu-mobile')).toBeHidden();
await expect(toggle).toHaveAttribute('aria-expanded', 'false');
await expect(toggle).toBeFocused();
});
test('il sottomenu dei servizi nel menu mobile', async ({ page }) => {
await page.goto('/');
await page.locator('[data-menu-open]').click();
const subToggle = page.locator('#menu-mobile [data-submenu-toggle]');
const sub = page.locator('#menu-mobile-servizi');
await expect(sub).toBeHidden();
await subToggle.click();
await expect(subToggle).toHaveAttribute('aria-expanded', 'true');
await expect(sub).toBeVisible();
await expect(sub.getByRole('link')).toHaveCount(SERVICE_PAGES.length);
await sub.getByRole('link').nth(2).click();
await expect(page).toHaveURL(/\/servizi\/[a-z-]+\/$/);
await expect(page.locator('#menu-mobile')).toBeHidden();
});
test('a 390 px non c’è scorrimento orizzontale', async ({ page }) => {
await page.goto('/');
const overflow = await page.evaluate(
() => document.documentElement.scrollWidth - document.documentElement.clientWidth,
);
expect(overflow, 'larghezza in eccesso della home a 390 px').toBeLessThanOrEqual(0);
});
+139
View File
@@ -0,0 +1,139 @@
/**
* Navigazione (brief §5.2, §5.3, §11.4): intestazione, sottomenu dei servizi, footer,
* breadcrumb, precedente/successivo e redirect delle ancore del vecchio sito.
*/
import { expect, test } from '@playwright/test';
import { SERVICE_PAGES } from '../helpers/site';
const MAIN_NAV = [
{ label: 'Lo studio', path: '/studio/' },
{ label: 'Servizi', path: '/servizi/' },
{ label: 'Contatti', path: '/contatti/' },
{ label: 'Dove siamo', path: '/dove-siamo/' },
{ label: 'Link utili', path: '/link-utili/' },
];
test('le voci dell’intestazione portano alle pagine giuste', async ({ page }) => {
for (const item of MAIN_NAV) {
await page.goto('/');
const nav = page.getByRole('navigation', { name: 'Principale' });
await nav.getByRole('link', { name: item.label, exact: true }).click();
await expect(page, `la voce «${item.label}» porta a ${item.path}`).toHaveURL(item.path);
await expect(
page.getByRole('navigation', { name: 'Principale' }).getByRole('link', {
name: item.label,
exact: true,
}),
`la voce «${item.label}» è evidenziata come pagina corrente`,
).toHaveAttribute('aria-current', 'page');
}
});
test('logo e pulsante «Richiedi un preventivo»', async ({ page }) => {
await page.goto('/studio/');
await page.locator('header .brand').first().click();
await expect(page).toHaveURL('/');
await page
.getByRole('navigation', { name: 'Principale' })
.getByRole('link', { name: 'Richiedi un preventivo' })
.click();
await expect(page).toHaveURL('/contatti/');
});
test('il sottomenu «Servizi» elenca i 6 servizi e si apre con il pulsante', async ({ page }) => {
await page.goto('/');
const toggle = page.locator('.nav [data-submenu-toggle]');
const submenu = page.locator('#sottomenu-servizi');
await expect(submenu).toBeHidden();
await toggle.click();
await expect(toggle).toHaveAttribute('aria-expanded', 'true');
await expect(submenu).toBeVisible();
await expect(submenu.getByRole('link')).toHaveCount(SERVICE_PAGES.length);
await submenu.getByRole('link').first().click();
await expect(page).toHaveURL(/\/servizi\/[a-z-]+\/$/);
await expect(
page.getByRole('navigation', { name: 'Principale' }).getByRole('link', {
name: 'Servizi',
exact: true,
}),
).toHaveAttribute('aria-current', 'true');
});
test('il sottomenu si apre anche al passaggio del mouse e si chiude con un clic fuori', async ({
page,
}) => {
await page.goto('/');
const submenu = page.locator('#sottomenu-servizi');
await page.locator('.nav__item--has-sub').hover();
await expect(submenu).toBeVisible();
await page.mouse.move(10, 600);
await expect(submenu).toBeHidden();
await page.locator('.nav [data-submenu-toggle]').click();
await expect(submenu).toBeVisible();
await page.mouse.move(10, 600);
await page.locator('main h1').click();
await expect(submenu).toBeHidden();
});
test('tutti i link del footer funzionano', async ({ page, request }) => {
await page.goto('/');
const hrefs = await page
.locator('footer a[href^="/"]')
.evaluateAll((links) => links.map((a) => a.getAttribute('href') ?? ''));
expect(hrefs.length, 'link interni nel footer').toBeGreaterThanOrEqual(11);
for (const href of new Set(hrefs)) {
const response = await request.get(href);
expect(response.status(), `link del footer ${href}`).toBe(200);
}
for (const label of ['Privacy policy', 'Cookie policy', 'Note legali', 'Accessibilità']) {
await expect(
page.getByRole('navigation', { name: 'Informazioni legali' }).getByRole('link', {
name: label,
}),
).toBeVisible();
}
});
test('breadcrumb, barra laterale e precedente/successivo nelle pagine dei servizi', async ({
page,
}) => {
for (const path of SERVICE_PAGES) {
await page.goto(path);
const breadcrumb = page.getByRole('navigation', { name: 'Percorso' });
await expect(breadcrumb.getByRole('link', { name: 'Home' })).toHaveAttribute('href', '/');
await expect(breadcrumb.getByRole('link', { name: 'Servizi' })).toHaveAttribute(
'href',
'/servizi/',
);
await expect(
page.locator('.sidenav a[aria-current="page"]'),
`servizio corrente evidenziato in ${path}`,
).toHaveAttribute('href', path);
}
await page.goto(SERVICE_PAGES[0]);
const pager = page.getByRole('navigation', { name: 'Servizio precedente e successivo' });
const next = await pager.locator('a[rel="next"]').getAttribute('href');
await pager.locator('a[rel="next"]').click();
await expect(page).toHaveURL(next ?? '');
await page
.getByRole('navigation', { name: 'Servizio precedente e successivo' })
.locator('a[rel="prev"]')
.click();
await expect(page).toHaveURL(SERVICE_PAGES[0]);
});
test('le ancore del vecchio sito portano al servizio corrispondente', async ({ page }) => {
await page.goto('/servizi/');
const cards = await page
.locator('[data-legacy-href]')
.evaluateAll((els) =>
els.map((el) => ({ id: el.id, href: el.getAttribute('data-legacy-href') })),
);
expect(cards.length, 'card con ancora del vecchio sito').toBe(6);
for (const { id, href } of cards) {
await page.goto(`/servizi/#${id}`);
await expect(page, `l'ancora #${id} porta a ${href}`).toHaveURL(href ?? '');
}
await page.goto('/servizi/#ancora-sconosciuta');
await expect(page).toHaveURL('/servizi/#ancora-sconosciuta');
});
+99
View File
@@ -0,0 +1,99 @@
/**
* Privacy (brief §8.2, §11.4): nessuna richiesta verso host esterni al caricamento delle pagine,
* nessun cookie, localStorage vuoto, mappa Google caricata solo dopo il clic.
*/
import { expect, test } from '@playwright/test';
import { ALL_PAGES, isLocalRequest, stubGoogle } from '../helpers/site';
test('nessuna richiesta verso host esterni, nessun cookie e localStorage vuoto', async ({
page,
context,
}) => {
const external: string[] = [];
page.on('request', (req) => {
if (!isLocalRequest(req.url())) external.push(`${req.url()} (pagina ${page.url()})`);
});
for (const path of ALL_PAGES) {
await page.goto(path, { waitUntil: 'networkidle' });
// scorrimento fino in fondo: eventuali contenuti caricati in modo differito partono ora
await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
await page.waitForLoadState('networkidle');
const storage = await page.evaluate(() => window.localStorage.length);
expect(storage, `voci in localStorage dopo ${path}`).toBe(0);
}
expect(external, 'richieste verso host diversi da localhost').toEqual([]);
expect(await context.cookies(), 'cookie impostati durante la navigazione').toEqual([]);
});
for (const path of ['/', '/contatti/', '/dove-siamo/']) {
test(`mappa click-to-load in ${path}`, async ({ page, context }) => {
const google = await stubGoogle(page);
await page.goto(path, { waitUntil: 'networkidle' });
await expect(page.locator('iframe'), 'iframe presenti prima del clic').toHaveCount(0);
expect(google, 'richieste a Google prima del clic').toEqual([]);
const blocks = page.locator('[data-map-consent]');
const count = await blocks.count();
expect(count, 'blocchi mappa nella pagina').toBeGreaterThan(0);
const first = blocks.first();
await expect(first).toContainText('Google Maps');
await expect(first.locator('a[href="/cookie-policy/"]')).toHaveCount(1);
await expect(first.locator('a[href^="https://www.google.com/maps/search/"]')).toHaveCount(1);
await expect(first.locator('a[href^="https://www.openstreetmap.org/search"]')).toHaveCount(1);
await first.locator('[data-map-load]').click();
const iframe = first.locator('iframe');
await expect(iframe).toHaveCount(1);
await expect(iframe).toHaveAttribute('src', /^https:\/\/www\.google\.com\/maps\/embed\?pb=/);
await expect(iframe).toHaveAttribute('title', /Mappa/);
await expect(iframe).toHaveAttribute('loading', 'lazy');
await expect
.poll(() => google.length, { message: 'richiesta a Google dopo il clic' })
.toBeGreaterThan(0);
const remembered = await page.evaluate(() => sessionStorage.getItem('mappa-consentita'));
expect(remembered, 'scelta ricordata in sessionStorage').toBe('1');
// la scelta vale per la sessione: ricaricando, le mappe compaiono senza un nuovo clic
await page.reload({ waitUntil: 'networkidle' });
await expect(page.locator('[data-map-consent] iframe')).toHaveCount(count);
const ours = (await context.cookies()).filter((c) => !c.domain.includes('google'));
expect(ours, 'cookie del sito dopo il caricamento della mappa').toEqual([]);
});
}
test('senza JavaScript restano i link esterni della mappa e la navigazione', async ({
browser,
}) => {
const context = await browser.newContext({ javaScriptEnabled: false });
const page = await context.newPage();
await page.goto('/dove-siamo/');
await expect(page.locator('[data-map-load]').first()).toBeHidden();
await expect(
page.locator('a[href^="https://www.google.com/maps/search/"]').first(),
).toBeVisible();
await expect(page.locator('iframe')).toHaveCount(0);
await page.goto('/');
await expect(
page.getByRole('navigation', { name: 'Principale' }).getByRole('link', { name: 'Lo studio' }),
).toBeVisible();
await context.close();
});
test('senza JavaScript il menu è navigabile anche su mobile', async ({ browser }) => {
const context = await browser.newContext({
javaScriptEnabled: false,
viewport: { width: 390, height: 844 },
});
const page = await context.newPage();
await page.goto('/');
await expect(page.locator('[data-menu-open]')).toBeHidden();
const menu = page.getByRole('navigation', { name: 'Menu mobile' });
await expect(menu.getByRole('link', { name: 'Contatti', exact: true })).toBeVisible();
await expect(menu.locator('#menu-mobile-servizi a').first()).toBeVisible();
await context.close();
});
+70
View File
@@ -0,0 +1,70 @@
/**
* Smoke test di tutte le pagine (brief §11.4): risposta 200, un solo <h1>, lang="it",
* titolo e descrizione presenti e unici, canonical corretto, nessun errore in console.
*/
import { expect, test } from '@playwright/test';
import { ALL_PAGES, SITE, collectConsoleErrors } from '../helpers/site';
for (const path of ALL_PAGES) {
test(`pagina ${path}: struttura e metadati`, async ({ page }) => {
const errors = collectConsoleErrors(page);
const response = await page.goto(path);
expect(response?.status(), `stato HTTP della pagina ${path}`).toBe(200);
await expect(page.locator('html'), `lang della pagina ${path}`).toHaveAttribute('lang', 'it');
await expect(page.locator('h1'), `numero di <h1> nella pagina ${path}`).toHaveCount(1);
await expect(page.locator('h1'), `<h1> visibile nella pagina ${path}`).toBeVisible();
const title = await page.title();
expect(title.length, `titolo della pagina ${path}`).toBeGreaterThan(10);
const description = await page.locator('meta[name="description"]').getAttribute('content');
expect(
description?.length ?? 0,
`meta description della pagina ${path}`,
).toBeGreaterThanOrEqual(120);
if (path !== '/404.html') {
await expect(
page.locator('link[rel="canonical"]'),
`canonical della pagina ${path}`,
).toHaveAttribute('href', `${SITE}${path}`);
}
await expect(page.locator('footer'), `P.IVA nel footer della pagina ${path}`).toContainText(
'P.IVA 01597790052',
);
expect(errors, `errori nella console della pagina ${path}`).toEqual([]);
});
}
test('titoli e descrizioni sono unici su tutto il sito', async ({ page }) => {
const titles = new Map<string, string>();
const descriptions = new Map<string, string>();
for (const path of ALL_PAGES) {
await page.goto(path);
const title = await page.title();
const description =
(await page.locator('meta[name="description"]').getAttribute('content')) ?? '';
expect(titles.get(title), `titolo «${title}» di ${path} già usato`).toBeUndefined();
expect(descriptions.get(description), `descrizione di ${path} già usata`).toBeUndefined();
titles.set(title, path);
descriptions.set(description, path);
}
});
test('un indirizzo inesistente mostra la pagina 404 personalizzata', async ({ page }) => {
const response = await page.goto('/pagina-che-non-esiste/');
expect(response?.status(), 'stato HTTP di un indirizzo inesistente').toBe(404);
await expect(page.locator('h1')).toHaveText('Pagina non trovata');
const main = page.locator('main');
for (const href of ['/', '/servizi/', '/contatti/']) {
await expect(main.locator(`a[href="${href}"]`), `link a ${href} nella 404`).toHaveCount(1);
}
await expect(page.locator('meta[name="robots"]')).toHaveAttribute('content', /noindex/);
});
test('la pagina di conferma del modulo è noindex', async ({ page }) => {
await page.goto('/contatti/grazie/');
await expect(page.locator('h1')).toHaveText('Richiesta inviata');
await expect(page.locator('meta[name="robots"]')).toHaveAttribute('content', /noindex/);
});
+67
View File
@@ -0,0 +1,67 @@
/**
* Supporto ai test: elenco delle pagine letto dalla sitemap generata in dist/ (nessuna lista da
* tenere allineata a mano), URL del sito e utilità comuni.
*/
import { existsSync, readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import type { Page } from '@playwright/test';
export const SITE = (process.env.SITE_URL || 'https://www.grassoezio.it').replace(/\/+$/, '');
const DIST = resolve(import.meta.dirname, '..', '..', 'dist');
function locs(xml: string): string[] {
return [...xml.matchAll(/<loc>([^<]+)<\/loc>/g)].map((m) => m[1].trim());
}
/** Percorsi delle pagine elencate nella sitemap (es. «/», «/studio/»). */
export function sitemapPaths(): string[] {
const index = resolve(DIST, 'sitemap-index.xml');
if (!existsSync(index)) {
throw new Error('Sitemap non trovata in dist/: eseguire `npm run build` prima dei test.');
}
const paths: string[] = [];
for (const sitemap of locs(readFileSync(index, 'utf8'))) {
const file = resolve(DIST, new URL(sitemap).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 (noindex). */
export const EXTRA_PAGES = ['/404.html', '/contatti/grazie/'];
export const PAGES = sitemapPaths();
export const ALL_PAGES = [...PAGES, ...EXTRA_PAGES];
export const SERVICE_PAGES = PAGES.filter((p) => /^\/servizi\/[^/]+\/$/.test(p));
/** Vero per le richieste che restano sul server locale di test. */
export function isLocalRequest(url: string): boolean {
const u = new URL(url);
if (u.protocol === 'data:' || u.protocol === 'blob:' || u.protocol === 'about:') return true;
return u.hostname === '127.0.0.1' || u.hostname === 'localhost';
}
/** Raccoglie errori della console e della pagina. */
export function collectConsoleErrors(page: Page): string[] {
const errors: string[] = [];
page.on('console', (msg) => {
if (msg.type() === 'error') errors.push(msg.text());
});
page.on('pageerror', (err) => errors.push(err.message));
return errors;
}
/** Risposta finta per Google Maps: nei test nessuna richiesta esce dalla macchina. */
export async function stubGoogle(page: Page): Promise<string[]> {
const requested: string[] = [];
await page.route('https://www.google.com/**', (route) => {
requested.push(route.request().url());
return route.fulfill({
status: 200,
contentType: 'text/html',
body: '<!doctype html><title>Mappa</title>',
});
});
return requested;
}