diff --git a/README.md b/README.md index 6189625..a36a056 100644 --- a/README.md +++ b/README.md @@ -13,8 +13,8 @@ Because they are standard custom elements, the components work in any page or fr ## Install ```bash -pnpm add etherpad-webcomponents -# or: npm install etherpad-webcomponents +pnpm add @samtv12345/etherpad-webcomponents +# or: npm install @samtv12345/etherpad-webcomponents ``` ## Usage @@ -23,10 +23,10 @@ Import the whole library, or just the components you need (each is individually ```js // everything -import 'etherpad-webcomponents'; +import '@samtv12345/etherpad-webcomponents'; // or a single component -import 'etherpad-webcomponents/EpButton.js'; +import '@samtv12345/etherpad-webcomponents/EpButton.js'; ``` ```html @@ -42,7 +42,7 @@ import 'etherpad-webcomponents/EpButton.js'; The named exports (classes) are also available for programmatic use: ```js -import { EpButton, EpTheme, themes } from 'etherpad-webcomponents'; +import { EpButton, EpTheme, themes } from '@samtv12345/etherpad-webcomponents'; ``` --- @@ -64,18 +64,49 @@ import { EpButton, EpTheme, themes } from 'etherpad-webcomponents'; | `` / `` | `EpToastContainer` / `EpToastItem` | `position`, `type`, `message`, `duration` | — | | `` | `EpToolbarSelect` | `options[]`, `value`, `icon-class`, `label`, `placeholder` | `ep-toolbar-select:change` | | `` | `EpUserBadge` | `name`, `color`, `size`, `online` | — | -| `` | `EpTheme` | `name` — applies a token set to its subtree | — | +| `` / `` | `EpTabs` / `EpTab` | `value`, `variant` (`underline`/`pills`); tab: `value`, `label`, `disabled` | `ep-tab-change` | +| `` | `EpTheme` | `name` (incl. `auto`), `light`, `dark`, `.tokens` — applies a token set to its subtree | `ep-theme-change` | | `` | `EpEditor` | `content`, `readonly`, `wrap`, `author-id` | `ready`, `content-changed`, `selection-changed` | ### Theming -Components read CSS custom properties (`--text-color`, `--primary-color`, `--bg-soft-color`, …). Wrap a subtree in `` to apply a token set. Built-in themes: **`colibris`** (default, matches Etherpad's skin), **`colibris-dark`**, **`high-contrast`**, and **`warm`**. Register your own at runtime: +Components only read CSS custom properties, so every colour, radius and shadow can be changed without touching the components. Built-in themes: **`colibris`** (default, Etherpad's light-green skin), **`colibris-dark`**, **`high-contrast`** and **`warm`**. + +| Token | Used for | +| --- | --- | +| `--bg-color`, `--bg-soft-color`, `--light-color`, `--super-light-color` | surfaces | +| `--text-color`, `--text-soft-color`, `--dark-color`, `--super-dark-color` | text, icons | +| `--middle-color` | borders | +| `--primary-color`, `--primary-text-color` | accent and text on the accent | +| `--danger-color`, `--success-color`, `--warning-color` | states | +| `--focus-color` | focus ring | +| `--radius`, `--radius-large`, `--shadow` | shape and elevation | +| `--main-font-family` | font | + +A theme only needs to state what differs from its base: ```js -import { EpTheme } from 'etherpad-webcomponents'; -EpTheme.registerTheme('brand', { '--primary-color': '#ff5722', /* …all ThemeTokens */ }); +import { defineTheme } from '@samtv12345/etherpad-webcomponents'; + +defineTheme('acme', { '--primary-color': '#7c3aed' }); // based on colibris +defineTheme('acme-dark', { '--primary-color': '#a78bfa' }, 'colibris-dark'); +``` + +```html + +… + + +… ``` +`` sets `data-scheme="light|dark"` on itself, fires `ep-theme-change` and updates live when a theme is redefined. Single tokens can be overridden per element with the `tokens` property. Without the element: + +- `applyTheme(document.documentElement, 'acme')` sets the tokens on any element (and removes tokens of the previous call that the new set lacks), +- `themeToCss('acme', ':root')` returns the tokens as a CSS rule, e.g. for rendering them server-side. + +`@samtv12345/etherpad-webcomponents/themes.js` contains only these functions and the token sets, without any custom element. + ### The editor (``) `` embeds Etherpad's Ace editor engine (under `src/editor/`: `Changeset`, `AttributePool`, `changesettracker`, content collector, op assemblers, etc.) as a self-contained element. It supports bold/italic/underline/strikethrough, ordered & unordered lists, indentation, undo/redo, and changeset-based collaboration. @@ -99,7 +130,7 @@ const pending = ed.prepareUserChangeset(); // { changeset, apool } to send to The lower-level engine pieces are also exported for advanced use: ```js -import { AceEditor, AttributePool, makeChangesetTracker } from 'etherpad-webcomponents'; +import { AceEditor, AttributePool, makeChangesetTracker } from '@samtv12345/etherpad-webcomponents'; ``` --- diff --git a/package.json b/package.json index 033b59d..0f727e6 100644 --- a/package.json +++ b/package.json @@ -23,7 +23,9 @@ "./EpToolbarSelect.js": "./dist/EpToolbarSelect.js", "./EpSelect.js": "./dist/EpSelect.js", "./EpUserBadge.js": "./dist/EpUserBadge.js", + "./EpTabs.js": "./dist/EpTabs.js", "./EpTheme.js": "./dist/EpTheme.js", + "./themes.js": "./dist/themes.js", "./EpEditor.js": "./dist/EpEditor.js", "./editor/AceEditor.js": "./dist/editor/AceEditor.js", "./editor/AttributePool.js": "./dist/editor/AttributePool.js", diff --git a/src/EpButton.ts b/src/EpButton.ts index f67c004..dd8f6f1 100644 --- a/src/EpButton.ts +++ b/src/EpButton.ts @@ -12,7 +12,7 @@ export class EpButton extends LitElement { button { font-family: var(--ep-font); padding: 5px 20px; - border-radius: 4px; + border-radius: var(--radius, 4px); font-size: 14px; font-weight: 700; cursor: pointer; @@ -34,7 +34,7 @@ export class EpButton extends LitElement { } button:focus-visible { - outline: 2px solid var(--dark-color, #576273); + outline: 2px solid var(--focus-color, var(--dark-color, #576273)); outline-offset: 2px; } @@ -59,7 +59,7 @@ export class EpButton extends LitElement { background with bg-coloured (white) text. */ :host([variant="primary"]) button { background: var(--primary-color, #64d29b); - color: var(--bg-color, #ffffff); + color: var(--primary-text-color, var(--bg-color, #ffffff)); border: none; transition: filter 0.15s ease, opacity 0.15s ease; } @@ -90,7 +90,7 @@ export class EpButton extends LitElement { color: var(--text-color, #485365); border: none; padding: 4px; - border-radius: 3px; + border-radius: calc(var(--radius, 4px) - 1px); min-width: 28px; min-height: 28px; justify-content: center; diff --git a/src/EpCard.ts b/src/EpCard.ts index 7b65d5d..d9c5ced 100644 --- a/src/EpCard.ts +++ b/src/EpCard.ts @@ -14,8 +14,8 @@ export class EpCard extends LitElement { .card { background: var(--bg-color, white); - border-radius: 5px; - box-shadow: 0 0 0 1px rgba(99, 114, 130, 0.16), 0 8px 16px rgba(27, 39, 51, 0.08); + border-radius: var(--radius-large, 5px); + box-shadow: var(--shadow, 0 0 0 1px rgba(99, 114, 130, 0.16), 0 8px 16px rgba(27, 39, 51, 0.08)); overflow: hidden; } diff --git a/src/EpCheckbox.ts b/src/EpCheckbox.ts index 9279fde..63d10f7 100644 --- a/src/EpCheckbox.ts +++ b/src/EpCheckbox.ts @@ -93,7 +93,7 @@ export class EpCheckbox extends LitElement { } :host(:focus-within) .track { - outline: 2px solid var(--dark-color, #576273); + outline: 2px solid var(--focus-color, var(--dark-color, #576273)); outline-offset: 2px; } @@ -112,7 +112,7 @@ export class EpCheckbox extends LitElement {
- ` group. Its content is the panel shown while the + * tab is selected. + */ +@customElement('ep-tab') +export class EpTab extends LitElement { + static styles = css` + :host { display: block; } + :host([hidden]) { display: none; } + `; + + /** Identifies the tab; defaults to its position. */ + @property({ reflect: true }) value = ''; + /** Text of the tab button. */ + @property() label = ''; + @property({ type: Boolean, reflect: true }) disabled = false; + + connectedCallback() { + super.connectedCallback(); + this.setAttribute('role', 'tabpanel'); + } + + updated(changed: Map) { + if (changed.has('label') || changed.has('value') || changed.has('disabled')) { + this.dispatchEvent(new Event('ep-tab-updated', { bubbles: true })); + } + if (changed.has('label')) { + if (this.label) this.setAttribute('aria-label', this.label); + else this.removeAttribute('aria-label'); + } + } + + render() { + return html``; + } +} + +/** + * Tab group. Children are `` elements; the header is built from their + * labels. + * + * + * … + * … + * + * + * Fires `ep-tab-change` (detail: `{ value }`) when the user picks a tab. + */ +@customElement('ep-tabs') +export class EpTabs extends LitElement { + static styles = css` + :host { + --ep-font: var(--main-font-family, Quicksand, Cantarell, "Open Sans", "Helvetica Neue", sans-serif); + display: block; + font-family: var(--ep-font); + color: var(--text-color, #485365); + } + + [role="tablist"] { + display: flex; + gap: 4px; + border-bottom: 1px solid var(--middle-color, #d2d2d2); + overflow-x: auto; + scrollbar-width: none; + } + + :host([variant="pills"]) [role="tablist"] { + border-bottom: none; + background: var(--bg-soft-color, #f2f3f4); + border-radius: var(--radius-large, 5px); + padding: 3px; + } + + button { + font: inherit; + font-size: 14px; + font-weight: 600; + color: var(--text-soft-color, #576273); + background: transparent; + border: none; + border-bottom: 2px solid transparent; + margin-bottom: -1px; + padding: 8px 14px; + cursor: pointer; + white-space: nowrap; + transition: color 0.15s ease, border-color 0.15s ease, background 0.15s ease; + } + + button:hover { color: var(--text-color, #485365); } + + button[aria-selected="true"] { + color: var(--text-color, #485365); + border-bottom-color: var(--primary-color, #64d29b); + } + + :host([variant="pills"]) button { + border-bottom: none; + margin: 0; + border-radius: calc(var(--radius, 4px) - 1px); + padding: 5px 12px; + } + + :host([variant="pills"]) button[aria-selected="true"] { + background: var(--bg-color, #ffffff); + box-shadow: 0 1px 2px rgba(27, 39, 51, 0.12); + } + + button:focus-visible { + outline: 2px solid var(--focus-color, var(--dark-color, #576273)); + outline-offset: -2px; + } + + button:disabled { + opacity: 0.4; + cursor: not-allowed; + } + + .panels { padding-top: var(--ep-tabs-gap, 16px); } + `; + + /** Value of the selected tab. Empty selects the first enabled tab. */ + @property({ reflect: true }) value = ''; + /** `underline` (default) or `pills`. */ + @property({ reflect: true }) variant: 'underline' | 'pills' = 'underline'; + + @state() private _tabs: EpTab[] = []; + + connectedCallback() { + super.connectedCallback(); + this.addEventListener('ep-tab-updated', this._collect); + } + + disconnectedCallback() { + super.disconnectedCallback(); + this.removeEventListener('ep-tab-updated', this._collect); + } + + private _collect = () => { + this._tabs = Array.from(this.children).filter( + (c): c is EpTab => c instanceof EpTab, + ); + this._keys = this._computeKeys(); + this._sync(); + }; + + /** Unique key per tab: its value, its position if it has none. */ + private _keys: string[] = []; + + private _computeKeys(): string[] { + const seen = new Set(); + return this._tabs.map((tab, i) => { + let key = tab.value || String(i); + if (seen.has(key)) { + console.warn(`ep-tabs: duplicate tab value "${key}"; only the first tab can be selected by it`); + key = `${key}#${i}`; + while (seen.has(key)) key += '#'; + } + seen.add(key); + return key; + }); + } + + /** Index of the selected tab (falls back to the first enabled tab), or -1. */ + private get _selectedIndex(): number { + const i = this._keys.indexOf(this.value); + if (i >= 0 && !this._tabs[i]?.disabled) return i; + return this._tabs.findIndex((t) => !t.disabled); + } + + /** The value actually selected (falls back to the first enabled tab). */ + get selected(): string { + const i = this._selectedIndex; + return i >= 0 ? this._keys[i] : ''; + } + + updated(changed: Map) { + if (changed.has('value')) this._sync(); + this._linkPanels(); + } + + private _sync() { + const selected = this._selectedIndex; + this._tabs.forEach((tab, i) => { + tab.hidden = i !== selected; + }); + } + + /** + * Tab buttons live in the shadow root and panels in the light DOM, so ID + * references cannot connect them. Where the browser supports ARIA element + * reflection, point each button at its panel; panels carry the tab label + * as aria-label in any case. + */ + private _linkPanels() { + const buttons = this.renderRoot.querySelectorAll('button[role="tab"]'); + buttons.forEach((btn, i) => { + const tab = this._tabs[i]; + if (tab && 'ariaControlsElements' in btn) { + (btn as HTMLButtonElement & { ariaControlsElements: Element[] }).ariaControlsElements = [tab]; + } + }); + } + + private _select(value: string, focus = false) { + if (value !== this.value) { + this.value = value; + this.dispatchEvent(new CustomEvent('ep-tab-change', { + bubbles: true, composed: true, detail: { value }, + })); + } + if (focus) { + this.updateComplete.then(() => { + this.renderRoot.querySelector('button[aria-selected="true"]')?.focus(); + }); + } + } + + private _onKeydown(e: KeyboardEvent) { + const enabled = this._tabs + .map((t, i) => ({ t, i })) + .filter(({ t }) => !t.disabled); + if (!enabled.length) return; + // Start from the button that has focus, not from the selection: the + // application may have changed the value meanwhile. + const focused = (e.target as HTMLElement | null)?.closest?.('button[role="tab"]') as HTMLButtonElement | null; + const from = focused ? Number(focused.dataset.index) : this._selectedIndex; + const at = enabled.findIndex(({ i }) => i === from); + let next = -1; + switch (e.key) { + case 'ArrowRight': next = (at + 1) % enabled.length; break; + case 'ArrowLeft': next = (at - 1 + enabled.length) % enabled.length; break; + case 'Home': next = 0; break; + case 'End': next = enabled.length - 1; break; + default: return; + } + e.preventDefault(); + this._select(this._keys[enabled[next].i], true); + } + + render() { + const selected = this._selectedIndex; + return html` +
+ ${this._tabs.map((tab, i) => { + const v = this._keys[i]; + const isSel = i === selected; + return html``; + })} +
+
+ +
+ `; + } +} + +declare global { + interface HTMLElementTagNameMap { + 'ep-tabs': EpTabs; + 'ep-tab': EpTab; + } +} diff --git a/src/EpTheme.ts b/src/EpTheme.ts index e77d561..18472e9 100644 --- a/src/EpTheme.ts +++ b/src/EpTheme.ts @@ -1,77 +1,11 @@ import { LitElement, html, css } from 'lit'; import { customElement, property } from 'lit/decorators.js'; +import { + DEFAULT_THEME, applyTheme, isDark, notifyThemeChanged, onThemeDefined, themes, +} from './themes.js'; +import type { ThemeTokens } from './themes.js'; -export interface ThemeTokens { - '--bg-color': string; - '--bg-soft-color': string; - '--text-color': string; - '--text-soft-color': string; - '--middle-color': string; - '--dark-color': string; - '--super-dark-color': string; - '--light-color': string; - '--super-light-color': string; - '--primary-color': string; - '--main-font-family': string; -} - -export const themes: Record = { - colibris: { - '--bg-color': 'white', - '--bg-soft-color': '#f2f3f4', - '--text-color': '#485365', - '--text-soft-color': '#576273', - '--middle-color': '#d2d2d2', - '--dark-color': '#576273', - '--super-dark-color': '#485365', - '--light-color': '#f2f3f4', - '--super-light-color': 'white', - '--primary-color': '#64d29b', - '--main-font-family': 'Quicksand, Cantarell, "Open Sans", "Helvetica Neue", sans-serif', - }, - - 'colibris-dark': { - '--bg-color': '#2c3143', - '--bg-soft-color': '#363b50', - '--text-color': '#e4e6eb', - '--text-soft-color': '#a8adb8', - '--middle-color': '#4a5068', - '--dark-color': '#a8adb8', - '--super-dark-color': '#e4e6eb', - '--light-color': '#363b50', - '--super-light-color': '#2c3143', - '--primary-color': '#64d29b', - '--main-font-family': 'Quicksand, Cantarell, "Open Sans", "Helvetica Neue", sans-serif', - }, - - 'high-contrast': { - '--bg-color': 'white', - '--bg-soft-color': '#f5f5f5', - '--text-color': '#111111', - '--text-soft-color': '#333333', - '--middle-color': '#999999', - '--dark-color': '#333333', - '--super-dark-color': '#111111', - '--light-color': '#f5f5f5', - '--super-light-color': 'white', - '--primary-color': '#0066cc', - '--main-font-family': '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif', - }, - - warm: { - '--bg-color': '#fdfbf7', - '--bg-soft-color': '#f5f0e8', - '--text-color': '#4a3f35', - '--text-soft-color': '#7a6e62', - '--middle-color': '#d6cfc5', - '--dark-color': '#7a6e62', - '--super-dark-color': '#4a3f35', - '--light-color': '#f5f0e8', - '--super-light-color': '#fdfbf7', - '--primary-color': '#c47a4a', - '--main-font-family': 'Georgia, "Times New Roman", serif', - }, -}; +export * from './themes.js'; @customElement('ep-theme') export class EpTheme extends LitElement { @@ -81,25 +15,76 @@ export class EpTheme extends LitElement { } `; - @property({ reflect: true }) name: string = 'colibris'; + /** + * Theme to apply. `auto` follows the operating system and picks `light` + * or `dark`. + */ + @property({ reflect: true }) name: string = DEFAULT_THEME; - updated(changed: Map) { - if (changed.has('name')) { - this._applyTokens(); - } + /** Theme used by `name="auto"` in light mode. */ + @property() light: string = DEFAULT_THEME; + + /** Theme used by `name="auto"` in dark mode. */ + @property() dark: string = 'colibris-dark'; + + /** Single tokens on top of the theme, e.g. `{ '--primary-color': '#7c3aed' }`. */ + @property({ attribute: false }) tokens: Partial = {}; + + private _media?: MediaQueryList; + private _onMedia = () => this._applyTokens(); + private _current = ''; + private _unsubscribe?: () => void; + + /** Theme name actually in use (resolves `auto`). */ + get resolvedName(): string { + if (this.name !== 'auto') return this.name; + return this._media?.matches ? this.dark : this.light; } connectedCallback() { super.connectedCallback(); + this._unsubscribe = onThemeDefined((n) => this.themeUpdated(n)); + if (typeof matchMedia === 'function') { + this._media = matchMedia('(prefers-color-scheme: dark)'); + this._media.addEventListener('change', this._onMedia); + } this._applyTokens(); } - private _applyTokens() { - const tokens = themes[this.name]; - if (!tokens) return; + disconnectedCallback() { + super.disconnectedCallback(); + this._unsubscribe?.(); + this._unsubscribe = undefined; + this._media?.removeEventListener('change', this._onMedia); + this._media = undefined; + } - for (const [prop, value] of Object.entries(tokens)) { - this.style.setProperty(prop, value); + updated(changed: Map) { + if (changed.has('name') || changed.has('light') || changed.has('dark') || changed.has('tokens')) { + this._applyTokens(); + } + } + + /** @internal called when a theme is (re)defined at runtime. */ + themeUpdated(name: string) { + if (name === this.resolvedName) this._applyTokens(); + } + + private _applyTokens() { + const name = this.resolvedName; + const base = themes[name]; + if (!base) { + console.warn(`ep-theme: unknown theme "${name}"`); + return; + } + const merged = { ...base, ...this.tokens } as ThemeTokens; + applyTheme(this, merged); + this.dataset.scheme = isDark(merged, resolveColor(merged['--bg-color'])) ? 'dark' : 'light'; + if (this._current !== name) { + this._current = name; + this.dispatchEvent(new CustomEvent('ep-theme-change', { + bubbles: true, composed: true, detail: { name }, + })); } } @@ -107,9 +92,10 @@ export class EpTheme extends LitElement { return html``; } - /** Register a custom theme at runtime. */ + /** Register a custom theme at runtime (full token set). */ static registerTheme(name: string, tokens: ThemeTokens) { themes[name] = tokens; + notifyThemeChanged(name); } /** Get all registered theme names. */ @@ -118,6 +104,30 @@ export class EpTheme extends LitElement { } } +let probe: HTMLElement | undefined; + +/** + * Lets the browser turn any CSS colour (named, hsl(), color-mix(), …) into + * rgb(), so isDark() can judge it. Returns undefined outside a browser. + */ +function resolveColor(value: string | undefined): string | undefined { + if (!value || typeof document === 'undefined' || !document.body) return undefined; + if (!probe) { + probe = document.createElement('span'); + probe.setAttribute('aria-hidden', 'true'); + probe.style.cssText = 'position:absolute;width:0;height:0;overflow:hidden;pointer-events:none;'; + } + probe.style.backgroundColor = ''; + probe.style.backgroundColor = value; + if (!probe.style.backgroundColor) return undefined; // invalid colour + document.body.appendChild(probe); + const rgb = getComputedStyle(probe).backgroundColor; + probe.remove(); + // Fully transparent (e.g. an unresolved var()) says nothing about the scheme. + if (/^rgba\(.*[,/]\s*0\)$/.test(rgb) || rgb === 'transparent') return undefined; + return rgb; +} + declare global { interface HTMLElementTagNameMap { 'ep-theme': EpTheme; diff --git a/src/EpToast.ts b/src/EpToast.ts index 4e4efde..a744a53 100644 --- a/src/EpToast.ts +++ b/src/EpToast.ts @@ -12,9 +12,9 @@ interface ToastOptions { } const toastIconSvg: Record = { - success: ``, - error: ``, - info: ``, + success: ``, + error: ``, + info: ``, }; @customElement('ep-toast-item') @@ -53,15 +53,15 @@ export class EpToastItem extends LitElement { align-items: flex-start; gap: 10px; padding: 12px 16px; - border-radius: 5px; - box-shadow: 0 0 0 1px rgba(99, 114, 130, 0.16), 0 8px 16px rgba(27, 39, 51, 0.08); + border-radius: var(--radius-large, 5px); + box-shadow: var(--shadow, 0 0 0 1px rgba(99, 114, 130, 0.16), 0 8px 16px rgba(27, 39, 51, 0.08)); background: var(--bg-color, white); color: var(--text-color, #485365); border-left: 3px solid var(--middle-color, #d2d2d2); } - :host([type="success"]) .toast { border-left-color: var(--primary-color, #64d29b); } - :host([type="error"]) .toast { border-left-color: #d1242f; } + :host([type="success"]) .toast { border-left-color: var(--success-color, var(--primary-color, #64d29b)); } + :host([type="error"]) .toast { border-left-color: var(--danger-color, #d1242f); } :host([type="info"]) .toast { border-left-color: var(--dark-color, #576273); } .icon { flex-shrink: 0; width: 16px; height: 16px; margin-top: 2px; } diff --git a/src/EpToolbarSelect.ts b/src/EpToolbarSelect.ts index 8cda926..a432688 100644 --- a/src/EpToolbarSelect.ts +++ b/src/EpToolbarSelect.ts @@ -30,7 +30,7 @@ export class EpToolbarSelect extends LitElement { height: 28px; padding: 0 8px; border: none; - border-radius: 3px; + border-radius: calc(var(--radius, 4px) - 1px); background: transparent; color: inherit; cursor: pointer; @@ -44,7 +44,7 @@ export class EpToolbarSelect extends LitElement { } .trigger:focus-visible { - outline: 2px solid var(--dark-color, #576273); + outline: 2px solid var(--focus-color, var(--dark-color, #576273)); outline-offset: 1px; } diff --git a/src/index.ts b/src/index.ts index 0e8baf2..90af843 100644 --- a/src/index.ts +++ b/src/index.ts @@ -14,7 +14,9 @@ export { EpToolbarSelect } from './EpToolbarSelect.js'; export { EpSelect } from './EpSelect.js'; export type { EpSelectOption } from './EpSelect.js'; export { EpUserBadge } from './EpUserBadge.js'; -export { EpTheme, themes } from './EpTheme.js'; +export { EpTabs, EpTab } from './EpTabs.js'; +export { EpTheme } from './EpTheme.js'; +export * from './themes.js'; export type { ThemeTokens } from './EpTheme.js'; export { EpEditor } from './EpEditor.js'; export { AceEditor } from './editor/AceEditor.js'; diff --git a/src/themes.ts b/src/themes.ts new file mode 100644 index 0000000..93f21b2 --- /dev/null +++ b/src/themes.ts @@ -0,0 +1,269 @@ +export interface ThemeTokens { + '--bg-color': string; + '--bg-soft-color': string; + '--text-color': string; + '--text-soft-color': string; + '--middle-color': string; + '--dark-color': string; + '--super-dark-color': string; + '--light-color': string; + '--super-light-color': string; + '--primary-color': string; + '--main-font-family': string; + /** Text colour on top of `--primary-color` (primary buttons, badges). */ + '--primary-text-color'?: string; + /** Errors, destructive actions. */ + '--danger-color'?: string; + /** Success notices. */ + '--success-color'?: string; + /** Warnings. */ + '--warning-color'?: string; + /** Focus ring colour. */ + '--focus-color'?: string; + /** Corner radius of buttons; inputs and selects use 1px less. */ + '--radius'?: string; + /** Corner radius of surfaces (cards, dialogs, menus, toasts). */ + '--radius-large'?: string; + /** `light` or `dark`; overrides the detection from `--bg-color`. */ + '--color-scheme'?: string; + /** Elevation of floating surfaces. */ + '--shadow'?: string; + /** Allows extra, app-specific tokens (`--my-token`). */ + [token: `--${string}`]: string | undefined; +} + +/** Name of the theme used when nothing else is selected. */ +export const DEFAULT_THEME = 'colibris'; + +const SHADOW = '0 0 0 1px rgba(99, 114, 130, 0.16), 0 8px 16px rgba(27, 39, 51, 0.08)'; +const SHADOW_DARK = '0 0 0 1px rgba(0, 0, 0, 0.3), 0 8px 16px rgba(0, 0, 0, 0.35)'; + + +/** Registry of all known themes. Prefer `defineTheme` for adding new ones. */ +export const themes: Record = { + colibris: { + '--bg-color': 'white', + '--bg-soft-color': '#f2f3f4', + '--text-color': '#485365', + '--text-soft-color': '#576273', + '--middle-color': '#d2d2d2', + '--dark-color': '#576273', + '--super-dark-color': '#485365', + '--light-color': '#f2f3f4', + '--super-light-color': 'white', + '--primary-color': '#64d29b', + '--main-font-family': 'Quicksand, Cantarell, "Open Sans", "Helvetica Neue", sans-serif', + '--primary-text-color': 'white', + '--danger-color': '#d1242f', + '--success-color': '#64d29b', + '--warning-color': '#d4a72c', + '--focus-color': '#576273', + '--radius': '4px', + '--radius-large': '5px', + '--shadow': SHADOW, + }, + + 'colibris-dark': { + '--bg-color': '#2c3143', + '--bg-soft-color': '#363b50', + '--text-color': '#e4e6eb', + '--text-soft-color': '#a8adb8', + '--middle-color': '#4a5068', + '--dark-color': '#a8adb8', + '--super-dark-color': '#e4e6eb', + '--light-color': '#363b50', + '--super-light-color': '#2c3143', + '--primary-color': '#64d29b', + '--main-font-family': 'Quicksand, Cantarell, "Open Sans", "Helvetica Neue", sans-serif', + '--primary-text-color': '#2c3143', + '--danger-color': '#ff6b6b', + '--success-color': '#64d29b', + '--warning-color': '#e3b341', + '--focus-color': '#a8adb8', + '--radius': '4px', + '--radius-large': '5px', + '--shadow': SHADOW_DARK, + }, + + 'high-contrast': { + '--bg-color': 'white', + '--bg-soft-color': '#f5f5f5', + '--text-color': '#111111', + '--text-soft-color': '#333333', + '--middle-color': '#999999', + '--dark-color': '#333333', + '--super-dark-color': '#111111', + '--light-color': '#f5f5f5', + '--super-light-color': 'white', + '--primary-color': '#0066cc', + '--main-font-family': '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif', + '--primary-text-color': 'white', + '--danger-color': '#b00020', + '--success-color': '#006b2e', + '--warning-color': '#8a5a00', + '--focus-color': '#111111', + '--radius': '4px', + '--radius-large': '5px', + '--shadow': SHADOW, + }, + + warm: { + '--bg-color': '#fdfbf7', + '--bg-soft-color': '#f5f0e8', + '--text-color': '#4a3f35', + '--text-soft-color': '#7a6e62', + '--middle-color': '#d6cfc5', + '--dark-color': '#7a6e62', + '--super-dark-color': '#4a3f35', + '--light-color': '#f5f0e8', + '--super-light-color': '#fdfbf7', + '--primary-color': '#c47a4a', + '--main-font-family': 'Georgia, "Times New Roman", serif', + '--primary-text-color': '#fdfbf7', + '--danger-color': '#b3261e', + '--success-color': '#5a8a3c', + '--warning-color': '#b7791f', + '--focus-color': '#7a6e62', + '--radius': '4px', + '--radius-large': '5px', + '--shadow': SHADOW, + }, +}; + +/** + * Registers a theme. Tokens that are not given are taken from `base` + * (default: colibris), so a theme only has to state what differs – e.g. a + * different accent colour: + * + * defineTheme('acme', { '--primary-color': '#7c3aed' }); + * + * Returns the complete token set. + */ +export function defineTheme( + name: string, + tokens: Partial, + base: string = DEFAULT_THEME, +): ThemeTokens { + const parent = themes[base]; + if (!parent) throw new Error(`ep-theme: unknown base theme "${base}"`); + const merged = { ...parent } as ThemeTokens; + for (const [k, v] of Object.entries(tokens)) { + if (v !== undefined) merged[k as keyof ThemeTokens] = v as never; + } + themes[name] = merged; + notifyThemeChanged(name); + return merged; +} + +/** Returns the tokens of a theme, or undefined if it is unknown. */ +export function getTheme(name: string): ThemeTokens | undefined { + return themes[name]; +} + +const TOKEN_NAME = /^--[a-zA-Z0-9_-]+$/; +const UNSAFE_VALUE = /[;{}<>\\]/; + +/** + * Renders a theme as plain CSS (`selector { --token: value; … }`), for pages + * that set tokens on `:root` – or server-side – instead of using ``. + * + * Token names must look like `--name`, and values must not contain + * `; { } < > \`; anything else throws instead of producing broken or + * injectable CSS. The selector is written as given and must be trusted. + */ +export function themeToCss(theme: string | Partial, selector = ':root'): string { + const tokens = typeof theme === 'string' ? themes[theme] : theme; + if (!tokens) throw new Error(`ep-theme: unknown theme "${theme}"`); + const body = Object.entries(tokens) + .filter(([, v]) => v !== undefined && v !== '') + .map(([k, v]) => { + if (!TOKEN_NAME.test(k)) throw new Error(`ep-theme: invalid token name "${k}"`); + const value = String(v); + if (UNSAFE_VALUE.test(value)) throw new Error(`ep-theme: invalid value for ${k}`); + return ` ${k}: ${value};`; + }) + .join('\n'); + return `${selector} {\n${body}\n}`; +} + +/** + * Sets a theme's tokens as inline custom properties on `el` (e.g. + * `document.documentElement`). Tokens set by an earlier call that the new + * theme does not define are removed again. + */ +export function applyTheme(el: HTMLElement, theme: string | Partial): void { + const tokens = typeof theme === 'string' ? themes[theme] : theme; + if (!tokens) return; + const previous = applied.get(el) ?? []; + const next: string[] = []; + for (const [prop, value] of Object.entries(tokens)) { + if (value === undefined || value === '') continue; + el.style.setProperty(prop, String(value)); + next.push(prop); + } + for (const prop of previous) { + if (!next.includes(prop)) el.style.removeProperty(prop); + } + applied.set(el, next); +} + +const applied = new WeakMap(); +const listeners = new Set<(name: string) => void>(); + +/** Calls `fn` whenever a theme is (re)defined at runtime. Returns an unsubscribe function. */ +export function onThemeDefined(fn: (name: string) => void): () => void { + listeners.add(fn); + return () => listeners.delete(fn); +} + +/** @internal */ +export function notifyThemeChanged(name: string) { + for (const fn of listeners) fn(name); +} + +const NAMED_COLORS: Record = { + black: [0, 0, 0], white: [255, 255, 255], + navy: [0, 0, 128], darkslategray: [47, 79, 79], darkslategrey: [47, 79, 79], + dimgray: [105, 105, 105], dimgrey: [105, 105, 105], gray: [128, 128, 128], grey: [128, 128, 128], + midnightblue: [25, 25, 112], darkblue: [0, 0, 139], indigo: [75, 0, 130], + silver: [192, 192, 192], whitesmoke: [245, 245, 245], ivory: [255, 255, 240], + snow: [255, 250, 250], ghostwhite: [248, 248, 255], linen: [250, 240, 230], +}; + +/** + * Parses hex (#rgb, #rgba, #rrggbb, #rrggbbaa), rgb()/rgba() and a few named + * colours. Returns undefined for anything else (hsl(), color-mix(), …); in a + * browser `` resolves such values through the CSS engine first. + */ +export function parseColor(value: string): [number, number, number] | undefined { + const v = value.trim().toLowerCase(); + if (NAMED_COLORS[v]) return NAMED_COLORS[v]; + const hex = /^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.exec(v); + if (hex) { + let h = hex[1]; + if (h.length <= 4) h = h.split('').map((c) => c + c).join(''); + return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16)) as [number, number, number]; + } + const rgb = /^rgba?\(\s*([\d.]+%?)[\s,]+([\d.]+%?)[\s,]+([\d.]+%?)/.exec(v); + if (rgb) { + return [rgb[1], rgb[2], rgb[3]].map((c) => + c.endsWith('%') ? Math.round(parseFloat(c) * 2.55) : Math.round(parseFloat(c)), + ) as [number, number, number]; + } + return undefined; +} + +/** + * Whether a theme has a dark background. Uses `--color-scheme` when the theme + * sets it (`light` / `dark`), otherwise the luminance of `--bg-color`. + * Unparseable colours count as light. + */ +export function isDark(tokens: Partial, resolvedBg?: string): boolean { + const scheme = tokens['--color-scheme']?.trim(); + if (scheme === 'dark') return true; + if (scheme === 'light') return false; + const rgb = parseColor(resolvedBg ?? tokens['--bg-color'] ?? ''); + if (!rgb) return false; + const [r, g, b] = rgb; + return 0.2126 * r + 0.7152 * g + 0.0722 * b < 128; +} diff --git a/stories/EpTabs.stories.ts b/stories/EpTabs.stories.ts new file mode 100644 index 0000000..2ae762e --- /dev/null +++ b/stories/EpTabs.stories.ts @@ -0,0 +1,145 @@ +import { html } from 'lit'; +import type { Meta, StoryObj } from '@storybook/web-components'; +import { expect, userEvent, fn } from 'storybook/test'; +import '../src/EpTabs.js'; +import type { EpTabs } from '../src/EpTabs.js'; + +type EpTabsArgs = { + value: string; + variant: 'underline' | 'pills'; + onChange: (e: Event) => void; +}; + +const meta: Meta = { + title: 'Components/EpTabs', + component: 'ep-tabs', + argTypes: { + value: { control: 'select', options: ['general', 'users', 'plugins'] }, + variant: { control: 'select', options: ['underline', 'pills'] }, + }, + args: { value: 'general', variant: 'underline', onChange: fn() }, +}; + +export default meta; +type Story = StoryObj; + +const tabs = (args: EpTabsArgs) => html` + +

General settings

+

User list

+

Locked

+

Plugins

+
+`; + +async function ready(canvasElement: HTMLElement) { + const host = canvasElement.querySelector('ep-tabs') as EpTabs; + await host.updateComplete; + await new Promise((r) => requestAnimationFrame(r)); + await host.updateComplete; + return host; +} + +const buttons = (host: EpTabs) => + Array.from(host.shadowRoot!.querySelectorAll('button[role="tab"]')); +const visible = (host: EpTabs) => + Array.from(host.querySelectorAll('ep-tab')).filter((t) => !t.hidden).map((t) => t.getAttribute('value')); + +export const Underline: Story = { + render: tabs, + play: async ({ canvasElement, args }) => { + const host = await ready(canvasElement); + await expect(buttons(host).map((b) => b.textContent)).toEqual(['General', 'Users', 'Locked', 'Plugins']); + await expect(visible(host)).toEqual(['general']); + + await userEvent.click(buttons(host)[1]); + await host.updateComplete; + await expect(host.value).toBe('users'); + await expect(visible(host)).toEqual(['users']); + await expect(args.onChange).toHaveBeenCalledTimes(1); + await expect(buttons(host)[1].getAttribute('aria-selected')).toBe('true'); + + // Arrow keys skip the disabled tab and wrap around. + buttons(host)[1].focus(); + await userEvent.keyboard('{ArrowRight}'); + await host.updateComplete; + await expect(host.value).toBe('plugins'); + await userEvent.keyboard('{ArrowRight}'); + await host.updateComplete; + await expect(host.value).toBe('general'); + await userEvent.keyboard('{End}'); + await host.updateComplete; + await expect(host.value).toBe('plugins'); + await expect(host.shadowRoot!.activeElement?.textContent).toBe('Plugins'); + }, +}; + +export const Pills: Story = { + args: { variant: 'pills', value: 'users' }, + render: tabs, + play: async ({ canvasElement }) => { + const host = await ready(canvasElement); + await expect(visible(host)).toEqual(['users']); + }, +}; + +export const UnknownValueFallsBackToFirst: Story = { + args: { value: 'does-not-exist' }, + render: tabs, + play: async ({ canvasElement }) => { + const host = await ready(canvasElement); + await expect(host.selected).toBe('general'); + await expect(visible(host)).toEqual(['general']); + }, +}; + +export const DuplicateValues: Story = { + render: () => html` + +

first

+

second

+

zero

+

positional

+
+ `, + play: async ({ canvasElement }) => { + const host = await ready(canvasElement); + const panels = Array.from(host.querySelectorAll('ep-tab')); + const shown = () => panels.filter((t) => !t.hidden).map((t) => t.textContent!.trim()); + await expect(shown()).toEqual(['first']); + // Every tab can still be selected on its own. + for (const [i, text] of ['first', 'second', 'zero', 'positional'].entries()) { + await userEvent.click(buttons(host)[i]); + await host.updateComplete; + await expect(shown()).toEqual([text]); + } + }, +}; + +export const ArrowKeysStartAtFocusedTab: Story = { + render: tabs, + play: async ({ canvasElement }) => { + const host = await ready(canvasElement); + buttons(host)[0].focus(); + // The application changes the selection while focus stays on "General". + host.value = 'plugins'; + await host.updateComplete; + await userEvent.keyboard('{ArrowRight}'); + await host.updateComplete; + await expect(host.value).toBe('users'); + }, +}; + +export const PanelsAreLabelled: Story = { + render: tabs, + play: async ({ canvasElement }) => { + const host = await ready(canvasElement); + const panel = host.querySelector('ep-tab')!; + await expect(panel.getAttribute('role')).toBe('tabpanel'); + await expect(panel.getAttribute('aria-label')).toBe('General'); + const btn = buttons(host)[0] as HTMLButtonElement & { ariaControlsElements?: Element[] }; + if ('ariaControlsElements' in btn) { + await expect(btn.ariaControlsElements).toEqual([panel]); + } + }, +}; diff --git a/stories/EpTheme.stories.ts b/stories/EpTheme.stories.ts index f2e9737..5326fa8 100644 --- a/stories/EpTheme.stories.ts +++ b/stories/EpTheme.stories.ts @@ -1,7 +1,9 @@ import { html } from 'lit'; import type { Meta, StoryObj } from '@storybook/web-components'; import { expect } from 'storybook/test'; -import { themes, EpTheme } from '../src/EpTheme.js'; +import { themes, EpTheme, defineTheme, applyTheme } from '../src/EpTheme.js'; +import '../src/EpTabs.js'; +import '../src/EpToast.js'; import '../src/EpButton.js'; import '../src/EpCard.js'; import '../src/EpInput.js'; @@ -322,3 +324,113 @@ export const Warm: Story = {
`, }; + +/** + * A custom theme only states what differs from its base – here the accent + * colour – and single tokens can be overridden per element via `.tokens`. + */ +export const CustomAccent: Story = { + render: () => { + defineTheme('story-violet', { '--primary-color': '#7c3aed', '--primary-text-color': '#ffffff' }); + return html` + +
+ Violet + +
+
+ +
+ Override +
+
+ `; + }, + play: async ({ canvasElement }) => { + const violet = canvasElement.querySelector('#violet') as EpTheme; + const override = canvasElement.querySelector('#override') as EpTheme; + await violet.updateComplete; + await override.updateComplete; + await expect(violet.style.getPropertyValue('--primary-color')).toBe('#7c3aed'); + await expect(violet.style.getPropertyValue('--bg-color')).toBe(themes.colibris['--bg-color']); + await expect(override.style.getPropertyValue('--primary-color')).toBe('#e11d48'); + + // Redefining a theme updates live elements. + defineTheme('story-violet', { '--primary-color': '#5b21b6' }); + await expect(violet.style.getPropertyValue('--primary-color')).toBe('#5b21b6'); + + // Switching themes sets data-scheme and fires ep-theme-change. + let changed = ''; + violet.addEventListener('ep-theme-change', (e) => { changed = (e as CustomEvent).detail.name; }, { once: true }); + violet.name = 'colibris-dark'; + await violet.updateComplete; + await expect(changed).toBe('colibris-dark'); + await expect(violet.dataset.scheme).toBe('dark'); + }, +}; + +export const Auto: Story = { + render: () => html` + +
+ Follows the operating system (light / dark). +
+
+ `, + play: async ({ canvasElement }) => { + const el = canvasElement.querySelector('#auto') as EpTheme; + await el.updateComplete; + const dark = matchMedia('(prefers-color-scheme: dark)').matches; + await expect(el.resolvedName).toBe(dark ? 'colibris-dark' : 'colibris'); + await expect(el.style.getPropertyValue('--bg-color')).toBe( + themes[dark ? 'colibris-dark' : 'colibris']['--bg-color'], + ); + }, +}; + +export const ApplyToElement: Story = { + render: () => html`
target
`, + play: async ({ canvasElement }) => { + const el = canvasElement.querySelector('#target') as HTMLElement; + applyTheme(el, { '--primary-color': '#111111', '--my-extra': '1px' }); + await expect(el.style.getPropertyValue('--my-extra')).toBe('1px'); + // Tokens of the previous call that the new set lacks are removed. + applyTheme(el, 'colibris'); + await expect(el.style.getPropertyValue('--my-extra')).toBe(''); + await expect(el.style.getPropertyValue('--primary-color')).toBe('#64d29b'); + }, +}; + +export const SchemeDetection: Story = { + render: () => html` + + + + + `, + play: async ({ canvasElement }) => { + const scheme = async (id: string) => { + const el = canvasElement.querySelector(`#${id}`) as EpTheme; + await el.updateComplete; + return el.dataset.scheme; + }; + await expect(await scheme('named')).toBe('dark'); + await expect(await scheme('hsl')).toBe('dark'); + await expect(await scheme('light-override')).toBe('light'); + await expect(await scheme('forced')).toBe('dark'); + }, +}; + +export const SuccessUsesItsOwnToken: Story = { + render: () => html` + + + + `, + play: async ({ canvasElement }) => { + const toast = canvasElement.querySelector('ep-toast-item') as HTMLElement & { updateComplete: Promise }; + await toast.updateComplete; + const box = toast.shadowRoot!.querySelector('.toast')!; + await expect(getComputedStyle(box).borderLeftColor).toBe('rgb(1, 2, 3)'); + }, +}; diff --git a/test/themes.test.ts b/test/themes.test.ts new file mode 100644 index 0000000..5123bd3 --- /dev/null +++ b/test/themes.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, it } from 'vitest'; +import { defineTheme, getTheme, isDark, onThemeDefined, parseColor, themeToCss, themes } from '../src/themes.js'; + +describe('themes', () => { + it('ships colibris as complete default', () => { + const c = getTheme('colibris')!; + expect(c['--primary-color']).toBe('#64d29b'); + for (const name of Object.keys(themes)) { + expect(Object.keys(themes[name]).sort()).toEqual(Object.keys(c).sort()); + } + }); + + it('defineTheme fills missing tokens from the base theme', () => { + const t = defineTheme('test-accent', { '--primary-color': '#7c3aed' }); + expect(t['--primary-color']).toBe('#7c3aed'); + expect(t['--bg-color']).toBe(themes.colibris['--bg-color']); + const d = defineTheme('test-accent-dark', { '--primary-color': '#7c3aed' }, 'colibris-dark'); + expect(d['--bg-color']).toBe(themes['colibris-dark']['--bg-color']); + expect(() => defineTheme('x', {}, 'nope')).toThrow(/unknown base theme/); + }); + + it('defineTheme does not change the base theme', () => { + defineTheme('test-iso', { '--bg-color': '#000000' }); + expect(themes.colibris['--bg-color']).toBe('white'); + }); + + it('notifies listeners about new themes', () => { + const seen: string[] = []; + const off = onThemeDefined((n) => seen.push(n)); + defineTheme('test-notify', {}); + off(); + defineTheme('test-notify-2', {}); + expect(seen).toEqual(['test-notify']); + }); + + it('themeToCss renders a rule', () => { + expect(themeToCss({ '--primary-color': 'red', '--radius': '4px' }, '.x')).toBe( + '.x {\n --primary-color: red;\n --radius: 4px;\n}', + ); + expect(themeToCss('colibris')).toContain('--primary-color: #64d29b;'); + expect(() => themeToCss('nope')).toThrow(/unknown theme/); + }); + + it('themeToCss rejects unsafe names and values instead of stripping them', () => { + expect(() => themeToCss({ '--primary-color': 'red; } body { display:none' })).toThrow(/invalid value/); + expect(() => themeToCss({ '--x': '