Kedy používať 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="/sk/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();
Súvisiaci článok (EN): Semantic HTML.
Custom Elements registruje nové značky HTML, Shadow DOM zapuzdruje strom a väčšinu selektorov CSS, template a slot oddeľujú štruktúru od obsahu. Všetky tri mechanizmy nie sú povinné. Vyberte autonómny prvok so spojovníkom v názve, napríklad pp-quantity. Hodí sa pre knižnice zdieľané medzi aplikáciami; pri bežnom tlačidle, poli či komponente jedného frameworku býva jednoduchšie natívne HTML alebo komponent frameworku.
Ukážkové počítadlo nie je formulárový prvok. [1][2][3][4]
Registrácia a životný cyklus
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;
}
}
Konštruktor pripravuje interný strom bez závislosti od atribútov či potomkov hostiteľa. connectedCallback sa môže opakovať pri presune alebo opätovnom vložení; disconnectedCallback uvoľňuje zdroje. Atribúty v observedAttributes spúšťajú attributeChangedCallback aj pri upgrade existujúcich prvkov.
Globálnu definíciu nemožno prepísať inou. Registračná funkcia akceptuje rovnakú triedu a odmieta konflikty. Modul rozširujúci HTMLElement importujte len v prehliadači. [2]
Registrácia a pripravenosť sa líšia. whenDefined() čaká na definíciu, nie na načítané dáta. upgrade() môže aktualizovať odpojený podstrom. Bežný presun môže vyvolať odpojenie a pripojenie; moveBefore() s connectedMoveCallback zachová stav, ak sú obe funkcie podporované. [15][16][17]
Atribúty, vlastnosti a validácia
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.");
}
}
Atribút je text alebo chýba; vlastnosť JavaScriptu môže obsahovať čísla a objekty. value prijíma kanonické celé čísla od 0 do 99; chýbajúci alebo neplatný text znamená 0. Setter odmieta neplatné čísla a platné premieta do atribútu. Vykreslenie atribút opäť nezapisuje.
Vlastná vlastnosť nastavená pred registráciou môže zakryť setter prototypu. Pri pripojení príklad obnoví platnú hodnotu, inak použije atribút. Pri odpojenom upgradovanom prvku nastane obnova až po pripojení. [2]
Booleovské atribúty ako required sa vyhodnocujú podľa prítomnosti, nie textu: required="false" možnosť stále zapína. Na vypnutie atribút odstráňte. [18]
Shadow DOM, šablóny a sloty
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 sprístupňuje shadowRoot; closed obmedzuje bežný prístup z hostiteľa, ale nie je bezpečnostnou hranicou. Selektory stránky obvykle nedosiahnu interné uzly, zdedené vlastnosti a CSS tokeny však môžu hranicu prekročiť. template uchováva neaktívne značky na klonovanie; slot zobrazuje zodpovedajúcich potomkov hostiteľa.
Priradené uzly zostávajú v light DOM. slotchange oznamuje zmenu priradenia, nie každú zmenu obsahu. Počítadlo vytvára strom cez DOM API, aby sa údaje neinterpretovali ako HTML. [3][4]
Samostatná ukážka deklaruje shadow strom s pomenovaným a predvoleným slotom. Bez priradených uzlov slot zobrazí náhradný obsah. Priradenie nepresúva uzly do shadow stromu. [3][4][19]
Udalosti a prístupnosť
Súvisiaci článok (EN): Event Bubbling, Capturing and Delegation.
quantity-change vzniká iba po skutočnej zmene aktiváciou tlačidla, nie pri priradení vlastnosti. bubbles umožňuje delegovanie a composed prekročenie hranice Shadow DOM aj pri vnorenom hostiteľovi. Pre retargeting sa nespoliehajte na interný event.target. Natívne tlačidlá type=button majú prístupné názvy; output oznamuje hodnotu.
Natívne tlačidlá type=button majú prístupné názvy a output zobrazuje výsledok. Na zachovanie fokusu na hraniciach používa počítadlo aria-disabled namiesto disabled. Atribút neblokuje aktiváciu: funkcia obmedzuje rozsah a pri nezmenenej hodnote nevyšle udalosť. Odlišný rámček signalizuje nedostupnosť nielen farbou. Testujte klávesnicu, kontrast, fokus a oznámenia čítačiek obrazovky. Sémantika sama nepreukazuje súlad s WCAG. [5][6][20]
Štýly a formuláre
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;
}
Súvisiaci článok (EN): CSS Variables and Themes.
CSS tokeny a ::part tvoria verejný kontrakt štýlov bez odhalenia súkromných tried. Samostatný štýlový súbor môže počas načítania krátko chýbať. Pri poliach uprednostnite natívne input. Vlastný prvok sa môže zapojiť do formulára cez static formAssociated, attachInternals, setFormValue a setValidity, musí však riešiť reset, disabled a obnovu.
Ukážkové počítadlo automaticky neprispieva do FormData. Hodnoty a limity validujte aj na serveri. [7][8][13][14]
Formulárový prvok s 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="/sk/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>
Počítadlo zostáva samostatné. Oddelená ukážka pp-consent predstavuje prvok súhlasu priradený k formuláru. Natívny checkbox v label poskytuje základnú sémantiku a klávesnicu. Zaškrtnutý odosiela yes pod názvom hostiteľa; nezaškrtnutý setFormValue(null, state) vylúči. Stav obnovenia je samostatný argument, nie odoslaná hodnota. [8][14][21]
required vyžaduje zaškrtnutie; setValidity nastaví valueMissing a vnútorné pole ako kotvu. Reset obnoví stav atribútu checked, ktorého zmena v tomto kontrakte mení aj aktuálny stav. formDisabledCallback rieši aj zakázaný nadradený fieldset, formStateRestoreCallback rozpozná uložené stavy. Obmedzená ukážka plne nenahrádza input: nemá verejnú vlastnosť checked ani vlastnú udalosť zmeny. Bez podpory API je nutná natívna alternatíva. Validujte na serveri a testujte oznámenia chýb čítačkami. [21][22]
React, Vue, Angular a SSR
React 19 podporuje Custom Elements: na klientovi používa existujúce vlastnosti, inak atribúty; pri SSR vynecháva hodnoty nevhodné pre atribúty podľa svojich pravidiel. Vue ponúka isCustomElement v kompilátore šablón, Angular CUSTOM_ELEMENTS_SCHEMA. V adaptéroch explicitne typujte vlastnosti a udalosti.
Declarative Shadow DOM umožňuje serveru dodať strom cez template shadowrootmode. Pri hydratácii nevolajte attachShadow bez podmienky: rovnaký režim môže deklaratívny strom vyprázdniť. Ukážka je len klientská; SSR vyžaduje pripojenie správania k existujúcim uzlom. [9][10][11][12]
V React 19 registrujte definíciu pred vykreslením, ak očakávate vlastnosti s objektmi. V SSR môžu reťazce, čísla a true byť atribúty; objekty, funkcie, symboly a false sa vynechajú. isCustomElement nastavte pri kompilácii šablón Vue; CUSTOM_ELEMENTS_SCHEMA v Angular nenahrádza typovaný kontrakt. [10][11][12]
Testovanie a verzovanie
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"]
}
Oddeľte čistú logiku od DOM na testovanie v Node.js. V prehliadači overte registráciu, počiatočné hodnoty, udalosti, opätovné pripojenie, limity, klávesnicu a integráciu. Given-When-Then opisuje počiatočný stav, akciu a výsledok. Jednotkové testy nedokazujú prístupnosť ani správanie prehliadača.
Verzujte značku, atribúty, vlastnosti, udalosti, sloty a CSS časti ako verejné API. Zmena významu udalosti alebo názvu part môže porušiť kompatibilitu. Testujte cieľové prehliadače, nie iba dostupnosť API. [2]
Testujte chýbajúcu položku FormData pri nezaškrtnutí, neplatné odoslanie, reset a deaktiváciu cez fieldset. Priame volanie callbacku obnovy testuje jeho logiku, nie obnovu prehliadačom po navigácii. [21]
