¿Cuándo utilizar 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="/es/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();
Artículo relacionado (EN): Semantic HTML.
Custom Elements registra nuevas etiquetas HTML, Shadow DOM encapsula un árbol y la mayoría de los selectores CSS, y template y slot separan la estructura del contenido. No es obligatorio utilizar los tres. Elige un elemento autónomo con un guion en el nombre, como pp-quantity.
Es útil en bibliotecas compartidas entre aplicaciones. Para botones, campos o componentes exclusivos de un framework, el HTML nativo o dicho framework suelen ser más sencillos. El contador del ejemplo no es un campo de formulario. [1][2][3][4]
Registro y ciclo de vida
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;
}
}
El constructor prepara el árbol interno sin depender de los atributos o hijos del anfitrión. connectedCallback puede repetirse al mover o reinsertar el elemento; disconnectedCallback libera recursos. Los atributos de observedAttributes activan attributeChangedCallback, incluida la actualización de elementos existentes.
Una definición global no puede sustituirse por otra. La función de registro acepta repetir la misma clase y rechaza conflictos. Importa el módulo que extiende HTMLElement únicamente en el navegador. [2]
Registro y disponibilidad son distintos. whenDefined() espera la definición, no los datos cargados. upgrade() puede actualizar un subárbol desconectado. Un traslado ordinario puede desconectar y reconectar el elemento; moveBefore() con connectedMoveCallback conserva el estado si ambos mecanismos están disponibles. [15][16][17]
Atributos, propiedades y validación
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 atributo contiene texto o está ausente; una propiedad JavaScript puede contener números y objetos. value acepta enteros canónicos entre 0 y 99; el texto ausente o inválido equivale a 0. El setter rechaza números inválidos y refleja los válidos en el atributo.
El renderizado no vuelve a escribirlo. Una propiedad propia asignada antes del registro puede ocultar el setter del prototipo. Al conectar, el ejemplo recupera el valor válido o utiliza el atributo. En un elemento actualizado pero separado, la recuperación espera a la conexión. [2]
Los atributos booleanos como required se interpretan por presencia, no por texto: required="false" sigue activando la opción. Elimina el atributo para desactivarla. [18]
Shadow DOM, plantillas y slots
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 expone shadowRoot; closed limita el acceso convencional desde el anfitrión, pero no es una frontera de seguridad. Los selectores de la página generalmente no alcanzan nodos internos, aunque las propiedades heredadas y los tokens CSS pueden cruzar la frontera. template guarda marcado inerte para clonarlo; slot presenta hijos correspondientes del anfitrión.
Los nodos asignados siguen en el light DOM. slotchange notifica cambios de asignación, no cualquier cambio de contenido. El contador construye el árbol con API DOM sin interpretar datos como HTML. [3][4]
El ejemplo independiente declara un árbol de sombra con un slot con nombre y uno predeterminado. Sin nodos asignados, muestra el contenido alternativo del slot. La asignación no mueve los nodos al árbol de sombra. [3][4][19]
Eventos y accesibilidad
Artículo relacionado (EN): Event Bubbling, Capturing and Delegation.
quantity-change se emite únicamente después de un cambio real por activación de un botón, no al asignar una propiedad. bubbles permite delegar eventos; composed permite cruzar límites de Shadow DOM, incluso con anfitriones anidados. El consumidor no debe depender del event.target interno debido al retargeting.
Los botones nativos type=button tienen nombres accesibles y output presenta el resultado. Para conservar el foco en los límites, el contador usa aria-disabled en vez de disabled. El atributo no bloquea la activación: la función limita el valor y no emite eventos si no cambia. Un borde distinto señala indisponibilidad sin depender solo del color. Comprueba teclado, contraste, foco y anuncios de lectores de pantalla. La semántica sola no garantiza WCAG. [5][6][20]
Estilos y formularios
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;
}
Artículo relacionado (EN): CSS Variables and Themes.
Los tokens CSS y ::part ofrecen un contrato público de estilos sin exponer clases privadas. La hoja separada puede dejar brevemente el componente sin estilos mientras carga. Prefiere input nativo para los campos. Un elemento personalizado puede participar en formularios mediante static formAssociated, attachInternals, setFormValue y setValidity, pero debe gestionar reset, disabled y restauración.
El contador no contribuye automáticamente a FormData. Valida también valores y límites en el servidor. [7][8][13][14]
Control de formulario 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="/es/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>
Formularios HTML: validación y accesibilidad.
El contador sigue siendo independiente. El ejemplo separado pp-consent muestra un control de consentimiento asociado al formulario. Una casilla nativa dentro de label proporciona semántica básica y teclado. Marcada envía yes bajo el nombre del anfitrión; desmarcada, setFormValue(null, state) la excluye. El estado de restauración es un argumento independiente, no el valor enviado. [8][14][21]
required exige marcar; setValidity establece valueMissing y usa el campo interno como ancla. Reset restaura el estado del atributo checked; cambiarlo también cambia el estado actual en este contrato. formDisabledCallback gestiona fieldset deshabilitado y formStateRestoreCallback reconoce estados guardados. Este ejemplo limitado no sustituye por completo a input: no expone una propiedad checked pública ni un evento personalizado de cambio. Hace falta una alternativa nativa si no hay soporte. Valida en el servidor y comprueba anuncios de errores con lectores de pantalla. [21][22]
React, Vue, Angular y SSR
React 19 admite Custom Elements: en el cliente utiliza propiedades existentes o atributos; durante SSR omite valores inadecuados para atributos según sus reglas. Vue permite configurar isCustomElement en el compilador de plantillas; Angular ofrece CUSTOM_ELEMENTS_SCHEMA.
Tipar explícitamente propiedades y eventos en cada adaptador. Declarative Shadow DOM permite entregar un árbol desde el servidor con template shadowrootmode. No invoques attachShadow incondicionalmente durante la hidratación de un árbol declarativo: el mismo modo puede vaciarlo.
La demo es solo cliente; SSR requiere reutilizar nodos existentes. [9][10][11][12]
En React 19 registra la definición antes de renderizar si esperas propiedades con objetos. En SSR cadenas, números y true pueden convertirse en atributos; objetos, funciones, símbolos y false se omiten. Configura isCustomElement al compilar plantillas Vue; CUSTOM_ELEMENTS_SCHEMA de Angular no sustituye un contrato tipado. [10][11][12]
Pruebas y versionado
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 lógica pura del DOM para probarla en Node.js. En el navegador comprueba registro, valores iniciales, eventos, reconexión, límites, teclado e integración. Given-When-Then describe estado inicial, acción y resultado. Las pruebas unitarias no demuestran accesibilidad ni comportamiento del navegador.
Versiona etiqueta, atributos, propiedades, eventos, slots y partes CSS como API pública. Cambiar el significado de un evento o el nombre de una parte puede romper compatibilidad. Prueba los navegadores objetivo, no solo la presencia de las API. [2]
Prueba la ausencia de entrada FormData al desmarcar, envío inválido, reset y deshabilitación por fieldset. Invocar directamente el callback de restauración prueba su lógica, no la restauración del navegador tras navegar. [21]
