css is now string | CSSStyleSheet. A sheet is adopted as-is: into its own
shadow root, an enclosing shadow root, or document.adoptedStyleSheets for
light DOM at the document level. Strings behave as before.
The examples import their styles with `with { type: 'css' }` and their
static templates with `with { type: 'text' }`. Safari doesn't support those
yet, so vite.config.ts rewrites them into modules Vite builds: a constructed
CSSStyleSheet, or the file's text. npm run examples now just runs vite,
with root set in the config.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
75 lines
2.0 KiB
TypeScript
75 lines
2.0 KiB
TypeScript
import { WebComponent, choice, string } from '../src/index.ts';
|
|
import { share } from './main-context.ts';
|
|
import { SWATCHES, THEMES } from './themes.ts';
|
|
import css from './color-swatch-picker.css' with { type: 'css' };
|
|
|
|
/**
|
|
* Light DOM radio group. The radios are real light-DOM `<input>`s, so arrow
|
|
* keys, focus and form behaviour are native. A pick is shared with the nearest
|
|
* `<main-context>` as a `theme` update.
|
|
*/
|
|
const SPEC = {
|
|
template: `
|
|
<fieldset>
|
|
<legend></legend>
|
|
<div class="swatches">
|
|
${THEMES.map(
|
|
(theme) => `
|
|
<label class="swatch" style="--swatch: ${SWATCHES[theme]}">
|
|
<input type="radio" value="${theme}">
|
|
<span>${theme}</span>
|
|
</label>`,
|
|
).join('')}
|
|
</div>
|
|
</fieldset>
|
|
`,
|
|
css,
|
|
events: {
|
|
change: true,
|
|
},
|
|
element: { legend: 'legend' },
|
|
elements: { radios: 'input[type=radio]' },
|
|
props: {
|
|
label: string({ default: 'Theme' }),
|
|
value: choice(THEMES, { default: 'sunset' }),
|
|
},
|
|
} as const;
|
|
|
|
// Each picker needs its own radio group name.
|
|
let count = 0;
|
|
|
|
export class ColorSwatchPicker extends WebComponent(SPEC) {
|
|
readonly #name = `color-swatch-picker-${(count += 1)}`;
|
|
|
|
override onConnect(): void {
|
|
for (const radio of this.refs.radios) radio.name = this.#name;
|
|
this.#render();
|
|
}
|
|
|
|
override onPropChange(): void {
|
|
this.#render();
|
|
}
|
|
|
|
override handleEvent(event: Event): void {
|
|
const radio = this.refs.radios.find((input) => input === event.target);
|
|
const theme = THEMES.find((name) => name === radio?.value);
|
|
if (theme && this.value !== theme) {
|
|
this.value = theme;
|
|
share(this, 'theme', theme);
|
|
}
|
|
}
|
|
|
|
#render(): void {
|
|
if (this.refs.legend) this.refs.legend.textContent = this.label;
|
|
for (const radio of this.refs.radios) radio.checked = radio.value === this.value;
|
|
}
|
|
}
|
|
|
|
customElements.define('color-swatch-picker', ColorSwatchPicker);
|
|
|
|
declare global {
|
|
interface HTMLElementTagNameMap {
|
|
'color-swatch-picker': ColorSwatchPicker;
|
|
}
|
|
}
|