From f6819bc00e3088e82411d02058daff4d7b894cd7 Mon Sep 17 00:00:00 2001 From: SamTV12345 Date: Mon, 23 Nov 2026 20:09:47 +0100 Subject: [PATCH 1/2] feat: pad building blocks - ep-toolbar / ep-toolbar-button / ep-toolbar-separator: roving tabindex, toggle and badge buttons, ep-toolbar-action, compact mode that moves priority="low" items into an overflow row - ep-avatar: initials or picture, readable text colour, status dot - ep-user-list: own entry with name field and colour button, others sorted; rename / colour / select events - ep-chat-panel: messages via property or slot, stays at the bottom, keeps position when older messages are prepended, Enter sends - ep-popup: non-modal panel below an anchor, Escape / outside click, focus handling, bottom sheet on narrow screens - ep-settings-section / ep-settings-row, ep-segmented - author colours are validated before they reach a style attribute (styleMap writes the first render as a string) - story Pad/Layout shows the parts together Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012RMvvMtnCwj6ycD9fwLYVu --- README.md | 11 + package.json | 7 + src/EpAvatar.ts | 94 +++++++++ src/EpChatMessage.ts | 4 +- src/EpChatPanel.ts | 317 +++++++++++++++++++++++++++++ src/EpCheckbox.ts | 8 +- src/EpPopup.ts | 275 +++++++++++++++++++++++++ src/EpSegmented.ts | 132 ++++++++++++ src/EpSettings.ts | 150 ++++++++++++++ src/EpToolbar.ts | 357 +++++++++++++++++++++++++++++++++ src/EpUserBadge.ts | 4 +- src/EpUserList.ts | 193 ++++++++++++++++++ src/index.ts | 10 + src/internal/color.ts | 42 ++++ stories/EpAvatar.stories.ts | 42 ++++ stories/EpChatPanel.stories.ts | 115 +++++++++++ stories/EpPopup.stories.ts | 115 +++++++++++ stories/EpToolbar.stories.ts | 107 ++++++++++ stories/EpUserList.stories.ts | 64 ++++++ stories/PadLayout.stories.ts | 88 ++++++++ 20 files changed, 2132 insertions(+), 3 deletions(-) create mode 100644 src/EpAvatar.ts create mode 100644 src/EpChatPanel.ts create mode 100644 src/EpPopup.ts create mode 100644 src/EpSegmented.ts create mode 100644 src/EpSettings.ts create mode 100644 src/EpToolbar.ts create mode 100644 src/EpUserList.ts create mode 100644 src/internal/color.ts create mode 100644 stories/EpAvatar.stories.ts create mode 100644 stories/EpChatPanel.stories.ts create mode 100644 stories/EpPopup.stories.ts create mode 100644 stories/EpToolbar.stories.ts create mode 100644 stories/EpUserList.stories.ts create mode 100644 stories/PadLayout.stories.ts diff --git a/README.md b/README.md index a36a056..33fe053 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,13 @@ import { EpButton, EpTheme, themes } from '@samtv12345/etherpad-webcomponents'; | `` / `` | `EpToastContainer` / `EpToastItem` | `position`, `type`, `message`, `duration` | — | | `` | `EpToolbarSelect` | `options[]`, `value`, `icon-class`, `label`, `placeholder` | `ep-toolbar-select:change` | | `` | `EpUserBadge` | `name`, `color`, `size`, `online` | — | +| `` | `EpAvatar` | `name`, `color`, `src`, `size`, `status` (`online`/`idle`/`offline`) | — | +| `` / `` / `` | `EpToolbar` / `EpToolbarButton` / `EpToolbarSeparator` | toolbar: `label`, `breakpoint`, `more-label`, slot `end`; button: `key`, `label`, `toggle`, `pressed`, `active`, `expanded`, `badge`, `priority="low"` | `ep-toolbar-action` | +| `` | `EpUserList` | `.users` (`{ id, name, color, self, status }`), `heading`, `selectable`, `readonly` | `ep-user-rename`, `ep-user-color-request`, `ep-user-select` | +| `` | `EpChatPanel` | `.messages` or slotted ``, `show-close`, `show-sticky`, `sticky`, `has-more`, `loading`, `readonly`, `floating` | `ep-chat-send`, `ep-chat-close`, `ep-chat-sticky`, `ep-chat-load-more` | +| `` | `EpPopup` | `open`, `heading`, `anchor`, `align`, `persistent`, slot `footer`; `show()`/`hide()`/`toggle()` | `ep-popup-open`, `ep-popup-close` | +| `` / `` | `EpSettingsSection` / `EpSettingsRow` | section: `heading`, `description`; row: `label`, `description`, `stacked`, `divided`, `disabled` | — | +| `` | `EpSegmented` | `.options` (`{ value, label, icon?, disabled? }`), `value`, `label` | `ep-change` | | `` / `` | `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` | @@ -107,6 +114,10 @@ defineTheme('acme-dark', { '--primary-color': '#a78bfa' }, 'colibris-dark'); `@samtv12345/etherpad-webcomponents/themes.js` contains only these functions and the token sets, without any custom element. +### Pad building blocks + +The pad, timeslider and sheet pages are put together from `ep-toolbar`, `ep-popup` + `ep-settings-*`, `ep-user-list` and `ep-chat-panel`; the story **Pad/Layout** shows them together. All of them only emit events – the app decides what a toolbar action, a sent chat message or a rename does. Every visible text is an attribute, so pages can pass in their translations. Toolbar colours can be set separately via `--toolbar-bg-color`, `--toolbar-text-color`, `--toolbar-border-color`, `--toolbar-hover-color`, `--toolbar-active-color` and `--toolbar-active-text-color`. + ### 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. diff --git a/package.json b/package.json index 4f16edc..5e442af 100644 --- a/package.json +++ b/package.json @@ -24,6 +24,13 @@ "./EpSelect.js": "./dist/EpSelect.js", "./EpUserBadge.js": "./dist/EpUserBadge.js", "./EpTabs.js": "./dist/EpTabs.js", + "./EpAvatar.js": "./dist/EpAvatar.js", + "./EpToolbar.js": "./dist/EpToolbar.js", + "./EpUserList.js": "./dist/EpUserList.js", + "./EpChatPanel.js": "./dist/EpChatPanel.js", + "./EpSettings.js": "./dist/EpSettings.js", + "./EpPopup.js": "./dist/EpPopup.js", + "./EpSegmented.js": "./dist/EpSegmented.js", "./EpTheme.js": "./dist/EpTheme.js", "./themes.js": "./dist/themes.js", "./EpEditor.js": "./dist/EpEditor.js", diff --git a/src/EpAvatar.ts b/src/EpAvatar.ts new file mode 100644 index 0000000..7244fd4 --- /dev/null +++ b/src/EpAvatar.ts @@ -0,0 +1,94 @@ +import { LitElement, html, css, nothing } from 'lit'; +import { customElement, property, state } from 'lit/decorators.js'; +import { styleMap } from 'lit/directives/style-map.js'; +import { initialsOf, readableTextOn, safeColor } from './internal/color.js'; + +/** + * Round user avatar: a picture if `src` is set and loads, otherwise the + * initials on the author colour (with readable text colour). + */ +@customElement('ep-avatar') +export class EpAvatar extends LitElement { + static styles = css` + :host { + --ep-avatar-size: 28px; + display: inline-block; + position: relative; + width: var(--ep-avatar-size); + height: var(--ep-avatar-size); + flex-shrink: 0; + font-family: var(--main-font-family, Quicksand, Cantarell, "Open Sans", "Helvetica Neue", sans-serif); + } + :host([size="small"]) { --ep-avatar-size: 20px; } + :host([size="large"]) { --ep-avatar-size: 40px; } + + .circle { + width: 100%; + height: 100%; + border-radius: 50%; + overflow: hidden; + display: flex; + align-items: center; + justify-content: center; + font-weight: 700; + font-size: calc(var(--ep-avatar-size) * 0.4); + line-height: 1; + user-select: none; + box-sizing: border-box; + } + img { width: 100%; height: 100%; object-fit: cover; display: block; } + + .status { + position: absolute; + right: -1px; + bottom: -1px; + width: calc(var(--ep-avatar-size) * 0.3); + height: calc(var(--ep-avatar-size) * 0.3); + min-width: 7px; + min-height: 7px; + border-radius: 50%; + border: 2px solid var(--bg-color, #ffffff); + box-sizing: content-box; + } + .status.online { background: var(--success-color, var(--primary-color, #64d29b)); } + .status.idle { background: var(--warning-color, #d4a72c); } + .status.offline { background: var(--middle-color, #d2d2d2); } + `; + + @property() name = ''; + /** Background colour (author colour). */ + @property() color = ''; + /** Optional picture URL. */ + @property() src = ''; + @property({ reflect: true }) size: 'small' | 'medium' | 'large' = 'medium'; + /** Small status dot: `online`, `idle`, `offline` or empty for none. */ + @property({ reflect: true }) status: '' | 'online' | 'idle' | 'offline' = ''; + + @state() private _imgFailed = false; + + updated(changed: Map) { + if (changed.has('src')) this._imgFailed = false; + } + + render() { + const color = safeColor(this.color); + const bg = color || 'var(--text-soft-color, #576273)'; + const fg = color ? readableTextOn(color) : 'var(--bg-color, #ffffff)'; + const showImg = this.src && !this._imgFailed; + return html` + + ${this.status ? html`` : nothing} + `; + } +} + +declare global { + interface HTMLElementTagNameMap { + 'ep-avatar': EpAvatar; + } +} diff --git a/src/EpChatMessage.ts b/src/EpChatMessage.ts index ad382f1..22a0aa9 100644 --- a/src/EpChatMessage.ts +++ b/src/EpChatMessage.ts @@ -1,5 +1,7 @@ import { LitElement, html, css } from 'lit'; import { customElement, property } from 'lit/decorators.js'; +import { styleMap } from 'lit/directives/style-map.js'; +import { safeColor } from './internal/color.js'; @customElement('ep-chat-message') export class EpChatMessage extends LitElement { @@ -47,7 +49,7 @@ export class EpChatMessage extends LitElement { render() { return html` - ${this.author}${this.time ? html`${this.time}` : html``} + ${this.author}${this.time ? html`${this.time}` : html``} `; } } diff --git a/src/EpChatPanel.ts b/src/EpChatPanel.ts new file mode 100644 index 0000000..31645e1 --- /dev/null +++ b/src/EpChatPanel.ts @@ -0,0 +1,317 @@ +import { LitElement, html, css, nothing } from 'lit'; +import { customElement, property, query } from 'lit/decorators.js'; +import { repeat } from 'lit/directives/repeat.js'; +import './EpChatMessage.js'; + +export interface EpChatEntry { + id?: string; + author: string; + authorColor?: string; + time?: string; + text: string; + own?: boolean; +} + +/** + * Chat box: header, scrolling message list and input. + * + * Messages come either from the `messages` property or as + * `` children (slot `messages`), whatever suits the app. + * The list stays at the bottom when new messages arrive, unless the user + * scrolled up. + * + * Events: `ep-chat-send` (detail `{ text }`), `ep-chat-close`, + * `ep-chat-sticky` (detail `{ sticky }`), `ep-chat-load-more` (scrolled to + * the top while `has-more` is set). + */ +@customElement('ep-chat-panel') +export class EpChatPanel extends LitElement { + static styles = css` + :host { + display: flex; + flex-direction: column; + min-height: 0; + height: 100%; + box-sizing: border-box; + background: var(--bg-color, #ffffff); + color: var(--text-color, #485365); + font-family: var(--main-font-family, Quicksand, Cantarell, "Open Sans", "Helvetica Neue", sans-serif); + font-size: 14px; + } + :host([floating]) { + 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; + } + header { + display: flex; + align-items: center; + gap: 4px; + padding: 8px 10px 8px 14px; + border-bottom: 1px solid var(--middle-color, #d2d2d2); + flex-shrink: 0; + } + h2 { + flex: 1; + margin: 0; + font-size: 14px; + font-weight: 700; + } + .icon-btn { + display: inline-flex; + align-items: center; + justify-content: center; + width: 28px; + height: 28px; + padding: 0; + border: none; + border-radius: var(--radius, 4px); + background: transparent; + color: var(--text-soft-color, #576273); + cursor: pointer; + } + .icon-btn:hover { background: var(--bg-soft-color, #f2f3f4); color: var(--text-color, #485365); } + .icon-btn[aria-pressed="true"] { color: var(--primary-color, #64d29b); } + .icon-btn:focus-visible, textarea:focus-visible, .send:focus-visible { + outline: 2px solid var(--focus-color, var(--dark-color, #576273)); + outline-offset: 1px; + } + .log { + flex: 1; + min-height: 0; + overflow-y: auto; + overscroll-behavior: contain; + } + .more { + text-align: center; + padding: 6px; + font-size: 12px; + color: var(--text-soft-color, #576273); + } + .empty { + padding: 16px 14px; + color: var(--text-soft-color, #576273); + } + form { + display: flex; + align-items: flex-end; + gap: 6px; + padding: 8px; + border-top: 1px solid var(--middle-color, #d2d2d2); + flex-shrink: 0; + } + textarea { + flex: 1; + min-width: 0; + resize: none; + font: inherit; + color: inherit; + line-height: 1.4; + max-height: 120px; + padding: 6px 8px; + box-sizing: border-box; + background: var(--bg-soft-color, #f2f3f4); + border: 1px solid var(--middle-color, #d2d2d2); + border-radius: calc(var(--radius, 4px) - 1px); + } + .send { + flex-shrink: 0; + height: 32px; + padding: 0 12px; + border: none; + border-radius: var(--radius, 4px); + background: var(--primary-color, #64d29b); + color: var(--primary-text-color, #ffffff); + font: inherit; + font-weight: 700; + cursor: pointer; + } + .send:disabled { opacity: 0.4; cursor: not-allowed; } + `; + + @property() heading = 'Chat'; + @property({ attribute: false }) messages: EpChatEntry[] = []; + @property() placeholder = 'Write a message'; + @property({ attribute: 'send-label' }) sendLabel = 'Send'; + @property({ attribute: 'close-label' }) closeLabel = 'Close'; + @property({ attribute: 'sticky-label' }) stickyLabel = 'Keep chat open'; + @property({ attribute: 'empty-label' }) emptyLabel = ''; + @property({ attribute: 'loading-label' }) loadingLabel = 'Loading…'; + /** Shows the sticky (pin) button and its state. */ + @property({ type: Boolean, reflect: true }) sticky = false; + @property({ type: Boolean, attribute: 'show-sticky' }) showSticky = false; + @property({ type: Boolean, attribute: 'show-close' }) showClose = false; + /** Card look with shadow, for a floating chat box. */ + @property({ type: Boolean, reflect: true }) floating = false; + /** Older messages can be loaded (`ep-chat-load-more` at the top). */ + @property({ type: Boolean, attribute: 'has-more' }) hasMore = false; + /** Set while older messages are loading. */ + @property({ type: Boolean }) loading = false; + /** Hides the input (read-only pad or chat disabled). */ + @property({ type: Boolean, reflect: true }) readonly = false; + @property({ type: Number }) maxlength = 1000; + + @query('.log') private _log!: HTMLElement; + @query('textarea') private _input?: HTMLTextAreaElement; + + private _atBottom = true; + private _prevHeight = 0; + private _prevTop = 0; + private _prepended = false; + private _loadingOlder = false; + private _resize?: ResizeObserver; + + /** Focuses the input. */ + focus(options?: FocusOptions) { + this._input?.focus(options); + } + + /** Scrolls to the newest message. */ + scrollToBottom() { + if (this._log) this._log.scrollTop = this._log.scrollHeight; + this._atBottom = true; + } + + protected willUpdate(changed: Map) { + if (!changed.has('messages')) return; + const old = (changed.get('messages') as EpChatEntry[] | undefined) ?? []; + const now = this.messages; + // Older messages were put in front of the existing ones. + this._prepended = old.length > 0 && now.length > old.length + && now[now.length - 1] === old[old.length - 1] && now[0] !== old[0]; + if (this._log) { + this._prevHeight = this._log.scrollHeight; + this._prevTop = this._log.scrollTop; + } + } + + protected firstUpdated() { + if (typeof ResizeObserver === 'function') { + // Late height changes (fonts, wrapped lines) keep the newest message visible. + this._resize = new ResizeObserver(() => { if (this._atBottom) this.scrollToBottom(); }); + this._resize.observe(this.renderRoot.querySelector('.items')!); + } + } + + disconnectedCallback() { + super.disconnectedCallback(); + this._resize?.disconnect(); + this._resize = undefined; + } + + protected updated(changed: Map) { + if (changed.has('messages')) void this._afterContentChange(this._prepended); + if (changed.has('loading') && !this.loading) this._loadingOlder = false; + } + + private async _afterContentChange(prepended = false) { + if (!this._log) return; + const prevHeight = this._prevHeight; + const prevTop = this._prevTop; + // Wait until the message elements have rendered, so heights are final. + const items = Array.from(this.renderRoot.querySelectorAll('ep-chat-message')) + .concat(Array.from(this.querySelectorAll('ep-chat-message'))) as Array }>; + await Promise.all(items.map((m) => m.updateComplete)); + if (prepended) { + // Keep the visible messages in place. + this._log.scrollTop = prevTop + (this._log.scrollHeight - prevHeight); + } else if (this._atBottom) { + this.scrollToBottom(); + } + } + + private _onSlotChange() { + void this._afterContentChange(); + } + + private _onScroll() { + const log = this._log; + this._atBottom = log.scrollHeight - log.scrollTop - log.clientHeight < 24; + if (log.scrollTop < 20 && this.hasMore && !this.loading && !this._loadingOlder) { + this._loadingOlder = true; + this.dispatchEvent(new CustomEvent('ep-chat-load-more', { bubbles: true, composed: true })); + } + } + + private _send(e?: Event) { + e?.preventDefault(); + const input = this._input; + if (!input) return; + const text = input.value.trim(); + if (!text) return; + this.dispatchEvent(new CustomEvent('ep-chat-send', { + bubbles: true, composed: true, detail: { text }, + })); + input.value = ''; + this._autosize(); + this._atBottom = true; + this.requestUpdate(); + } + + private _onKeydown(e: KeyboardEvent) { + if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) this._send(e); + } + + private _autosize() { + const t = this._input; + if (!t) return; + t.style.height = 'auto'; + t.style.height = `${Math.min(t.scrollHeight, 120)}px`; + } + + private _toggleSticky() { + this.sticky = !this.sticky; + this.dispatchEvent(new CustomEvent('ep-chat-sticky', { + bubbles: true, composed: true, detail: { sticky: this.sticky }, + })); + } + + render() { + const empty = !this.messages.length && !this.querySelector('[slot="messages"]'); + return html` +
+

