Designing a component API
Web component API design: data in through properties, news out through events, methods or properties, a custom elements manifest, and safe renames.
- 01Design what goes in and what comes outTake data in through attributes and properties, send news out as events, and never reach into the page.
- 02Choose a method or a propertyKeep state in a property that HTML can set, and make methods short actions that update it, as
<dialog>does. - 03Document an API and change it safelyDescribe it in a custom elements manifest, deprecate an old name before you remove it, and number versions with semver.
What makes a good web component API?
Ravi's tea kit is growing. Asha uses its timer on the Leaf and Kettle menu page. Now Meena wants it too. She runs a tea stall at the market, and her stall has its own page.
That changes things for Ravi. Two pages now depend on his tags. If he renames one attribute, a page breaks, and he may never hear about it. So before the kit grows, he asks a question. What should the outside of a component look like, so it's easy to use and safe to change?
A web component's API is every part a page can use: its attributes, properties, methods, events, slots, CSS parts, and CSS custom properties. A good one works like a built-in element. Data goes in through attributes and properties. News comes out as events. Actions are methods. And every part is written down, and changed with care.
API is short for application programming interface. Here, it means the parts of your component that other people's code touches. This page uses the kit's timer from the outside:
<p>Green tea: <tea-timer seconds="2"></tea-timer></p> <script type="module"> import "./tea-kit/index.js"; const timer = document.querySelector("tea-timer"); console.log("It counts", timer.seconds, "seconds"); timer.addEventListener("tea-timer-done", () => { console.log("Time to pour"); });</script>- Line 1 writes the timer with a
secondsattribute. That's data going in, from HTML. - Line 4 loads every component in the kit.
- Line 7 reads the
secondsproperty. It printsIt counts 2 seconds. - Lines 8 to 10 listen for
tea-timer-done, the event from lesson 5.3. Two seconds later, the console printsTime to pour.
That's all the page needs. It never sees the countdown, the private #controller field, or how the timer draws Ready. Those stay inside. Ravi can rewrite them any day, and no page will notice.
seconds attribute, the seconds property, and the tea-timer-done event. The countdown and #controller stay inside, so Ravi can change them freely.The timer uses three kinds of API. Components can have seven:
- Attributes, like
seconds="2", written in HTML. Lessons 5.1 and 5.2 built them. - Properties, like
timer.seconds, set and read from JavaScript. - Methods, like
dialog.show(), that do something now. - Events, like
tea-timer-done, that tell the page what happened. - Slots, the places where the page's own content goes. Stage 3, Shadow DOM, templates, and slots, builds them.
- CSS parts, the inner elements a page may style with
::part(). - CSS custom properties, like
--tea-card-color, that a page sets to theme a component. Lesson 2.3 styled a library's parts and custom properties.
A café's menu is a promise. Customers order what it says, by the names it uses. The kitchen can change its recipes, its pans, and its staff, and nobody out front can tell. But if a dish vanishes from the menu, regulars notice the next morning.
- In real life: The menu on the wall
- In JavaScript: The public API: attributes, properties, methods, events, slots, parts, and custom properties
- In real life: Ordering by name
- In JavaScript: A page writing
seconds="2"or listening fortea-timer-done - In real life: The recipes in the kitchen
- In JavaScript: Private code, like
#controllerand the countdown - In real life: Taking a dish off the menu
- In JavaScript: A breaking change
Design a component's outside the way built-in elements do. Data comes in through attributes and properties, and news goes out as events. State lives in properties, and actions are methods. Write every public part down. Then change it only with a deprecation first, and a new major version.
The JavaScript path's Designing good APIs lesson covers API design for functions and classes. This lesson is about what's different for a component. Its API lives in HTML, CSS, and JavaScript at once.
What does properties down, events up mean?
It's a rule about which way things travel between a component and the page around it. Lit's docs call it properties down, events up. The W3C TAG, a group that reviews the web's design, calls it data down, events up.
- Down: the page, which owns the component, sends data in. It sets attributes and properties.
- Up: the component sends news out. It dispatches events, as lesson 5.3 showed.
Built-in elements already work this way. A page sets an input's value. When the user types, the input fires an input event. The input never reaches out to change the form around it.
What goes wrong when a component reaches out
Ravi's first cup broke that rule. When you press Add, it finds the <span> in its parent and adds 1 to it. On Asha's cart page, that span is the cart count. Try it, then switch to Meena's page:
<p> Cart: <span>0</span> teas <tea-cup tea="Green tea"></tea-cup></p> <script src="tea-cup.js"></script>Press Add. The cart goes from 0 to 1. The cup's parent is Asha's <p>, and its <span> happens to be the cart count.
- In the
tea-cup.jstab, line 5 looks for a<span>in the cup's parent,this.parentElement. - Line 6 adds 1 to whatever it finds.
- On both pages, lines 1 to 4 put the cup in a
<p>, next to a<span>.
On Asha's page, Add makes the cart show Cart: 1 teas. On Meena's page, the same click turns the price from 4 into 5. Nothing throws. The cup just changed something that wasn't its business.
<span> in its parent. On Asha's page, that span is the cart. On Meena's page, it's the price, so one click turns 4 into 5.The cup assumed every page looks like Asha's. The W3C TAG warns against exactly this: don't make an element depend on a certain parent. web.dev's checklist adds two smaller cases. Don't change the class attribute on your own element, and don't overwrite attributes like tabindex that the page set. Those belong to the page too.
A delivery rider reads the address on the parcel, rides there, and rings the bell. She doesn't walk in and put the parcel on a shelf. Every house keeps its shelves somewhere else. So she rings, and the people inside decide where it goes.
- In real life: The address on the parcel
- In JavaScript: The attributes and properties the page sets
- In real life: Ringing the bell
- In JavaScript: Dispatching
tea-add - In real life: Walking in to put things on a shelf
- In JavaScript: Changing the parent's
<span> - In real life: The next house, with different shelves
- In JavaScript: Meena's page
Telling the page instead
Here is Meena's page with the cup from lesson 5.3. The cup only dispatches tea-add. Meena's own script decides what an add means on her page:
<p> Mint tea, price <span>4</span> <tea-cup tea="Mint tea"></tea-cup></p><p>Basket: <output>empty</output></p> <script src="tea-cup.js"></script><script> const basket = document.querySelector("output"); document.addEventListener("tea-add", (event) => { basket.textContent = event.detail.tea; });</script>- In the
tea-cup.jstab, line 7 dispatchestea-add, with the tea indetail. Line 6 makes it bubble and leave shadow roots, as lesson 5.3 advised. - Line 5 of the page is Meena's basket.
- Lines 10 to 12 are her listener. It writes the tea into the basket.
Press Add. The basket shows Mint tea, and the price stays at 4. On Asha's page, the same cup works with the cart listener from lesson 5.3's overview. Each page owns its data. The cup only reports what the user did.
What if two components need to talk, like a cup and a cart? They still don't touch each other. The page listens to one, and sets a property on the other. Lit calls this a mediator. Stage 7, Building components well, comes back to it in a lesson on data flow between components.
Lit adds one more rule. A component that changes one of its own public properties because of the user should dispatch an event. An input fires input when the user types, for the same reason. Lesson 5.3 covered when to dispatch, and when to stay quiet.
Should a web component use a method or a property?
Lesson 2.2 compared the two to a light switch and a doorbell. A property is a switch: it stays where you put it, and anyone can look at it. A method is a doorbell: it does something now. Most components need both. The question is which job gets which.
Built-in elements answer it the same way every time:
- State is a property. Whether a dialog is open is a fact you can read at any moment. So it's
dialog.open. - Actions are methods. Moving the cursor into a box happens once, then it's done. So it's
input.focus(). - A method that changes state changes the property too. So the property always tells the truth.
Here are two built-ins doing that last one:
<dialog>Green tea is brewing.</dialog><details> <summary>Brewing guide</summary> Brew green tea for 3 minutes.</details> <script> const dialog = document.querySelector("dialog"); const details = document.querySelector("details"); dialog.show(); console.log(dialog.open, dialog.hasAttribute("open")); dialog.close(); console.log(dialog.open, dialog.hasAttribute("open")); details.open = true; console.log(details.hasAttribute("open"), "show" in details);</script>- Line 11 calls
dialog.show(). Line 12 printstrue true. The property istrue, and the attribute is there. - Line 13 calls
close(). Line 14 printsfalse false. - Line 16 sets
details.open = true. Line 17 printstrue false. The attribute appeared, anddetailshas noshow()method at all.
The result shows the brewing guide open, because line 16 opened it. The HTML Standard spells out the dialog's side. show() adds the open attribute, and close() removes it. The attribute is the one place the state lives. Here is the same pattern across five built-ins. Read each row across:
| Element | State you set or read (properties) | Actions you call (methods) |
|---|---|---|
<dialog> | open, which reflects the open attribute. | show(), showModal(), and close(). Each one adds or removes open. |
<details> | open, which reflects the open attribute. | None. Setting open does the whole job. |
<input> | value and disabled. | focus() and select(). They act once, and leave no setting behind. |
<form> | action and method, which reflect their attributes. | reset() and submit(). They act on the whole form at once. |
<video> | muted and currentTime. You can only read paused. | play() and pause(). Playing can take time, so play() gives back a promise. |
The W3C TAG's design principles give a test for the hard cases. Reading a property should only read. It shouldn't change anything, or take a long time. If it would, make it a method.
Why state belongs in a property
A property backed by an attribute can be set from more places than a method can:
- HTML.
<details open>works before any script runs. Nothing in HTML can callshow(). - Templates. Lit's docs prefer setting properties to calling methods. Templates in Lit and in frameworks set properties easily.
- Reading back. Any code can ask
menu.openlater. A method call leaves nothing to ask.
Many homes have a hallway light with two switches, one at each end of the stairs. You can use either one. There's still only one light, and everyone can see whether it's on.
- In real life: The switch at the bottom of the stairs
- In JavaScript:
menu.show() - In real life: The switch at the top
- In JavaScript:
menu.open = true - In real life: The one light
- In JavaScript: The
openattribute - In real life: Anyone looking up at the light
- In JavaScript: Code that reads
menu.open
Ravi's menu follows the same plan. Its show() and hide() only set open. The open setter writes the attribute, as in lesson 5.1. Pick any of the four ways to open it:
<tea-menu></tea-menu> <script src="tea-menu.js"></script><script> const menu = document.querySelector("tea-menu"); menu.show(); console.log(menu.open, menu.hasAttribute("open"));</script>show() sets this.open = true. The setter adds the open attribute, and attributeChangedCallback() draws the menu.
- In the
tea-menu.jstab, lines 4 to 10 are the property. Its getter reads the attribute, and its setter writes it withtoggleAttribute(). - Lines 12 to 18 are the two methods. Each one is a single line that sets
this.open. - Lines 20 to 22 draw the menu whenever the attribute changes.
- In the page, line 6 is your choice. Line 7 prints
true trueevery time.
show() sets open, the setter writes the attribute, and HTML can write the attribute itself. However you open the menu, menu.open reads true.Web Awesome's details element does exactly this. Its show() method sets this.open = true, then gives back a promise that waits for the opening animation. Its docs say the open attribute reflects the state, whichever way you open it. Waiting is something only a method can offer. So the method adds what a property can't, and leaves the state in the property.
How do you document a web component's API?
Meena can't read Ravi's mind. She needs a list of what she may use. Semantic versioning, the numbering rule near the end of this lesson, even requires one. A package must declare its public API.
Write down every part a page can touch. For each kind, say this:
- Attributes and properties: the name, the type, the default, and whether they reflect.
- Methods: what each one does, what it takes, and what it gives back.
- Events: the name, when it fires, what it carries, and whether it bubbles or can be canceled.
- Slots: where the page's content goes. The default slot has no name.
- CSS parts and custom properties: what each one styles.
Leave everything else out, on purpose. Cory LaViska, who created the Shoelace library, puts it simply. Every part you expose is an API you're promising to support. Private code can change any day. Documented parts can't, without a new major version.
Lesson 2.1 read docs like this from the other side: Web Awesome's tables of attributes, slots, events, and parts. Those tables are made from a file the library ships. The next section opens one. First, here's how authors write the facts down: as comments above the class.
JSDoc tags the analyzer reads
JSDoc is a way of writing comments above code, with tags that start with @. The Custom Elements Manifest Analyzer, a tool from Open Web Components, reads them. Ravi plans the tea card before he builds it in stage 3, so he writes its comment first:
/**
* A card for one tea on the menu.
*
* @tag tea-card
* @attr {string} tea - The tea's name.
* @prop {number} price - The price, as a number.
* @fires {Event} tea-card-select - The user picked this tea.
* @slot - The tea's description.
* @csspart title - The tea's name at the top.
* @cssprop --tea-card-color - The card's background color.
*/
export class TeaCard extends HTMLElement {}- Line 4 names the tag.
- Lines 5 and 6 describe an attribute and a property. The part in braces, like
{string}, is the type. - Line 7 describes an event.
- Lines 8 to 10 describe a slot, a CSS part, and a custom property. Line 8 has no name, so it's the default slot.
Run the analyzer on this file, and each tag lands in its own list. Read each row across:
| JSDoc tag | What it describes | Where it lands in the manifest |
|---|---|---|
@attr | An attribute the page writes in HTML. | It goes in attributes. |
@prop | A property the page sets from JavaScript. | It goes in members, as a field. |
@fires | An event the component dispatches. | It goes in events. |
@slot | A place for the page's own content. No name means the default slot. | It goes in slots. |
@csspart | An inner element the page may style with ::part(). | It goes in cssParts. |
@cssprop | A CSS custom property the component reads. | It goes in cssProperties. |
The analyzer finds a lot without tags. It reads observedAttributes, class fields, methods, and dispatchEvent() calls by itself. Its docs say slots, CSS parts, and custom properties need JSDoc. The tea timer needs a tag too. It reads seconds without observing it, so only @attr tells the analyzer it's an attribute.
You can try this without installing anything, in the analyzer's online playground. Paste a class with a comment, and watch the manifest change.
What is a custom elements manifest?
A custom elements manifest is one JSON file that describes every custom element in a package. It's usually called custom-elements.json. Its format is shared. People who build tools wrote it together: tools for editors, docs sites, linters, and framework wrappers. Each tool reads the same file, whatever library made the components.
A packet of tea has one printed label: the name, the ingredients, and the brewing time. The shop's shelf tag, the delivery app, and the website all copy from that label. Nobody types the facts in three times.
- In real life: The label on the tea packet
- In JavaScript:
custom-elements.json - In real life: The shelf tag, the delivery app, and the website
- In JavaScript: Docs sites, code editors, and framework wrappers
- In real life: Printing the label from the recipe
- In JavaScript: The analyzer writing the manifest from your code
Ravi writes the timer's manifest by hand, so you can read every line. It's now part of the kit, as tea-kit/custom-elements.json:
{
"schemaVersion": "2.1.0",
"modules": [
{
"kind": "javascript-module",
"path": "tea-timer.js",
"declarations": [
{
"kind": "class",
"name": "TeaTimer",
"customElement": true,
"tagName": "tea-timer",
"description": "A brewing timer. It counts down, then shows Ready.",
"superclass": { "name": "HTMLElement" },
"attributes": [
{
"name": "seconds",
"fieldName": "seconds",
"type": { "text": "number" },
"default": "60",
"description": "How long to brew, in seconds."
}
],
"members": [
{
"kind": "field",
"name": "seconds",
"attribute": "seconds",
"reflects": true,
"type": { "text": "number" },
"default": "60",
"description": "How long to brew, in seconds."
}
],
"events": [
{
"name": "tea-timer-done",
"type": { "text": "TeaTimerDoneEvent" },
"description": "The countdown reached zero. It bubbles and is composed."
}
]
},
{
"kind": "class",
"name": "TeaTimerDoneEvent",
"superclass": { "name": "Event" },
"members": [
{
"kind": "field",
"name": "seconds",
"type": { "text": "number" },
"description": "How long the timer counted, in seconds."
}
]
}
],
"exports": [
{ "kind": "js", "name": "TeaTimer", "declaration": { "name": "TeaTimer" } },
{ "kind": "js", "name": "TeaTimerDoneEvent", "declaration": { "name": "TeaTimerDoneEvent" } },
{ "kind": "custom-element-definition", "name": "tea-timer", "declaration": { "name": "TeaTimer" } }
]
}
]
}- Line 2 says which version of the format the file uses: 2.1.0.
- Lines 5 and 6 describe one module, the file
tea-timer.js. - Lines 9 to 12 say it declares a class,
TeaTimer. It's a custom element, with the tagtea-timer. - Lines 15 to 23 list the
secondsattribute. Its default is the string"60", because attributes are always strings.fieldNamelinks it to the property. - Lines 24 to 34 list the
secondsproperty.reflects: truesays it and the attribute stay in sync. - Lines 35 to 41 list the event, and its type: the
TeaTimerDoneEventclass. - Lines 43 to 55 describe that class, and its
secondsfield. - Lines 57 to 61 list what the file exports, and which class defines
tea-timer.
Every field comes from the format's schema: a file that says which fields are allowed, and which are required. The format lives on GitHub, as TypeScript types and as a JSON Schema, at version 2.1.0. This lesson's test checks the kit's file against that schema. The schema also explains default: it's the attribute's real text, not a description.
Pointing tools to the manifest
A package tells tools where its manifest is with one field in its package.json:
{
"name": "tea-kit",
"version": "1.5.0",
"type": "module",
"customElements": "custom-elements.json"
}Line 5 is the field, customElements. The format's README explains why it exists. A tool can find the manifest without downloading the whole package. Lesson 2.1 found this field in Web Awesome's package.
Writing it by hand or with the analyzer
One component is easy to describe by hand. A whole library isn't. Install the analyzer with npm i -D @custom-elements-manifest/analyzer, then run cem analyze. It writes custom-elements.json from your code and its JSDoc. Run it again after each change, and the docs keep up with the code. Still, read what it wrote. A manifest is only as right as the comments it came from.
Burton Smith, who builds a component library, lists what teams make from a manifest: API docs, editor hints, Storybook pages, and wrappers for React and other frameworks. Stage 11, Testing, tooling, and publishing, covers the analyzer, its plugins, and editor support.
What counts as a breaking change in a web component?
A breaking change is a change that can stop a working page from working, when the page itself didn't change. For a component, that covers much more than JavaScript names. Burton Smith points out that web components have more public APIs than framework components. Each one is a promise. These changes break it:
- Renaming or removing anything public. Attributes, properties, methods, events, slots, CSS parts, and custom properties. Old HTML, scripts, and CSS still use the old name.
- Changing a default. The kit's label uses 3 minutes when
minutesis missing, from lesson 5.2. Change it to 4, and every label withoutminutesshows a different time. - Changing when an event fires. The timer dispatches only after it shows Ready. Dispatch earlier, and a listener reads the old text.
- Changing an event's shape. Listeners that read
detail.teabreak if it becomesdetail.name. - Changing a property's type. Code that adds 1 to
minutesbreaks if it turns from a number into a string.
Adding things is usually safe. A new optional attribute, a new event, or a new part changes nothing for old pages. Private code is safe too. No page can reach a #private method. Sort these changes:
- Rename the timer's
secondsattribute toduration - Rename the card's
titleCSS part toheading - Change the label's default
minutesfrom 3 to 4 - Change
event.detail.teatoevent.detail.name - Dispatch
tea-timer-donebefore the timer shows Ready - Add an optional
pausedattribute - Rename the private
#render()method - Add
tea, and keeptypeworking with a warning
Sort each change to the tea kit by whether it could break a page that didn't change.
Semantic versioning
Semantic versioning, or semver, is a rule for version numbers. npm's docs recommend it for every package. A version has three numbers, like 1.4.2: major, minor, and patch.
- The patch number goes up for bug fixes that leave the API alone:
1.4.3. - The minor number goes up for new features that break nothing:
1.5.0. - The major number goes up for any breaking change:
2.0.0.
So the number is a message. A page on 1.4.2 can take 1.5.0 safely. A jump to 2.0.0 says: read the changelog first. That's why everything in the breaking list needs a major version, even a new default.
How do you rename an attribute or event without breaking pages?
You don't do it in one step. You add the new name, keep the old one working for a while, and remove it later. Marking the old name as on its way out is called deprecating it. Semver says a deprecation goes in a minor version. Its FAQ adds that at least one minor version should carry the deprecation, before a major version removes the old name.
Ravi has two names he regrets. His first cup called its tea attribute type. But on inputs and buttons, type means something else. And its event was add, with no prefix, which lesson 5.3 warned against.
Leaf and Kettle renames its Morning Mix to Breakfast Blend. For a month, the menu shows the new name with a small note: "was Morning Mix". Regulars who ask for Morning Mix still get their tea. After the month, the old name goes.
- In real life: Breakfast Blend, the new name
- In JavaScript: The new attribute,
tea - In real life: Staff still taking orders for Morning Mix
- In JavaScript: The getter falling back to
type - In real life: The note under the new name
- In JavaScript: The console warning, and
deprecatedin the manifest - In real life: The month both names work
- In JavaScript: The minor versions before 2.0.0
- In real life: Dropping the old name
- In JavaScript: Removing
typein 2.0.0
Keeping an old attribute working
Version 1.5.0 of the cup reads tea, and falls back to type. Try Meena's old page, Asha's updated page, and Meena's page on version 2.0.0:
<p><tea-cup type="Green tea"></tea-cup></p><p><tea-cup type="Mint tea"></tea-cup></p> <script src="tea-cup.js"></script>Meena still writes type. The getter falls back to it, so both cups work. The console shows one warning, however many cups there are.
- In the
tea-cup.jstab on version 1.5.0, line 5 readsteafirst. The??operator gives back its right side when the left side isnullorundefined. So a cup with onlytypestill works. - Lines 9 to 12 warn the first time a cup with
typeconnects. The flag on line 1,warned, keeps it to one warning per page. - Line 13 draws the cup through the getter.
On version 1.5.0, both pages show Cup: Green tea and Cup: Mint tea. Only Meena's page prints the warning, once. On version 2.0.0, the fallback is gone, and Meena's cups show Cup: null. The warning gave her a whole minor version to switch.
tea and keeps type working, with a warning. That's a minor version. Version 2.0.0 removes type, so old pages show Cup: null. That's a major version.A console warning only reaches people who open the console. So mark the old name in the docs too. The manifest has a field for it: every attribute, event, slot, part, and custom property can have deprecated, set to true or to a reason. The analyzer fills it in from a @deprecated tag in a property's comment.
Keeping an old event working
For an event, dispatch both names, the new one first:
<tea-cup tea="Green tea"></tea-cup> <script> class TeaCup extends HTMLElement { connectedCallback() { this.innerHTML = "<button>Add</button>"; this.addEventListener("click", () => { const tea = this.getAttribute("tea"); const options = { bubbles: true, composed: true, detail: { tea } }; this.dispatchEvent(new CustomEvent("tea-add", options)); // Deprecated in 1.5.0. Remove in 2.0.0. this.dispatchEvent(new CustomEvent("add", options)); }); } } customElements.define("tea-cup", TeaCup); document.addEventListener("add", (event) => console.log("Meena's old listener:", event.detail.tea)); document.addEventListener("tea-add", (event) => console.log("Asha's new listener:", event.detail.tea));</script>- Line 10 dispatches the new
tea-add. - Line 12 dispatches the old
add, with the same options. The comment on line 11 says when it goes. - Lines 18 and 19 stand for two pages' listeners: Meena's old one, and Asha's new one.
Press Add. The console prints Asha's new listener: Green tea, then Meena's old listener: Green tea. Both pages keep working until 2.0.0.
Parts, slots, and custom properties have moves of their own. An element can carry two part names, so old and new CSS both match. Web Awesome's button does this. Its inner button has part="base button", and its docs comment marks base as deprecated. Burton Smith shows the same idea for slots and custom properties. The JavaScript path's lesson on retiring an old API covers the rest: warning once, and writing the changelog.
Adding API docs to the tea kit
Ravi's kit now ships its first docs. Two files changed in the latest kit:
tea-kit/tea-timer.jsgot JSDoc comments. Its code is the same as in lesson 5.3.tea-kit/custom-elements.jsonis new. It's the manifest from the section above.
A manifest is data, so code can read it. This page does a small version of what a docs tool does. It loads the manifest, and checks the timer's documented default against the real one:
<p>Green tea: <tea-timer seconds="2"></tea-timer></p> <script type="module"> import "./tea-kit/index.js"; async function checkDocs() { const response = await fetch("./tea-kit/custom-elements.json"); const manifest = await response.json(); const docs = manifest.modules[0].declarations[0]; const fresh = document.createElement(docs.tagName); for (const attribute of docs.attributes) { const real = String(fresh[attribute.fieldName]); console.log(attribute.name, attribute.default === real ? "matches" : "differs", real); } for (const event of docs.events) { document.addEventListener(event.name, () => console.log(event.name, "arrived")); } } checkDocs();</script>- Lines 7 and 8 load the manifest with
fetch(), and read it as JSON. - Line 9 picks the first declaration,
TeaTimer. - Line 10 makes a fresh timer, with no attributes.
- Lines 11 to 14 compare each attribute's documented
defaultwith what the fresh timer's property really gives back. Line 13 printsseconds matches 60. - Lines 15 to 17 listen for every documented event. After 2 seconds, line 16 prints
tea-timer-done arrived.
Now open the tea-kit/tea-timer.js tab. Lines 14 to 20 are the class's JSDoc comment, with @tag on line 17, @attr on line 18, and @fires on line 19. Line 24 describes the property, and line 9 the event's field.
Why it matters: if Ravi ever changes the default in the code but not in the docs, line 13 prints differs. This lesson's test runs the same kind of check on every field, so the kit's docs can't quietly go wrong.
An API checklist for the kit
Ravi keeps this list next to the kit, and checks each new component against it:
- Simple data is an attribute with a matching property (5.1, 5.2).
- Rich data, like arrays and objects, is a property only.
- A property set before the upgrade still works (4.2).
- State is a property. Actions are methods that update it.
- News goes out as prefixed events that bubble and are composed (5.3).
- The component never changes its parent, the page, or the page's own attributes on it.
- Every public part is in the manifest.
- A rename goes through a deprecation in a minor version, then a removal in a major one.
web.dev's Custom element best practices has a longer checklist, with the reason for each item. Its shadow DOM items wait for stage 3 and stage 4.
Common mix-ups
- "Only the JavaScript properties are a component's API." No. Attributes, events, slots, CSS parts, and custom properties are API too. Renaming any of them breaks someone.
- "A component should update the page itself when something happens." No. It dispatches an event, and the page decides. Then the same component works on any page.
- "A method is the best way to change state." No. Keep state in a property backed by an attribute, so HTML and templates can set it. A method can wrap it.
- "If show() sets the state, the property can't." No. Both lead to the same attribute, as
dialog.show()anddialog.open = truedo. - "Changing a default isn't breaking, because no name changed." No. Every page that relied on the old default now shows something else.
- "Deprecating means deleting." No. A deprecated name still works. It goes later, in a major version.
- "Browsers read custom-elements.json." No. Tools read it: editors, docs sites, and linters. The browser never loads it.
- "Only Lit components can have a manifest." No. The format is shared. You can write one by hand, or have the analyzer write it from plain JavaScript.
Practice exercises
Answer first, then use the hints. The results run live, so you can check yourself.
What does line 4 print?
const dialog = document.createElement("dialog");
dialog.show();
dialog.close();
console.log(dialog.open, dialog.getAttribute("open"));false null. show() added the open attribute, and close() removed it. The property reads the attribute, so it's false. getAttribute() gives back null for an attribute that isn't there.
Version 1 of this label used 3 minutes when minutes was missing. A later version changed line 6 to 4. Meena's page didn't change. What does it show now?
<tea-label name="Green tea"></tea-label>
<script>
class TeaLabel extends HTMLElement {
get minutes() {
return Number(this.getAttribute("minutes") ?? 4);
}
connectedCallback() {
const name = this.getAttribute("name");
this.textContent = `${name}: brew for ${this.minutes} minutes`;
}
}
customElements.define("tea-label", TeaLabel);
</script>Green tea: brew for 4 minutes. The page never wrote minutes, so it gets the new default. Its text changed without any change to the page. That's a breaking change, and it needs a major version.
Press Add: the basket stays empty, and the console shows an error. Make the cup tell the page instead. What does the basket show after one click?
<p>Basket: <output>empty</output></p><tea-cup tea="Mint tea"></tea-cup> <script> class TeaCup extends HTMLElement { connectedCallback() { const tea = this.getAttribute("tea"); this.innerHTML = `<button>Add ${tea}</button>`; this.addEventListener("click", () => { updateCart(tea); }); } } customElements.define("tea-cup", TeaCup); document.addEventListener("tea-add", (event) => { document.querySelector("output").textContent = event.detail.tea; });</script><p>Basket: <output>empty</output></p><tea-cup tea="Mint tea"></tea-cup> <script> class TeaCup extends HTMLElement { connectedCallback() { const tea = this.getAttribute("tea"); this.innerHTML = `<button>Add ${tea}</button>`; this.addEventListener("click", () => { this.dispatchEvent(new CustomEvent("tea-add", { bubbles: true, composed: true, detail: { tea } })); }); } } customElements.define("tea-cup", TeaCup); document.addEventListener("tea-add", (event) => { document.querySelector("output").textContent = event.detail.tea; });</script>Mint tea. The starter throws ReferenceError: updateCart is not defined, because Meena's page has no such function. Dispatching tea-add lets the page's own listener on lines 16 to 18 fill the basket.
The menu shows Menu closed, but line 17 prints true. Fix hide() so the property agrees. What does the console print then?
<tea-menu open></tea-menu> <script> class TeaMenu extends HTMLElement { get open() { return this.hasAttribute("open"); } hide() { this.textContent = "Menu closed"; } } customElements.define("tea-menu", TeaMenu); const menu = document.querySelector("tea-menu"); menu.hide(); console.log(menu.open);</script><tea-menu open></tea-menu> <script> class TeaMenu extends HTMLElement { get open() { return this.hasAttribute("open"); } hide() { this.removeAttribute("open"); this.textContent = "Menu closed"; } } customElements.define("tea-menu", TeaMenu); const menu = document.querySelector("tea-menu"); menu.hide(); console.log(menu.open);</script>false. The starter only changed the text, so the attribute stayed, and menu.open said true. Removing the attribute keeps the state in one place, so the screen and the property agree.
Meena's old code sets cup.type, the property's old name. Nothing happens, and the cup still shows Cup: Green tea. Keep type working, with a warning. What does the cup show then?
<tea-cup tea="Green tea"></tea-cup> <script> class TeaCup extends HTMLElement { static observedAttributes = ["tea"]; get tea() { return this.getAttribute("tea"); } set tea(value) { this.setAttribute("tea", value); } attributeChangedCallback() { this.textContent = `Cup: ${this.tea}`; } } customElements.define("tea-cup", TeaCup); // Meena's old code still sets the old property. document.querySelector("tea-cup").type = "Mint tea";</script><tea-cup tea="Green tea"></tea-cup> <script> class TeaCup extends HTMLElement { static observedAttributes = ["tea"]; get tea() { return this.getAttribute("tea"); } set tea(value) { this.setAttribute("tea", value); } get type() { return this.tea; } set type(value) { console.warn("<tea-cup>: type is deprecated. Use tea instead."); this.tea = value; } attributeChangedCallback() { this.textContent = `Cup: ${this.tea}`; } } customElements.define("tea-cup", TeaCup); // Meena's old code still sets the old property. document.querySelector("tea-cup").type = "Mint tea";</script>Cup: Mint tea. The type setter warns, then sets tea, which writes the attribute and draws the cup again. Old code keeps working, and the console says what to use instead.
Start from Web Awesome's package.json, follow its customElements field to the manifest, and find wa-button's base part. Which part does it tell you to use instead?
const base = "https://cdn.jsdelivr.net/npm/@awesome.me/webawesome@3.15.0/";
const info = await (await fetch(base + "package.json")).json();
const manifest = await (await fetch(base + info.customElements)).json();
const button = manifest.modules
.flatMap((module) => module.declarations ?? [])
.find((item) => item.tagName === "wa-button");
console.log(button.cssParts.find((part) => part.name === "base").description);button. The snippet prints the part's description, which says to use the button part instead. Its deprecated field adds that base will go in a future major version. The button carries both names until then.
Check your understanding
For each question, ask which way the data goes, where the state lives, and who could break.
Question 1 of 8Asha's page wants the cup to show Mint tea. How should it tell the cup?
Choose an answer to see the explanation.
Question 2 of 8The cup that adds 1 to a
<span>in its parent sits on Meena's price list. What happens when she presses Add?Choose an answer to see the explanation.
Question 3 of 8What does this details snippet print?
Read the code, then predictconst details = document.createElement("details"); details.open = true; console.log(details.hasAttribute("open"), "show" in details);Choose an answer to see the explanation.
Question 4 of 8Why should a component's open state be a property, not only a
show()method?Choose an answer to see the explanation.
Question 5 of 8Which change to the tea timer needs a new major version?
Choose an answer to see the explanation.
Question 6 of 8The cup is at version 1.4.2. Ravi adds
teaand keepstypeworking, with a warning. What's the next version?Choose an answer to see the explanation.
Question 7 of 8What does the
customElementsfield in a package.json do?Choose an answer to see the explanation.
Question 8 of 8Which JSDoc tag tells the analyzer about an event?
Choose an answer to see the explanation.
Key takeaways
- A component's API is every part a page can touch: attributes, properties, methods, events, slots, CSS parts, and custom properties.
- Properties down, events up. The page sends data in, and the component sends news out.
- A component never reaches into its parent or the page. Then the same component works on every page.
- State lives in a property backed by an attribute. Methods are actions that update it, like
dialog.show(). - A custom elements manifest describes every public part in one JSON file that tools read. A package points to it with
customElementsin its package.json. - JSDoc tags like
@attr,@prop,@fires,@slot,@csspart, and@cssproplet the analyzer write the manifest for you. - Renames, removals, new defaults, and changes to an event's timing or shape are breaking. They need a major version.
- Deprecate first: keep the old name working, warn, and mark it in the docs, in a minor version. Remove it in the next major one.
Remember the one-liner.
Data in through properties, news out through events, state in properties, actions in methods, every part written down, and no rename without a deprecation first.
Sources
The facts on this page come from these standards, docs, source files, and posts:
- Component composition: Passing data up and down the tree, Lit.
- Guidelines for creating web platform compatible components, W3C TAG.
- Custom element best practices, web.dev.
- HTML Standard: The dialog element, WHATWG.
- HTML Standard: The details element, WHATWG.
- Web Platform Design Principles: Accessors should behave like properties, not methods, W3C TAG.
- details.ts at v3.15.0, open, show(), and hide(), Web Awesome.
- When To Create CSS Parts, Cory LaViska.
- Custom Elements Manifest Analyzer: Getting started, Open Web Components.
- custom-elements-manifest at v2.1.0, the README and schema, webcomponents on GitHub.
- You Should Be Shipping a Manifest with Your Web Components, Burton Smith.
- Semantic Versioning 2.0.0, semver.org.
- About semantic versioning, npm Docs.
- Deprecating Your Web Component APIs, Burton Smith.
- button.ts at v3.15.0, the deprecated base part, Web Awesome.
Coming next: Working with children. Read and react to the elements a user puts inside your component, including ones added later.