Quando usare i Web Components?
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Quantity component</title>
<link rel="stylesheet" href="/it/demo.css" />
<script type="module" src="demo.js"></script>
</head>
<body>
<main>
<h1>Quantity</h1>
<pp-quantity value="2"></pp-quantity>
<noscript>Changing the quantity requires JavaScript.</noscript>
</main>
</body>
</html>
demo.ts
import { registerQuantity } from "./quantity-element.js";
registerQuantity();
Articolo correlato (EN): Semantic HTML.
Custom Elements registra nuovi tag HTML, Shadow DOM incapsula un albero e la maggior parte dei selettori CSS, template e slot separano struttura e contenuto. Non servono necessariamente tutti e tre. Scegli un elemento autonomo con un trattino nel nome, come pp-quantity.
È utile per librerie condivise tra applicazioni; per pulsanti, campi o componenti di un solo framework, HTML nativo o componenti del framework sono spesso più semplici. Il contatore non è un campo di modulo. [1][2][3][4]
Registrazione e ciclo di vita
quantity-element.ts
import {
isQuantity,
MAX_QUANTITY,
MIN_QUANTITY,
parseQuantity,
stepQuantity,
} from "./quantity.js";
import { createQuantityView } from "./quantity-view.js";
import type { QuantityView } from "./quantity-view.js";
export const QUANTITY_TAG = "pp-quantity";
export const QUANTITY_CHANGE = "quantity-change";
export interface QuantityChangeDetail {
readonly value: number;
}
export class QuantityElement extends HTMLElement {
static readonly observedAttributes = ["value"];
private readonly view: QuantityView;
private listeners: AbortController | undefined;
constructor() {
super();
const root = this.attachShadow({ mode: "open" });
this.view = createQuantityView(root);
}
get value(): number {
return parseQuantity(this.getAttribute("value"));
}
set value(value: number) {
if (!isQuantity(value)) {
throw new RangeError("Invalid quantity.");
}
this.setAttribute("value", String(value));
}
connectedCallback(): void {
if (!this.isConnected) {
return;
}
this.upgradeValue();
this.render();
this.listeners?.abort();
this.listeners = new AbortController();
const options = { signal: this.listeners.signal };
this.view.decrease.addEventListener("click", this.decrease, options);
this.view.increase.addEventListener("click", this.increase, options);
}
disconnectedCallback(): void {
this.listeners?.abort();
this.listeners = undefined;
}
attributeChangedCallback(): void {
this.render();
}
private upgradeValue(): void {
if (!Object.hasOwn(this, "value")) {
return;
}
const previous: unknown = Reflect.get(this, "value");
if (!Reflect.deleteProperty(this, "value")) {
throw new TypeError("Cannot upgrade value property.");
}
if (isQuantity(previous)) {
this.value = previous;
}
}
private readonly decrease = (): void => {
this.change(-1);
};
private readonly increase = (): void => {
this.change(1);
};
private change(step: -1 | 1): void {
const current = this.value;
const next = stepQuantity(current, step);
if (next === current) {
return;
}
this.value = next;
this.dispatchEvent(
new CustomEvent<QuantityChangeDetail>(QUANTITY_CHANGE, {
detail: { value: next },
bubbles: true,
composed: true,
}),
);
}
private render(): void {
const value = parseQuantity(this.getAttribute("value"));
this.view.output.value = String(value);
this.view.decrease.setAttribute(
"aria-disabled",
String(value === MIN_QUANTITY),
);
this.view.increase.setAttribute(
"aria-disabled",
String(value === MAX_QUANTITY),
);
}
}
export function registerQuantity(): void {
const existing = customElements.get(QUANTITY_TAG);
if (existing === QuantityElement) {
return;
}
if (existing !== undefined) {
throw new Error(`Custom element already registered: ${QUANTITY_TAG}`);
}
customElements.define(QUANTITY_TAG, QuantityElement);
}
declare global {
interface HTMLElementTagNameMap {
"pp-quantity": QuantityElement;
}
}
Il costruttore prepara l’albero interno senza dipendere dagli attributi o figli dell’host. connectedCallback può ripetersi dopo spostamenti o reinserimenti; disconnectedCallback libera risorse. Gli attributi in observedAttributes attivano attributeChangedCallback anche durante l’upgrade di elementi esistenti.
Una definizione globale non può essere sovrascritta. La funzione accetta la registrazione ripetuta della stessa classe e rifiuta i conflitti. Importa il modulo che estende HTMLElement solo nel browser. [2]
Registrazione e disponibilità sono diverse. whenDefined() attende la definizione, non i dati caricati. upgrade() può aggiornare un sottoalbero scollegato. Uno spostamento ordinario può scollegare e ricollegare l’elemento; moveBefore() con connectedMoveCallback preserva lo stato se entrambi sono supportati. [15][16][17]
Attributi, proprietà e validazione
quantity.ts
export const MIN_QUANTITY = 0;
export const MAX_QUANTITY = 99;
export function isQuantity(value: unknown): value is number {
if (typeof value !== "number") {
return false;
}
if (!Number.isSafeInteger(value)) {
return false;
}
if (value < MIN_QUANTITY) {
return false;
}
return value <= MAX_QUANTITY;
}
export function parseQuantity(raw: string | null): number {
if (raw === null) {
return MIN_QUANTITY;
}
if (!/^\d{1,2}$/.test(raw)) {
return MIN_QUANTITY;
}
const value = Number(raw);
if (String(value) !== raw) {
return MIN_QUANTITY;
}
return isQuantity(value) ? value : MIN_QUANTITY;
}
export function stepQuantity(value: number, step: -1 | 1): number {
if (!isQuantity(value)) {
throw new RangeError("Invalid quantity.");
}
switch (step) {
case -1:
return Math.max(MIN_QUANTITY, value - 1);
case 1:
return Math.min(MAX_QUANTITY, value + 1);
default:
throw new RangeError("Invalid step.");
}
}
Un attributo contiene testo o è assente; una proprietà JavaScript può contenere numeri e oggetti. value accetta interi canonici da 0 a 99; testo mancante o non valido vale 0. Il setter rifiuta numeri non validi e riflette quelli validi nell’attributo. Il rendering non riscrive l’attributo.
Una proprietà propria impostata prima della registrazione può nascondere il setter del prototipo. Alla connessione l’esempio recupera il valore valido o usa l’attributo. Se l’elemento aggiornato è staccato, il recupero avviene alla connessione. [2]
Gli attributi booleani come required dipendono dalla presenza, non dal testo: required="false" attiva ancora l’opzione. Rimuovere l’attributo per disattivarla. [18]
Shadow DOM, template e slot
quantity-view.ts
export interface QuantityView {
decrease: HTMLButtonElement;
increase: HTMLButtonElement;
output: HTMLOutputElement;
}
function createButton(label: string, text: string): HTMLButtonElement {
const button = document.createElement("button");
button.type = "button";
button.textContent = text;
button.setAttribute("aria-label", label);
button.setAttribute("part", "button");
return button;
}
export function createQuantityView(root: ShadowRoot): QuantityView {
const stylesheet = document.createElement("link");
stylesheet.rel = "stylesheet";
stylesheet.href = new URL("./quantity.css", import.meta.url).href;
const group = document.createElement("div");
group.className = "quantity";
group.setAttribute("role", "group");
group.setAttribute("aria-label", "Quantity");
const decrease = createButton("Decrease quantity", "−");
const increase = createButton("Increase quantity", "+");
const output = document.createElement("output");
output.setAttribute("part", "value");
output.setAttribute("aria-label", "Current quantity");
group.append(decrease, output, increase);
root.append(stylesheet, group);
return { decrease, increase, output };
}
slot-demo.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Declarative Shadow DOM and slots</title>
</head>
<body>
<main>
<div id="panel">
<template shadowrootmode="open">
<section>
<h2><slot name="heading">Summary</slot></h2>
<slot>No details available.</slot>
</section>
</template>
<span slot="heading">Order summary</span>
<p>Two items in the order.</p>
</div>
</main>
</body>
</html>
open espone shadowRoot; closed limita l’accesso convenzionale dall’host ma non è un confine di sicurezza. I selettori della pagina normalmente non raggiungono nodi interni, mentre proprietà ereditate e token CSS possono attraversare il confine. template contiene markup inerte da clonare; slot presenta i figli corrispondenti dell’host.
I nodi assegnati restano nel light DOM. slotchange segnala modifiche all’assegnazione, non ogni modifica dei contenuti. Il contatore crea l’albero tramite API DOM senza interpretare dati come HTML. [3][4]
L’esempio indipendente dichiara un albero shadow con uno slot nominato e uno predefinito. Senza nodi assegnati, lo slot mostra il contenuto alternativo. L’assegnazione non sposta i nodi nell’albero shadow. [3][4][19]
Eventi e accessibilità
Articolo correlato (EN): Event Bubbling, Capturing and Delegation.
quantity-change viene emesso solo dopo una reale modifica tramite attivazione di un pulsante, non dopo l’assegnazione di una proprietà. bubbles abilita la delega, composed attraversa i confini Shadow DOM anche con host annidati. Non dipendere dall’event.target interno a causa del retargeting.
I pulsanti nativi type=button hanno nomi accessibili e output presenta il risultato. Per conservare il focus ai limiti, il contatore usa aria-disabled anziché disabled. L’attributo non blocca l’attivazione: la funzione limita il valore e non emette eventi se non cambia. Un bordo diverso segnala indisponibilità senza dipendere solo dal colore. Verificare tastiera, contrasto, focus e annunci dello screen reader. La semantica non dimostra da sola la conformità WCAG. [5][6][20]
Stili e moduli
quantity.css
:host {
display: inline-block;
color: var(--quantity-text, #172033);
}
.quantity {
display: flex;
align-items: center;
gap: 0.75rem;
}
button {
min-width: 44px;
min-height: 44px;
border: 1px solid currentColor;
border-radius: 0.5rem;
background: var(--quantity-surface, #ffffff);
color: inherit;
font: inherit;
cursor: pointer;
}
button:focus-visible {
outline: 3px solid var(--quantity-focus, #174cc9);
outline-offset: 3px;
}
button[aria-disabled="true"] {
border-style: dashed;
cursor: default;
}
output {
min-width: 3ch;
text-align: center;
font-variant-numeric: tabular-nums;
}
demo.css
body {
font: 1rem/1.6 system-ui, sans-serif;
padding: 2rem;
}
pp-quantity {
--quantity-text: #172033;
--quantity-surface: #f5f7fb;
--quantity-focus: #174cc9;
}
pp-quantity::part(button) {
border-radius: 0.75rem;
}
Articolo correlato (EN): CSS Variables and Themes.
Token CSS e ::part definiscono un contratto pubblico senza esporre classi private. Il foglio separato può lasciare temporaneamente il componente senza stili durante il caricamento. Preferisci input nativo per i campi. Un elemento personalizzato può partecipare ai moduli mediante static formAssociated, attachInternals, setFormValue e setValidity; deve gestire reset, disabled e ripristino.
Il contatore non contribuisce automaticamente a FormData. Valida valori e limiti anche sul server. [7][8][13][14]
Controllo di modulo con ElementInternals
consent-element.ts
const CONSENT_TAG = "pp-consent";
const CHECKED_STATE = "checked";
const UNCHECKED_STATE = "unchecked";
const SUBMISSION_VALUE = "yes";
export class ConsentElement extends HTMLElement {
static readonly formAssociated = true;
static readonly observedAttributes = ["checked", "required"];
private readonly internals: ElementInternals;
private readonly input: HTMLInputElement;
private listeners: AbortController | undefined;
constructor() {
super();
this.internals = this.attachInternals();
const root = this.attachShadow({ mode: "open" });
const label = document.createElement("label");
this.input = document.createElement("input");
this.input.type = "checkbox";
label.append(this.input, " Accept terms");
root.append(label);
}
connectedCallback(): void {
if (!this.isConnected) {
return;
}
this.syncForm();
this.listeners?.abort();
this.listeners = new AbortController();
this.input.addEventListener("change", this.handleChange, {
signal: this.listeners.signal,
});
}
disconnectedCallback(): void {
this.listeners?.abort();
this.listeners = undefined;
}
attributeChangedCallback(name: string): void {
if (name === "checked") {
this.input.checked = this.hasAttribute("checked");
}
this.syncForm();
}
formDisabledCallback(disabled: boolean): void {
this.input.disabled = disabled;
}
formResetCallback(): void {
this.input.checked = this.hasAttribute("checked");
this.syncForm();
}
formStateRestoreCallback(state: unknown): void {
switch (state) {
case CHECKED_STATE:
this.input.checked = true;
break;
case UNCHECKED_STATE:
this.input.checked = false;
break;
default:
return;
}
this.syncForm();
}
private readonly handleChange = (): void => {
this.syncForm();
};
private syncForm(): void {
this.input.required = this.hasAttribute("required");
if (this.input.checked) {
this.internals.setFormValue(SUBMISSION_VALUE, CHECKED_STATE);
this.internals.setValidity({});
return;
}
this.internals.setFormValue(null, UNCHECKED_STATE);
if (!this.input.required) {
this.internals.setValidity({});
return;
}
this.internals.setValidity(
{ valueMissing: true },
"Accept the terms to continue.",
this.input,
);
}
}
export function registerConsent(): void {
const existing = customElements.get(CONSENT_TAG);
if (existing === ConsentElement) {
return;
}
if (existing !== undefined) {
throw new Error(`Custom element already registered: ${CONSENT_TAG}`);
}
customElements.define(CONSENT_TAG, ConsentElement);
}
consent-demo.ts
import { registerConsent } from "./consent-element.js";
registerConsent();
consent-demo.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Form-associated custom element</title>
<link rel="stylesheet" href="/it/demo.css" />
<script type="module" src="consent-demo.js"></script>
</head>
<body>
<main>
<h1>Consent</h1>
<form method="get">
<fieldset>
<legend>Terms</legend>
<pp-consent name="consent" required></pp-consent>
</fieldset>
<button type="submit">Continue</button>
<button type="reset">Reset</button>
</form>
</main>
</body>
</html>
Il contatore resta indipendente. L’esempio separato pp-consent mostra un controllo di consenso associato al modulo. Una checkbox nativa in un label offre semantica di base e tastiera. Se selezionata invia yes con il nome dell’host; altrimenti setFormValue(null, state) la esclude. Lo stato di ripristino è un argomento separato, non il valore inviato. [8][14][21]
required impone la selezione; setValidity imposta valueMissing con il campo interno come ancora. Reset ripristina lo stato dell’attributo checked; modificarlo cambia anche lo stato corrente in questo contratto. formDisabledCallback gestisce anche un fieldset disabilitato, formStateRestoreCallback riconosce gli stati salvati. L’esempio limitato non sostituisce completamente input: non espone una proprietà checked pubblica né un evento personalizzato di modifica. Senza supporto serve un’alternativa nativa. Validare sul server e verificare gli annunci degli errori con screen reader. [21][22]
React, Vue, Angular e SSR
React 19 supporta Custom Elements: sul client usa proprietà esistenti, altrimenti attributi; in SSR omette valori inadatti agli attributi secondo le sue regole. Vue configura isCustomElement nel compilatore dei template, Angular offre CUSTOM_ELEMENTS_SCHEMA. Definisci esplicitamente i tipi di proprietà ed eventi negli adattatori.
Declarative Shadow DOM consegna un albero dal server con template shadowrootmode. Non chiamare attachShadow incondizionatamente durante l’idratazione: con lo stesso modo può svuotare l’albero. La demo è solo client; SSR richiede il riutilizzo dei nodi esistenti. [9][10][11][12]
In React 19 registrare la definizione prima del rendering se sono attese proprietà oggetto. In SSR stringhe, numeri e true possono diventare attributi; oggetti, funzioni, simboli e false sono omessi. Configurare isCustomElement compilando i template Vue; CUSTOM_ELEMENTS_SCHEMA di Angular non sostituisce un contratto tipizzato. [10][11][12]
Test e versionamento
quantity.test.mjs
import assert from "node:assert/strict";
import { test } from "node:test";
import {
isQuantity,
parseQuantity,
stepQuantity,
} from "./dist/quantity.js";
test("accepts integer boundaries", () => {
// Given
const values = [0, 99];
// When
const results = values.map(isQuantity);
// Then
assert.deepEqual(results, [true, true]);
});
test("rejects invalid values", () => {
const values = [-1, 100, NaN, Infinity, 1.5, "2", null, {}];
assert.deepEqual(values.map(isQuantity), values.map(() => false));
});
test("parses canonical attributes", () => {
assert.equal(parseQuantity("2"), 2);
assert.equal(parseQuantity("99"), 99);
});
test("falls back for malformed attributes", () => {
const values = [null, "", "02", "2\n", "2.5", " 2", "1e1", "100"];
assert.deepEqual(values.map(parseQuantity), values.map(() => 0));
});
test("does not cross the lower bound", () => {
assert.equal(stepQuantity(0, -1), 0);
});
test("does not cross the upper bound", () => {
assert.equal(stepQuantity(99, 1), 99);
});
test("increments and decrements", () => {
assert.equal(stepQuantity(3, 1), 4);
assert.equal(stepQuantity(3, -1), 2);
});
test("rejects invalid starting quantity", () => {
assert.throws(() => stepQuantity(100, -1), RangeError);
});
test("rejects invalid runtime steps", () => {
// Given
const invalidSteps = [0, 2, NaN, "1"];
// When / Then
for (const step of invalidSteps) {
assert.throws(() => stepQuantity(3, step), RangeError);
}
});
tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "Bundler",
"lib": ["ES2022", "DOM"],
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"outDir": "dist"
},
"include": ["*.ts"]
}
Separa la logica pura dal DOM per testarla in Node.js. Nel browser verifica registrazione, stato iniziale, eventi, riconnessione, limiti, tastiera e integrazione. Given-When-Then descrive stato iniziale, azione e risultato. I test unitari non dimostrano accessibilità o comportamento del browser.
Versiona tag, attributi, proprietà, eventi, slot e parti CSS come API pubblica. Cambiare significato di un evento o nome di una parte può rompere la compatibilità. Prova i browser di destinazione, non solo la presenza delle API. [2]
Testare l’assenza della voce FormData se non selezionata, invio non valido, reset e disabilitazione via fieldset. Chiamare direttamente il callback di ripristino verifica la logica, non il ripristino del browser dopo la navigazione. [21]