${this.heading}

+ + ${this.showSticky ? html` + ` : nothing} + ${this.showClose ? html` + ` : nothing} +
+
+
+ ${this.loading ? html`
${this.loadingLabel}
` : nothing} + ${repeat( + this.messages, + (m, i) => m.id ?? i, + (m) => html`${m.text}`, + )} + + ${empty && this.emptyLabel ? html`
${this.emptyLabel}
` : nothing} +
+
+ ${this.readonly ? nothing : html` +
+ + +
`} + `; + } +} + +declare global { + interface HTMLElementTagNameMap { + 'ep-chat-panel': EpChatPanel; + } +} diff --git a/src/EpCheckbox.ts b/src/EpCheckbox.ts index 63d10f7..0cb12e3 100644 --- a/src/EpCheckbox.ts +++ b/src/EpCheckbox.ts @@ -106,6 +106,8 @@ export class EpCheckbox extends LitElement { @property({ reflect: true }) variant: 'default' | 'retro' = 'default'; @property({ type: Boolean, reflect: true }) disabled = false; @property() label = ''; + /** Accessible name when no visible `label` is shown (e.g. inside a settings row). */ + @property({ attribute: 'accessible-name' }) accessibleName = ''; render() { return html` @@ -116,11 +118,15 @@ export class EpCheckbox extends LitElement { .checked="${this.checked}" ?disabled="${this.disabled}" @change="${this._toggle}" - aria-label="${this.label}" /> + aria-label="${this.label || this.accessibleName}" /> ${this.label ? html`${this.label}` : ''} `; } + focus(options?: FocusOptions) { + this.renderRoot.querySelector('input')?.focus(options); + } + private _toggle() { if (this.disabled) return; this.checked = !this.checked; diff --git a/src/EpPopup.ts b/src/EpPopup.ts new file mode 100644 index 0000000..4075086 --- /dev/null +++ b/src/EpPopup.ts @@ -0,0 +1,275 @@ +import { LitElement, html, css, nothing } from 'lit'; +import { customElement, property, query } from 'lit/decorators.js'; + +const FOCUSABLE = 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"]), ep-checkbox, ep-select, ep-dropdown, ep-button, ep-segmented'; + +/** + * Non-modal panel that drops down from a toolbar button (settings, share, + * import/export, users …). The page stays usable behind it. + * + * Positioned below `anchor` (an element or its id) and right-aligned to it, + * or fixed top-right without an anchor. On narrow screens it becomes a + * full-width sheet. Escape and a click outside close it (unless + * `persistent`); focus moves into it on open and back to the anchor on + * close. + * + * Events: `ep-popup-open`, `ep-popup-close` (detail `{ reason }`: + * `escape` | `outside` | `button` | `api`). + */ +@customElement('ep-popup') +export class EpPopup extends LitElement { + static styles = css` + :host { + position: fixed; + z-index: var(--ep-popup-z-index, 1000); + display: none; + top: var(--ep-popup-top, 56px); + right: var(--ep-popup-right, 12px); + width: var(--ep-popup-width, 360px); + max-width: calc(100vw - 24px); + max-height: calc(100vh - var(--ep-popup-top, 56px) - 12px); + font-family: var(--main-font-family, Quicksand, Cantarell, "Open Sans", "Helvetica Neue", sans-serif); + font-size: 14px; + color: var(--text-color, #485365); + } + :host([open]) { display: flex; } + .panel { + display: flex; + flex-direction: column; + width: 100%; + max-height: inherit; + background: var(--bg-color, #ffffff); + 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; + animation: ep-popup-in 0.12s ease-out; + } + @keyframes ep-popup-in { + from { opacity: 0; transform: translateY(-4px); } + to { opacity: 1; transform: none; } + } + @media (prefers-reduced-motion: reduce) { + .panel { animation: none; } + } + header { + display: flex; + align-items: center; + gap: 8px; + padding: 14px 12px 10px 18px; + } + h2 { + flex: 1; + margin: 0; + font-size: 16px; + font-weight: 700; + } + .close { + display: inline-flex; + align-items: center; + justify-content: center; + width: 28px; + height: 28px; + padding: 0; + border: none; + border-radius: var(--radius, 4px); + background: transparent; + color: var(--text-soft-color, #576273); + cursor: pointer; + } + .close:hover { background: var(--bg-soft-color, #f2f3f4); color: var(--text-color, #485365); } + .close:focus-visible { + outline: 2px solid var(--focus-color, var(--dark-color, #576273)); + outline-offset: 1px; + } + .body { + padding: 0 18px 16px; + overflow-y: auto; + overscroll-behavior: contain; + } + :host(:not([heading])) .body { padding-top: 16px; } + footer { + display: flex; + justify-content: flex-end; + gap: 8px; + padding: 10px 18px; + border-top: 1px solid var(--middle-color, #d2d2d2); + } + footer[hidden] { display: none; } + + @media (max-width: 600px) { + :host { + left: 0 !important; + right: 0 !important; + width: 100%; + max-width: 100%; + top: auto !important; + bottom: 0; + max-height: 85vh; + } + .panel { + border-bottom-left-radius: 0; + border-bottom-right-radius: 0; + } + } + `; + + @property({ type: Boolean, reflect: true }) open = false; + @property({ reflect: true }) heading = ''; + /** Element or element id the popup hangs below. */ + @property() anchor: string | HTMLElement = ''; + /** `end` (default) aligns the right edges, `start` the left edges. */ + @property() align: 'start' | 'end' = 'end'; + /** Escape and clicks outside do not close it. */ + @property({ type: Boolean }) persistent = false; + @property({ attribute: 'close-label' }) closeLabel = 'Close'; + @property({ type: Boolean, attribute: 'hide-close' }) hideClose = false; + + @query('.panel') private _panel!: HTMLElement; + + private _returnFocus: HTMLElement | null = null; + private _hasFooter = false; + + show() { this.open = true; } + hide() { this._close('api'); } + toggle() { if (this.open) this.hide(); else this.show(); } + + connectedCallback() { + super.connectedCallback(); + if (this.open) this._listen(true); + } + + disconnectedCallback() { + super.disconnectedCallback(); + this._listen(false); + } + + private _listen(on: boolean) { + if (on) { + document.addEventListener('pointerdown', this._onOutside, true); + document.addEventListener('keydown', this._onKeydown); + window.addEventListener('resize', this._position); + window.addEventListener('scroll', this._position, true); + } else { + document.removeEventListener('pointerdown', this._onOutside, true); + document.removeEventListener('keydown', this._onKeydown); + window.removeEventListener('resize', this._position); + window.removeEventListener('scroll', this._position, true); + } + } + + private _anchorEl(): HTMLElement | null { + if (!this.anchor) return null; + if (typeof this.anchor !== 'string') return this.anchor; + const root = this.getRootNode() as Document | ShadowRoot; + return (root.getElementById?.(this.anchor) ?? document.getElementById(this.anchor)) as HTMLElement | null; + } + + private _position = () => { + const a = this._anchorEl(); + if (!a || !this.open) return; + const r = a.getBoundingClientRect(); + this.style.top = `${Math.round(r.bottom + 6)}px`; + this.style.setProperty('--ep-popup-top', `${Math.round(r.bottom + 6)}px`); + if (this.align === 'start') { + this.style.left = `${Math.max(12, Math.round(r.left))}px`; + this.style.right = 'auto'; + } else { + this.style.right = `${Math.max(12, Math.round(document.documentElement.clientWidth - r.right))}px`; + this.style.left = 'auto'; + } + }; + + private _onOutside = (e: PointerEvent) => { + if (this.persistent || !this.open) return; + const path = e.composedPath(); + if (path.includes(this)) return; + const a = this._anchorEl(); + // The anchor usually toggles the popup itself. + if (a && path.includes(a)) return; + this._close('outside'); + }; + + private _onKeydown = (e: KeyboardEvent) => { + if (e.key !== 'Escape' || this.persistent || !this.open) return; + e.stopPropagation(); + this._close('escape'); + }; + + private _close(reason: 'escape' | 'outside' | 'button' | 'api') { + if (!this.open) return; + this.open = false; + this.dispatchEvent(new CustomEvent('ep-popup-close', { + bubbles: true, composed: true, detail: { reason }, + })); + // Only return focus if it was inside the popup (an outside click moves it elsewhere). + if (reason !== 'outside') { + const target = this._returnFocus ?? this._anchorEl(); + target?.focus?.(); + } + this._returnFocus = null; + } + + protected updated(changed: Map) { + if (changed.has('open')) { + const was = changed.get('open'); + if (this.open) { + this._returnFocus = (document.activeElement as HTMLElement | null) ?? null; + this._listen(true); + this._position(); + this.dispatchEvent(new CustomEvent('ep-popup-open', { bubbles: true, composed: true })); + requestAnimationFrame(() => this._focusFirst()); + } else if (was) { + this._listen(false); + } + } + if (changed.has('anchor') || changed.has('align')) this._position(); + } + + private _focusFirst() { + if (!this.open) return; + for (const el of Array.from(this.querySelectorAll(FOCUSABLE))) { + if ((el as HTMLButtonElement).disabled || el.closest('[hidden]')) continue; + el.focus(); + if (this._focusInside()) return; + } + this._panel?.focus(); + } + + private _focusInside(): boolean { + let a: Element | null = document.activeElement; + while (a?.shadowRoot?.activeElement) a = a.shadowRoot.activeElement; + const host = document.activeElement; + return !!host && (host === this || this.contains(host) || a === this._panel); + } + + private _onFooterSlot(e: Event) { + this._hasFooter = (e.target as HTMLSlotElement).assignedNodes({ flatten: true }).length > 0; + this.requestUpdate(); + } + + render() { + return html` + + `; + } +} + +declare global { + interface HTMLElementTagNameMap { + 'ep-popup': EpPopup; + } +} diff --git a/src/EpSegmented.ts b/src/EpSegmented.ts new file mode 100644 index 0000000..393f48f --- /dev/null +++ b/src/EpSegmented.ts @@ -0,0 +1,132 @@ +import { LitElement, html, css, nothing } from 'lit'; +import { customElement, property } from 'lit/decorators.js'; +import { unsafeSVG } from 'lit/directives/unsafe-svg.js'; + +export interface EpSegmentedOption { + value: string; + label: string; + /** + * Optional inline SVG markup shown before the label. It is inserted as is, + * so only pass trusted, static markup. + */ + icon?: string; + disabled?: boolean; +} + +/** + * A row of mutually exclusive options (e.g. light / dark / system). Behaves + * like a radio group: arrow keys change the selection. + * + * Fires `ep-change` (detail `{ value }`). + */ +@customElement('ep-segmented') +export class EpSegmented extends LitElement { + static styles = css` + :host { + display: inline-flex; + font-family: var(--main-font-family, Quicksand, Cantarell, "Open Sans", "Helvetica Neue", sans-serif); + font-size: 13px; + } + :host([disabled]) { opacity: 0.5; pointer-events: none; } + [role="radiogroup"] { + display: inline-flex; + gap: 2px; + padding: 2px; + background: var(--bg-soft-color, #f2f3f4); + border: 1px solid var(--middle-color, #d2d2d2); + border-radius: var(--radius, 4px); + } + button { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 4px 10px; + border: none; + border-radius: calc(var(--radius, 4px) - 1px); + background: transparent; + color: var(--text-soft-color, #576273); + font: inherit; + font-weight: 600; + cursor: pointer; + white-space: nowrap; + } + button:hover { color: var(--text-color, #485365); } + button[aria-checked="true"] { + background: var(--bg-color, #ffffff); + color: var(--text-color, #485365); + box-shadow: 0 1px 2px rgba(27, 39, 51, 0.12); + } + button:disabled { opacity: 0.4; cursor: not-allowed; } + button:focus-visible { + outline: 2px solid var(--focus-color, var(--dark-color, #576273)); + outline-offset: 1px; + } + svg { width: 16px; height: 16px; flex-shrink: 0; } + `; + + @property({ attribute: false }) options: EpSegmentedOption[] = []; + @property({ reflect: true }) value = ''; + @property({ type: Boolean, reflect: true }) disabled = false; + /** Accessible name of the group. */ + @property() label = ''; + + private _choose(value: string, focus = false) { + if (value !== this.value) { + this.value = value; + this.dispatchEvent(new CustomEvent('ep-change', { + bubbles: true, composed: true, detail: { value }, + })); + } + if (focus) { + this.updateComplete.then(() => + this.renderRoot.querySelector('button[aria-checked="true"]')?.focus()); + } + } + + focus(options?: FocusOptions) { + const btn = this.renderRoot.querySelector('button[tabindex="0"]'); + btn?.focus(options); + } + + private _onKeydown(e: KeyboardEvent) { + const enabled = this.options.filter((o) => !o.disabled); + if (!enabled.length) return; + const at = enabled.findIndex((o) => o.value === this.value); + let next: number; + switch (e.key) { + case 'ArrowRight': case 'ArrowDown': next = (at + 1) % enabled.length; break; + case 'ArrowLeft': case 'ArrowUp': 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._choose(enabled[next].value, true); + } + + render() { + const hasSelection = this.options.some((o) => o.value === this.value && !o.disabled); + const firstEnabled = this.options.find((o) => !o.disabled)?.value; + return html` +
+ ${this.options.map((o) => { + const checked = o.value === this.value; + const tabbable = hasSelection ? checked : o.value === firstEnabled; + return html``; + })} +
+ `; + } +} + +declare global { + interface HTMLElementTagNameMap { + 'ep-segmented': EpSegmented; + } +} diff --git a/src/EpSettings.ts b/src/EpSettings.ts new file mode 100644 index 0000000..5ad5437 --- /dev/null +++ b/src/EpSettings.ts @@ -0,0 +1,150 @@ +import { LitElement, html, css, nothing } from 'lit'; +import { customElement, property } from 'lit/decorators.js'; + +/** Group of settings rows with a heading. */ +@customElement('ep-settings-section') +export class EpSettingsSection extends LitElement { + static styles = css` + :host { + display: block; + font-family: var(--main-font-family, Quicksand, Cantarell, "Open Sans", "Helvetica Neue", sans-serif); + color: var(--text-color, #485365); + } + :host([hidden]) { display: none; } + :host(:not(:first-of-type)) { margin-top: 20px; } + h3 { + margin: 0 0 4px; + font-size: 12px; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.04em; + color: var(--text-soft-color, #576273); + } + .description { + margin: 0 0 8px; + font-size: 13px; + color: var(--text-soft-color, #576273); + } + .rows { + display: flex; + flex-direction: column; + } + `; + + @property() heading = ''; + @property() description = ''; + + render() { + return html` +
+ ${this.heading ? html`

${this.heading}

` : nothing} + ${this.description ? html`

${this.description}

` : nothing} +
+
+ `; + } +} + +/** + * One setting: label (and optional description) on the left, the control + * (slotted, e.g. ``, ``, ``) on the + * right. `stacked` puts the control below the label. + * + * Clicking the label activates a slotted `ep-checkbox` or focuses the + * control. + */ +@customElement('ep-settings-row') +export class EpSettingsRow extends LitElement { + static styles = css` + :host { + display: flex; + align-items: center; + gap: 16px; + padding: 8px 0; + min-height: 32px; + font-family: var(--main-font-family, Quicksand, Cantarell, "Open Sans", "Helvetica Neue", sans-serif); + font-size: 14px; + color: var(--text-color, #485365); + } + :host([hidden]) { display: none; } + :host([divided]) { border-top: 1px solid var(--middle-color, #d2d2d2); } + :host([stacked]) { + flex-direction: column; + align-items: stretch; + gap: 6px; + } + :host([disabled]) { opacity: 0.5; pointer-events: none; } + .text { + flex: 1; + min-width: 0; + cursor: default; + } + .label { font-weight: 600; } + .description { + margin-top: 2px; + font-size: 12px; + color: var(--text-soft-color, #576273); + } + .control { + display: flex; + align-items: center; + justify-content: flex-end; + flex-shrink: 0; + } + :host([stacked]) .control { justify-content: flex-start; } + `; + + @property() label = ''; + @property() description = ''; + @property({ type: Boolean, reflect: true }) stacked = false; + @property({ type: Boolean, reflect: true }) divided = false; + @property({ type: Boolean, reflect: true }) disabled = false; + + private _control(): HTMLElement | undefined { + const slot = this.renderRoot.querySelector('slot:not([name])'); + return slot?.assignedElements({ flatten: true })[0] as HTMLElement | undefined; + } + + updated() { + this._nameControl(); + } + + /** Gives the control the row label as accessible name. */ + private _nameControl() { + const control = this._control(); + if (!control || !this.label) return; + if (control.tagName === 'EP-CHECKBOX') { + if (!control.getAttribute('label')) control.setAttribute('accessible-name', this.label); + } else if (!control.hasAttribute('aria-label') && !control.hasAttribute('aria-labelledby')) { + control.setAttribute('aria-label', this.label); + } + } + + private _onLabelClick() { + const control = this._control(); + if (!control) return; + if (control.tagName === 'EP-CHECKBOX') { + const input = control.shadowRoot?.querySelector('input'); + if (input) input.click(); + return; + } + control.focus(); + } + + render() { + return html` +
+
${this.label}
+ ${this.description ? html`
${this.description}
` : nothing} +
+
+ `; + } +} + +declare global { + interface HTMLElementTagNameMap { + 'ep-settings-section': EpSettingsSection; + 'ep-settings-row': EpSettingsRow; + } +} diff --git a/src/EpToolbar.ts b/src/EpToolbar.ts new file mode 100644 index 0000000..3d57822 --- /dev/null +++ b/src/EpToolbar.ts @@ -0,0 +1,357 @@ +import { LitElement, html, css, nothing } from 'lit'; +import { customElement, property, state } from 'lit/decorators.js'; + +/** + * Button for ``. Put an icon (SVG, icon font element, …) inside; + * `label` becomes tooltip and accessible name. + * + * Fires a normal `click`, and `ep-toolbar-action` (detail: `{ key }`) when + * it has a `key`. + */ +@customElement('ep-toolbar-button') +export class EpToolbarButton extends LitElement { + static styles = css` + :host { + display: inline-flex; + position: relative; + } + :host([hidden]) { display: none; } + + button { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 6px; + min-width: var(--ep-toolbar-button-size, 32px); + height: var(--ep-toolbar-button-size, 32px); + padding: 0 6px; + box-sizing: border-box; + border: none; + border-radius: var(--radius, 4px); + background: transparent; + color: var(--toolbar-text-color, var(--text-color, #485365)); + font: inherit; + font-size: 14px; + cursor: pointer; + transition: background 0.15s ease, color 0.15s ease; + } + button:hover { + background: var(--toolbar-hover-color, var(--bg-soft-color, #f2f3f4)); + } + :host([pressed]) button, + :host([active]) button { + background: var(--toolbar-active-color, var(--bg-soft-color, #f2f3f4)); + color: var(--toolbar-active-text-color, var(--primary-color, #64d29b)); + } + button:focus-visible { + outline: 2px solid var(--focus-color, var(--dark-color, #576273)); + outline-offset: 1px; + } + :host([disabled]) button { + opacity: 0.4; + cursor: not-allowed; + } + ::slotted(svg), ::slotted(.icon) { + width: 18px; + height: 18px; + flex-shrink: 0; + } + .text { white-space: nowrap; } + .badge { + min-width: 16px; + height: 16px; + padding: 0 4px; + box-sizing: border-box; + border-radius: 8px; + background: var(--primary-color, #64d29b); + color: var(--primary-text-color, #ffffff); + font-size: 11px; + font-weight: 700; + line-height: 16px; + text-align: center; + } + `; + + /** Tooltip and accessible name. */ + @property() label = ''; + /** Identifier reported by `ep-toolbar-action`. */ + @property({ reflect: true }) key = ''; + /** Makes the button a toggle; reflects `pressed` as aria-pressed. */ + @property({ type: Boolean, reflect: true }) toggle = false; + @property({ type: Boolean, reflect: true }) pressed = false; + /** Highlights the button without toggle semantics (e.g. open popup). */ + @property({ type: Boolean, reflect: true }) active = false; + @property({ type: Boolean, reflect: true }) disabled = false; + /** Shows the label next to the icon. */ + @property({ type: Boolean, attribute: 'show-label' }) showLabel = false; + /** + * For buttons that open something: `true` / `false` becomes aria-expanded, + * empty leaves it out. + */ + @property({ reflect: true }) expanded: '' | 'true' | 'false' = ''; + /** Small counter (e.g. users online). Empty hides it. */ + @property() badge = ''; + /** `low` items move into the overflow row on narrow toolbars. */ + @property({ reflect: true }) priority: 'normal' | 'low' = 'normal'; + + /** @internal roving tabindex managed by the toolbar. */ + @property({ attribute: false }) rovingTabIndex = 0; + + focus(options?: FocusOptions) { + this.renderRoot.querySelector('button')?.focus(options); + } + + private _onClick(e: MouseEvent) { + if (this.disabled) { + e.stopImmediatePropagation(); + e.preventDefault(); + return; + } + if (this.toggle) this.pressed = !this.pressed; + if (this.key) { + this.dispatchEvent(new CustomEvent('ep-toolbar-action', { + bubbles: true, composed: true, + detail: { key: this.key, pressed: this.toggle ? this.pressed : undefined }, + })); + } + } + + render() { + const badge = this.badge !== '' && this.badge !== undefined && this.badge !== null; + return html` + + `; + } +} + +/** Vertical divider between toolbar groups. */ +@customElement('ep-toolbar-separator') +export class EpToolbarSeparator extends LitElement { + static styles = css` + :host { + display: inline-block; + width: 1px; + height: 20px; + margin: 0 6px; + background: var(--toolbar-border-color, var(--middle-color, #d2d2d2)); + align-self: center; + flex-shrink: 0; + } + :host([hidden]) { display: none; } + `; + + connectedCallback() { + super.connectedCallback(); + this.setAttribute('role', 'separator'); + this.setAttribute('aria-orientation', 'vertical'); + } +} + +/** + * Editor toolbar. Default slot: left side (formatting), slot `end`: right + * side (actions). Arrow keys, Home and End move between the buttons; only + * one button is in the tab order. + * + * Below `breakpoint` pixels the toolbar becomes `compact`: buttons with + * `priority="low"` move into a second row that a "more" button opens. + */ +@customElement('ep-toolbar') +export class EpToolbar extends LitElement { + static styles = css` + :host { + display: block; + background: var(--toolbar-bg-color, var(--bg-color, #ffffff)); + color: var(--toolbar-text-color, var(--text-color, #485365)); + border-bottom: 1px solid var(--toolbar-border-color, var(--middle-color, #d2d2d2)); + font-family: var(--main-font-family, Quicksand, Cantarell, "Open Sans", "Helvetica Neue", sans-serif); + } + .row { + display: flex; + align-items: center; + gap: 2px; + padding: var(--ep-toolbar-padding, 6px 10px); + min-height: 32px; + } + .start, .end { + display: flex; + align-items: center; + gap: 2px; + min-width: 0; + } + .start { flex: 1; flex-wrap: wrap; } + .end { flex-shrink: 0; } + .more { display: none; } + :host([compact]) .more { display: inline-flex; } + .overflow { + display: none; + flex-wrap: wrap; + gap: 2px; + padding: 4px 10px 6px; + border-top: 1px solid var(--toolbar-border-color, var(--middle-color, #d2d2d2)); + } + :host([compact][expanded]) .overflow { display: flex; } + `; + + /** Accessible name of the toolbar. */ + @property() label = ''; + /** Width in px below which the toolbar turns compact. 0 disables it. */ + @property({ type: Number }) breakpoint = 800; + /** Label of the "more" button. */ + @property({ attribute: 'more-label' }) moreLabel = 'More'; + @property({ type: Boolean, reflect: true }) compact = false; + @property({ type: Boolean, reflect: true }) expanded = false; + + @state() private _focusIndex = 0; + + private _resize?: ResizeObserver; + private _mutation?: MutationObserver; + + connectedCallback() { + super.connectedCallback(); + if (typeof ResizeObserver === 'function') { + this._resize = new ResizeObserver(() => this._measure()); + this._resize.observe(this); + } + this._mutation = new MutationObserver(() => this._placeItems()); + this._mutation.observe(this, { childList: true, subtree: true, attributes: true, attributeFilter: ['priority', 'disabled', 'hidden'] }); + } + + disconnectedCallback() { + super.disconnectedCallback(); + this._resize?.disconnect(); + this._mutation?.disconnect(); + } + + firstUpdated() { + this._measure(); + } + + updated(changed: Map) { + if (changed.has('compact')) { + if (!this.compact) this.expanded = false; + this._placeItems(); + } + if (changed.has('breakpoint')) this._measure(); + } + + private _measure() { + const width = this.getBoundingClientRect().width; + this.compact = this.breakpoint > 0 && width > 0 && width < this.breakpoint; + } + + /** In compact mode low-priority buttons go to the overflow slot. */ + private _placeItems() { + for (const el of Array.from(this.querySelectorAll('[priority="low"]'))) { + if (el.parentElement !== this) continue; + if (this.compact) { + if (el.dataset.homeSlot === undefined) el.dataset.homeSlot = el.getAttribute('slot') ?? ''; + if (el.getAttribute('slot') !== 'overflow') el.setAttribute('slot', 'overflow'); + } else if (el.dataset.homeSlot !== undefined) { + const home = el.dataset.homeSlot; + delete el.dataset.homeSlot; + if (home) el.setAttribute('slot', home); + else el.removeAttribute('slot'); + } + } + this._updateRoving(); + } + + /** Buttons in visual order, without hidden or collapsed ones. */ + get items(): EpToolbarButton[] { + const slots = ['', 'end', 'overflow']; + const all = Array.from(this.querySelectorAll('ep-toolbar-button')); + const bySlot = (b: EpToolbarButton) => { + const top = Array.from(this.children).find((c) => c === b || c.contains(b)); + return slots.indexOf(top?.getAttribute('slot') ?? ''); + }; + return all + .filter((b) => !b.hidden && !b.closest('[hidden]')) + .filter((b) => !(bySlot(b) === 2 && !(this.compact && this.expanded))) + .sort((a, b) => bySlot(a) - bySlot(b)); + } + + private _updateRoving() { + const items = this.items; + if (this._focusIndex >= items.length) this._focusIndex = Math.max(0, items.length - 1); + for (const b of Array.from(this.querySelectorAll('ep-toolbar-button'))) { + b.rovingTabIndex = -1; + } + if (items[this._focusIndex]) items[this._focusIndex].rovingTabIndex = 0; + } + + private _onFocusIn(e: FocusEvent) { + const btn = e.composedPath().find((n) => n instanceof EpToolbarButton) as EpToolbarButton | undefined; + if (!btn) return; + const i = this.items.indexOf(btn); + if (i >= 0 && i !== this._focusIndex) { + this._focusIndex = i; + this._updateRoving(); + } + } + + private _onKeydown(e: KeyboardEvent) { + const items = this.items; + if (!items.length) return; + let next: number; + switch (e.key) { + case 'ArrowRight': next = (this._focusIndex + 1) % items.length; break; + case 'ArrowLeft': next = (this._focusIndex - 1 + items.length) % items.length; break; + case 'Home': next = 0; break; + case 'End': next = items.length - 1; break; + default: return; + } + e.preventDefault(); + this._focusIndex = next; + this._updateRoving(); + items[next].focus(); + } + + private _toggleMore() { + this.expanded = !this.expanded; + this.updateComplete.then(() => this._updateRoving()); + } + + render() { + return html` + + + `; + } +} + +declare global { + interface HTMLElementTagNameMap { + 'ep-toolbar': EpToolbar; + 'ep-toolbar-button': EpToolbarButton; + 'ep-toolbar-separator': EpToolbarSeparator; + } +} diff --git a/src/EpUserBadge.ts b/src/EpUserBadge.ts index 566e81d..6d7add9 100644 --- a/src/EpUserBadge.ts +++ b/src/EpUserBadge.ts @@ -1,5 +1,7 @@ import { LitElement, html, css } from 'lit'; import { customElement, property } from 'lit/decorators.js'; +import { styleMap } from 'lit/directives/style-map.js'; +import { safeColor } from './internal/color.js'; @customElement('ep-user-badge') export class EpUserBadge extends LitElement { @@ -59,7 +61,7 @@ export class EpUserBadge extends LitElement { render() { const initial = this.name ? this.name.charAt(0) : '?'; return html` -
+
${initial}
${this.name ? html`${this.name}` : ''} diff --git a/src/EpUserList.ts b/src/EpUserList.ts new file mode 100644 index 0000000..8a917be --- /dev/null +++ b/src/EpUserList.ts @@ -0,0 +1,193 @@ +import { LitElement, html, css, nothing } from 'lit'; +import { customElement, property } from 'lit/decorators.js'; +import { styleMap } from 'lit/directives/style-map.js'; +import './EpAvatar.js'; +import { safeColor } from './internal/color.js'; + +export interface EpUser { + id: string; + name: string; + color: string; + /** The current user: shown first, name and colour can be changed. */ + self?: boolean; + status?: '' | 'online' | 'idle' | 'offline'; +} + +/** + * List of the users in a pad. The own entry has a name field and a colour + * button. + * + * Events: + * - `ep-user-rename` (detail `{ name }`) when the own name is committed + * (Enter or leaving the field), + * - `ep-user-color-request` (detail `{ anchor }`) when the colour button is + * clicked; the app opens its colour picker at `anchor`, + * - `ep-user-select` (detail `{ user }`) when another user is clicked. + */ +@customElement('ep-user-list') +export class EpUserList extends LitElement { + static styles = css` + :host { + display: block; + font-family: var(--main-font-family, Quicksand, Cantarell, "Open Sans", "Helvetica Neue", sans-serif); + font-size: 14px; + color: var(--text-color, #485365); + } + .heading { + display: flex; + align-items: baseline; + justify-content: space-between; + margin: 0 0 8px; + font-size: 12px; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.04em; + color: var(--text-soft-color, #576273); + } + ul { list-style: none; margin: 0; padding: 0; } + li { + display: flex; + align-items: center; + gap: 10px; + padding: 6px 8px; + border-radius: var(--radius, 4px); + min-height: 32px; + } + li.other { cursor: default; } + li.other[data-clickable] { cursor: pointer; } + li.other[data-clickable]:hover { background: var(--bg-soft-color, #f2f3f4); } + .name { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + .unnamed { color: var(--text-soft-color, #576273); font-style: italic; } + .color-btn { + width: 28px; + height: 28px; + padding: 0; + border-radius: 50%; + border: 2px solid var(--bg-color, #ffffff); + box-shadow: 0 0 0 1px var(--middle-color, #d2d2d2); + cursor: pointer; + flex-shrink: 0; + } + .color-btn:focus-visible, input:focus-visible, li[data-clickable]:focus-visible { + outline: 2px solid var(--focus-color, var(--dark-color, #576273)); + outline-offset: 2px; + } + input { + flex: 1; + min-width: 0; + font: inherit; + color: inherit; + background: var(--bg-soft-color, #f2f3f4); + border: 1px solid var(--middle-color, #d2d2d2); + border-radius: calc(var(--radius, 4px) - 1px); + padding: 5px 8px; + } + input:disabled { opacity: 0.6; } + .empty { color: var(--text-soft-color, #576273); padding: 6px 8px; } + `; + + @property({ attribute: false }) users: EpUser[] = []; + /** Heading above the list; empty hides it. */ + @property() heading = ''; + @property({ attribute: 'name-placeholder' }) namePlaceholder = 'Enter your name'; + @property({ attribute: 'unnamed-label' }) unnamedLabel = 'Unnamed'; + @property({ attribute: 'color-label' }) colorLabel = 'Change your colour'; + @property({ attribute: 'empty-label' }) emptyLabel = ''; + /** Others can be clicked (`ep-user-select`). */ + @property({ type: Boolean }) selectable = false; + /** Own name and colour cannot be changed (read-only pad). */ + @property({ type: Boolean, reflect: true }) readonly = false; + + private _committed = ''; + + private get _sorted(): EpUser[] { + const self = this.users.filter((u) => u.self); + const others = this.users + .filter((u) => !u.self) + .sort((a, b) => (a.name || '￿').localeCompare(b.name || '￿')); + return [...self, ...others]; + } + + private _commit(input: HTMLInputElement) { + const name = input.value.trim(); + if (name === this._committed) return; + this._committed = name; + this.dispatchEvent(new CustomEvent('ep-user-rename', { + bubbles: true, composed: true, detail: { name }, + })); + } + + private _requestColor(e: Event) { + this.dispatchEvent(new CustomEvent('ep-user-color-request', { + bubbles: true, composed: true, detail: { anchor: e.currentTarget }, + })); + } + + private _select(user: EpUser) { + if (!this.selectable) return; + this.dispatchEvent(new CustomEvent('ep-user-select', { + bubbles: true, composed: true, detail: { user }, + })); + } + + private _renderSelf(u: EpUser) { + this._committed = u.name ?? ''; + return html` +
  • + + { + if (e.key === 'Enter') { e.preventDefault(); this._commit(e.target as HTMLInputElement); } + if (e.key === 'Escape') { (e.target as HTMLInputElement).value = this._committed; } + }} + @blur=${(e: FocusEvent) => this._commit(e.target as HTMLInputElement)} /> +
  • `; + } + + private _renderOther(u: EpUser) { + const clickable = this.selectable; + return html` +
  • this._select(u)} + @keydown=${(e: KeyboardEvent) => { + if (clickable && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); this._select(u); } + }}> + + ${u.name || this.unnamedLabel} +
  • `; + } + + render() { + const users = this._sorted; + return html` + ${this.heading + ? html`
    ${this.heading}${users.length}
    ` + : nothing} +
      + ${users.map((u) => (u.self ? this._renderSelf(u) : this._renderOther(u)))} +
    + ${users.length <= 1 && this.emptyLabel ? html`
    ${this.emptyLabel}
    ` : nothing} + `; + } +} + +declare global { + interface HTMLElementTagNameMap { + 'ep-user-list': EpUserList; + } +} diff --git a/src/index.ts b/src/index.ts index 90af843..3657980 100644 --- a/src/index.ts +++ b/src/index.ts @@ -15,6 +15,16 @@ export { EpSelect } from './EpSelect.js'; export type { EpSelectOption } from './EpSelect.js'; export { EpUserBadge } from './EpUserBadge.js'; export { EpTabs, EpTab } from './EpTabs.js'; +export { EpAvatar } from './EpAvatar.js'; +export { EpToolbar, EpToolbarButton, EpToolbarSeparator } from './EpToolbar.js'; +export { EpUserList } from './EpUserList.js'; +export type { EpUser } from './EpUserList.js'; +export { EpChatPanel } from './EpChatPanel.js'; +export type { EpChatEntry } from './EpChatPanel.js'; +export { EpSettingsSection, EpSettingsRow } from './EpSettings.js'; +export { EpPopup } from './EpPopup.js'; +export { EpSegmented } from './EpSegmented.js'; +export type { EpSegmentedOption } from './EpSegmented.js'; export { EpTheme } from './EpTheme.js'; export * from './themes.js'; export type { ThemeTokens } from './EpTheme.js'; diff --git a/src/internal/color.ts b/src/internal/color.ts new file mode 100644 index 0000000..7ffaaf3 --- /dev/null +++ b/src/internal/color.ts @@ -0,0 +1,42 @@ +import { parseColor } from '../themes.js'; + +/** + * Black or white, whichever reads better on `bg` (WCAG relative luminance). + * Falls back to white for colours that cannot be parsed. + */ +export function readableTextOn(bg: string, dark = '#1f2328', light = '#ffffff'): string { + const rgb = parseColor(bg); + if (!rgb) return light; + const [r, g, b] = rgb.map((c) => { + const s = c / 255; + return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4; + }); + const lum = 0.2126 * r + 0.7152 * g + 0.0722 * b; + // Contrast against white vs. against near-black. + return (1.05 / (lum + 0.05)) >= ((lum + 0.05) / 0.05) ? light : dark; +} + +/** Up to two initials of a name ("Ada Lovelace" → "AL", "sam" → "S"). */ +export function initialsOf(name: string): string { + const parts = name.trim().split(/\s+/).filter(Boolean); + if (!parts.length) return '?'; + const first = Array.from(parts[0])[0] ?? ''; + const last = parts.length > 1 ? Array.from(parts[parts.length - 1])[0] ?? '' : ''; + return (first + last).toUpperCase(); +} + +/** + * Returns `value` if it is a single valid CSS colour, otherwise undefined. + * Colours often come from other users (author colours), and Lit's styleMap + * writes the first render as a style string, so a value like + * `red;background:url(…)` must not get through. + */ +export function safeColor(value: string | undefined | null): string | undefined { + if (!value) return undefined; + const v = value.trim(); + if (!v || /[;{}<>\\]/.test(v)) return undefined; + if (typeof CSS !== 'undefined' && typeof CSS.supports === 'function' && !CSS.supports('color', v)) { + return undefined; + } + return v; +} diff --git a/stories/EpAvatar.stories.ts b/stories/EpAvatar.stories.ts new file mode 100644 index 0000000..c0f40cf --- /dev/null +++ b/stories/EpAvatar.stories.ts @@ -0,0 +1,42 @@ +import { html } from 'lit'; +import type { Meta, StoryObj } from '@storybook/web-components'; +import { expect } from 'storybook/test'; +import '../src/EpAvatar.js'; +import type { EpAvatar } from '../src/EpAvatar.js'; + +const meta: Meta = { title: 'Pad/EpAvatar', component: 'ep-avatar' }; +export default meta; + +export const Variants: StoryObj = { + render: () => html` +
    + + + + + +
    + `, + play: async ({ canvasElement }) => { + const get = async (id: string) => { + const el = canvasElement.querySelector(`#${id}`) as EpAvatar; + await el.updateComplete; + return el.shadowRoot!.querySelector('.circle') as HTMLElement; + }; + const a = await get('a'); + await expect(a.textContent!.trim()).toBe('AL'); + await expect(a.getAttribute('aria-label')).toBe('Ada Lovelace'); + // Light background → dark text, dark background → white text. + await expect(getComputedStyle(a).color).toBe('rgb(31, 35, 40)'); + await expect(getComputedStyle(await get('b')).color).toBe('rgb(255, 255, 255)'); + await expect((await get('b')).textContent!.trim()).toBe('S'); + await expect((await get('c')).textContent!.trim()).toBe('?'); + // A crafted colour cannot add other declarations. + await expect((await get('d')).style.backgroundImage).toBe(''); + // A failing picture falls back to the initials. + await new Promise((r) => setTimeout(r, 300)); + const e = await get('e'); + await expect(e.querySelector('img')).toBeNull(); + await expect(e.textContent!.trim()).toBe('BP'); + }, +}; diff --git a/stories/EpChatPanel.stories.ts b/stories/EpChatPanel.stories.ts new file mode 100644 index 0000000..944555f --- /dev/null +++ b/stories/EpChatPanel.stories.ts @@ -0,0 +1,115 @@ +import { html } from 'lit'; +import type { Meta, StoryObj } from '@storybook/web-components'; +import { expect, userEvent, fn } from 'storybook/test'; +import '../src/EpChatPanel.js'; +import type { EpChatEntry, EpChatPanel } from '../src/EpChatPanel.js'; + +type Args = { onSend: (e: Event) => void; onClose: (e: Event) => void; onSticky: (e: Event) => void; onMore: (e: Event) => void }; +const meta: Meta = { + title: 'Pad/EpChatPanel', + component: 'ep-chat-panel', + args: { onSend: fn(), onClose: fn(), onSticky: fn(), onMore: fn() }, +}; +export default meta; + +const make = (n: number, from = 0): EpChatEntry[] => + Array.from({ length: n }, (_, i) => ({ + id: String(from + i), + author: i % 2 ? 'Ada' : 'Sam', + authorColor: i % 2 ? '#c2255c' : '#2b8a3e', + time: '12:0' + (i % 10), + text: `Message ${from + i}`, + own: i % 2 === 0, + })); + +export const Default: StoryObj = { + render: (args) => html` +
    + +
    `, + play: async ({ canvasElement, args }) => { + const chat = canvasElement.querySelector('ep-chat-panel') as EpChatPanel; + await chat.updateComplete; + await new Promise((r) => requestAnimationFrame(r)); + const root = chat.shadowRoot!; + const log = root.querySelector('.log') as HTMLElement; + // Starts at the newest message. + await expect(log.scrollHeight - log.scrollTop - log.clientHeight).toBeLessThan(2); + + const input = root.querySelector('textarea')!; + await userEvent.type(input, 'Hallo{Enter}'); + await expect(((args.onSend as ReturnType).mock.calls[0][0] as CustomEvent).detail).toEqual({ text: 'Hallo' }); + await expect(input.value).toBe(''); + // Shift+Enter is a line break, blank messages are not sent. + // (dispatched directly: user-event restores its own copy of the value) + const key = (init: KeyboardEventInit) => + input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true, ...init })); + input.value = 'line'; + await expect(key({ shiftKey: true })).toBe(true); // not prevented → newline + input.value = ' '; + key({}); + await expect(args.onSend).toHaveBeenCalledTimes(1); + + // New message while at the bottom → stays at the bottom. + chat.messages = [...chat.messages, ...make(1, 500)]; + await chat.updateComplete; + await new Promise((r) => requestAnimationFrame(r)); + await expect(log.scrollHeight - log.scrollTop - log.clientHeight).toBeLessThan(2); + + // Scrolled up → new messages do not pull the view down. + log.scrollTop = 200; + log.dispatchEvent(new Event('scroll')); + chat.messages = [...chat.messages, ...make(1, 501)]; + await chat.updateComplete; + await expect(log.scrollTop).toBe(200); + + // Top reached → load more once; prepending keeps the view in place. + log.scrollTop = 0; + log.dispatchEvent(new Event('scroll')); + log.dispatchEvent(new Event('scroll')); + await expect(args.onMore).toHaveBeenCalledTimes(1); + const first = root.querySelector('ep-chat-message') as HTMLElement; + const before = first.getBoundingClientRect().top; + chat.loading = true; + await chat.updateComplete; + chat.messages = [...make(10, 0), ...chat.messages]; + chat.loading = false; + await chat.updateComplete; + await new Promise((r) => requestAnimationFrame(r)); + await expect(Math.abs(first.getBoundingClientRect().top - before)).toBeLessThan(30); + + const sticky = root.querySelector('[part="sticky-button"]') as HTMLButtonElement; + await userEvent.click(sticky); + await expect(sticky.getAttribute('aria-pressed')).toBe('true'); + await expect(((args.onSticky as ReturnType).mock.calls[0][0] as CustomEvent).detail).toEqual({ sticky: true }); + await userEvent.click(root.querySelector('[part="close-button"]')!); + await expect(args.onClose).toHaveBeenCalledTimes(1); + }, +}; + +export const SlottedAndReadonly: StoryObj = { + render: () => html` +
    + + Slotted message + +
    `, + play: async ({ canvasElement }) => { + const chat = canvasElement.querySelector('ep-chat-panel') as EpChatPanel; + await chat.updateComplete; + await expect(chat.shadowRoot!.querySelector('textarea')).toBeNull(); + await expect(chat.shadowRoot!.querySelector('.empty')).toBeNull(); + }, +}; + +export const Empty: StoryObj = { + render: () => html`
    `, + play: async ({ canvasElement }) => { + const chat = canvasElement.querySelector('ep-chat-panel') as EpChatPanel; + await chat.updateComplete; + await expect(chat.shadowRoot!.querySelector('.empty')!.textContent).toBe('No messages yet'); + }, +}; diff --git a/stories/EpPopup.stories.ts b/stories/EpPopup.stories.ts new file mode 100644 index 0000000..4cc51fa --- /dev/null +++ b/stories/EpPopup.stories.ts @@ -0,0 +1,115 @@ +import { html } from 'lit'; +import type { Meta, StoryObj } from '@storybook/web-components'; +import { expect, userEvent, fn } from 'storybook/test'; +import '../src/EpPopup.js'; +import '../src/EpSettings.js'; +import '../src/EpSegmented.js'; +import '../src/EpCheckbox.js'; +import '../src/EpButton.js'; +import type { EpPopup } from '../src/EpPopup.js'; +import type { EpSegmented } from '../src/EpSegmented.js'; +import type { EpCheckbox } from '../src/EpCheckbox.js'; + +type Args = { onClose: (e: Event) => void; onChange: (e: Event) => void }; +const meta: Meta = { + title: 'Pad/EpPopup', + component: 'ep-popup', + args: { onClose: fn(), onChange: fn() }, +}; +export default meta; + +const SUN = ''; +const MOON = ''; + +export const Settings: StoryObj = { + render: (args) => html` +
    + +
    + + + + + + + + + + + + + + Done + + `, + play: async ({ canvasElement, args }) => { + const popup = canvasElement.querySelector('ep-popup') as EpPopup; + const anchor = canvasElement.querySelector('#anchor') as HTMLButtonElement; + await expect(popup.open).toBe(false); + + await userEvent.click(anchor); + await popup.updateComplete; + await new Promise((r) => requestAnimationFrame(r)); + await expect(popup.open).toBe(true); + const box = popup.getBoundingClientRect(); + const a = anchor.getBoundingClientRect(); + await expect(Math.round(box.top)).toBe(Math.round(a.bottom + 6)); + await expect(Math.abs(box.right - a.right)).toBeLessThan(2); + // Focus moved into the popup. + await expect(popup.contains(document.activeElement)).toBe(true); + + // Clicking a row label toggles its checkbox; the row names the control. + const lines = canvasElement.querySelector('#lines') as EpCheckbox; + await expect(lines.shadowRoot!.querySelector('input')!.getAttribute('aria-label')).toBe('Line numbers'); + const row = lines.closest('ep-settings-row')!; + await userEvent.click(row.shadowRoot!.querySelector('.label')!); + await expect(lines.checked).toBe(true); + await expect(canvasElement.querySelector('select')!.getAttribute('aria-label')).toBe('Language'); + + // Segmented control: click and arrows, disabled option skipped. + const seg = canvasElement.querySelector('#theme') as EpSegmented; + const radios = Array.from(seg.shadowRoot!.querySelectorAll('[role="radio"]')); + await userEvent.click(radios[1]); + await expect(seg.value).toBe('dark'); + await userEvent.keyboard('{ArrowRight}'); + await expect(seg.value).toBe('light'); + await expect(args.onChange).toHaveBeenCalledTimes(2); + + // Escape closes and returns focus to the anchor. + await userEvent.keyboard('{Escape}'); + await expect(popup.open).toBe(false); + await expect(document.activeElement).toBe(anchor); + await expect(((args.onClose as ReturnType).mock.calls[0][0] as CustomEvent).detail).toEqual({ reason: 'escape' }); + + // Outside click closes; clicking the anchor toggles instead of double-handling. + await userEvent.click(anchor); + await popup.updateComplete; + await expect(popup.open).toBe(true); + await userEvent.click(canvasElement.querySelector('div')!, { pointerEventsCheck: 0 }); + await expect(popup.open).toBe(false); + await expect(((args.onClose as ReturnType).mock.calls[1][0] as CustomEvent).detail).toEqual({ reason: 'outside' }); + await userEvent.click(anchor); + await popup.updateComplete; + await userEvent.click(anchor); + await popup.updateComplete; + await expect(popup.open).toBe(false); + }, +}; + +export const Persistent: StoryObj = { + render: () => html`

    Stays open.

    `, + play: async ({ canvasElement }) => { + const popup = canvasElement.querySelector('ep-popup') as EpPopup; + await popup.updateComplete; + await userEvent.keyboard('{Escape}'); + await userEvent.click(document.body, { pointerEventsCheck: 0 }); + await expect(popup.open).toBe(true); + await userEvent.click(popup.shadowRoot!.querySelector('.close')!); + await expect(popup.open).toBe(false); + }, +}; diff --git a/stories/EpToolbar.stories.ts b/stories/EpToolbar.stories.ts new file mode 100644 index 0000000..3aca2e4 --- /dev/null +++ b/stories/EpToolbar.stories.ts @@ -0,0 +1,107 @@ +import { html } from 'lit'; +import type { Meta, StoryObj } from '@storybook/web-components'; +import { expect, userEvent, fn } from 'storybook/test'; +import '../src/EpToolbar.js'; +import type { EpToolbar, EpToolbarButton } from '../src/EpToolbar.js'; + +const icon = (d: string) => html``; +const B = 'M4 2h4.5a3 3 0 0 1 2.1 5.15A3.25 3.25 0 0 1 9.25 14H4V2zm2 2v3h2.5a1.5 1.5 0 0 0 0-3H6zm0 5v3h3.25a1.5 1.5 0 0 0 0-3H6z'; +const I = 'M6 2h6v2H9.9l-2 8H10v2H4v-2h2.1l2-8H6z'; +const U = 'M4 2h2v5a2 2 0 0 0 4 0V2h2v5a4 4 0 0 1-8 0zM3 13h10v1.5H3z'; +const LIST = 'M2 3h2v2H2zm4 0h8v2H6zM2 7h2v2H2zm4 0h8v2H6zm-4 4h2v2H2zm4 0h8v2H6z'; +const GEAR = 'M8 5a3 3 0 1 0 0 6 3 3 0 0 0 0-6zm6 3-.1-1 1.5-1.2-1.5-2.6-1.8.6a5 5 0 0 0-1.7-1L10 0H7l-.4 1.8a5 5 0 0 0-1.7 1l-1.8-.6L1.6 4.8 3.1 6 3 8l.1 1-1.5 1.2 1.5 2.6 1.8-.6a5 5 0 0 0 1.7 1L7 16h3l.4-1.8a5 5 0 0 0 1.7-1l1.8.6 1.5-2.6L13.9 9z'; +const USERS = 'M6 7a3 3 0 1 0 0-6 3 3 0 0 0 0 6zm-5 8a5 5 0 0 1 10 0zm10.5-8a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5zM12 15a6 6 0 0 0-1.6-4.2A4.5 4.5 0 0 1 16 15z'; + +type Args = { onAction: (e: Event) => void; breakpoint: number }; + +const meta: Meta = { + title: 'Pad/EpToolbar', + component: 'ep-toolbar', + args: { onAction: fn(), breakpoint: 800 }, +}; +export default meta; +type Story = StoryObj; + +const bar = (args: Args, width = '100%') => html` +
    + + ${icon(B)} + ${icon(I)} + ${icon(U)} + + ${icon(LIST)} + ${icon(LIST)} + ${icon(GEAR)} + ${icon(USERS)} + +
    +`; + +const ready = async (root: HTMLElement) => { + const tb = root.querySelector('ep-toolbar') as EpToolbar; + await tb.updateComplete; + await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))); + await tb.updateComplete; + return tb; +}; +const inner = (b: EpToolbarButton) => b.shadowRoot!.querySelector('button')!; + +export const Default: Story = { + render: (args) => bar(args), + play: async ({ canvasElement, args }) => { + const tb = await ready(canvasElement); + const [bold, italic] = tb.items; + await expect(tb.items.length).toBe(7); + await expect(inner(bold).getAttribute('aria-label')).toBe('Bold'); + await expect(inner(bold).getAttribute('aria-pressed')).toBe('false'); + + await userEvent.click(inner(bold)); + await expect(bold.pressed).toBe(true); + await expect(inner(bold).getAttribute('aria-pressed')).toBe('true'); + await expect(args.onAction).toHaveBeenCalledTimes(1); + const ev = (args.onAction as ReturnType).mock.calls[0][0] as CustomEvent; + await expect(ev.detail).toEqual({ key: 'bold', pressed: true }); + + // Roving tabindex: only the focused button is tabbable; arrows move. + await expect(inner(bold).tabIndex).toBe(0); + await expect(inner(italic).tabIndex).toBe(-1); + await userEvent.keyboard('{ArrowRight}'); + await expect(italic.shadowRoot!.activeElement).toBe(inner(italic)); + await expect(inner(italic).tabIndex).toBe(0); + await userEvent.keyboard('{End}'); + await expect(tb.items[tb.items.length - 1].getAttribute('key')).toBe('users'); + await userEvent.keyboard('{ArrowRight}'); + await expect(bold.shadowRoot!.activeElement).toBe(inner(bold)); + + // Disabled buttons do not fire actions. + const disabled = tb.items.find((b) => b.key === 'disabled')!; + await userEvent.click(inner(disabled)); + await expect(args.onAction).toHaveBeenCalledTimes(1); + }, +}; + +export const Compact: Story = { + render: (args) => bar(args, '420px'), + play: async ({ canvasElement }) => { + const tb = await ready(canvasElement); + await expect(tb.compact).toBe(true); + const low = tb.querySelector('[key="list"]')!; + await expect(low.getAttribute('slot')).toBe('overflow'); + // Hidden overflow items are not reachable by arrow keys. + await expect(tb.items.some((b) => b.key === 'list')).toBe(false); + + const more = tb.shadowRoot!.querySelector('.more') as EpToolbarButton; + await userEvent.click(inner(more)); + await tb.updateComplete; + await expect(tb.expanded).toBe(true); + await expect(inner(more).getAttribute('aria-expanded')).toBe('true'); + await expect(tb.items.some((b) => b.key === 'list')).toBe(true); + + // Back to wide: items return to their slot. + tb.breakpoint = 0; + await tb.updateComplete; + await new Promise((r) => requestAnimationFrame(r)); + await expect(tb.compact).toBe(false); + await expect(low.hasAttribute('slot')).toBe(false); + }, +}; diff --git a/stories/EpUserList.stories.ts b/stories/EpUserList.stories.ts new file mode 100644 index 0000000..cff1bd7 --- /dev/null +++ b/stories/EpUserList.stories.ts @@ -0,0 +1,64 @@ +import { html } from 'lit'; +import type { Meta, StoryObj } from '@storybook/web-components'; +import { expect, userEvent, fn } from 'storybook/test'; +import '../src/EpUserList.js'; +import type { EpUser, EpUserList } from '../src/EpUserList.js'; + +type Args = { onRename: (e: Event) => void; onColor: (e: Event) => void; onSelect: (e: Event) => void }; +const meta: Meta = { + title: 'Pad/EpUserList', + component: 'ep-user-list', + args: { onRename: fn(), onColor: fn(), onSelect: fn() }, +}; +export default meta; + +const users: EpUser[] = [ + { id: 'b', name: 'Zoe', color: '#ffa8a8', status: 'online' }, + { id: 'c', name: '', color: '#a5d8ff' }, + { id: 'a', name: 'Sam', color: '#b2f2bb', self: true }, + { id: 'd', name: 'Ada', color: '#ffec99', status: 'idle' }, +]; + +export const Default: StoryObj = { + render: (args) => html` +
    + +
    `, + play: async ({ canvasElement, args }) => { + const list = canvasElement.querySelector('ep-user-list') as EpUserList; + await list.updateComplete; + const root = list.shadowRoot!; + const rows = Array.from(root.querySelectorAll('li')); + // Own entry first, others sorted by name, unnamed last. + await expect(rows[0].classList.contains('self')).toBe(true); + await expect(rows.slice(1).map((r) => r.querySelector('.name')!.textContent)).toEqual(['Ada', 'Zoe', 'Unnamed']); + await expect(root.querySelector('.heading')!.textContent).toContain('4'); + + const input = root.querySelector('input')!; + input.value = ''; + await userEvent.type(input, 'Samuel{Enter}'); + await expect(args.onRename).toHaveBeenCalledTimes(1); + await expect(((args.onRename as ReturnType).mock.calls[0][0] as CustomEvent).detail).toEqual({ name: 'Samuel' }); + // Blurring without change does not fire again. + input.blur(); + await expect(args.onRename).toHaveBeenCalledTimes(1); + + await userEvent.click(root.querySelector('.color-btn')!); + await expect(args.onColor).toHaveBeenCalledTimes(1); + + await userEvent.click(rows[1]); + await expect(((args.onSelect as ReturnType).mock.calls[0][0] as CustomEvent).detail.user.name).toBe('Ada'); + }, +}; + +export const ReadOnly: StoryObj = { + render: () => html`
    `, + play: async ({ canvasElement }) => { + const list = canvasElement.querySelector('ep-user-list') as EpUserList; + await list.updateComplete; + await expect(list.shadowRoot!.querySelector('input')!.disabled).toBe(true); + await expect(list.shadowRoot!.querySelector('.color-btn')!.disabled).toBe(true); + }, +}; diff --git a/stories/PadLayout.stories.ts b/stories/PadLayout.stories.ts new file mode 100644 index 0000000..3baaf6e --- /dev/null +++ b/stories/PadLayout.stories.ts @@ -0,0 +1,88 @@ +import { html } from 'lit'; +import type { Meta, StoryObj } from '@storybook/web-components'; +import { expect } from 'storybook/test'; +import '../src/EpTheme.js'; +import '../src/EpToolbar.js'; +import '../src/EpUserList.js'; +import '../src/EpChatPanel.js'; +import '../src/EpPopup.js'; +import '../src/EpSettings.js'; +import '../src/EpCheckbox.js'; +import '../src/EpSegmented.js'; +import type { EpPopup } from '../src/EpPopup.js'; + +const i = (d: string) => html``; +const P = { + bold: 'M4 2h4.5a3 3 0 0 1 2.1 5.15A3.25 3.25 0 0 1 9.25 14H4V2zm2 2v3h2.5a1.5 1.5 0 0 0 0-3H6zm0 5v3h3.25a1.5 1.5 0 0 0 0-3H6z', + italic: 'M6 2h6v2H9.9l-2 8H10v2H4v-2h2.1l2-8H6z', + list: 'M2 3h2v2H2zm4 0h8v2H6zM2 7h2v2H2zm4 0h8v2H6zm-4 4h2v2H2zm4 0h8v2H6z', + undo: 'M5.5 3 1.5 7l4 4V8h4a3 3 0 0 1 0 6H8v2h1.5a5 5 0 0 0 0-10h-4z', + history: 'M8 1a7 7 0 1 1-6.6 4.7l1.9.6A5 5 0 1 0 8 3v2L4.5 2 8-1zM7 5h2v3.6l2.4 1.4-1 1.7L7 9.7z', + gear: 'M8 5a3 3 0 1 0 0 6 3 3 0 0 0 0-6zm6 3-.1-1 1.5-1.2-1.5-2.6-1.8.6a5 5 0 0 0-1.7-1L10 0H7l-.4 1.8a5 5 0 0 0-1.7 1l-1.8-.6L1.6 4.8 3.1 6 3 8l.1 1-1.5 1.2 1.5 2.6 1.8-.6a5 5 0 0 0 1.7 1L7 16h3l.4-1.8a5 5 0 0 0 1.7-1l1.8.6 1.5-2.6L13.9 9z', + users: 'M6 7a3 3 0 1 0 0-6 3 3 0 0 0 0 6zm-5 8a5 5 0 0 1 10 0zm10.5-8a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5zM12 15a6 6 0 0 0-1.6-4.2A4.5 4.5 0 0 1 16 15z', +}; + +type Args = { theme: string }; +const meta: Meta = { + title: 'Pad/Layout', + argTypes: { theme: { control: 'select', options: ['colibris', 'colibris-dark', 'high-contrast', 'warm'] } }, + args: { theme: 'colibris' }, + parameters: { layout: 'fullscreen' }, +}; +export default meta; + +export const Pad: StoryObj = { + render: (args) => html` + +
    + + ${i(P.bold)} + ${i(P.italic)} + + ${i(P.list)} + ${i(P.undo)} + ${i(P.history)} + ((e.currentTarget as HTMLElement).closest('ep-theme')!.querySelector('ep-popup') as EpPopup).toggle()}>${i(P.gear)} + ${i(P.users)} + +
    +
    +

    Meeting notes

    +

    Collaborative text with bold parts and a list:

    +
    • Theme tokens
    • Pad building blocks
    +
    +
    +
    + +
    +
    + +
    +
    +
    + + + + + + + + + +
    +
    + `, + play: async ({ canvasElement }) => { + const popup = canvasElement.querySelector('ep-popup') as EpPopup; + await popup.updateComplete; + await expect(popup.open).toBe(true); + }, +}; From fb82baae7533161b13da8574860ab48bc397c646 Mon Sep 17 00:00:00 2001 From: SamTV12345 Date: Mon, 23 Nov 2026 20:17:22 +0100 Subject: [PATCH 2/2] fix: Qodo findings on the pad building blocks - chat: keeps the first visible message in place on any content change while scrolled up (rebuilt entries, slotted prepends, loading row); load-more re-arms when messages arrive; empty label follows slotted messages - user list: rename baseline only changes with the own name - popup: clamped to the viewport for both alignments; closing via the open property also emits ep-popup-close and returns focus - settings row: disabled rows disable their control; row labels follow label changes (marked with data-ep-row-label) and reach ep-segmented - segmented: disabled blocks keyboard; ArrowLeft without selection goes to the last option - toolbar: items whose priority changes leave the overflow row; "more" is part of the roving order in compact mode Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012RMvvMtnCwj6ycD9fwLYVu --- src/EpChatPanel.ts | 86 +++++++++++++++++------------ src/EpPopup.ts | 54 +++++++++++++------ src/EpSegmented.ts | 11 ++-- src/EpSettings.ts | 56 ++++++++++++++++--- src/EpToolbar.ts | 26 ++++++--- src/EpUserList.ts | 13 ++++- stories/EpChatPanel.stories.ts | 84 +++++++++++++++++++++++++++++ stories/EpPopup.stories.ts | 98 ++++++++++++++++++++++++++++++++++ stories/EpToolbar.stories.ts | 23 ++++++++ stories/EpUserList.stories.ts | 22 ++++++++ 10 files changed, 402 insertions(+), 71 deletions(-) diff --git a/src/EpChatPanel.ts b/src/EpChatPanel.ts index 31645e1..878f9af 100644 --- a/src/EpChatPanel.ts +++ b/src/EpChatPanel.ts @@ -1,5 +1,5 @@ import { LitElement, html, css, nothing } from 'lit'; -import { customElement, property, query } from 'lit/decorators.js'; +import { customElement, property, query, state } from 'lit/decorators.js'; import { repeat } from 'lit/directives/repeat.js'; import './EpChatMessage.js'; @@ -155,11 +155,11 @@ export class EpChatPanel extends LitElement { @query('textarea') private _input?: HTMLTextAreaElement; private _atBottom = true; - private _prevHeight = 0; - private _prevTop = 0; - private _prepended = false; private _loadingOlder = false; private _resize?: ResizeObserver; + /** Message that stays in place while the reader is scrolled up. */ + private _anchor?: { el: Element; offset: number }; + @state() private _slotted = 0; /** Focuses the input. */ focus(options?: FocusOptions) { @@ -170,25 +170,14 @@ export class EpChatPanel extends LitElement { scrollToBottom() { if (this._log) this._log.scrollTop = this._log.scrollHeight; this._atBottom = true; - } - - protected willUpdate(changed: Map) { - if (!changed.has('messages')) return; - const old = (changed.get('messages') as EpChatEntry[] | undefined) ?? []; - const now = this.messages; - // Older messages were put in front of the existing ones. - this._prepended = old.length > 0 && now.length > old.length - && now[now.length - 1] === old[old.length - 1] && now[0] !== old[0]; - if (this._log) { - this._prevHeight = this._log.scrollHeight; - this._prevTop = this._log.scrollTop; - } + this._anchor = undefined; } protected firstUpdated() { if (typeof ResizeObserver === 'function') { - // Late height changes (fonts, wrapped lines) keep the newest message visible. - this._resize = new ResizeObserver(() => { if (this._atBottom) this.scrollToBottom(); }); + // Any height change of the content (new, older or re-rendered + // messages, loading row, fonts) goes through _keepPosition. + this._resize = new ResizeObserver(() => this._keepPosition()); this._resize.observe(this.renderRoot.querySelector('.items')!); } } @@ -200,33 +189,60 @@ export class EpChatPanel extends LitElement { } protected updated(changed: Map) { - if (changed.has('messages')) void this._afterContentChange(this._prepended); + if (changed.has('messages') || changed.has('hasMore')) this._loadingOlder = false; if (changed.has('loading') && !this.loading) this._loadingOlder = false; + void this._afterRender(); } - private async _afterContentChange(prepended = false) { - if (!this._log) return; - const prevHeight = this._prevHeight; - const prevTop = this._prevTop; - // Wait until the message elements have rendered, so heights are final. - const items = Array.from(this.renderRoot.querySelectorAll('ep-chat-message')) - .concat(Array.from(this.querySelectorAll('ep-chat-message'))) as Array }>; + /** Waits until the message elements have rendered, then keeps position. */ + private async _afterRender() { + const items = this._messageElements() as Array }>; await Promise.all(items.map((m) => m.updateComplete)); - if (prepended) { - // Keep the visible messages in place. - this._log.scrollTop = prevTop + (this._log.scrollHeight - prevHeight); - } else if (this._atBottom) { - this.scrollToBottom(); + this._keepPosition(); + } + + private _messageElements(): Element[] { + const own = Array.from(this.renderRoot.querySelectorAll('.items > ep-chat-message')); + const slot = this.renderRoot.querySelector('slot[name="messages"]'); + return own.concat(slot?.assignedElements({ flatten: true }) ?? []); + } + + /** At the bottom: follow new messages. Scrolled up: keep the anchor still. */ + private _keepPosition() { + const log = this._log; + if (!log) return; + if (this._atBottom) { + log.scrollTop = log.scrollHeight; + return; + } + const a = this._anchor; + if (a && a.el.isConnected) { + const delta = this._offsetOf(a.el) - a.offset; + if (delta !== 0) log.scrollTop += delta; } + this._recordAnchor(); + } + + private _offsetOf(el: Element): number { + return el.getBoundingClientRect().top - this._log.getBoundingClientRect().top; + } + + private _recordAnchor() { + const top = this._log.getBoundingClientRect().top; + const el = this._messageElements().find((m) => m.getBoundingClientRect().bottom > top); + this._anchor = el ? { el, offset: this._offsetOf(el) } : undefined; } - private _onSlotChange() { - void this._afterContentChange(); + private _onSlotChange(e: Event) { + this._slotted = (e.target as HTMLSlotElement).assignedElements({ flatten: true }).length; + this._loadingOlder = false; + void this._afterRender(); } private _onScroll() { const log = this._log; this._atBottom = log.scrollHeight - log.scrollTop - log.clientHeight < 24; + if (!this._atBottom) this._recordAnchor(); if (log.scrollTop < 20 && this.hasMore && !this.loading && !this._loadingOlder) { this._loadingOlder = true; this.dispatchEvent(new CustomEvent('ep-chat-load-more', { bubbles: true, composed: true })); @@ -267,7 +283,7 @@ export class EpChatPanel extends LitElement { } render() { - const empty = !this.messages.length && !this.querySelector('[slot="messages"]'); + const empty = !this.messages.length && !this._slotted; return html`

    ${this.heading}

    diff --git a/src/EpPopup.ts b/src/EpPopup.ts index 4075086..bdabe92 100644 --- a/src/EpPopup.ts +++ b/src/EpPopup.ts @@ -128,6 +128,8 @@ export class EpPopup extends LitElement { private _returnFocus: HTMLElement | null = null; private _hasFooter = false; + private _closeReason: 'escape' | 'outside' | 'button' | 'api' = 'api'; + private _hadFocus = false; show() { this.open = true; } hide() { this._close('api'); } @@ -168,15 +170,17 @@ export class EpPopup extends LitElement { const a = this._anchorEl(); if (!a || !this.open) return; const r = a.getBoundingClientRect(); + const viewport = document.documentElement.clientWidth; + const width = this.getBoundingClientRect().width || 360; + const margin = 12; this.style.top = `${Math.round(r.bottom + 6)}px`; this.style.setProperty('--ep-popup-top', `${Math.round(r.bottom + 6)}px`); - if (this.align === 'start') { - this.style.left = `${Math.max(12, Math.round(r.left))}px`; - this.style.right = 'auto'; - } else { - this.style.right = `${Math.max(12, Math.round(document.documentElement.clientWidth - r.right))}px`; - this.style.left = 'auto'; - } + // Keep the whole panel inside the viewport on both sides. + const maxLeft = Math.max(margin, viewport - width - margin); + let left = this.align === 'start' ? r.left : r.right - width; + left = Math.min(Math.max(margin, left), maxLeft); + this.style.left = `${Math.round(left)}px`; + this.style.right = 'auto'; }; private _onOutside = (e: PointerEvent) => { @@ -197,16 +201,15 @@ export class EpPopup extends LitElement { private _close(reason: 'escape' | 'outside' | 'button' | 'api') { if (!this.open) return; + this._closeReason = reason; this.open = false; - this.dispatchEvent(new CustomEvent('ep-popup-close', { - bubbles: true, composed: true, detail: { reason }, - })); - // Only return focus if it was inside the popup (an outside click moves it elsewhere). - if (reason !== 'outside') { - const target = this._returnFocus ?? this._anchorEl(); - target?.focus?.(); + } + + protected willUpdate(changed: Map) { + // Before the panel is hidden: was focus inside it? + if (changed.has('open') && !this.open && changed.get('open')) { + this._hadFocus = this.matches(':focus-within'); } - this._returnFocus = null; } protected updated(changed: Map) { @@ -217,14 +220,31 @@ export class EpPopup extends LitElement { this._listen(true); this._position(); this.dispatchEvent(new CustomEvent('ep-popup-open', { bubbles: true, composed: true })); - requestAnimationFrame(() => this._focusFirst()); + requestAnimationFrame(() => { this._position(); this._focusFirst(); }); } else if (was) { - this._listen(false); + this._didClose(); } } if (changed.has('anchor') || changed.has('align')) this._position(); } + /** Runs for every way of closing, including `open = false` set by the app. */ + private _didClose() { + const reason = this._closeReason; + this._closeReason = 'api'; + this._listen(false); + this.dispatchEvent(new CustomEvent('ep-popup-close', { + bubbles: true, composed: true, detail: { reason }, + })); + // Return focus only if it was in the popup (an outside click put it elsewhere). + if (this._hadFocus && reason !== 'outside') { + const target = this._returnFocus ?? this._anchorEl(); + target?.focus?.(); + } + this._hadFocus = false; + this._returnFocus = null; + } + private _focusFirst() { if (!this.open) return; for (const el of Array.from(this.querySelectorAll(FOCUSABLE))) { diff --git a/src/EpSegmented.ts b/src/EpSegmented.ts index 393f48f..938b5fa 100644 --- a/src/EpSegmented.ts +++ b/src/EpSegmented.ts @@ -71,6 +71,7 @@ export class EpSegmented extends LitElement { @property() label = ''; private _choose(value: string, focus = false) { + if (this.disabled) return; if (value !== this.value) { this.value = value; this.dispatchEvent(new CustomEvent('ep-change', { @@ -89,13 +90,14 @@ export class EpSegmented extends LitElement { } private _onKeydown(e: KeyboardEvent) { + if (this.disabled) return; const enabled = this.options.filter((o) => !o.disabled); if (!enabled.length) return; const at = enabled.findIndex((o) => o.value === this.value); let next: number; switch (e.key) { - case 'ArrowRight': case 'ArrowDown': next = (at + 1) % enabled.length; break; - case 'ArrowLeft': case 'ArrowUp': next = (at - 1 + enabled.length) % enabled.length; break; + case 'ArrowRight': case 'ArrowDown': next = at < 0 ? 0 : (at + 1) % enabled.length; break; + case 'ArrowLeft': case 'ArrowUp': next = at < 0 ? enabled.length - 1 : (at - 1 + enabled.length) % enabled.length; break; case 'Home': next = 0; break; case 'End': next = enabled.length - 1; break; default: return; @@ -108,14 +110,15 @@ export class EpSegmented extends LitElement { const hasSelection = this.options.some((o) => o.value === this.value && !o.disabled); const firstEnabled = this.options.find((o) => !o.disabled)?.value; return html` -
    +
    ${this.options.map((o) => { const checked = o.value === this.value; const tabbable = hasSelection ? checked : o.value === firstEnabled; return html``; diff --git a/src/EpSettings.ts b/src/EpSettings.ts index 5ad5437..8b72227 100644 --- a/src/EpSettings.ts +++ b/src/EpSettings.ts @@ -106,17 +106,57 @@ export class EpSettingsRow extends LitElement { } updated() { - this._nameControl(); + this._syncControl(); } - /** Gives the control the row label as accessible name. */ - private _nameControl() { + private _syncControl() { const control = this._control(); - if (!control || !this.label) return; + if (!control) return; + this._nameControl(control); + this._disableControl(control); + } + + /** + * Gives the control the row label as accessible name. Names set by the row + * are marked with `data-ep-row-label` so they follow label changes (e.g. a + * language switch); names set by the page are left alone. + */ + private _nameControl(control: HTMLElement) { + const ours = control.hasAttribute('data-ep-row-label'); + const label = this.label; + const set = (attr: string) => { + if (label) control.setAttribute(attr, label); + else control.removeAttribute(attr); + if (label) control.setAttribute('data-ep-row-label', attr); + else control.removeAttribute('data-ep-row-label'); + }; if (control.tagName === 'EP-CHECKBOX') { - if (!control.getAttribute('label')) control.setAttribute('accessible-name', this.label); - } else if (!control.hasAttribute('aria-label') && !control.hasAttribute('aria-labelledby')) { - control.setAttribute('aria-label', this.label); + if (ours || (!control.getAttribute('label') && !control.getAttribute('accessible-name'))) set('accessible-name'); + } else if (control.tagName === 'EP-SEGMENTED') { + // Its radiogroup takes the name from the label property. + if (ours || !control.getAttribute('label')) set('label'); + } else if (ours || (!control.hasAttribute('aria-label') && !control.hasAttribute('aria-labelledby'))) { + set('aria-label'); + } + } + + /** + * A disabled row disables its control too (keyboard included). Controls + * that were disabled by the page stay disabled when the row is enabled. + */ + private _disableControl(control: HTMLElement) { + const el = control as HTMLElement & { disabled?: boolean }; + const ours = control.hasAttribute('data-ep-row-disabled'); + if (this.disabled) { + if (!el.disabled && !control.hasAttribute('disabled')) { + if ('disabled' in el) el.disabled = true; + else control.setAttribute('disabled', ''); + control.setAttribute('data-ep-row-disabled', ''); + } + } else if (ours) { + if ('disabled' in el) el.disabled = false; + control.removeAttribute('disabled'); + control.removeAttribute('data-ep-row-disabled'); } } @@ -137,7 +177,7 @@ export class EpSettingsRow extends LitElement {
    ${this.label}
    ${this.description ? html`
    ${this.description}
    ` : nothing}
    -
    +
    `; } } diff --git a/src/EpToolbar.ts b/src/EpToolbar.ts index 3d57822..49e9921 100644 --- a/src/EpToolbar.ts +++ b/src/EpToolbar.ts @@ -255,9 +255,10 @@ export class EpToolbar extends LitElement { /** In compact mode low-priority buttons go to the overflow slot. */ private _placeItems() { - for (const el of Array.from(this.querySelectorAll('[priority="low"]'))) { - if (el.parentElement !== this) continue; - if (this.compact) { + // Current low-priority items plus those moved earlier (their priority may have changed). + for (const el of Array.from(this.children) as HTMLElement[]) { + const eligible = this.compact && el.getAttribute('priority') === 'low'; + if (eligible) { if (el.dataset.homeSlot === undefined) el.dataset.homeSlot = el.getAttribute('slot') ?? ''; if (el.getAttribute('slot') !== 'overflow') el.setAttribute('slot', 'overflow'); } else if (el.dataset.homeSlot !== undefined) { @@ -270,7 +271,14 @@ export class EpToolbar extends LitElement { this._updateRoving(); } - /** Buttons in visual order, without hidden or collapsed ones. */ + private get _more(): EpToolbarButton | null { + return this.renderRoot?.querySelector('.more') ?? null; + } + + /** + * Buttons in visual order, without hidden or collapsed ones. In compact + * mode the "more" button follows the `end` items. + */ get items(): EpToolbarButton[] { const slots = ['', 'end', 'overflow']; const all = Array.from(this.querySelectorAll('ep-toolbar-button')); @@ -278,16 +286,22 @@ export class EpToolbar extends LitElement { const top = Array.from(this.children).find((c) => c === b || c.contains(b)); return slots.indexOf(top?.getAttribute('slot') ?? ''); }; - return all + const visible = all .filter((b) => !b.hidden && !b.closest('[hidden]')) .filter((b) => !(bySlot(b) === 2 && !(this.compact && this.expanded))) .sort((a, b) => bySlot(a) - bySlot(b)); + const more = this._more; + if (!this.compact || !more) return visible; + const firstOverflow = visible.findIndex((b) => bySlot(b) === 2); + if (firstOverflow < 0) return [...visible, more]; + return [...visible.slice(0, firstOverflow), more, ...visible.slice(firstOverflow)]; } private _updateRoving() { const items = this.items; if (this._focusIndex >= items.length) this._focusIndex = Math.max(0, items.length - 1); - for (const b of Array.from(this.querySelectorAll('ep-toolbar-button'))) { + const more = this._more; + for (const b of [...Array.from(this.querySelectorAll('ep-toolbar-button')), ...(more ? [more] : [])]) { b.rovingTabIndex = -1; } if (items[this._focusIndex]) items[this._focusIndex].rovingTabIndex = 0; diff --git a/src/EpUserList.ts b/src/EpUserList.ts index 8a917be..dcfa6a4 100644 --- a/src/EpUserList.ts +++ b/src/EpUserList.ts @@ -104,7 +104,19 @@ export class EpUserList extends LitElement { /** Own name and colour cannot be changed (read-only pad). */ @property({ type: Boolean, reflect: true }) readonly = false; + /** Last name sent or received for the own entry. */ private _committed = ''; + private _lastSelfName: string | undefined; + + protected willUpdate(changed: Map) { + if (!changed.has('users')) return; + const name = this.users.find((u) => u.self)?.name ?? ''; + // Only an actual change of the own name resets the baseline, not every render. + if (name !== this._lastSelfName) { + this._lastSelfName = name; + this._committed = name; + } + } private get _sorted(): EpUser[] { const self = this.users.filter((u) => u.self); @@ -137,7 +149,6 @@ export class EpUserList extends LitElement { } private _renderSelf(u: EpUser) { - this._committed = u.name ?? ''; return html`
  • +
  • +

    Content

    `, + play: async ({ canvasElement }) => { + const popup = canvasElement.querySelector('ep-popup') as EpPopup; + popup.show(); + await popup.updateComplete; + await new Promise((r) => requestAnimationFrame(r)); + const box = popup.getBoundingClientRect(); + await expect(box.right).toBeLessThanOrEqual(document.documentElement.clientWidth - 11); + await expect(box.left).toBeGreaterThanOrEqual(11); + }, +}; + +export const ClosedByTheApp: StoryObj = { + render: (args) => html` + + `, + play: async ({ canvasElement, args }) => { + const popup = canvasElement.querySelector('ep-popup') as EpPopup; + const opener = canvasElement.querySelector('#opener') as HTMLButtonElement; + opener.focus(); + popup.open = true; + await popup.updateComplete; + await new Promise((r) => requestAnimationFrame(r)); + await expect(document.activeElement).toBe(canvasElement.querySelector('#inside')); + // The app sets the property directly. + popup.open = false; + await popup.updateComplete; + await expect(args.onClose).toHaveBeenCalledTimes(1); + await expect(((args.onClose as ReturnType).mock.calls[0][0] as CustomEvent).detail).toEqual({ reason: 'api' }); + await expect(document.activeElement).toBe(opener); + }, +}; + +export const RowSyncsControl: StoryObj = { + render: () => html` + + + + + `, + play: async ({ canvasElement }) => { + const $ = (id: string) => canvasElement.querySelector(`#${id}`) as unknown as T; + const rows = Array.from(canvasElement.querySelectorAll('ep-settings-row')) as Array; label: string; disabled: boolean }>; + await Promise.all(rows.map((r) => r.updateComplete)); + + // Disabled row → disabled control (keyboard too); re-enabling restores it. + const c1 = $('c1'); + await expect(c1.disabled).toBe(true); + rows[0].disabled = false; + await rows[0].updateComplete; + await expect(c1.disabled).toBe(false); + // A control the page disabled stays disabled. + rows[4].disabled = false; + await rows[4].updateComplete; + await expect($('s3').disabled).toBe(true); + + // Labels follow the row label, page labels are kept. + await expect($('s1').getAttribute('aria-label')).toBe('Font'); + rows[1].label = 'Schriftart'; + await rows[1].updateComplete; + await expect($('s1').getAttribute('aria-label')).toBe('Schriftart'); + await expect($('s2').getAttribute('aria-label')).toBe('Page label'); + + // The segmented control's radiogroup gets the row label. + const g1 = $('g1'); + await g1.updateComplete; + await expect(g1.shadowRoot!.querySelector('[role="radiogroup"]')!.getAttribute('aria-label')).toBe('Theme'); + }, +}; + +export const SegmentedEdgeCases: StoryObj = { + render: (args) => html` + + `, + play: async ({ canvasElement, args }) => { + const none = canvasElement.querySelector('#none') as EpSegmented; + await none.updateComplete; + none.focus(); + await userEvent.keyboard('{ArrowLeft}'); + await expect(none.value).toBe('c'); + + const off = canvasElement.querySelector('#off') as EpSegmented; + await off.updateComplete; + const radios = Array.from(off.shadowRoot!.querySelectorAll('[role="radio"]')); + await expect(radios.every((r) => r.disabled)).toBe(true); + radios[0].dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight', bubbles: true })); + await expect(off.value).toBe('a'); + await expect(args.onChange).toHaveBeenCalledTimes(1); + }, +}; diff --git a/stories/EpToolbar.stories.ts b/stories/EpToolbar.stories.ts index 3aca2e4..d478cf7 100644 --- a/stories/EpToolbar.stories.ts +++ b/stories/EpToolbar.stories.ts @@ -105,3 +105,26 @@ export const Compact: Story = { await expect(low.hasAttribute('slot')).toBe(false); }, }; + +export const CompactKeyboardAndPriority: Story = { + render: (args) => bar(args, '420px'), + play: async ({ canvasElement }) => { + const tb = await ready(canvasElement); + const more = tb.shadowRoot!.querySelector('.more') as EpToolbarButton; + // "More" is part of the arrow-key order in compact mode, after the end items. + await expect(tb.items[tb.items.length - 1]).toBe(more); + inner(tb.items[0]).focus(); + await userEvent.keyboard('{End}'); + await expect(more.shadowRoot!.activeElement).toBe(inner(more)); + await expect(inner(more).tabIndex).toBe(0); + await expect(inner(tb.items[0]).tabIndex).toBe(-1); + + // A button that stops being low priority comes back from the overflow row. + const low = tb.querySelector('[key="list"]')!; + await expect(low.getAttribute('slot')).toBe('overflow'); + low.setAttribute('priority', 'normal'); + await new Promise((r) => setTimeout(r, 0)); + await expect(low.hasAttribute('slot')).toBe(false); + await expect(tb.items.includes(low as EpToolbarButton)).toBe(true); + }, +}; diff --git a/stories/EpUserList.stories.ts b/stories/EpUserList.stories.ts index cff1bd7..5ca831f 100644 --- a/stories/EpUserList.stories.ts +++ b/stories/EpUserList.stories.ts @@ -62,3 +62,25 @@ export const ReadOnly: StoryObj = { await expect(list.shadowRoot!.querySelector('.color-btn')!.disabled).toBe(true); }, }; + +export const RenameIsSentOnce: StoryObj = { + render: (args) => html`
    `, + play: async ({ canvasElement, args }) => { + const list = canvasElement.querySelector('ep-user-list') as EpUserList; + await list.updateComplete; + const input = list.shadowRoot!.querySelector('input')!; + input.value = 'New name'; + input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })); + await expect(args.onRename).toHaveBeenCalledTimes(1); + // Unrelated update before the app applied the rename (own name still old). + list.users = users.map((u) => (u.id === 'b' ? { ...u, name: 'Zoey' } : u)); + await list.updateComplete; + input.dispatchEvent(new FocusEvent('blur')); + await expect(args.onRename).toHaveBeenCalledTimes(1); + // The app confirms the new name: no event either. + list.users = users.map((u) => (u.self ? { ...u, name: 'New name' } : u)); + await list.updateComplete; + input.dispatchEvent(new FocusEvent('blur')); + await expect(args.onRename).toHaveBeenCalledTimes(1); + }, +};