@unframed/cli 1.0.0-rc.0 → 1.0.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json
CHANGED
package/registry.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version": "1.0.0-rc.
|
|
2
|
+
"version": "1.0.0-rc.1",
|
|
3
3
|
"components": {
|
|
4
4
|
"accordion": {
|
|
5
5
|
"name": "accordion",
|
|
@@ -851,7 +851,7 @@
|
|
|
851
851
|
"components/avatar/avatar.ts": "import { LitElement, css, html, nothing, type PropertyDeclarations, type PropertyValues } from 'lit';\nimport { defineElement } from '../../internal/define.js';\nimport { iconSvg, icons } from '../../internal/icons.js';\nimport { hostStyles } from '../../internal/shared.styles.js';\n\nexport type AvatarSize = 'sm' | 'md' | 'lg' | 'xl';\nexport type AvatarShape = 'circle' | 'square';\n\n/** \"John Smith\" -> \"JS\", \"john\" -> \"J\". */\nfunction initialsOf(name: string): string {\n const words = name.trim().split(/\\s+/).filter(Boolean);\n const letters = words.length > 1 ? [words[0], words[words.length - 1]] : words;\n return letters.map((w) => [...w][0]?.toUpperCase() ?? '').join('');\n}\n\n/**\n * A picture of a person or an entity. Shows the image when it loads, the\n * initials of `name` when there's no image or it fails, and a generic icon\n * when there's neither.\n *\n * `name` is also the accessible name. When the name is already written next\n * to the avatar, set `decorative` so screen readers don't read it twice.\n *\n * @summary Shows a person's picture, initials or icon.\n * @tag uf-avatar\n *\n * @slot - Custom content instead of the initials or icon, e.g. an `<uf-icon>`.\n *\n * @csspart base - The avatar.\n * @csspart image - The `<img>`.\n * @csspart initials - The initials.\n * @csspart icon - The fallback icon.\n *\n * @cssprop --uf-avatar-size - Width and height. Overrides `size`.\n * @cssprop --uf-avatar-bg - Background behind initials and icon.\n * @cssprop --uf-avatar-color - Color of the initials and icon.\n * @cssprop --uf-avatar-radius - Corner radius. Overrides `shape`.\n */\nexport class UfAvatar extends LitElement {\n static override styles = [\n hostStyles,\n css`\n :host {\n display: inline-flex;\n vertical-align: middle;\n --_size: 2.5rem;\n --_radius: 50%;\n }\n\n :host([size='sm']) {\n --_size: 2rem;\n }\n :host([size='lg']) {\n --_size: 3rem;\n }\n :host([size='xl']) {\n --_size: 4rem;\n }\n :host([shape='square']) {\n --_radius: var(--uf-radius-md);\n }\n\n .base {\n position: relative;\n display: inline-grid;\n place-items: center;\n width: var(--uf-avatar-size, var(--_size));\n height: var(--uf-avatar-size, var(--_size));\n overflow: hidden;\n border-radius: var(--uf-avatar-radius, var(--_radius));\n background: var(--uf-avatar-bg, var(--uf-color-accent-tint));\n color: var(--uf-avatar-color, var(--uf-color-on-accent-tint));\n font-family: var(--uf-font-family-sans);\n /* Initials scale with the avatar. */\n font-size: calc(var(--uf-avatar-size, var(--_size)) * 0.4);\n font-weight: var(--uf-font-weight-semibold);\n line-height: 1;\n user-select: none;\n }\n\n .image {\n width: 100%;\n height: 100%;\n object-fit: cover;\n }\n\n .icon {\n width: 60%;\n height: 60%;\n }\n\n ::slotted(*) {\n font-size: inherit;\n }\n `,\n ];\n\n static override properties: PropertyDeclarations = {\n src: {},\n name: {},\n initials: {},\n size: { reflect: true },\n shape: { reflect: true },\n decorative: { type: Boolean },\n loading: {},\n };\n\n /** Image URL. */\n declare src: string | undefined;\n /** The person's or entity's name: the accessible name, and the source of the initials. */\n declare name: string | undefined;\n /** Initials to show instead of the ones taken from `name`. */\n declare initials: string | undefined;\n /** Size: `sm`, `md`, `lg` or `xl`. */\n declare size: AvatarSize;\n /** `circle` or `square` (rounded corners). */\n declare shape: AvatarShape;\n /** Hides the avatar from assistive tech, when the name is already shown next to it. */\n declare decorative: boolean;\n /** The image's `loading` attribute: `lazy` waits until it's near the viewport. */\n declare loading: 'eager' | 'lazy';\n\n /** The image failed to load: show the fallback. */\n #failed = false;\n\n constructor() {\n super();\n this.size = 'md';\n this.shape = 'circle';\n this.decorative = false;\n this.loading = 'eager';\n }\n\n override willUpdate(changed: PropertyValues<this>): void {\n // A new image gets a new chance to load.\n if (changed.has('src')) this.#failed = false;\n }\n\n override render() {\n const showImage = Boolean(this.src) && !this.#failed;\n const initials = this.initials ?? (this.name ? initialsOf(this.name) : '');\n const labelled = !this.decorative && Boolean(this.name);\n\n return html`<span\n class=\"base\"\n part=\"base\"\n role=${labelled ? 'img' : nothing}\n aria-label=${labelled ? this.name! : nothing}\n aria-hidden=${labelled ? nothing : 'true'}\n >\n ${showImage\n ? html`<img\n class=\"image\"\n part=\"image\"\n src=${this.src!}\n alt=\"\"\n loading=${this.loading}\n @error=${() => {\n this.#failed = true;\n this.requestUpdate();\n }}\n />`\n : html`<slot>\n ${initials\n ? html`<span part=\"initials\">${initials}</span>`\n : iconSvg(icons.user)}\n </slot>`}\n </span>`;\n }\n}\n\ndefineElement('uf-avatar', UfAvatar);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-avatar': UfAvatar;\n }\n}\n",
|
|
852
852
|
"components/badge/badge.ts": "import { LitElement, css, html, type PropertyDeclarations } from 'lit';\nimport { defineElement } from '../../internal/define.js';\nimport { hostStyles } from '../../internal/shared.styles.js';\n\nexport type BadgeVariant = 'neutral' | 'accent' | 'info' | 'success' | 'warning' | 'danger';\nexport type BadgeAppearance = 'soft' | 'solid' | 'outline';\nexport type BadgeSize = 'sm' | 'md' | 'lg';\n\n/**\n * A short label for a status, a category or a count. It's plain text for\n * assistive tech: write text that makes sense out of context (\"3 unread\", not\n * just \"3\"), or describe it in the surrounding element's label.\n *\n * @summary Labels a status, a category or a count.\n * @tag uf-badge\n *\n * @slot - The badge text.\n * @slot prefix - An icon before the text.\n *\n * @csspart base - The badge.\n * @csspart dot - The status dot, when `dot` is set.\n *\n * @cssprop --uf-badge-bg - Background color.\n * @cssprop --uf-badge-color - Text color.\n * @cssprop --uf-badge-border-color - Border color.\n * @cssprop --uf-badge-radius - Corner radius. Use `999px` for a pill.\n */\nexport class UfBadge extends LitElement {\n static override styles = [\n hostStyles,\n css`\n :host {\n display: inline-flex;\n vertical-align: middle;\n --_bg: var(--uf-color-surface-hover);\n --_fg: var(--uf-color-text);\n --_border: transparent;\n }\n\n .base {\n display: inline-flex;\n align-items: center;\n gap: 0.375em;\n min-height: 1.5rem;\n padding: 0 var(--uf-space-2);\n border: 1px solid var(--uf-badge-border-color, var(--_border));\n border-radius: var(--uf-badge-radius, var(--uf-radius-sm));\n background: var(--uf-badge-bg, var(--_bg));\n color: var(--uf-badge-color, var(--_fg));\n font-family: var(--uf-font-family-sans);\n font-size: var(--uf-font-size-sm);\n font-weight: var(--uf-font-weight-medium);\n line-height: 1;\n white-space: nowrap;\n }\n\n :host([size='sm']) .base {\n min-height: 1.25rem;\n padding: 0 var(--uf-space-1);\n font-size: 0.75rem;\n }\n\n :host([size='lg']) .base {\n min-height: 1.75rem;\n padding: 0 var(--uf-space-3);\n font-size: var(--uf-font-size-md);\n }\n\n .dot {\n width: 0.5em;\n height: 0.5em;\n border-radius: 50%;\n background: currentColor;\n }\n\n ::slotted([slot='prefix']) {\n display: inline-flex;\n font-size: 1.1em;\n }\n\n /* Soft (default): a subtle background with strong text. */\n :host([variant='accent']) {\n --_bg: var(--uf-color-accent-tint);\n --_fg: var(--uf-color-on-accent-tint);\n }\n :host([variant='info']) {\n --_bg: var(--uf-color-info-subtle);\n --_fg: var(--uf-color-info);\n }\n :host([variant='success']) {\n --_bg: var(--uf-color-success-subtle);\n --_fg: var(--uf-color-success);\n }\n :host([variant='warning']) {\n --_bg: var(--uf-color-warning-subtle);\n --_fg: var(--uf-color-warning);\n }\n :host([variant='danger']) {\n --_bg: var(--uf-color-danger-subtle);\n --_fg: var(--uf-color-danger-text);\n }\n\n /* Solid: the bold colors of toasts. */\n :host([appearance='solid']) {\n --_bg: var(--uf-color-toast-neutral-bg);\n --_fg: var(--uf-color-toast-neutral-text);\n }\n :host([appearance='solid'][variant='accent']) {\n --_bg: var(--uf-color-accent);\n --_fg: var(--uf-color-on-accent);\n }\n :host([appearance='solid'][variant='info']) {\n --_bg: var(--uf-color-toast-info-bg);\n --_fg: var(--uf-color-toast-info-text);\n }\n :host([appearance='solid'][variant='success']) {\n --_bg: var(--uf-color-toast-success-bg);\n --_fg: var(--uf-color-toast-success-text);\n }\n :host([appearance='solid'][variant='warning']) {\n --_bg: var(--uf-color-toast-warning-bg);\n --_fg: var(--uf-color-toast-warning-text);\n }\n :host([appearance='solid'][variant='danger']) {\n --_bg: var(--uf-color-toast-danger-bg);\n --_fg: var(--uf-color-toast-danger-text);\n }\n\n /* Outline: no fill, the text color as border. */\n :host([appearance='outline']) {\n --_bg: transparent;\n --_border: currentColor;\n }\n :host([appearance='outline'][variant='neutral']) {\n --_border: var(--uf-color-border-strong);\n }\n :host([appearance='outline'][variant='accent']) {\n --_fg: var(--uf-color-accent-strong);\n }\n `,\n ];\n\n static override properties: PropertyDeclarations = {\n variant: { reflect: true },\n appearance: { reflect: true },\n size: { reflect: true },\n dot: { type: Boolean, reflect: true },\n };\n\n /** Color, by meaning: `neutral`, `accent`, `info`, `success`, `warning` or `danger`. */\n declare variant: BadgeVariant;\n /** `soft` (tinted background), `solid` (bold background) or `outline` (border only). */\n declare appearance: BadgeAppearance;\n /** Size: `sm`, `md` or `lg`. */\n declare size: BadgeSize;\n /** Shows a status dot before the text. */\n declare dot: boolean;\n\n constructor() {\n super();\n this.variant = 'neutral';\n this.appearance = 'soft';\n this.size = 'md';\n this.dot = false;\n }\n\n override render() {\n return html`<span class=\"base\" part=\"base\">\n ${this.dot ? html`<span class=\"dot\" part=\"dot\" aria-hidden=\"true\"></span>` : null}\n <slot name=\"prefix\"></slot>\n <slot></slot>\n </span>`;\n }\n}\n\ndefineElement('uf-badge', UfBadge);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-badge': UfBadge;\n }\n}\n",
|
|
853
853
|
"components/breadcrumbs/breadcrumbs.ts": "import { LitElement, css, html, nothing, type PropertyDeclarations } from 'lit';\nimport { ifDefined } from 'lit/directives/if-defined.js';\nimport { defineElement } from '../../internal/define.js';\nimport { Translator } from '../../internal/i18n.js';\nimport { iconSvg, icons } from '../../internal/icons.js';\nimport { focusRing, hostStyles } from '../../internal/shared.styles.js';\n\n/**\n * One step of a breadcrumb trail, inside `<uf-breadcrumbs>`. The last item is\n * the current page: plain text, announced as the current page.\n *\n * @summary A step in a breadcrumb trail.\n * @tag uf-breadcrumb-item\n *\n * @slot - The label.\n * @slot prefix - An icon before the label.\n * @slot separator - Set by `<uf-breadcrumbs>`; you don't need it yourself.\n *\n * @csspart link - The link, for items with `href`.\n * @csspart label - The current page's label, or an item without `href`.\n * @csspart separator - The separator after the item.\n */\nexport class UfBreadcrumbItem extends LitElement {\n static override styles = [\n hostStyles,\n css`\n :host {\n display: inline-flex;\n align-items: center;\n min-width: 0;\n }\n\n .link,\n .label {\n display: inline-flex;\n align-items: center;\n gap: var(--uf-space-1);\n min-width: 0;\n border-radius: var(--uf-radius-sm);\n }\n\n .link {\n color: var(--uf-color-text-muted);\n text-decoration: none;\n }\n\n .link:hover {\n color: var(--uf-color-text);\n text-decoration: underline;\n }\n\n .link:focus-visible {\n ${focusRing}\n }\n\n .label {\n color: var(--uf-color-text);\n }\n\n :host([current]) .label {\n font-weight: var(--uf-font-weight-medium);\n }\n\n .separator {\n display: inline-flex;\n margin: 0 var(--uf-space-2);\n color: var(--uf-color-text-muted);\n }\n\n .separator .icon {\n width: 1em;\n height: 1em;\n }\n\n ::slotted([slot='prefix']) {\n display: inline-flex;\n }\n `,\n ];\n\n static override properties: PropertyDeclarations = {\n href: {},\n target: {},\n current: { type: Boolean, reflect: true },\n };\n\n /** Link to this step. */\n declare href: string | undefined;\n /** Link target, used with `href`. */\n declare target: string | undefined;\n /** The current page. `<uf-breadcrumbs>` sets it on the last item. */\n declare current: boolean;\n\n constructor() {\n super();\n this.current = false;\n }\n\n override connectedCallback(): void {\n super.connectedCallback();\n this.setAttribute('role', 'listitem');\n }\n\n override render() {\n const content = html`<slot name=\"prefix\"></slot><slot></slot>`;\n return html`\n ${this.href && !this.current\n ? html`<a class=\"link\" part=\"link\" href=${this.href} target=${ifDefined(this.target)}>${content}</a>`\n : html`<span class=\"label\" part=\"label\" aria-current=${ifDefined(this.current ? 'page' : undefined)}>${content}</span>`}\n ${this.current\n ? nothing\n : html`<span class=\"separator\" part=\"separator\" aria-hidden=\"true\"><slot name=\"separator\">${iconSvg(icons['chevron-right'])}</slot></span>`}\n `;\n }\n}\n\n/**\n * Shows where the current page sits in the site: a trail of links, from the\n * top level to here. It's a navigation landmark with a list inside, and the\n * last item is marked as the current page.\n *\n * @summary Shows the path to the current page.\n * @tag uf-breadcrumbs\n *\n * @slot - `<uf-breadcrumb-item>` elements.\n * @slot separator - A custom separator, e.g. `<span slot=\"separator\">/</span>`. Copied between the items.\n *\n * @csspart base - The `<nav>` element.\n * @csspart list - The list of items.\n */\nexport class UfBreadcrumbs extends LitElement {\n static override styles = [\n hostStyles,\n css`\n :host {\n display: block;\n }\n\n .list {\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n row-gap: var(--uf-space-1);\n font-family: var(--uf-font-family-sans);\n font-size: var(--uf-font-size-sm);\n line-height: 1.5;\n }\n\n slot[name='separator'] {\n display: none;\n }\n `,\n ];\n\n static override properties: PropertyDeclarations = {\n label: {},\n };\n\n /** Accessible name of the navigation. Defaults to \"Breadcrumb\", in the page's language. */\n declare label: string | undefined;\n\n readonly #translator = new Translator(this);\n\n get #items(): UfBreadcrumbItem[] {\n return [...this.children].filter((el): el is UfBreadcrumbItem => el.localName === 'uf-breadcrumb-item');\n }\n\n /** Marks the last item as current, and copies a custom separator into the others. */\n #sync = (): void => {\n const items = this.#items;\n const separator = this.querySelector<HTMLElement>(':scope > [slot=\"separator\"]');\n items.forEach((item, i) => {\n item.current = i === items.length - 1;\n item.querySelectorAll(':scope > [data-uf-separator]').forEach((copy) => copy.remove());\n if (separator && !item.current) {\n const copy = separator.cloneNode(true) as HTMLElement;\n copy.setAttribute('data-uf-separator', '');\n item.append(copy);\n }\n });\n };\n\n override render() {\n return html`\n <nav part=\"base\" aria-label=${this.label || this.#translator.t('breadcrumb')}>\n <div class=\"list\" part=\"list\" role=\"list\"><slot @slotchange=${this.#sync}></slot></div>\n </nav>\n <slot name=\"separator\" @slotchange=${this.#sync}></slot>\n `;\n }\n}\n\ndefineElement('uf-breadcrumb-item', UfBreadcrumbItem);\ndefineElement('uf-breadcrumbs', UfBreadcrumbs);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-breadcrumb-item': UfBreadcrumbItem;\n 'uf-breadcrumbs': UfBreadcrumbs;\n }\n}\n",
|
|
854
|
-
"components/button/button.ts": "import { LitElement, html, nothing, type PropertyDeclarations } from 'lit';\nimport { classMap } from 'lit/directives/class-map.js';\nimport { ifDefined } from 'lit/directives/if-defined.js';\nimport { defineElement } from '../../internal/define.js';\nimport { buttonStyles } from './button.styles.js';\n\nexport type ButtonVariant = 'primary' | 'secondary' | 'outline' | 'ghost' | 'danger' | 'link';\nexport type ButtonSize = 'sm' | 'md' | 'lg';\nexport type ButtonType = 'button' | 'submit' | 'reset';\n\n/**\n * A button that works like a native `<button>`, inside or outside a form,\n * or renders as a link when `href` is set.\n *\n * @summary Triggers an action or navigates to a URL.\n * @tag uf-button\n *\n * @slot - The button's label.\n * @slot prefix - An icon or element before the label.\n * @slot suffix - An icon or element after the label.\n *\n * ARIA state set on the host (`aria-expanded`, `aria-haspopup`, `aria-pressed`,\n * `aria-current`, `aria-description`) is forwarded to the inner button, so\n * popovers, tooltips and toggle patterns work with it like with a native button.\n *\n * @csspart base - The inner `<button>` or `<a>`.\n * @csspart label - The wrapper around the default slot.\n * @csspart prefix - The prefix slot.\n * @csspart suffix - The suffix slot.\n * @csspart spinner - The loading spinner.\n *\n * @cssprop --uf-button-bg - Background color (all states unless overridden).\n * @cssprop --uf-button-bg-hover - Background color on hover.\n * @cssprop --uf-button-bg-active - Background color while pressed.\n * @cssprop --uf-button-color - Text color.\n * @cssprop --uf-button-border-color - Border color.\n * @cssprop --uf-button-radius - Corner radius.\n * @cssprop --uf-button-height - Height.\n * @cssprop --uf-button-padding - Horizontal padding.\n * @cssprop --uf-button-gap - Space between prefix, label and suffix.\n * @cssprop --uf-button-font-family - Font family.\n * @cssprop --uf-button-font-weight - Font weight.\n */\nexport class UfButton extends LitElement {\n static override styles = buttonStyles;\n static override shadowRootOptions = { ...LitElement.shadowRootOptions, delegatesFocus: true };\n static formAssociated = true;\n\n static override properties: PropertyDeclarations = {\n variant: { reflect: true },\n size: { reflect: true },\n type: { reflect: true },\n disabled: { type: Boolean, reflect: true },\n loading: { type: Boolean, reflect: true },\n label: {},\n href: {},\n target: {},\n rel: {},\n download: {},\n };\n\n /** Visual style. */\n declare variant: ButtonVariant;\n /** Size of the button. */\n declare size: ButtonSize;\n /** Behaviour inside a form. Defaults to `button` so it never submits by accident. */\n declare type: ButtonType;\n /** Disables the button. */\n declare disabled: boolean;\n /** Shows a spinner and ignores clicks, while keeping the button focusable. */\n declare loading: boolean;\n /** Accessible name, for icon-only buttons. */\n declare label: string | undefined;\n /** Renders the button as a link to this URL. */\n declare href: string | undefined;\n /** Link target, used with `href`. */\n declare target: string | undefined;\n /** Link rel, used with `href`. Defaults to `noreferrer noopener` when `target=\"_blank\"`. */\n declare rel: string | undefined;\n /** Download filename, used with `href`. */\n declare download: string | undefined;\n static #forwardedAria = ['aria-expanded', 'aria-haspopup', 'aria-pressed', 'aria-current', 'aria-description'];\n\n readonly #internals = this.attachInternals();\n /** True when the default slot has no text or elements: an icon-only button. */\n #iconOnly = false;\n readonly #ariaObserver = new MutationObserver(() => this.requestUpdate());\n /** Set when an ancestor `<fieldset disabled>` disables the button. */\n #formDisabled = false;\n\n constructor() {\n super();\n this.variant = 'primary';\n this.size = 'md';\n this.type = 'button';\n this.disabled = false;\n this.loading = false;\n // Registered first, so it runs before any listener a consumer adds.\n this.addEventListener('click', this.#handleClick);\n }\n\n override connectedCallback(): void {\n super.connectedCallback();\n this.#ariaObserver.observe(this, { attributes: true, attributeFilter: UfButton.#forwardedAria });\n }\n\n override disconnectedCallback(): void {\n super.disconnectedCallback();\n this.#ariaObserver.disconnect();\n }\n\n #aria(name: string): string | undefined {\n return this.getAttribute(name) ?? undefined;\n }\n\n /**\n * Whether the default slot gets text or elements, read from the children so it's\n * known before rendering: checking the slot after a render would render twice.\n */\n #hasLabel(): boolean {\n return [...this.childNodes].some((node) => {\n if (node instanceof HTMLSlotElement && !node.slot) return node.assignedNodes({ flatten: true }).some((n) => n.nodeType === Node.ELEMENT_NODE || n.textContent?.trim());\n if (node.nodeType === Node.ELEMENT_NODE) return !(node as Element).slot;\n return node.nodeType === Node.TEXT_NODE && Boolean(node.textContent?.trim());\n });\n }\n\n override willUpdate(): void {\n this.#iconOnly = !this.#hasLabel();\n }\n\n #onLabelChange = (): void => {\n if (this.#iconOnly === this.#hasLabel()) this.requestUpdate();\n };\n\n /** The form this button belongs to, if any. */\n get form(): HTMLFormElement | null {\n return this.#internals.form;\n }\n\n /** @internal */\n formDisabledCallback(disabled: boolean): void {\n this.#formDisabled = disabled;\n this.requestUpdate();\n }\n\n get #isDisabled(): boolean {\n return this.disabled || this.#formDisabled;\n }\n\n #handleClick = (event: MouseEvent): void => {\n if (this.#isDisabled || this.loading) {\n event.preventDefault();\n event.stopImmediatePropagation();\n return;\n }\n if (this.href) return;\n\n const form = this.#internals.form;\n if (this.type === 'submit') form?.requestSubmit();\n else if (this.type === 'reset') form?.reset();\n };\n\n override render() {\n const disabled = this.#isDisabled;\n const classes = classMap({ base: true, disabled, loading: this.loading, 'icon-only': this.#iconOnly });\n const content = html`\n <slot name=\"prefix\" part=\"prefix\"></slot>\n <span class=\"label\" part=\"label\"><slot @slotchange=${this.#onLabelChange}></slot></span>\n <slot name=\"suffix\" part=\"suffix\"></slot>\n ${this.loading ? html`<span class=\"spinner\" part=\"spinner\" aria-hidden=\"true\"></span>` : nothing}\n `;\n\n if (this.href) {\n const rel = this.rel ?? (this.target === '_blank' ? 'noreferrer noopener' : undefined);\n return html`<a\n part=\"base\"\n class=${classes}\n href=${ifDefined(disabled ? undefined : this.href)}\n target=${ifDefined(disabled ? undefined : this.target)}\n rel=${ifDefined(rel)}\n download=${ifDefined(this.download)}\n role=${ifDefined(disabled ? 'link' : undefined)}\n tabindex=${ifDefined(disabled ? '0' : undefined)}\n aria-disabled=${ifDefined(disabled ? 'true' : undefined)}\n aria-busy=${ifDefined(this.loading ? 'true' : undefined)}\n aria-label=${ifDefined(this.label)}\n aria-current=${ifDefined(this.#aria('aria-current'))}\n aria-description=${ifDefined(this.#aria('aria-description'))}\n >${content}</a\n >`;\n }\n\n return html`<button\n part=\"base\"\n class=${classes}\n type=\"button\"\n ?disabled=${disabled}\n aria-disabled=${ifDefined(this.loading ? 'true' : undefined)}\n aria-busy=${ifDefined(this.loading ? 'true' : undefined)}\n aria-label=${ifDefined(this.label)}\n aria-expanded=${ifDefined(this.#aria('aria-expanded'))}\n aria-haspopup=${ifDefined(this.#aria('aria-haspopup') as 'true' | undefined)}\n aria-pressed=${ifDefined(this.#aria('aria-pressed'))}\n aria-description=${ifDefined(this.#aria('aria-description'))}\n >\n ${content}\n </button>`;\n }\n}\n\ndefineElement('uf-button', UfButton);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-button': UfButton;\n }\n}\n",
|
|
854
|
+
"components/button/button.ts": "import { LitElement, html, nothing, type PropertyDeclarations } from 'lit';\nimport { classMap } from 'lit/directives/class-map.js';\nimport { ifDefined } from 'lit/directives/if-defined.js';\nimport { defineElement } from '../../internal/define.js';\nimport { buttonStyles } from './button.styles.js';\n\nexport type ButtonVariant = 'primary' | 'secondary' | 'outline' | 'ghost' | 'danger' | 'link';\nexport type ButtonSize = 'sm' | 'md' | 'lg';\nexport type ButtonType = 'button' | 'submit' | 'reset';\n\n/**\n * A button that works like a native `<button>`, inside or outside a form,\n * or renders as a link when `href` is set.\n *\n * @summary Triggers an action or navigates to a URL.\n * @tag uf-button\n *\n * @slot - The button's label.\n * @slot prefix - An icon or element before the label.\n * @slot suffix - An icon or element after the label.\n *\n * ARIA state set on the host (`aria-expanded`, `aria-haspopup`, `aria-pressed`,\n * `aria-current`, `aria-description`) is forwarded to the inner button, so\n * popovers, tooltips and toggle patterns work with it like with a native button.\n *\n * @csspart base - The inner `<button>` or `<a>`.\n * @csspart label - The wrapper around the default slot.\n * @csspart prefix - The prefix slot.\n * @csspart suffix - The suffix slot.\n * @csspart spinner - The loading spinner.\n *\n * @cssprop --uf-button-bg - Background color (all states unless overridden).\n * @cssprop --uf-button-bg-hover - Background color on hover.\n * @cssprop --uf-button-bg-active - Background color while pressed.\n * @cssprop --uf-button-color - Text color.\n * @cssprop --uf-button-border-color - Border color.\n * @cssprop --uf-button-radius - Corner radius.\n * @cssprop --uf-button-height - Height.\n * @cssprop --uf-button-padding - Horizontal padding.\n * @cssprop --uf-button-gap - Space between prefix, label and suffix.\n * @cssprop --uf-button-font-family - Font family.\n * @cssprop --uf-button-font-weight - Font weight.\n */\nexport class UfButton extends LitElement {\n static override styles = buttonStyles;\n static override shadowRootOptions = { ...LitElement.shadowRootOptions, delegatesFocus: true };\n static formAssociated = true;\n\n static override properties: PropertyDeclarations = {\n variant: { reflect: true },\n size: { reflect: true },\n type: { reflect: true },\n disabled: { type: Boolean, reflect: true },\n loading: { type: Boolean, reflect: true },\n label: {},\n href: {},\n target: {},\n rel: {},\n download: {},\n };\n\n /** Visual style. */\n declare variant: ButtonVariant;\n /** Size of the button. */\n declare size: ButtonSize;\n /** Behaviour inside a form. Defaults to `button` so it never submits by accident. */\n declare type: ButtonType;\n /** Disables the button. */\n declare disabled: boolean;\n /** Shows a spinner and ignores clicks, while keeping the button focusable. */\n declare loading: boolean;\n /** Accessible name, for icon-only buttons. */\n declare label: string | undefined;\n /** Renders the button as a link to this URL. */\n declare href: string | undefined;\n /** Link target, used with `href`. */\n declare target: string | undefined;\n /** Link rel, used with `href`. Defaults to `noreferrer noopener` when `target=\"_blank\"`. */\n declare rel: string | undefined;\n /** Download filename, used with `href`. */\n declare download: string | undefined;\n static #forwardedAria = ['aria-expanded', 'aria-haspopup', 'aria-pressed', 'aria-current', 'aria-description'];\n\n readonly #internals = this.attachInternals();\n /** True when the default slot has no text or elements: an icon-only button. */\n #iconOnly = false;\n readonly #ariaObserver = new MutationObserver(() => this.requestUpdate());\n /** Set when an ancestor `<fieldset disabled>` disables the button. */\n #formDisabled = false;\n\n constructor() {\n super();\n this.variant = 'primary';\n this.size = 'md';\n this.type = 'button';\n this.disabled = false;\n this.loading = false;\n // Registered first, so it runs before any listener a consumer adds.\n this.addEventListener('click', this.#handleClick);\n }\n\n override connectedCallback(): void {\n super.connectedCallback();\n this.#ariaObserver.observe(this, { attributes: true, attributeFilter: UfButton.#forwardedAria });\n }\n\n override disconnectedCallback(): void {\n super.disconnectedCallback();\n this.#ariaObserver.disconnect();\n }\n\n #aria(name: string): string | undefined {\n return this.getAttribute(name) ?? undefined;\n }\n\n /**\n * Whether the default slot gets text or elements, read from the children so it's\n * known before rendering: checking the slot after a render would render twice.\n */\n #hasLabel(): boolean {\n return [...this.childNodes].some((node) => {\n if (node instanceof HTMLSlotElement && !node.slot) return node.assignedNodes({ flatten: true }).some((n) => n.nodeType === Node.ELEMENT_NODE || n.textContent?.trim());\n if (node.nodeType === Node.ELEMENT_NODE) return !(node as Element).slot;\n return node.nodeType === Node.TEXT_NODE && Boolean(node.textContent?.trim());\n });\n }\n\n override willUpdate(): void {\n this.#iconOnly = !this.#hasLabel();\n }\n\n #onLabelChange = (): void => {\n if (this.#iconOnly === this.#hasLabel()) this.requestUpdate();\n };\n\n /** The form this button belongs to, if any. */\n get form(): HTMLFormElement | null {\n return this.#internals.form;\n }\n\n /** @internal */\n formDisabledCallback(disabled: boolean): void {\n this.#formDisabled = disabled;\n // The browser also calls this when an update adds or removes the element's own\n // `disabled` attribute, after render. Lit drops a request made during an update,\n // so the control would stay disabled: ask again once the update is done.\n if (this.isUpdatePending) void this.updateComplete.then(() => this.requestUpdate());\n else this.requestUpdate();\n }\n\n get #isDisabled(): boolean {\n return this.disabled || this.#formDisabled;\n }\n\n #handleClick = (event: MouseEvent): void => {\n if (this.#isDisabled || this.loading) {\n event.preventDefault();\n event.stopImmediatePropagation();\n return;\n }\n if (this.href) return;\n\n const form = this.#internals.form;\n if (this.type === 'submit') form?.requestSubmit();\n else if (this.type === 'reset') form?.reset();\n };\n\n override render() {\n const disabled = this.#isDisabled;\n const classes = classMap({ base: true, disabled, loading: this.loading, 'icon-only': this.#iconOnly });\n const content = html`\n <slot name=\"prefix\" part=\"prefix\"></slot>\n <span class=\"label\" part=\"label\"><slot @slotchange=${this.#onLabelChange}></slot></span>\n <slot name=\"suffix\" part=\"suffix\"></slot>\n ${this.loading ? html`<span class=\"spinner\" part=\"spinner\" aria-hidden=\"true\"></span>` : nothing}\n `;\n\n if (this.href) {\n const rel = this.rel ?? (this.target === '_blank' ? 'noreferrer noopener' : undefined);\n return html`<a\n part=\"base\"\n class=${classes}\n href=${ifDefined(disabled ? undefined : this.href)}\n target=${ifDefined(disabled ? undefined : this.target)}\n rel=${ifDefined(rel)}\n download=${ifDefined(this.download)}\n role=${ifDefined(disabled ? 'link' : undefined)}\n tabindex=${ifDefined(disabled ? '0' : undefined)}\n aria-disabled=${ifDefined(disabled ? 'true' : undefined)}\n aria-busy=${ifDefined(this.loading ? 'true' : undefined)}\n aria-label=${ifDefined(this.label)}\n aria-current=${ifDefined(this.#aria('aria-current'))}\n aria-description=${ifDefined(this.#aria('aria-description'))}\n >${content}</a\n >`;\n }\n\n return html`<button\n part=\"base\"\n class=${classes}\n type=\"button\"\n ?disabled=${disabled}\n aria-disabled=${ifDefined(this.loading ? 'true' : undefined)}\n aria-busy=${ifDefined(this.loading ? 'true' : undefined)}\n aria-label=${ifDefined(this.label)}\n aria-expanded=${ifDefined(this.#aria('aria-expanded'))}\n aria-haspopup=${ifDefined(this.#aria('aria-haspopup') as 'true' | undefined)}\n aria-pressed=${ifDefined(this.#aria('aria-pressed'))}\n aria-description=${ifDefined(this.#aria('aria-description'))}\n >\n ${content}\n </button>`;\n }\n}\n\ndefineElement('uf-button', UfButton);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-button': UfButton;\n }\n}\n",
|
|
855
855
|
"components/button/button.styles.ts": "import { css } from 'lit';\nimport { focusRing, hostStyles } from '../../internal/shared.styles.js';\n\nexport const buttonStyles = [\n hostStyles,\n css`\n :host {\n display: inline-block;\n --_height: var(--uf-size-control-md);\n --_padding: var(--uf-space-4);\n --_font-size: var(--uf-font-size-md);\n --_bg: var(--uf-color-accent);\n --_bg-hover: var(--uf-color-accent-hover);\n --_bg-active: var(--uf-color-accent-active);\n --_fg: var(--uf-color-on-accent);\n --_border: transparent;\n }\n\n :host([size='sm']) {\n --_height: var(--uf-size-control-sm);\n --_padding: var(--uf-space-3);\n --_font-size: var(--uf-font-size-sm);\n }\n\n :host([size='lg']) {\n --_height: var(--uf-size-control-lg);\n --_padding: var(--uf-space-5);\n --_font-size: var(--uf-font-size-lg);\n }\n\n /* Grey at rest, so it never looks like a faded (disabled) primary; accent tint on hover, like outline and ghost. */\n :host([variant='secondary']) {\n --_bg: var(--uf-color-neutral-fill);\n --_bg-hover: var(--uf-color-accent-tint);\n --_bg-active: var(--uf-color-accent-tint-hover);\n --_fg: var(--uf-color-text);\n --_fg-hover: var(--uf-color-on-accent-tint);\n }\n\n :host([variant='outline']) {\n --_bg: transparent;\n --_bg-hover: var(--uf-color-accent-tint);\n --_bg-active: var(--uf-color-accent-tint-hover);\n --_fg: var(--uf-color-on-accent-tint);\n --_border: var(--uf-color-accent-strong);\n }\n\n :host([variant='ghost']) {\n --_bg: transparent;\n --_bg-hover: var(--uf-color-accent-tint);\n --_bg-active: var(--uf-color-accent-tint-hover);\n --_fg: var(--uf-color-text);\n --_fg-hover: var(--uf-color-on-accent-tint);\n }\n\n :host([variant='danger']) {\n --_bg: var(--uf-color-danger);\n --_bg-hover: var(--uf-color-danger-hover);\n --_bg-active: var(--uf-color-danger-hover);\n --_fg: var(--uf-color-on-danger);\n }\n\n /* Looks like a text link: no fill, no side padding (lines up with text), underline on hover.\n After the size rules, so its padding wins. */\n :host([variant='link']) {\n --_bg: transparent;\n --_bg-hover: transparent;\n --_bg-active: transparent;\n --_fg: var(--uf-color-accent-strong);\n --_padding: 0;\n }\n\n :host([variant='link']) .base:hover:not(.disabled),\n :host([variant='link']) .base:focus-visible {\n text-decoration: underline;\n text-underline-offset: 0.2em;\n }\n\n .base {\n position: relative;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n gap: var(--uf-button-gap, var(--uf-space-2));\n width: 100%;\n height: var(--uf-button-height, var(--_height));\n padding: 0 var(--uf-button-padding, var(--_padding));\n border: 1px solid var(--uf-button-border-color, var(--_border));\n /* In a <uf-button-group>: one border between neighbors, square inner corners. */\n border-width: var(--_uf-group-border-width, 1px);\n border-radius: var(--_uf-group-radius, var(--uf-button-radius, var(--uf-radius-control)));\n background: var(--uf-button-bg, var(--_bg));\n color: var(--uf-button-color, var(--_fg));\n font-family: var(--uf-button-font-family, var(--uf-font-family-sans));\n font-size: var(--_font-size);\n font-weight: var(--uf-button-font-weight, var(--uf-font-weight-medium));\n line-height: 1;\n white-space: nowrap;\n text-decoration: none;\n cursor: pointer;\n user-select: none;\n -webkit-tap-highlight-color: transparent;\n transition:\n background-color var(--uf-duration-fast) ease,\n border-color var(--uf-duration-fast) ease,\n color var(--uf-duration-fast) ease;\n }\n\n /* Icon-only: no empty label (its gaps pushed the icon off-center), and square. */\n /* In a <uf-button-group>: a line between buttons with no border to share, filled or ghost. */\n :host(:not([variant='outline'], [variant='link'])) .base {\n box-shadow: var(--_uf-group-divider, none);\n }\n\n .base.icon-only {\n width: var(--uf-button-height, var(--_height));\n padding: 0;\n }\n\n .base.icon-only .label {\n display: none;\n }\n\n /* No hover or pressed look on a disabled (or loading) button: it can't be used. */\n .base:hover:not(.disabled, .loading) {\n background: var(--uf-button-bg-hover, var(--_bg-hover));\n color: var(--uf-button-color, var(--_fg-hover, var(--_fg)));\n }\n\n .base:active:not(.disabled, .loading) {\n background: var(--uf-button-bg-active, var(--_bg-active));\n }\n\n .base:focus-visible {\n ${focusRing}\n }\n\n .base.disabled {\n opacity: 0.5;\n cursor: not-allowed;\n }\n\n .base.loading {\n cursor: progress;\n }\n\n /* opacity, not visibility, so the label stays in the accessibility tree. */\n .base.loading .label,\n .base.loading ::slotted(*) {\n opacity: 0;\n }\n\n ::slotted(svg) {\n width: 1em;\n height: 1em;\n flex: none;\n }\n\n .spinner {\n position: absolute;\n inset: 0;\n margin: auto;\n width: 1em;\n height: 1em;\n border: 2px solid currentColor;\n border-right-color: transparent;\n border-radius: 50%;\n animation: spin 0.6s linear infinite;\n }\n\n @media (prefers-reduced-motion: reduce) {\n .spinner {\n animation-duration: 1.5s;\n }\n }\n\n @keyframes spin {\n to {\n transform: rotate(360deg);\n }\n }\n `,\n];\n",
|
|
856
856
|
"components/button-group/button-group.ts": "import { LitElement, css, html, type PropertyDeclarations } from 'lit';\nimport { defineElement } from '../../internal/define.js';\nimport { hostStyles } from '../../internal/shared.styles.js';\n\nexport type ButtonGroupOrientation = 'horizontal' | 'vertical';\n\n/**\n * Related buttons joined into one bar, like \"Bold / Italic / Underline\" or\n * \"Save\" with a menu of other ways to save. For one choice among a few, use\n * `<uf-segmented-control>` instead.\n *\n * Neighbors share one border, and only the outer corners are rounded. Filled\n * and ghost buttons get a thin line between them. Buttons can be wrapped, in a\n * `<uf-tooltip>` or as the trigger of a `<uf-dropdown>`, and stay joined.\n *\n * It's a group for assistive tech: give it a `label` that says what the\n * buttons have in common.\n *\n * @summary Joins related buttons into one bar.\n * @tag uf-button-group\n *\n * @slot - `<uf-button>` elements, alone or wrapped in a tooltip or dropdown.\n */\nexport class UfButtonGroup extends LitElement {\n static override styles = [\n hostStyles,\n css`\n :host {\n --_radius: var(--uf-button-radius, var(--uf-radius-control));\n --_divider: color-mix(in srgb, currentColor 30%, transparent);\n display: inline-flex;\n vertical-align: middle;\n }\n\n :host([orientation='vertical']) {\n flex-direction: column;\n }\n\n /*\n * The buttons read these private properties. Custom properties pass through\n * wrappers, so a button inside a tooltip or a dropdown gets them too.\n * A button on its own keeps its corners.\n */\n ::slotted(:not(:first-child):not(:last-child)) {\n --_uf-group-radius: 0;\n }\n\n ::slotted(:first-child:not(:last-child)) {\n --_uf-group-radius: var(--_radius) 0 0 var(--_radius);\n }\n\n ::slotted(:last-child:not(:first-child)) {\n --_uf-group-radius: 0 var(--_radius) var(--_radius) 0;\n }\n\n /* One border between neighbors, and a line between filled and ghost buttons. */\n ::slotted(:not(:first-child)) {\n --_uf-group-border-width: 1px 1px 1px 0;\n --_uf-group-divider: inset 1px 0 0 var(--_divider);\n }\n\n :host(:dir(rtl)) ::slotted(:first-child:not(:last-child)) {\n --_uf-group-radius: 0 var(--_radius) var(--_radius) 0;\n }\n\n :host(:dir(rtl)) ::slotted(:last-child:not(:first-child)) {\n --_uf-group-radius: var(--_radius) 0 0 var(--_radius);\n }\n\n :host(:dir(rtl)) ::slotted(:not(:first-child)) {\n --_uf-group-border-width: 1px 0 1px 1px;\n --_uf-group-divider: inset -1px 0 0 var(--_divider);\n }\n\n /* After the RTL rules: a vertical group is the same in both directions. */\n :host([orientation='vertical']) ::slotted(:first-child:not(:last-child)) {\n --_uf-group-radius: var(--_radius) var(--_radius) 0 0;\n }\n\n :host([orientation='vertical']) ::slotted(:last-child:not(:first-child)) {\n --_uf-group-radius: 0 0 var(--_radius) var(--_radius);\n }\n\n :host([orientation='vertical']) ::slotted(:not(:first-child)) {\n --_uf-group-border-width: 0 1px 1px;\n --_uf-group-divider: inset 0 1px 0 var(--_divider);\n }\n\n /* The focus ring above the neighbors, not under the next button. */\n ::slotted(:focus-within) {\n position: relative;\n z-index: 1;\n }\n `,\n ];\n\n static override properties: PropertyDeclarations = {\n label: {},\n orientation: { reflect: true },\n };\n\n /** What the buttons have in common, for assistive tech. */\n declare label: string | undefined;\n /** Side by side, or stacked. */\n declare orientation: ButtonGroupOrientation;\n\n constructor() {\n super();\n this.orientation = 'horizontal';\n }\n\n override connectedCallback(): void {\n super.connectedCallback();\n this.setAttribute('role', 'group');\n }\n\n override updated(): void {\n if (this.label) this.setAttribute('aria-label', this.label);\n else this.removeAttribute('aria-label');\n }\n\n override render() {\n return html`<slot></slot>`;\n }\n}\n\ndefineElement('uf-button-group', UfButtonGroup);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-button-group': UfButtonGroup;\n }\n}\n",
|
|
857
857
|
"components/calendar/calendar.ts": "import { LitElement, css, html, nothing, type PropertyDeclarations, type PropertyValues } from 'lit';\nimport { classMap } from 'lit/directives/class-map.js';\nimport { addDays, addMonths, clamp, firstDayOfWeek, formatter, parseIso, startOfMonth, toIso, todayIso } from '../../internal/dates.js';\nimport { defineElement } from '../../internal/define.js';\nimport { Translator } from '../../internal/i18n.js';\nimport { iconSvg, icons } from '../../internal/icons.js';\nimport { focusRing, hostStyles } from '../../internal/shared.styles.js';\nimport { uniqueId } from '../../internal/slot.js';\n\n/**\n * A month grid to pick a date. Arrow keys move by day and week, Page Up and\n * Page Down by month (with Shift, by year), Home and End to the start and end\n * of the week, Enter or Space selects. Month and weekday names, and the first\n * day of the week, follow the nearest `lang` attribute.\n *\n * With `range`, it picks a start and an end date instead: the first pick sets\n * `start`, the second `end` (swapped if it's earlier), with the days between\n * highlighted as the pointer or keyboard moves.\n *\n * Use it inline, e.g. for a booking page. For a form field, use\n * `<uf-date-picker>` or `<uf-date-range-picker>`, which open one in a popup.\n *\n * @summary Shows a month to pick a date from.\n * @tag uf-calendar\n *\n * @event change - The user picked a date (read `value`), or, with `range`, completed a range (read `start` and `end`).\n *\n * @csspart base - The calendar.\n * @csspart header - The month title and the previous and next buttons.\n * @csspart title - The month and year.\n * @csspart nav-button - The previous and next month buttons.\n * @csspart grid - The `<table>` of days.\n * @csspart weekday - A weekday heading.\n * @csspart day - Every day.\n * @csspart selected - The selected day.\n * @csspart today - Today.\n * @csspart range-start - With `range`, the start date.\n * @csspart range-end - With `range`, the end date.\n * @csspart in-range - With `range`, a day between the start and the end.\n *\n * @cssprop --uf-calendar-day-size - Width and height of a day.\n */\nexport class UfCalendar extends LitElement {\n static override styles = [\n hostStyles,\n css`\n :host {\n display: inline-block;\n --_day: var(--uf-calendar-day-size, 2.25rem);\n }\n\n .base {\n display: inline-flex;\n flex-direction: column;\n gap: var(--uf-space-2);\n color: var(--uf-color-text);\n font-family: var(--uf-font-family-sans);\n font-size: var(--uf-font-size-sm);\n }\n\n .header {\n display: flex;\n align-items: center;\n gap: var(--uf-space-1);\n }\n\n .title {\n flex: 1;\n margin: 0;\n font-size: var(--uf-font-size-md);\n font-weight: var(--uf-font-weight-semibold);\n text-align: center;\n text-transform: capitalize;\n }\n\n .nav {\n display: inline-grid;\n place-items: center;\n width: var(--_day);\n height: var(--_day);\n padding: 0;\n border: 0;\n border-radius: var(--uf-radius-control);\n background: transparent;\n color: var(--uf-color-text);\n cursor: pointer;\n }\n\n .nav:hover:not(:disabled) {\n background: var(--uf-color-accent-tint);\n color: var(--uf-color-on-accent-tint);\n }\n\n .nav:focus-visible {\n ${focusRing}\n }\n\n .nav:disabled {\n opacity: 0.35;\n cursor: not-allowed;\n }\n\n .nav svg {\n width: 1.125em;\n height: 1.125em;\n }\n\n table {\n border-collapse: collapse;\n }\n\n th {\n width: var(--_day);\n height: 1.75rem;\n padding: 0;\n color: var(--uf-color-text-muted);\n font-weight: var(--uf-font-weight-medium);\n font-size: 0.75rem;\n }\n\n td {\n width: var(--_day);\n height: var(--_day);\n padding: 0;\n border-radius: var(--uf-radius-control);\n text-align: center;\n font-variant-numeric: tabular-nums;\n cursor: pointer;\n user-select: none;\n }\n\n td:hover:not([aria-disabled='true']) {\n background: var(--uf-color-accent-tint);\n color: var(--uf-color-on-accent-tint);\n }\n\n td:focus-visible {\n ${focusRing}\n }\n\n td.outside {\n color: var(--uf-color-text-muted);\n }\n\n td.today {\n font-weight: var(--uf-font-weight-semibold);\n box-shadow: inset 0 0 0 1px var(--uf-color-accent-strong);\n }\n\n td[aria-selected='true'],\n td[aria-selected='true']:hover {\n background: var(--uf-color-accent);\n color: var(--uf-color-on-accent);\n font-weight: var(--uf-font-weight-semibold);\n }\n\n /* Range: the days between the ends tinted, the ends filled. */\n td.in-range,\n td.in-range:hover {\n border-radius: 0;\n background: var(--uf-color-accent-tint);\n color: var(--uf-color-on-accent-tint);\n }\n\n td.range-start,\n td.range-end,\n td.range-start:hover,\n td.range-end:hover {\n background: var(--uf-color-accent);\n color: var(--uf-color-on-accent);\n font-weight: var(--uf-font-weight-semibold);\n }\n\n td[aria-disabled='true'] {\n color: var(--uf-color-text-muted);\n text-decoration: line-through;\n opacity: 0.5;\n cursor: not-allowed;\n }\n `,\n ];\n\n static override properties: PropertyDeclarations = {\n value: {},\n min: {},\n max: {},\n firstDayOfWeek: { type: Number, attribute: 'first-day-of-week' },\n isDateDisabled: { attribute: false },\n range: { type: Boolean, reflect: true },\n start: {},\n end: {},\n };\n\n /** The selected date, as `YYYY-MM-DD`, or an empty string. */\n declare value: string;\n /** The earliest date that can be picked, as `YYYY-MM-DD`. */\n declare min: string | undefined;\n /** The latest date that can be picked, as `YYYY-MM-DD`. */\n declare max: string | undefined;\n /** First day of the week: 0 Sunday … 6 Saturday. Defaults to the language's. */\n declare firstDayOfWeek: number | undefined;\n /** Rules out dates, e.g. weekends: called with each date as `YYYY-MM-DD`, returns true to disable it. */\n declare isDateDisabled: ((date: string) => boolean) | undefined;\n /** Picks a range, from `start` to `end`, instead of one date. */\n declare range: boolean;\n /** With `range`, the first date of the range, as `YYYY-MM-DD`, or an empty string. */\n declare start: string;\n /** With `range`, the last date of the range, as `YYYY-MM-DD`, or an empty string. */\n declare end: string;\n\n readonly #translator = new Translator(this);\n readonly #id = uniqueId('uf-calendar');\n /** The day with keyboard focus; its month is the one shown. */\n #focused: Date = parseIso(todayIso())!;\n /** Focus the focused day after the next render (keyboard navigation). */\n #moveFocus = false;\n\n /** With `range`, the day under the pointer or keyboard while the end is being picked. */\n #preview: Date | null = null;\n\n constructor() {\n super();\n this.value = '';\n this.range = false;\n this.start = '';\n this.end = '';\n }\n\n override willUpdate(changed: PropertyValues<this>): void {\n // Show the selected date's month when the value changes from outside.\n if (changed.has('value') || changed.has('start') || changed.has('min') || changed.has('max')) {\n const selected = parseIso(this.range ? this.start : this.value);\n this.#focused = clamp(selected ?? this.#focused, parseIso(this.min), parseIso(this.max));\n }\n }\n\n override updated(): void {\n if (this.#moveFocus) {\n this.#moveFocus = false;\n this.#focusedCell()?.focus();\n }\n }\n\n /** Moves keyboard focus to the selected day, or today. */\n override focus(options?: FocusOptions): void {\n this.#focusedCell()?.focus(options);\n }\n\n #focusedCell(): HTMLElement | null {\n return this.renderRoot.querySelector<HTMLElement>(`td[data-date=\"${toIso(this.#focused)}\"]`);\n }\n\n #isDisabled(date: Date): boolean {\n const min = parseIso(this.min);\n const max = parseIso(this.max);\n return Boolean((min && date < min) || (max && date > max) || this.isDateDisabled?.(toIso(date)));\n }\n\n #moveTo(date: Date, focus: boolean): void {\n this.#focused = clamp(date, parseIso(this.min), parseIso(this.max));\n this.#moveFocus = focus;\n this.requestUpdate();\n }\n\n #select(date: Date): void {\n if (this.#isDisabled(date)) return;\n this.#focused = date;\n const iso = toIso(date);\n if (this.range) {\n this.#selectInRange(iso);\n return;\n }\n if (iso === this.value) return;\n this.value = iso;\n this.dispatchEvent(new Event('change', { bubbles: true, composed: true }));\n }\n\n /** First pick: the start. Second pick: the end, swapped with the start if earlier. */\n #selectInRange(iso: string): void {\n if (!this.start || this.end) {\n this.start = iso;\n this.end = '';\n this.#preview = null;\n return;\n }\n [this.start, this.end] = iso < this.start ? [iso, this.start] : [this.start, iso];\n this.#preview = null;\n this.dispatchEvent(new Event('change', { bubbles: true, composed: true }));\n }\n\n /** While the end is being picked, the day the range would end on. */\n #setPreview(date: Date | null): void {\n if (!this.range || !this.start || this.end) return;\n this.#preview = date;\n this.requestUpdate();\n }\n\n #onKeyDown = (event: KeyboardEvent): void => {\n const date = this.#focused;\n const weekStart = this.#weekStart;\n const offset = (date.getUTCDay() - weekStart + 7) % 7;\n const moves: Record<string, () => Date> = {\n ArrowLeft: () => addDays(date, getComputedStyle(this).direction === 'rtl' ? 1 : -1),\n ArrowRight: () => addDays(date, getComputedStyle(this).direction === 'rtl' ? -1 : 1),\n ArrowUp: () => addDays(date, -7),\n ArrowDown: () => addDays(date, 7),\n Home: () => addDays(date, -offset),\n End: () => addDays(date, 6 - offset),\n PageUp: () => addMonths(date, event.shiftKey ? -12 : -1),\n PageDown: () => addMonths(date, event.shiftKey ? 12 : 1),\n };\n if (moves[event.key]) {\n event.preventDefault();\n this.#moveTo(moves[event.key](), true);\n this.#setPreview(this.#focused);\n } else if (event.key === 'Enter' || event.key === ' ') {\n event.preventDefault();\n this.#select(date);\n }\n };\n\n get #weekStart(): number {\n return this.firstDayOfWeek ?? firstDayOfWeek(this.#translator.lang);\n }\n\n override render() {\n const lang = this.#translator.lang;\n const weekStart = this.#weekStart;\n const month = startOfMonth(this.#focused);\n const first = addDays(month, -((month.getUTCDay() - weekStart + 7) % 7));\n // Always six weeks, so the calendar keeps its height from month to month.\n const days = Array.from({ length: 42 }, (_, i) => addDays(first, i));\n const weekdays = days.slice(0, 7);\n const min = parseIso(this.min);\n const max = parseIso(this.max);\n const today = todayIso();\n const titleId = `${this.#id}-title`;\n const long = formatter(lang, { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });\n // The range shown: start to end, or start to the previewed day while the end is picked.\n let [from, to] = [this.start, this.end || (this.#preview ? toIso(this.#preview) : '')];\n if (from && to && to < from) [from, to] = [to, from];\n\n return html`<div class=\"base\" part=\"base\">\n <div class=\"header\" part=\"header\">\n <button\n class=\"nav\"\n part=\"nav-button\"\n type=\"button\"\n aria-label=${this.#translator.t('previousMonth')}\n ?disabled=${Boolean(min && addDays(month, -1) < min)}\n @click=${() => this.#moveTo(addMonths(this.#focused, -1), false)}\n >\n ${iconSvg(icons['chevron-left'])}\n </button>\n <h2 id=${titleId} class=\"title\" part=\"title\" aria-live=\"polite\">${formatter(lang, { month: 'long', year: 'numeric' }).format(month)}</h2>\n <button\n class=\"nav\"\n part=\"nav-button\"\n type=\"button\"\n aria-label=${this.#translator.t('nextMonth')}\n ?disabled=${Boolean(max && addMonths(month, 1) > max)}\n @click=${() => this.#moveTo(addMonths(this.#focused, 1), false)}\n >\n ${iconSvg(icons['chevron-right'])}\n </button>\n </div>\n <table role=\"grid\" part=\"grid\" aria-labelledby=${titleId} @keydown=${this.#onKeyDown}>\n <thead>\n <tr>\n ${weekdays.map(\n (day) =>\n html`<th scope=\"col\" part=\"weekday\" abbr=${formatter(lang, { weekday: 'long' }).format(day)}>\n ${formatter(lang, { weekday: 'narrow' }).format(day)}\n </th>`,\n )}\n </tr>\n </thead>\n <tbody>\n ${[0, 1, 2, 3, 4, 5].map(\n (week) => html`<tr>\n ${days.slice(week * 7, week * 7 + 7).map((day) => {\n const iso = toIso(day);\n const isStart = this.range && Boolean(from) && iso === from;\n const isEnd = this.range && Boolean(to) && iso === to;\n const between = this.range && Boolean(from && to) && iso > from && iso < to;\n const selected = this.range ? isStart || isEnd || (between && Boolean(this.end)) : iso === this.value;\n const isToday = iso === today;\n const outside = day.getUTCMonth() !== month.getUTCMonth();\n const disabled = this.#isDisabled(day);\n const parts = [\n 'day',\n selected && !this.range ? 'selected' : '',\n isToday ? 'today' : '',\n isStart ? 'range-start' : '',\n isEnd ? 'range-end' : '',\n between ? 'in-range' : '',\n ]\n .filter(Boolean)\n .join(' ');\n return html`<td\n part=${parts}\n class=${classMap({\n outside,\n today: isToday,\n 'range-start': isStart,\n 'range-end': isEnd,\n 'in-range': between,\n })}\n data-date=${iso}\n tabindex=${iso === toIso(this.#focused) ? 0 : -1}\n aria-label=${long.format(day)}\n aria-selected=${selected ? 'true' : 'false'}\n aria-disabled=${disabled ? 'true' : nothing}\n aria-current=${isToday ? 'date' : nothing}\n @click=${() => this.#select(day)}\n @pointerenter=${() => this.#setPreview(day)}\n @focus=${() => {\n // A day of another month is focused by the pointer, just before its click: moving\n // to its month now would re-render the grid, and the click would land on another day.\n if (!outside && toIso(this.#focused) !== iso) this.#moveTo(day, false);\n }}\n >\n ${day.getUTCDate()}\n </td>`;\n })}\n </tr>`,\n )}\n </tbody>\n </table>\n </div>`;\n }\n}\n\ndefineElement('uf-calendar', UfCalendar);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-calendar': UfCalendar;\n }\n}\n",
|
|
@@ -861,7 +861,7 @@
|
|
|
861
861
|
"internal/field.ts": "import { css, html, nothing, type TemplateResult } from 'lit';\nimport { classMap } from 'lit/directives/class-map.js';\n\n/** Size of a form field. */\nexport type FieldSize = 'sm' | 'md' | 'lg';\n\nexport interface FieldParts {\n /** Id of the native control the label points at. */\n controlId: string;\n hintId: string;\n errorId: string;\n label?: string;\n hasLabelSlot: boolean;\n hint?: string;\n hasHintSlot: boolean;\n /** Visible error, shown once the user interacted with an invalid field. */\n error: string;\n required: boolean;\n control: TemplateResult;\n /** Shown at the end of the label's row, e.g. a slider's value. Not part of the label's text. */\n labelEnd?: TemplateResult;\n}\n\n/** ids for `aria-describedby` on the native control. */\nexport function describedBy(parts: Pick<FieldParts, 'hintId' | 'errorId' | 'hint' | 'hasHintSlot' | 'error'>): string | undefined {\n const ids = [];\n if (parts.hint || parts.hasHintSlot) ids.push(parts.hintId);\n if (parts.error) ids.push(parts.errorId);\n return ids.length ? ids.join(' ') : undefined;\n}\n\n/**\n * Label, control, hint and error laid out as one field. The label lives inside\n * the shadow root because an outside `<label for>` can't reach the native control.\n */\nexport function renderField(parts: FieldParts): TemplateResult {\n const hasLabel = Boolean(parts.label) || parts.hasLabelSlot;\n const hasHint = Boolean(parts.hint) || parts.hasHintSlot;\n return html`\n <div class=${classMap({ field: true, invalid: Boolean(parts.error) })} part=\"field\">\n <div class=\"field-label-row\" ?hidden=${!hasLabel && !parts.labelEnd}>\n <label for=${parts.controlId} class=\"field-label\" part=\"form-label\" ?hidden=${!hasLabel}>\n <slot name=\"label\">${parts.label}</slot>\n ${parts.required ? html`<span class=\"required\" aria-hidden=\"true\">*</span>` : nothing}\n </label>\n ${parts.labelEnd ?? nothing}\n </div>\n ${parts.control}\n <div id=${parts.hintId} class=\"field-hint\" part=\"hint\" ?hidden=${!hasHint}>\n <slot name=\"hint\">${parts.hint}</slot>\n </div>\n <div id=${parts.errorId} class=\"field-error\" part=\"error\" ?hidden=${!parts.error}>${parts.error}</div>\n </div>\n `;\n}\n\nexport const fieldStyles = css`\n :host {\n display: block;\n }\n\n .field {\n display: flex;\n flex-direction: column;\n gap: var(--uf-space-1);\n font-family: var(--uf-font-family-sans);\n }\n\n .field-label-row {\n display: flex;\n justify-content: space-between;\n align-items: baseline;\n gap: var(--uf-space-2);\n }\n\n .field-label {\n font-size: var(--uf-font-size-md);\n font-weight: var(--uf-font-weight-medium);\n color: var(--uf-color-text);\n }\n\n .required {\n margin-inline-start: 0.125em;\n color: var(--uf-color-danger-text);\n }\n\n .field-hint,\n .field-error {\n font-size: var(--uf-font-size-sm);\n line-height: 1.4;\n }\n\n .field-hint {\n color: var(--uf-color-text-muted);\n }\n\n .field-error {\n color: var(--uf-color-danger-text);\n }\n\n [hidden] {\n display: none !important;\n }\n`;\n\n/** The bordered box shared by input, textarea and select. */\nexport const controlBoxStyles = css`\n .box {\n --_height: var(--uf-size-control-md);\n --_padding: var(--uf-space-3);\n --_font-size: var(--uf-font-size-md);\n display: flex;\n align-items: center;\n gap: var(--uf-space-2);\n min-height: var(--_height);\n padding: 0 var(--_padding);\n border: 1px solid var(--uf-field-border-color, var(--uf-color-border-strong));\n border-radius: var(--uf-field-radius, var(--uf-radius-control));\n background: var(--uf-field-bg, var(--uf-color-surface));\n color: var(--uf-color-text);\n font-size: var(--_font-size);\n transition:\n border-color var(--uf-duration-fast) ease,\n box-shadow var(--uf-duration-fast) ease;\n }\n\n :host([size='sm']) .box {\n --_height: var(--uf-size-control-sm);\n --_padding: var(--uf-space-2);\n --_font-size: var(--uf-font-size-sm);\n }\n\n :host([size='lg']) .box {\n --_height: var(--uf-size-control-lg);\n --_padding: var(--uf-space-4);\n --_font-size: var(--uf-font-size-lg);\n }\n\n .box:hover:not(.disabled) {\n border-color: var(--uf-color-text-muted);\n }\n\n .box:focus-within {\n border-color: var(--uf-color-focus-ring);\n box-shadow: 0 0 0 1px var(--uf-color-focus-ring);\n }\n\n /* A 2px error outline: the border plus an inset shadow, so the box keeps its size. */\n .invalid .box,\n .invalid .box:hover,\n .invalid .box:focus-within {\n border-color: var(--uf-color-danger-text);\n box-shadow: inset 0 0 0 1px var(--uf-color-danger-text);\n }\n\n /* Grey instead of faded: a faded field still looks like one you can type in. */\n .box.disabled {\n border-color: var(--uf-color-border);\n background: var(--uf-color-neutral-fill);\n color: var(--uf-color-text-muted);\n cursor: not-allowed;\n }\n\n .native {\n flex: 1;\n min-width: 0;\n height: 100%;\n padding: 0;\n border: 0;\n outline: none;\n background: transparent;\n color: inherit;\n font: inherit;\n }\n\n .native::placeholder {\n color: var(--uf-color-text-muted);\n opacity: 1;\n }\n\n .native:disabled {\n cursor: not-allowed;\n }\n\n ::slotted([slot='prefix']),\n ::slotted([slot='suffix']) {\n display: inline-flex;\n flex: none;\n color: var(--uf-color-text-muted);\n }\n\n ::slotted(svg) {\n width: 1em;\n height: 1em;\n }\n`;\n",
|
|
862
862
|
"internal/select-all.ts": "/**\n * How a `<uf-checkbox>` asks its `<uf-checkbox-group>` to update \"select all\"\n * when its `checked` changes from code. A symbol, so it isn't public API.\n */\nexport const syncSelectAll = Symbol('syncSelectAll');\n\nexport interface SelectAllHost extends HTMLElement {\n [syncSelectAll](): void;\n}\n",
|
|
863
863
|
"internal/toggle-control.ts": "import type { PropertyDeclarations, PropertyValues } from 'lit';\nimport type { FieldSize } from './field.js';\nimport { FormControl } from './form-control.js';\n\n/**\n * Shared logic for checkbox-like controls: `checked` state, the `checked`\n * attribute as the reset default, and submitting `value` only when checked.\n */\nexport abstract class ToggleControl extends FormControl {\n static override properties: PropertyDeclarations = {\n checked: { type: Boolean, attribute: false },\n defaultChecked: { type: Boolean, attribute: 'checked' },\n value: {},\n size: { reflect: true },\n };\n\n /** Whether the control is on. */\n declare checked: boolean;\n /** Initial state, restored on form reset. Set with the `checked` attribute. */\n declare defaultChecked: boolean;\n /** Value submitted with the form when checked. */\n declare value: string;\n /** Size of the control and its label: `sm`, `md` or `lg`. */\n declare size: FieldSize;\n\n constructor() {\n super();\n this.checked = false;\n this.defaultChecked = false;\n this.value = 'on';\n this.size = 'md';\n }\n\n protected get nativeInput(): HTMLInputElement | null {\n return this.renderRoot.querySelector('input');\n }\n\n /** Toggles the control, as if the user clicked it. */\n toggle(): void {\n this.nativeInput?.click();\n }\n\n override willUpdate(changed: PropertyValues<this>): void {\n if (changed.has('defaultChecked') && this.checked === Boolean(changed.get('defaultChecked'))) {\n this.checked = this.defaultChecked;\n }\n }\n\n override updated(): void {\n this.syncFormState();\n }\n\n protected syncFormState(): void {\n const input = this.nativeInput;\n if (!input) return;\n this.internals.setFormValue(this.checked ? this.value : null, String(this.checked));\n this.internals.states?.[this.checked ? 'add' : 'delete']('checked');\n this.setValidityFrom(input);\n }\n\n protected resetValue(): void {\n this.checked = this.defaultChecked;\n }\n\n /** @internal */\n formStateRestoreCallback(state: string | null): void {\n this.checked = state === 'true';\n }\n\n protected onNativeChange = (event: Event): void => {\n this.checked = (event.target as HTMLInputElement).checked;\n this.markInteracted();\n this.emitChange();\n };\n}\n",
|
|
864
|
-
"internal/form-control.ts": "import { LitElement, type PropertyDeclarations } from 'lit';\nimport { Translator } from './i18n.js';\n\n/**\n * Base class for form-associated controls. Handles everything a native control\n * gets for free: form value, validity, reset, state restore, `<fieldset disabled>`,\n * and the `user-invalid` custom state (only set after the user interacted or\n * tried to submit, so pristine fields aren't shown as errors).\n *\n * Subclasses implement `syncFormState()` and call it whenever their value changes.\n */\n/** Forms (or lone controls) that already focused their first invalid control in this submission. */\nconst focusedForInvalid = new WeakSet<HTMLElement>();\n\nexport abstract class FormControl extends LitElement {\n static formAssociated = true;\n static override shadowRootOptions = { ...LitElement.shadowRootOptions, delegatesFocus: true };\n\n static override properties: PropertyDeclarations = {\n name: { reflect: true },\n disabled: { type: Boolean, reflect: true },\n required: { type: Boolean, reflect: true },\n };\n\n /** Name submitted with the form. */\n declare name: string;\n /** Disables the control. */\n declare disabled: boolean;\n /** Makes the control required for form submission. */\n declare required: boolean;\n\n protected readonly internals = this.attachInternals();\n /** Built-in text, e.g. validation messages, in the page's language. */\n protected readonly translator = new Translator(this);\n #formDisabled = false;\n #interacted = false;\n #customError = '';\n /** True while checkValidity() runs, so its `invalid` event isn't taken for a submit attempt. */\n #checking = false;\n\n constructor() {\n super();\n this.name = '';\n this.disabled = false;\n this.required = false;\n // Fired by the form when submission is blocked by this control, and by reportValidity().\n this.addEventListener('invalid', this.#onInvalid);\n }\n\n /**\n * Shows the error inline instead of the browser's bubble, which would repeat it.\n * Cancelling the event also stops the browser from focusing the field, so the\n * first invalid control of a submission is focused here instead.\n */\n #onInvalid = (event: Event): void => {\n if (this.#checking) return;\n event.preventDefault();\n this.markInteracted();\n const group = this.internals.form ?? this;\n if (focusedForInvalid.has(group)) return;\n focusedForInvalid.add(group);\n // A submission fires `invalid` on every invalid control in one task: only the first gets focus.\n // Cleared after the task, not in a microtask: those run between the events of a user's submit.\n setTimeout(() => focusedForInvalid.delete(group));\n this.focus();\n };\n\n /** True while an update runs, so changes made during it don't start a nested one. */\n #updating = false;\n\n /**\n * Properties that change the submitted value or the validity. Subclasses add\n * their own constraints (`pattern`, `min`...).\n */\n protected static formStateProperties: ReadonlySet<PropertyKey> = new Set([\n 'value',\n 'checked',\n 'defaultValue',\n 'defaultChecked',\n 'required',\n 'name',\n ]);\n\n /**\n * Form value and validity come from the rendered control, but the form reads\n * them synchronously: `input.value = 'x'; form.requestSubmit()` must see the\n * new value. So changing one of `formStateProperties` on a rendered control\n * updates it at once, instead of in the next microtask. Other properties keep\n * Lit's batched updates.\n */\n override requestUpdate(...args: Parameters<LitElement['requestUpdate']>): void {\n super.requestUpdate(...args);\n const [name] = args;\n const formState = (this.constructor as typeof FormControl).formStateProperties;\n if (name !== undefined && formState.has(name) && this.hasUpdated && !this.#updating && this.isUpdatePending) {\n this.performUpdate();\n }\n }\n\n protected override performUpdate(): void {\n this.#updating = true;\n try {\n super.performUpdate();\n } finally {\n this.#updating = false;\n }\n }\n\n /** The form this control belongs to, if any. */\n get form(): HTMLFormElement | null {\n return this.internals.form;\n }\n\n /** The control's validity state, like a native input's. */\n get validity(): ValidityState {\n return this.internals.validity;\n }\n\n /** The error message shown when the value is invalid. */\n get validationMessage(): string {\n return this.internals.validationMessage;\n }\n\n /** Whether the control takes part in form validation. */\n get willValidate(): boolean {\n return this.internals.willValidate;\n }\n\n /** Returns whether the value is valid, without showing an error. */\n checkValidity(): boolean {\n this.#checking = true;\n try {\n return this.internals.checkValidity();\n } finally {\n this.#checking = false;\n }\n }\n\n /** Returns whether the value is valid, and shows the error if not. */\n reportValidity(): boolean {\n this.markInteracted();\n return this.internals.reportValidity();\n }\n\n /** Sets a custom error message. Pass an empty string to clear it. */\n setCustomValidity(message: string): void {\n this.#customError = message;\n this.syncFormState();\n }\n\n /** True when the control is disabled directly or through a disabled fieldset. */\n protected get isDisabled(): boolean {\n return this.disabled || this.#formDisabled;\n }\n\n /** True when the control is invalid and the user has interacted with it. */\n protected get showInvalid(): boolean {\n return this.#interacted && !this.internals.validity.valid;\n }\n\n protected get customError(): string {\n return this.#customError;\n }\n\n /** Call after user input or blur, so validation errors may be shown. */\n protected markInteracted(): void {\n if (this.#interacted) return;\n this.#interacted = true;\n this.#updateStates();\n }\n\n /**\n * Sets validity from flags. A custom error set through `setCustomValidity`\n * takes precedence. `anchor` is the element the browser points its bubble at.\n */\n protected setValidity(flags: ValidityStateFlags, message: string, anchor?: HTMLElement): void {\n if (this.#customError) {\n this.internals.setValidity({ ...flags, customError: true }, this.#customError, anchor);\n } else if (Object.values(flags).some(Boolean)) {\n this.internals.setValidity(flags, message || this.translator.t('invalidValue'), anchor);\n } else {\n this.internals.setValidity({});\n }\n this.#updateStates();\n }\n\n /** Copies a native control's validity onto the host. */\n protected setValidityFrom(control: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement): void {\n control.setCustomValidity(this.#customError);\n const v = control.validity;\n this.setValidity(\n {\n valueMissing: v.valueMissing,\n typeMismatch: v.typeMismatch,\n patternMismatch: v.patternMismatch,\n tooLong: v.tooLong,\n tooShort: v.tooShort,\n rangeUnderflow: v.rangeUnderflow,\n rangeOverflow: v.rangeOverflow,\n stepMismatch: v.stepMismatch,\n badInput: v.badInput,\n },\n control.validationMessage,\n control,\n );\n }\n\n #shownInvalid = false;\n\n #updateStates(): void {\n const invalid = this.showInvalid;\n // Only re-render on a real change: syncFormState() runs from updated().\n if (invalid === this.#shownInvalid) return;\n this.#shownInvalid = invalid;\n this.internals.states?.[invalid ? 'add' : 'delete']('user-invalid');\n this.requestUpdate();\n }\n\n /** Updates the submitted value and validity. */\n protected abstract syncFormState(): void;\n\n /** Restores the initial value, called on form reset. */\n protected abstract resetValue(): void;\n\n /** @internal */\n formDisabledCallback(disabled: boolean): void {\n this.#formDisabled = disabled;\n this.requestUpdate();\n }\n\n /** @internal */\n formResetCallback(): void {\n this.resetValue();\n this.#interacted = false;\n this.syncFormState();\n }\n\n /** Dispatches a bubbling `change` event, which native `change` events don't cross shadow roots. */\n protected emitChange(): void {\n this.dispatchEvent(new Event('change', { bubbles: true }));\n }\n}\n",
|
|
864
|
+
"internal/form-control.ts": "import { LitElement, type PropertyDeclarations } from 'lit';\nimport { Translator } from './i18n.js';\n\n/**\n * Base class for form-associated controls. Handles everything a native control\n * gets for free: form value, validity, reset, state restore, `<fieldset disabled>`,\n * and the `user-invalid` custom state (only set after the user interacted or\n * tried to submit, so pristine fields aren't shown as errors).\n *\n * Subclasses implement `syncFormState()` and call it whenever their value changes.\n */\n/** Forms (or lone controls) that already focused their first invalid control in this submission. */\nconst focusedForInvalid = new WeakSet<HTMLElement>();\n\nexport abstract class FormControl extends LitElement {\n static formAssociated = true;\n static override shadowRootOptions = { ...LitElement.shadowRootOptions, delegatesFocus: true };\n\n static override properties: PropertyDeclarations = {\n name: { reflect: true },\n disabled: { type: Boolean, reflect: true },\n required: { type: Boolean, reflect: true },\n };\n\n /** Name submitted with the form. */\n declare name: string;\n /** Disables the control. */\n declare disabled: boolean;\n /** Makes the control required for form submission. */\n declare required: boolean;\n\n protected readonly internals = this.attachInternals();\n /** Built-in text, e.g. validation messages, in the page's language. */\n protected readonly translator = new Translator(this);\n #formDisabled = false;\n #interacted = false;\n #customError = '';\n /** True while checkValidity() runs, so its `invalid` event isn't taken for a submit attempt. */\n #checking = false;\n\n constructor() {\n super();\n this.name = '';\n this.disabled = false;\n this.required = false;\n // Fired by the form when submission is blocked by this control, and by reportValidity().\n this.addEventListener('invalid', this.#onInvalid);\n }\n\n /**\n * Shows the error inline instead of the browser's bubble, which would repeat it.\n * Cancelling the event also stops the browser from focusing the field, so the\n * first invalid control of a submission is focused here instead.\n */\n #onInvalid = (event: Event): void => {\n if (this.#checking) return;\n event.preventDefault();\n this.markInteracted();\n const group = this.internals.form ?? this;\n if (focusedForInvalid.has(group)) return;\n focusedForInvalid.add(group);\n // A submission fires `invalid` on every invalid control in one task: only the first gets focus.\n // Cleared after the task, not in a microtask: those run between the events of a user's submit.\n setTimeout(() => focusedForInvalid.delete(group));\n this.focus();\n };\n\n /** True while an update runs, so changes made during it don't start a nested one. */\n #updating = false;\n\n /**\n * Properties that change the submitted value or the validity. Subclasses add\n * their own constraints (`pattern`, `min`...).\n */\n protected static formStateProperties: ReadonlySet<PropertyKey> = new Set([\n 'value',\n 'checked',\n 'defaultValue',\n 'defaultChecked',\n 'required',\n 'name',\n ]);\n\n /**\n * Form value and validity come from the rendered control, but the form reads\n * them synchronously: `input.value = 'x'; form.requestSubmit()` must see the\n * new value. So changing one of `formStateProperties` on a rendered control\n * updates it at once, instead of in the next microtask. Other properties keep\n * Lit's batched updates.\n */\n override requestUpdate(...args: Parameters<LitElement['requestUpdate']>): void {\n super.requestUpdate(...args);\n const [name] = args;\n const formState = (this.constructor as typeof FormControl).formStateProperties;\n if (name !== undefined && formState.has(name) && this.hasUpdated && !this.#updating && this.isUpdatePending) {\n this.performUpdate();\n }\n }\n\n protected override performUpdate(): void {\n this.#updating = true;\n try {\n super.performUpdate();\n } finally {\n this.#updating = false;\n }\n }\n\n /** The form this control belongs to, if any. */\n get form(): HTMLFormElement | null {\n return this.internals.form;\n }\n\n /** The control's validity state, like a native input's. */\n get validity(): ValidityState {\n return this.internals.validity;\n }\n\n /** The error message shown when the value is invalid. */\n get validationMessage(): string {\n return this.internals.validationMessage;\n }\n\n /** Whether the control takes part in form validation. */\n get willValidate(): boolean {\n return this.internals.willValidate;\n }\n\n /** Returns whether the value is valid, without showing an error. */\n checkValidity(): boolean {\n this.#checking = true;\n try {\n return this.internals.checkValidity();\n } finally {\n this.#checking = false;\n }\n }\n\n /** Returns whether the value is valid, and shows the error if not. */\n reportValidity(): boolean {\n this.markInteracted();\n return this.internals.reportValidity();\n }\n\n /** Sets a custom error message. Pass an empty string to clear it. */\n setCustomValidity(message: string): void {\n this.#customError = message;\n this.syncFormState();\n }\n\n /** True when the control is disabled directly or through a disabled fieldset. */\n protected get isDisabled(): boolean {\n return this.disabled || this.#formDisabled;\n }\n\n /** True when the control is invalid and the user has interacted with it. */\n protected get showInvalid(): boolean {\n return this.#interacted && !this.internals.validity.valid;\n }\n\n protected get customError(): string {\n return this.#customError;\n }\n\n /** Call after user input or blur, so validation errors may be shown. */\n protected markInteracted(): void {\n if (this.#interacted) return;\n this.#interacted = true;\n this.#updateStates();\n }\n\n /**\n * Sets validity from flags. A custom error set through `setCustomValidity`\n * takes precedence. `anchor` is the element the browser points its bubble at.\n */\n protected setValidity(flags: ValidityStateFlags, message: string, anchor?: HTMLElement): void {\n if (this.#customError) {\n this.internals.setValidity({ ...flags, customError: true }, this.#customError, anchor);\n } else if (Object.values(flags).some(Boolean)) {\n this.internals.setValidity(flags, message || this.translator.t('invalidValue'), anchor);\n } else {\n this.internals.setValidity({});\n }\n this.#updateStates();\n }\n\n /** Copies a native control's validity onto the host. */\n protected setValidityFrom(control: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement): void {\n control.setCustomValidity(this.#customError);\n const v = control.validity;\n this.setValidity(\n {\n valueMissing: v.valueMissing,\n typeMismatch: v.typeMismatch,\n patternMismatch: v.patternMismatch,\n tooLong: v.tooLong,\n tooShort: v.tooShort,\n rangeUnderflow: v.rangeUnderflow,\n rangeOverflow: v.rangeOverflow,\n stepMismatch: v.stepMismatch,\n badInput: v.badInput,\n },\n control.validationMessage,\n control,\n );\n }\n\n #shownInvalid = false;\n\n #updateStates(): void {\n const invalid = this.showInvalid;\n // Only re-render on a real change: syncFormState() runs from updated().\n if (invalid === this.#shownInvalid) return;\n this.#shownInvalid = invalid;\n this.internals.states?.[invalid ? 'add' : 'delete']('user-invalid');\n this.requestUpdate();\n }\n\n /** Updates the submitted value and validity. */\n protected abstract syncFormState(): void;\n\n /** Restores the initial value, called on form reset. */\n protected abstract resetValue(): void;\n\n /** @internal */\n formDisabledCallback(disabled: boolean): void {\n this.#formDisabled = disabled;\n // The browser also calls this when an update adds or removes the element's own\n // `disabled` attribute, after render. Lit drops a request made during an update,\n // so the control would stay disabled: ask again once the update is done.\n if (this.isUpdatePending) void this.updateComplete.then(() => this.requestUpdate());\n else this.requestUpdate();\n }\n\n /** @internal */\n formResetCallback(): void {\n this.resetValue();\n this.#interacted = false;\n this.syncFormState();\n }\n\n /** Dispatches a bubbling `change` event, which native `change` events don't cross shadow roots. */\n protected emitChange(): void {\n this.dispatchEvent(new Event('change', { bubbles: true }));\n }\n}\n",
|
|
865
865
|
"internal/toggle.styles.ts": "import { css } from 'lit';\n\n/** Layout shared by checkbox, switch and radio: control, label, hint and error. */\nexport const toggleStyles = css`\n :host {\n display: block;\n font-family: var(--uf-font-family-sans);\n font-size: var(--uf-font-size-md);\n color: var(--uf-color-text);\n }\n\n :host([size='sm']) {\n font-size: var(--uf-font-size-sm);\n }\n\n :host([size='lg']) {\n font-size: var(--uf-font-size-lg);\n }\n\n .root {\n display: inline-flex;\n align-items: flex-start;\n gap: var(--uf-space-2);\n cursor: pointer;\n line-height: 1.4;\n }\n\n /* Grey instead of faded, like disabled fields. */\n .root.disabled {\n color: var(--uf-color-text-muted);\n cursor: not-allowed;\n }\n\n .control {\n position: relative;\n display: inline-flex;\n flex: none;\n /* Vertically centers the control on the first line of the label. */\n margin-top: calc((1.4em - var(--_control-height)) / 2);\n }\n\n .native {\n appearance: none;\n margin: 0;\n cursor: inherit;\n transition:\n background-color var(--uf-duration-fast) ease,\n border-color var(--uf-duration-fast) ease;\n }\n\n .native:focus-visible {\n outline: var(--uf-focus-ring-width) solid var(--uf-color-focus-ring);\n outline-offset: var(--uf-focus-ring-offset);\n }\n\n .hint,\n .error {\n margin: var(--uf-space-1) 0 0 calc(var(--_control-width) + var(--uf-space-2));\n font-size: var(--uf-font-size-sm);\n line-height: 1.4;\n }\n\n .hint {\n color: var(--uf-color-text-muted);\n }\n\n .error {\n color: var(--uf-color-danger-text);\n }\n\n [hidden] {\n display: none !important;\n }\n`;\n",
|
|
866
866
|
"components/checkbox-group/checkbox-group.ts": "import { LitElement, css, html, nothing, type PropertyDeclarations } from 'lit';\nimport { classMap } from 'lit/directives/class-map.js';\nimport { ifDefined } from 'lit/directives/if-defined.js';\nimport { defineElement } from '../../internal/define.js';\nimport { fieldStyles } from '../../internal/field.js';\nimport { hostStyles } from '../../internal/shared.styles.js';\nimport { syncSelectAll } from '../../internal/select-all.js';\nimport { HasSlotController, uniqueId } from '../../internal/slot.js';\nimport '../checkbox/checkbox.js';\nimport type { UfCheckbox } from '../checkbox/checkbox.js';\n\n/**\n * Groups related `<uf-checkbox>`es under one label. Mark one checkbox with\n * `select-all` to get the \"select all\" pattern: it checks or unchecks the\n * others, and turns indeterminate when only some are checked.\n *\n * Each checkbox still submits its own `name` and `value` with a form;\n * `value` on the group lists the checked values, for frameworks.\n *\n * @summary Groups checkboxes, with an optional \"select all\".\n * @tag uf-checkbox-group\n *\n * @slot - `<uf-checkbox>` elements.\n * @slot label - The group label, when you need markup. Overrides `label`.\n * @slot hint - Help text below the checkboxes. Overrides `hint`.\n *\n * @event change - A checkbox in the group changed (including through \"select all\").\n *\n * @csspart base - The element with `role=\"group\"`.\n * @csspart form-label - The group label.\n * @csspart options - The wrapper around the checkboxes.\n * @csspart hint - The hint text.\n *\n * @cssprop --uf-checkbox-group-indent - Indent of the checkboxes under a \"select all\".\n */\nexport class UfCheckboxGroup extends LitElement {\n static override styles = [\n hostStyles,\n fieldStyles,\n css`\n .options {\n display: flex;\n flex-direction: column;\n gap: var(--uf-space-2);\n margin-top: var(--uf-space-1);\n }\n\n :host([orientation='horizontal']) .options {\n flex-direction: row;\n flex-wrap: wrap;\n gap: var(--uf-space-2) var(--uf-space-5);\n }\n\n /* The checkboxes controlled by \"select all\" sit indented under it. */\n .has-select-all ::slotted(uf-checkbox:not([select-all])) {\n margin-inline-start: var(--uf-checkbox-group-indent, calc(1.125rem + var(--uf-space-2)));\n }\n `,\n ];\n\n static override properties: PropertyDeclarations = {\n label: {},\n hint: {},\n orientation: { reflect: true },\n };\n\n /** Visible group label. */\n declare label: string | undefined;\n /** Help text below the checkboxes. */\n declare hint: string | undefined;\n /** Lays the checkboxes out in a column or a row. */\n declare orientation: 'vertical' | 'horizontal';\n\n readonly #slots = new HasSlotController(this, 'label', 'hint');\n readonly #id = uniqueId('uf-checkbox-group');\n\n constructor() {\n super();\n this.orientation = 'vertical';\n // Runs before listeners added later (e.g. a framework's), so they see the synced state.\n this.addEventListener('change', this.#onChange);\n }\n\n get #selectAll(): UfCheckbox | null {\n return this.querySelector<UfCheckbox>('uf-checkbox[select-all]');\n }\n\n /** The checkboxes in the group, other than \"select all\". */\n get #options(): UfCheckbox[] {\n return [...this.querySelectorAll<UfCheckbox>('uf-checkbox')].filter((c) => !c.selectAll);\n }\n\n /** The values of the checked checkboxes (other than \"select all\"). */\n get value(): string[] {\n return this.#options.filter((c) => c.checked).map((c) => c.value);\n }\n\n set value(values: string[]) {\n const wanted = new Set(values ?? []);\n this.#updateOptions((option) => wanted.has(option.value));\n }\n\n /** True while the group checks options itself, so they don't each update \"select all\" halfway. */\n #updatingOptions = false;\n\n #updateOptions(checked: (option: UfCheckbox) => boolean): void {\n this.#updatingOptions = true;\n try {\n for (const option of this.#options) option.checked = checked(option);\n } finally {\n this.#updatingOptions = false;\n }\n this[syncSelectAll]();\n }\n\n /** Updates \"select all\" to match the other checkboxes. The checkboxes call it when they change. @internal */\n [syncSelectAll](): void {\n const selectAll = this.#selectAll;\n if (!selectAll || this.#updatingOptions) return;\n const options = this.#options;\n const checked = options.filter((c) => c.checked).length;\n selectAll.checked = checked > 0 && checked === options.length;\n selectAll.indeterminate = checked > 0 && checked < options.length;\n }\n\n #onChange = (event: Event): void => {\n const target = event.target as UfCheckbox;\n if (target.localName !== 'uf-checkbox' || !this.contains(target)) return;\n if (target.selectAll) {\n const checked = target.checked;\n // Disabled checkboxes keep their state, like any control the user can't change.\n this.#updateOptions((option) => (option.disabled ? option.checked : checked));\n } else {\n this[syncSelectAll]();\n }\n };\n\n override render() {\n const labelId = `${this.#id}-label`;\n const hintId = `${this.#id}-hint`;\n const hasLabel = Boolean(this.label) || this.#slots.has('label');\n const hasHint = Boolean(this.hint) || this.#slots.has('hint');\n\n return html`\n <div\n class=${classMap({ field: true, 'has-select-all': Boolean(this.#selectAll) })}\n part=\"base\"\n role=\"group\"\n aria-labelledby=${ifDefined(hasLabel ? labelId : undefined)}\n aria-describedby=${ifDefined(hasHint ? hintId : undefined)}\n >\n <div id=${labelId} class=\"field-label\" part=\"form-label\" ?hidden=${!hasLabel}>\n <slot name=\"label\">${this.label}</slot>\n </div>\n <div class=\"options\" part=\"options\">\n <slot\n @slotchange=${() => {\n this[syncSelectAll]();\n this.requestUpdate();\n }}\n ></slot>\n </div>\n <div id=${hintId} class=\"field-hint\" part=\"hint\" ?hidden=${!hasHint}>\n <slot name=\"hint\">${this.hint ?? nothing}</slot>\n </div>\n </div>\n `;\n }\n}\n\ndefineElement('uf-checkbox-group', UfCheckboxGroup);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-checkbox-group': UfCheckboxGroup;\n }\n}\n",
|
|
867
867
|
"components/combobox/combobox.ts": "import { css, html, nothing, type PropertyDeclarations, type PropertyValues } from 'lit';\nimport { classMap } from 'lit/directives/class-map.js';\nimport { ifDefined } from 'lit/directives/if-defined.js';\nimport { live } from 'lit/directives/live.js';\nimport { defineElement } from '../../internal/define.js';\nimport { controlBoxStyles, describedBy, fieldStyles, renderField, type FieldSize } from '../../internal/field.js';\nimport { FormControl } from '../../internal/form-control.js';\nimport { iconSvg, icons } from '../../internal/icons.js';\nimport { flattenOptions, observeOptions, readItems, type Item, type OptionItem } from '../../internal/options.js';\nimport { autoUpdate, positionFloating } from '../../internal/position.js';\nimport { hostStyles } from '../../internal/shared.styles.js';\nimport { HasSlotController, uniqueId } from '../../internal/slot.js';\n\n/** A visible option, with its group and its index among visible options. */\ninterface Row {\n option: OptionItem;\n group?: string;\n index: number;\n}\n\n/**\n * A text field with a filterable list of options, following the WAI-ARIA\n * combobox pattern. Typing filters the list; arrow keys move through it and\n * Enter picks an option. Only listed values can be chosen. Write options as\n * plain `<option>` and `<optgroup>` children, like `<uf-select>`.\n *\n * @summary Lets users search a list and pick one option.\n * @tag uf-combobox\n *\n * @slot - `<option>` and `<optgroup>` elements. They are read, not rendered.\n * @slot label - The label, when you need markup. Overrides `label`.\n * @slot hint - Help text below the field. Overrides `hint`.\n * @slot prefix - An icon before the input.\n *\n * @event input - Fired as the user types in the field (the search text, not the value).\n * @event change - Fired when the selected value changes.\n * @event uf-show - The list opened.\n * @event uf-hide - The list closed.\n *\n * @csspart field - The wrapper around label, control, hint and error.\n * @csspart form-label - The label.\n * @csspart box - The bordered box.\n * @csspart input - The native `<input>`.\n * @csspart toggle - The button that opens the list.\n * @csspart listbox - The floating list.\n * @csspart option - Each option.\n * @csspart group-label - Each group heading.\n * @csspart empty - The \"no results\" message.\n * @csspart hint - The hint text.\n * @csspart error - The validation message.\n *\n * @cssprop --uf-combobox-max-height - Maximum height of the list before it scrolls.\n * @cssprop --uf-field-bg - Background of the box.\n * @cssprop --uf-field-border-color - Border color of the box.\n * @cssprop --uf-field-radius - Corner radius of the box.\n *\n * @cssstate user-invalid - The value is invalid and the user has interacted with the field.\n */\nexport class UfCombobox extends FormControl {\n static override styles = [\n hostStyles,\n fieldStyles,\n controlBoxStyles,\n css`\n .box {\n padding-inline-end: 0;\n }\n\n .toggle {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n align-self: stretch;\n width: calc(var(--_height) - 2px);\n padding: 0;\n border: 0;\n background: transparent;\n color: var(--uf-color-text-muted);\n cursor: pointer;\n }\n\n .toggle:disabled {\n cursor: not-allowed;\n }\n\n .toggle .icon {\n width: 1em;\n height: 1em;\n transition: rotate var(--uf-duration-fast) ease;\n }\n\n .toggle.open .icon {\n rotate: 180deg;\n }\n\n .listbox {\n position: fixed;\n inset: auto;\n margin: 0;\n max-height: var(--uf-combobox-max-height, 16rem);\n padding: var(--uf-space-1) 0;\n overflow: auto;\n border: 1px solid var(--uf-color-border);\n border-radius: var(--uf-radius-control);\n background: var(--uf-color-surface-overlay);\n color: var(--uf-color-text);\n font-family: var(--uf-font-family-sans);\n font-size: var(--uf-font-size-md);\n box-shadow: var(--uf-shadow-overlay);\n }\n\n .option {\n display: flex;\n align-items: center;\n gap: var(--uf-space-2);\n min-height: var(--uf-size-control-sm);\n padding: 0 var(--uf-space-3) 0 var(--uf-space-2);\n cursor: pointer;\n user-select: none;\n }\n\n .option .check {\n display: inline-flex;\n width: 1rem;\n flex: none;\n }\n\n .option .icon {\n width: 1rem;\n height: 1rem;\n }\n\n .option.active {\n background: var(--uf-color-accent-tint);\n color: var(--uf-color-on-accent-tint);\n }\n\n .option[aria-selected='true'] {\n font-weight: var(--uf-font-weight-medium);\n }\n\n .option[aria-disabled='true'] {\n opacity: 0.5;\n cursor: not-allowed;\n }\n\n .group-label {\n padding: var(--uf-space-2) var(--uf-space-3) var(--uf-space-1);\n color: var(--uf-color-text-muted);\n font-size: var(--uf-font-size-sm);\n font-weight: var(--uf-font-weight-semibold);\n }\n\n .empty {\n padding: var(--uf-space-2) var(--uf-space-3);\n color: var(--uf-color-text-muted);\n }\n\n .sr-only {\n position: absolute;\n width: 1px;\n height: 1px;\n overflow: hidden;\n clip-path: inset(50%);\n white-space: nowrap;\n }\n `,\n ];\n\n static override properties: PropertyDeclarations = {\n value: { attribute: false },\n defaultValue: { attribute: 'value' },\n label: {},\n hint: {},\n placeholder: {},\n size: { reflect: true },\n open: { type: Boolean, reflect: true },\n };\n\n /** The selected option's value, or an empty string. */\n declare value: string;\n /** Initially selected value, restored on form reset. Set with the `value` attribute. */\n declare defaultValue: string | undefined;\n /** Visible label. */\n declare label: string | undefined;\n /** Help text below the field. */\n declare hint: string | undefined;\n /** Placeholder text in the field. */\n declare placeholder: string | undefined;\n /** Size of the field. */\n declare size: FieldSize;\n /** Whether the list is showing. */\n declare open: boolean;\n\n readonly #slots = new HasSlotController(this, 'label', 'hint');\n readonly #id = uniqueId('uf-combobox');\n #observer?: MutationObserver;\n #items: Item[] = [];\n #itemsChanged = false;\n #hasInitialized = false;\n /** Text the user typed; null while the field shows the selected option's label. */\n #query: string | null = null;\n /** Index of the highlighted row among visible options, or -1. */\n #active = -1;\n #cleanup?: () => void;\n\n constructor() {\n super();\n this.value = '';\n this.size = 'md';\n this.open = false;\n this.addEventListener('focusout', this.#onFocusOut);\n }\n\n override connectedCallback(): void {\n super.connectedCallback();\n this.#readItems();\n this.#observer = observeOptions(this, () => this.#readItems());\n }\n\n override disconnectedCallback(): void {\n super.disconnectedCallback();\n this.#observer?.disconnect();\n this.#cleanup?.();\n }\n\n get #input(): HTMLInputElement | null {\n return this.renderRoot.querySelector('input');\n }\n\n get #listbox(): HTMLElement | null {\n return this.renderRoot.querySelector('.listbox');\n }\n\n get #options(): OptionItem[] {\n return flattenOptions(this.#items);\n }\n\n get #selected(): OptionItem | undefined {\n return this.#options.find((o) => o.value === this.value);\n }\n\n /** Options matching the current search, in order, with their group. */\n get #rows(): Row[] {\n const query = this.#query?.trim().toLowerCase() ?? '';\n const rows: Row[] = [];\n const add = (option: OptionItem, group?: string) => {\n if (!query || option.label.toLowerCase().includes(query)) rows.push({ option, group, index: rows.length });\n };\n for (const item of this.#items) {\n if (item.kind === 'group') item.options.forEach((o) => add(o, item.label));\n else add(item);\n }\n return rows;\n }\n\n #readItems(): void {\n this.#items = readItems(this);\n this.#itemsChanged = true;\n this.requestUpdate();\n }\n\n #initialValue(): string {\n if (this.defaultValue !== undefined && this.defaultValue !== null) return this.defaultValue;\n return this.#options.find((o) => o.selected)?.value ?? '';\n }\n\n /** Opens the list. */\n show(): void {\n if (!this.isDisabled) this.open = true;\n }\n\n /** Closes the list. */\n hide(): void {\n this.open = false;\n }\n\n override willUpdate(changed: PropertyValues<this>): void {\n if (changed.has('defaultValue') || this.#itemsChanged) {\n this.#itemsChanged = false;\n // Frameworks often connect the element before appending its options: wait for them.\n if (this.#items.length && !this.#hasInitialized) {\n // A value set before the options were read (e.g. by a framework) wins if it exists.\n if (!(this.value && this.#selected)) this.value = this.#initialValue();\n this.#hasInitialized = true;\n } else if (this.#items.length && this.value && !this.#selected) {\n this.value = this.#initialValue();\n }\n }\n if (changed.has('open') && !this.open) {\n this.#query = null;\n this.#active = -1;\n }\n }\n\n override updated(changed: PropertyValues<this>): void {\n this.syncFormState();\n if (changed.has('open')) this.#syncPopup();\n this.renderRoot.querySelector('.option.active')?.scrollIntoView({ block: 'nearest' });\n }\n\n #syncPopup(): void {\n const listbox = this.#listbox;\n const box = this.renderRoot.querySelector<HTMLElement>('.box');\n if (!listbox || !box) return;\n if (this.open && !listbox.matches(':popover-open')) {\n listbox.showPopover();\n this.#cleanup = autoUpdate(box, listbox, () => {\n listbox.style.minWidth = `${box.offsetWidth}px`;\n positionFloating(box, listbox, 'bottom-start', 4);\n });\n this.dispatchEvent(new Event('uf-show'));\n } else if (!this.open && listbox.matches(':popover-open')) {\n listbox.hidePopover();\n this.#cleanup?.();\n this.#cleanup = undefined;\n this.dispatchEvent(new Event('uf-hide'));\n }\n }\n\n protected syncFormState(): void {\n const input = this.#input;\n if (!input) return;\n this.internals.setFormValue(this.value);\n this.setValidity({ valueMissing: this.required && !this.value }, this.translator.t('selectItem'), input);\n }\n\n protected resetValue(): void {\n this.value = this.#initialValue();\n this.#query = null;\n }\n\n /** @internal */\n formStateRestoreCallback(state: string | null): void {\n this.value = state ?? '';\n }\n\n #select(option: OptionItem): void {\n if (option.disabled) return;\n const changed = option.value !== this.value;\n this.value = option.value;\n this.#query = null;\n this.hide();\n this.markInteracted();\n if (changed) this.emitChange();\n }\n\n /** Highlights the next or previous enabled row, wrapping around. */\n #move(step: 1 | -1, rows: Row[]): void {\n const enabled = rows.filter((r) => !r.option.disabled);\n if (!enabled.length) return;\n const position = enabled.findIndex((r) => r.index === this.#active);\n const next = position === -1 ? (step === 1 ? 0 : enabled.length - 1) : (position + step + enabled.length) % enabled.length;\n this.#active = enabled[next].index;\n this.requestUpdate();\n }\n\n /** On opening, highlight the selected option, or the first one. */\n #openWithActive(rows: Row[], fromEnd = false): void {\n const selected = rows.find((r) => r.option.value === this.value && !r.option.disabled);\n const enabled = rows.filter((r) => !r.option.disabled);\n this.#active = selected?.index ?? (fromEnd ? enabled[enabled.length - 1] : enabled[0])?.index ?? -1;\n this.show();\n }\n\n #onInput = (event: Event): void => {\n this.#query = (event.target as HTMLInputElement).value;\n // Highlight the first match, so Enter picks it.\n this.#active = this.#rows.find((r) => !r.option.disabled)?.index ?? -1;\n this.show();\n this.requestUpdate();\n };\n\n #onKeyDown = (event: KeyboardEvent): void => {\n const rows = this.#rows;\n switch (event.key) {\n case 'ArrowDown':\n event.preventDefault();\n if (!this.open || event.altKey) this.#openWithActive(rows);\n else this.#move(1, rows);\n break;\n case 'ArrowUp':\n event.preventDefault();\n if (!this.open) this.#openWithActive(rows, true);\n else this.#move(-1, rows);\n break;\n case 'Enter': {\n const row = rows.find((r) => r.index === this.#active);\n if (this.open && row) {\n event.preventDefault();\n this.#select(row.option);\n }\n break;\n }\n case 'Escape':\n if (this.open) {\n event.preventDefault();\n this.hide();\n }\n break;\n }\n };\n\n /** Leaving the field: accept an exact match, clear on empty text, otherwise revert. */\n #commitText(): void {\n if (this.#query === null) return;\n const text = this.#query.trim().toLowerCase();\n if (!text) {\n if (this.value) {\n this.value = '';\n this.markInteracted();\n this.emitChange();\n }\n } else {\n const match = this.#options.find((o) => !o.disabled && o.label.toLowerCase() === text);\n if (match) this.#select(match);\n }\n this.#query = null;\n this.requestUpdate();\n }\n\n #onFocusOut = (event: FocusEvent): void => {\n const next = event.relatedTarget as Node | null;\n if (next && (this.contains(next) || this.renderRoot.contains(next))) return;\n this.#commitText();\n this.markInteracted();\n this.hide();\n };\n\n #onToggleClick = (): void => {\n if (this.open) this.hide();\n else this.#openWithActive(this.#rows);\n this.#input?.focus();\n };\n\n #renderOption(row: Row) {\n const { option } = row;\n const selected = option.value === this.value;\n return html`\n <div\n id=${`${this.#id}-option-${row.index}`}\n class=${classMap({ option: true, active: row.index === this.#active })}\n part=\"option\"\n role=\"option\"\n aria-selected=${selected ? 'true' : 'false'}\n aria-disabled=${option.disabled ? 'true' : 'false'}\n @pointerdown=${(e: Event) => e.preventDefault()}\n @click=${() => this.#select(option)}\n @pointermove=${() => {\n if (!option.disabled && this.#active !== row.index) {\n this.#active = row.index;\n this.requestUpdate();\n }\n }}\n >\n <span class=\"check\">${selected ? iconSvg(icons.check) : nothing}</span>\n ${option.label}\n </div>\n `;\n }\n\n #renderRows(rows: Row[]) {\n const out = [];\n let group: string | undefined;\n for (const row of rows) {\n if (row.group !== group) {\n group = row.group;\n if (group) out.push(html`<div class=\"group-label\" part=\"group-label\" role=\"presentation\">${group}</div>`);\n }\n out.push(this.#renderOption(row));\n }\n return out;\n }\n\n override render() {\n const ids = { hintId: `${this.#id}-hint`, errorId: `${this.#id}-error` };\n const listboxId = `${this.#id}-listbox`;\n const error = this.showInvalid ? this.validationMessage : '';\n const hasHintSlot = this.#slots.has('hint');\n const rows = this.#rows;\n const activeId = this.open && this.#active >= 0 ? `${this.#id}-option-${this.#active}` : undefined;\n const text = this.#query ?? this.#selected?.label ?? '';\n\n return renderField({\n ...ids,\n controlId: this.#id,\n label: this.label,\n hasLabelSlot: this.#slots.has('label'),\n hint: this.hint,\n hasHintSlot,\n error,\n required: this.required,\n control: html`\n <div class=${classMap({ box: true, disabled: this.isDisabled })} part=\"box\">\n <slot name=\"prefix\"></slot>\n <input\n id=${this.#id}\n class=\"native\"\n part=\"input\"\n type=\"text\"\n role=\"combobox\"\n autocomplete=\"off\"\n .value=${live(text)}\n placeholder=${ifDefined(this.placeholder)}\n ?disabled=${this.isDisabled}\n aria-expanded=${this.open ? 'true' : 'false'}\n aria-controls=${listboxId}\n aria-autocomplete=\"list\"\n aria-activedescendant=${ifDefined(activeId)}\n aria-required=${this.required ? 'true' : 'false'}\n aria-invalid=${error ? 'true' : 'false'}\n aria-describedby=${ifDefined(describedBy({ ...ids, hint: this.hint, hasHintSlot, error }))}\n @input=${this.#onInput}\n @keydown=${this.#onKeyDown}\n @click=${() => !this.open && this.#openWithActive(this.#rows)}\n />\n <button\n class=${classMap({ toggle: true, open: this.open })}\n part=\"toggle\"\n type=\"button\"\n tabindex=\"-1\"\n aria-label=${this.translator.t('showOptions')}\n ?disabled=${this.isDisabled}\n @pointerdown=${(e: Event) => e.preventDefault()}\n @click=${this.#onToggleClick}\n >\n ${iconSvg(icons['chevron-down'])}\n </button>\n </div>\n <div id=${listboxId} class=\"listbox\" part=\"listbox\" popover=\"manual\" role=\"listbox\" aria-label=${ifDefined(this.label)}>\n ${rows.length ? this.#renderRows(rows) : html`<div class=\"empty\" part=\"empty\" role=\"option\" aria-disabled=\"true\" aria-selected=\"false\">${this.translator.t('noResults')}</div>`}\n </div>\n <div class=\"sr-only\" role=\"status\">\n ${this.open && this.#query !== null\n ? rows.length === 1\n ? this.translator.t('oneResult')\n : this.translator.t('results', { count: rows.length })\n : ''}\n </div>\n `,\n });\n }\n}\n\ndefineElement('uf-combobox', UfCombobox);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-combobox': UfCombobox;\n }\n}\n",
|
|
@@ -887,7 +887,7 @@
|
|
|
887
887
|
"components/progress/progress.ts": "import { LitElement, css, html, nothing, type PropertyDeclarations } from 'lit';\nimport { ifDefined } from 'lit/directives/if-defined.js';\nimport { defineElement } from '../../internal/define.js';\nimport { Translator } from '../../internal/i18n.js';\nimport { hostStyles } from '../../internal/shared.styles.js';\nimport { HasSlotController, uniqueId } from '../../internal/slot.js';\n\nexport type ProgressVariant = 'accent' | 'success' | 'warning' | 'danger';\nexport type ProgressSize = 'sm' | 'md' | 'lg';\n\n/**\n * A bar that shows how far a task has got. Without a `value` it's\n * indeterminate: an animated bar for work whose length isn't known, like a\n * native `<progress>`.\n *\n * @summary Shows how far a task has got.\n * @tag uf-progress\n *\n * @slot label - The label, when you need markup. Overrides `label`.\n *\n * @csspart base - The wrapper around label and bar.\n * @csspart label - The label.\n * @csspart value - The percentage, when `show-value` is set.\n * @csspart track - The bar's background.\n * @csspart indicator - The filled part of the bar.\n *\n * @cssprop --uf-progress-height - Height of the bar.\n * @cssprop --uf-progress-radius - Corner radius of the bar. Use `999px` for a pill.\n * @cssprop --uf-progress-track-color - Color of the bar's background.\n * @cssprop --uf-progress-indicator-color - Color of the filled part.\n */\nexport class UfProgress extends LitElement {\n static override styles = [\n hostStyles,\n css`\n :host {\n display: block;\n --_height: var(--uf-progress-height, 0.5rem);\n --_color: var(--uf-color-accent);\n }\n\n :host([size='sm']) {\n --_height: var(--uf-progress-height, 0.25rem);\n }\n\n :host([size='lg']) {\n --_height: var(--uf-progress-height, 0.75rem);\n }\n\n :host([variant='success']) {\n --_color: var(--uf-color-success);\n }\n :host([variant='warning']) {\n --_color: var(--uf-color-warning);\n }\n :host([variant='danger']) {\n --_color: var(--uf-color-danger);\n }\n\n .base {\n display: flex;\n flex-direction: column;\n gap: var(--uf-space-1);\n font-family: var(--uf-font-family-sans);\n font-size: var(--uf-font-size-sm);\n color: var(--uf-color-text);\n }\n\n .header {\n display: flex;\n justify-content: space-between;\n gap: var(--uf-space-2);\n }\n\n .label {\n font-weight: var(--uf-font-weight-medium);\n }\n\n .value {\n color: var(--uf-color-text-muted);\n font-variant-numeric: tabular-nums;\n }\n\n .track {\n position: relative;\n height: var(--_height);\n border-radius: var(--uf-progress-radius, var(--uf-radius-control));\n background: var(--uf-progress-track-color, var(--uf-color-surface-hover));\n overflow: hidden;\n }\n\n .indicator {\n height: 100%;\n border-radius: inherit;\n background: var(--uf-progress-indicator-color, var(--_color));\n transition: width var(--uf-duration-base) ease;\n }\n\n .indeterminate .indicator {\n position: absolute;\n width: 40%;\n animation: uf-progress-slide 1.5s ease-in-out infinite;\n }\n\n @keyframes uf-progress-slide {\n from {\n left: -40%;\n }\n to {\n left: 100%;\n }\n }\n\n @media (prefers-reduced-motion: reduce) {\n .indicator {\n transition: none;\n }\n .indeterminate .indicator {\n animation-duration: 4s;\n }\n }\n\n [hidden] {\n display: none !important;\n }\n `,\n ];\n\n static override properties: PropertyDeclarations = {\n value: { type: Number },\n max: { type: Number },\n label: {},\n showValue: { type: Boolean, attribute: 'show-value' },\n variant: { reflect: true },\n size: { reflect: true },\n };\n\n /** Progress so far, from 0 to `max`. Leave it out for an indeterminate bar. */\n declare value: number | undefined;\n /** The value that means done. */\n declare max: number;\n /** Visible label, also the bar's accessible name. Without one, it's named \"Progress\". */\n declare label: string | undefined;\n /** Shows the percentage next to the label. */\n declare showValue: boolean;\n /** Color, by meaning: `accent`, `success`, `warning` or `danger`. */\n declare variant: ProgressVariant;\n /** Height of the bar: `sm`, `md` or `lg`. */\n declare size: ProgressSize;\n\n readonly #slots = new HasSlotController(this, 'label');\n readonly #id = uniqueId('uf-progress');\n readonly #translator = new Translator(this);\n\n constructor() {\n super();\n this.max = 100;\n this.showValue = false;\n this.variant = 'accent';\n this.size = 'md';\n }\n\n /** The value as a percentage, or undefined when indeterminate. */\n get #percent(): number | undefined {\n if (this.value == null || Number.isNaN(this.value)) return undefined;\n const max = this.max > 0 ? this.max : 100;\n return Math.round((Math.min(Math.max(this.value, 0), max) / max) * 100);\n }\n\n override render() {\n const percent = this.#percent;\n const indeterminate = percent === undefined;\n const hasLabel = Boolean(this.label) || this.#slots.has('label');\n const showValue = this.showValue && !indeterminate;\n const labelId = `${this.#id}-label`;\n return html`\n <div class=\"base\" part=\"base\">\n <div class=\"header\" ?hidden=${!hasLabel && !showValue}>\n <span id=${labelId} class=\"label\" part=\"label\" ?hidden=${!hasLabel}><slot name=\"label\">${this.label}</slot></span>\n ${showValue ? html`<span class=\"value\" part=\"value\" aria-hidden=\"true\">${percent}%</span>` : nothing}\n </div>\n <div\n class=\"track ${indeterminate ? 'indeterminate' : ''}\"\n part=\"track\"\n role=\"progressbar\"\n aria-labelledby=${ifDefined(hasLabel ? labelId : undefined)}\n aria-label=${ifDefined(hasLabel ? undefined : this.#translator.t('progress'))}\n aria-valuemin=\"0\"\n aria-valuemax=\"100\"\n aria-valuenow=${ifDefined(percent)}\n >\n <div class=\"indicator\" part=\"indicator\" style=${indeterminate ? '' : `width: ${percent}%`}></div>\n </div>\n </div>\n `;\n }\n}\n\ndefineElement('uf-progress', UfProgress);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-progress': UfProgress;\n }\n}\n",
|
|
888
888
|
"components/radio/radio.ts": "import { LitElement, css, html, type PropertyDeclarations } from 'lit';\nimport { defineElement } from '../../internal/define.js';\nimport { hostStyles } from '../../internal/shared.styles.js';\n\n/**\n * One option inside `<uf-radio-group>`. The group manages checked state,\n * focus and keyboard navigation.\n *\n * @summary An option in a radio group.\n * @tag uf-radio\n *\n * @slot - The label.\n *\n * @csspart control - The circle.\n * @csspart label - The label text.\n *\n * @cssprop --uf-radio-size - Size of the circle.\n * @cssprop --uf-radio-checked-bg - Color of the circle when checked.\n *\n * @cssstate checked - The radio is selected.\n */\nexport class UfRadio extends LitElement {\n static override styles = [\n hostStyles,\n css`\n :host {\n --_size: var(--uf-radio-size, var(--_circle, 1.125rem));\n display: flex;\n align-items: flex-start;\n gap: var(--uf-space-2);\n font-family: var(--uf-font-family-sans);\n font-size: var(--uf-font-size-md);\n line-height: 1.4;\n color: var(--uf-color-text);\n cursor: pointer;\n outline: none;\n }\n\n /* The group's size. */\n :host([data-group-size='sm']) {\n --_circle: 1rem;\n font-size: var(--uf-font-size-sm);\n }\n\n :host([data-group-size='lg']) {\n --_circle: 1.25rem;\n font-size: var(--uf-font-size-lg);\n }\n\n /* Grey instead of faded, like disabled fields. */\n :host([disabled]),\n :host([data-group-disabled]) {\n color: var(--uf-color-text-muted);\n cursor: not-allowed;\n }\n\n .control {\n position: relative;\n flex: none;\n width: var(--_size);\n height: var(--_size);\n margin-top: calc((1.4em - var(--_size)) / 2);\n border: 1px solid var(--uf-color-border-strong);\n border-radius: 50%;\n background: var(--uf-color-surface);\n transition: border-color var(--uf-duration-fast) ease;\n }\n\n :host(:hover:not([disabled], [data-group-disabled])) .control {\n border-color: var(--uf-color-text-muted);\n }\n\n :host([checked]) .control {\n border: calc(var(--_size) * 0.3) solid var(--uf-radio-checked-bg, var(--uf-color-accent-strong));\n }\n\n :host([disabled]) .control,\n :host([data-group-disabled]) .control {\n border-color: var(--uf-color-border);\n background: var(--uf-color-neutral-fill);\n }\n\n :host([disabled][checked]) .control,\n :host([data-group-disabled][checked]) .control {\n border-color: var(--uf-color-text-muted);\n }\n\n :host([data-invalid]) .control {\n border-color: var(--uf-color-danger-text);\n box-shadow: inset 0 0 0 1px var(--uf-color-danger-text);\n }\n\n :host(:focus-visible) .control {\n outline: var(--uf-focus-ring-width) solid var(--uf-color-focus-ring);\n outline-offset: var(--uf-focus-ring-offset);\n }\n `,\n ];\n\n static override properties: PropertyDeclarations = {\n value: { reflect: true },\n checked: { type: Boolean, reflect: true },\n disabled: { type: Boolean, reflect: true },\n };\n\n /** Value the group takes when this radio is selected. */\n declare value: string;\n /** Whether this radio is selected. Set by the group. */\n declare checked: boolean;\n /** Disables this option. */\n declare disabled: boolean;\n\n readonly #internals = this.attachInternals();\n\n constructor() {\n super();\n this.value = '';\n this.checked = false;\n this.disabled = false;\n }\n\n override connectedCallback(): void {\n super.connectedCallback();\n // Real attributes rather than ElementInternals ARIA, so axe, Testing Library\n // and older assistive tech all see them.\n this.setAttribute('role', 'radio');\n }\n\n override updated(): void {\n const groupDisabled = this.hasAttribute('data-group-disabled');\n this.setAttribute('aria-checked', String(this.checked));\n this.setAttribute('aria-disabled', String(this.disabled || groupDisabled));\n this.#internals.states?.[this.checked ? 'add' : 'delete']('checked');\n }\n\n override render() {\n return html`\n <span class=\"control\" part=\"control\"></span>\n <span class=\"label\" part=\"label\"><slot></slot></span>\n `;\n }\n}\n\ndefineElement('uf-radio', UfRadio);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-radio': UfRadio;\n }\n}\n",
|
|
889
889
|
"components/radio-group/radio-group.ts": "import { css, html, nothing, type PropertyDeclarations, type PropertyValues } from 'lit';\nimport { classMap } from 'lit/directives/class-map.js';\nimport { ifDefined } from 'lit/directives/if-defined.js';\nimport { defineElement } from '../../internal/define.js';\nimport { describedBy, fieldStyles, type FieldSize } from '../../internal/field.js';\nimport { FormControl } from '../../internal/form-control.js';\nimport { hostStyles } from '../../internal/shared.styles.js';\nimport { HasSlotController, uniqueId } from '../../internal/slot.js';\nimport '../radio/radio.js';\nimport type { UfRadio } from '../radio/radio.js';\n\n/**\n * A group of `<uf-radio>` options with one selected value. Arrow keys move\n * the selection, and only the selected option is in the tab order.\n *\n * @summary Lets users pick exactly one option from a list.\n * @tag uf-radio-group\n *\n * @slot - `<uf-radio>` elements.\n * @slot label - The group label, when you need markup. Overrides `label`.\n * @slot hint - Help text below the options. Overrides `hint`.\n *\n * @event input - Fired when the selection changes.\n * @event change - Fired when the selection changes.\n *\n * @csspart base - The element with `role=\"radiogroup\"`.\n * @csspart form-label - The group label.\n * @csspart options - The wrapper around the radios.\n * @csspart hint - The hint text.\n * @csspart error - The validation message.\n *\n * @cssstate user-invalid - Required with nothing selected, after the user interacted.\n */\nexport class UfRadioGroup extends FormControl {\n static override shadowRootOptions = { ...FormControl.shadowRootOptions, delegatesFocus: false };\n\n static override styles = [\n hostStyles,\n fieldStyles,\n css`\n .options {\n display: flex;\n flex-direction: column;\n gap: var(--uf-space-2);\n margin-top: var(--uf-space-1);\n }\n\n :host([orientation='horizontal']) .options {\n flex-direction: row;\n flex-wrap: wrap;\n gap: var(--uf-space-2) var(--uf-space-5);\n }\n `,\n ];\n\n static override properties: PropertyDeclarations = {\n value: { attribute: false },\n defaultValue: { attribute: 'value' },\n label: {},\n hint: {},\n orientation: { reflect: true },\n size: { reflect: true },\n };\n\n /** The selected radio's value, or an empty string. */\n declare value: string;\n /** Initially selected value, restored on form reset. Set with the `value` attribute. */\n declare defaultValue: string;\n /** Visible group label. */\n declare label: string | undefined;\n /** Help text below the options. */\n declare hint: string | undefined;\n /** Lays the options out in a column or a row. */\n declare orientation: 'vertical' | 'horizontal';\n /** Size of the radios and their labels: `sm`, `md` or `lg`. */\n declare size: FieldSize;\n\n readonly #slots = new HasSlotController(this, 'label', 'hint');\n readonly #id = uniqueId('uf-radio-group');\n\n constructor() {\n super();\n this.value = '';\n this.defaultValue = '';\n this.orientation = 'vertical';\n this.size = 'md';\n this.addEventListener('click', this.#onClick);\n this.addEventListener('keydown', this.#onKeyDown);\n }\n\n get #radios(): UfRadio[] {\n return [...this.querySelectorAll('uf-radio')];\n }\n\n #isEnabled(radio: UfRadio): boolean {\n return !radio.disabled && !this.isDisabled;\n }\n\n override willUpdate(changed: PropertyValues<this>): void {\n if (changed.has('defaultValue') && this.value === (changed.get('defaultValue') ?? '')) {\n this.value = this.defaultValue ?? '';\n }\n }\n\n override updated(): void {\n this.#syncRadios();\n this.syncFormState();\n }\n\n /** Reflects the group's value, disabled state, size and roving tabindex onto the radios. */\n #syncRadios(): void {\n const radios = this.#radios;\n const enabled = radios.filter((r) => this.#isEnabled(r));\n const focusable = enabled.find((r) => r.value === this.value) ?? enabled[0];\n const invalid = this.showInvalid;\n for (const radio of radios) {\n radio.checked = radio.value === this.value;\n radio.tabIndex = radio === focusable ? 0 : -1;\n radio.toggleAttribute('data-group-disabled', this.isDisabled);\n radio.setAttribute('data-group-size', this.size);\n radio.toggleAttribute('data-invalid', invalid);\n radio.requestUpdate();\n }\n }\n\n protected syncFormState(): void {\n this.internals.setFormValue(this.value || null);\n this.setValidity(\n { valueMissing: this.required && !this.value },\n this.translator.t('selectOption'),\n this.#radios[0],\n );\n }\n\n protected resetValue(): void {\n this.value = this.defaultValue ?? '';\n }\n\n /** @internal */\n formStateRestoreCallback(state: string | null): void {\n this.value = state ?? '';\n }\n\n #select(radio: UfRadio): void {\n radio.focus();\n if (radio.value === this.value) return;\n this.value = radio.value;\n this.markInteracted();\n this.dispatchEvent(new Event('input', { bubbles: true, composed: true }));\n this.emitChange();\n }\n\n #onClick = (event: MouseEvent): void => {\n const radio = (event.target as Element).closest('uf-radio');\n if (radio && this.contains(radio) && this.#isEnabled(radio)) this.#select(radio);\n };\n\n #onKeyDown = (event: KeyboardEvent): void => {\n const radios = this.#radios.filter((r) => this.#isEnabled(r));\n const current = (event.target as Element).closest('uf-radio');\n if (!current || !radios.length) return;\n\n const index = radios.indexOf(current);\n const step = { ArrowDown: 1, ArrowRight: 1, ArrowUp: -1, ArrowLeft: -1 }[event.key];\n if (step) {\n event.preventDefault();\n this.#select(radios[(index + step + radios.length) % radios.length]);\n } else if (event.key === ' ') {\n event.preventDefault();\n this.#select(current);\n }\n };\n\n /** Moves focus to the selected radio, or the first enabled one. */\n override focus(options?: FocusOptions): void {\n this.#radios.find((r) => r.tabIndex === 0)?.focus(options);\n }\n\n override render() {\n const ids = { hintId: `${this.#id}-hint`, errorId: `${this.#id}-error` };\n const labelId = `${this.#id}-label`;\n const error = this.showInvalid ? this.validationMessage : '';\n const hasHintSlot = this.#slots.has('hint');\n const hasLabel = Boolean(this.label) || this.#slots.has('label');\n\n return html`\n <div\n class=${classMap({ field: true, invalid: Boolean(error) })}\n part=\"base\"\n role=\"radiogroup\"\n aria-labelledby=${ifDefined(hasLabel ? labelId : undefined)}\n aria-describedby=${ifDefined(describedBy({ ...ids, hint: this.hint, hasHintSlot, error }))}\n aria-required=${this.required ? 'true' : 'false'}\n aria-invalid=${error ? 'true' : 'false'}\n aria-disabled=${this.isDisabled ? 'true' : 'false'}\n >\n <div id=${labelId} class=\"field-label\" part=\"form-label\" ?hidden=${!hasLabel}>\n <slot name=\"label\">${this.label}</slot>\n ${this.required ? html`<span class=\"required\" aria-hidden=\"true\">*</span>` : nothing}\n </div>\n <div class=\"options\" part=\"options\">\n <slot @slotchange=${() => this.#syncRadios()}></slot>\n </div>\n <div id=${ids.hintId} class=\"field-hint\" part=\"hint\" ?hidden=${!this.hint && !hasHintSlot}>\n <slot name=\"hint\">${this.hint}</slot>\n </div>\n <div id=${ids.errorId} class=\"field-error\" part=\"error\" ?hidden=${!error}>${error}</div>\n </div>\n `;\n }\n}\n\ndefineElement('uf-radio-group', UfRadioGroup);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-radio-group': UfRadioGroup;\n }\n}\n",
|
|
890
|
-
"components/segmented-control/segmented-control.ts": "import { css, html, nothing, type PropertyDeclarations, type PropertyValues } from 'lit';\nimport { classMap } from 'lit/directives/class-map.js';\nimport { ifDefined } from 'lit/directives/if-defined.js';\nimport { defineElement } from '../../internal/define.js';\nimport { describedBy, fieldStyles, type FieldSize } from '../../internal/field.js';\nimport { FormControl } from '../../internal/form-control.js';\nimport { flattenOptions, readItems, type OptionItem } from '../../internal/options.js';\nimport { focusRing, hostStyles } from '../../internal/shared.styles.js';\nimport { HasSlotController, uniqueId } from '../../internal/slot.js';\n\n/**\n * A row of buttons for one choice among a few, like \"List / Grid\" or \"Day /\n * Week / Month\". The choices are plain `<option>` children. One is always\n * selected: the `value` attribute, an option marked `selected`, or the first.\n *\n * It's a radio group for assistive tech: arrow keys move and select, Home and\n * End jump to the ends, and it submits its value with a form.\n *\n * @summary Picks one of a few options, side by side.\n * @tag uf-segmented-control\n *\n * @slot - `<option>` elements. `disabled` options can't be picked.\n * @slot label - The label, when you need markup. Overrides `label`.\n * @slot hint - Help text below the options. Overrides `hint`.\n *\n * @event input - The user picked another option.\n * @event change - The user picked another option.\n *\n * @csspart base - The element with `role=\"radiogroup\"`.\n * @csspart form-label - The label.\n * @csspart options - The row of buttons.\n * @csspart option - One button. The selected one also has the part `selected`.\n * @csspart selected - The selected button.\n * @csspart hint - The hint text.\n *\n * @cssprop --uf-segmented-control-bg - Background behind the buttons.\n * @cssprop --uf-segmented-control-selected-bg - Background of the selected button.\n * @cssprop --uf-segmented-control-selected-color - Text color of the selected button.\n * @cssprop --uf-segmented-control-radius - Corner radius of the row.\n */\nexport class UfSegmentedControl extends FormControl {\n static override styles = [\n hostStyles,\n fieldStyles,\n css`\n :host {\n display: inline-block;\n }\n\n .options {\n --_height: var(--uf-size-control-md);\n display: inline-flex;\n gap: 2px;\n padding: 2px;\n border: 1px solid var(--uf-color-border-strong);\n border-radius: var(--uf-segmented-control-radius, var(--uf-radius-control));\n background: var(--uf-segmented-control-bg, var(--uf-color-surface));\n }\n\n :host([size='sm']) .options {\n --_height: var(--uf-size-control-sm);\n }\n\n :host([size='lg']) .options {\n --_height: var(--uf-size-control-lg);\n }\n\n .option {\n min-height: calc(var(--_height) - 6px);\n padding: 0 var(--uf-space-3);\n border: 0;\n border-radius: inherit;\n background: transparent;\n color: var(--uf-color-text-muted);\n font: inherit;\n font-size: var(--uf-font-size-md);\n font-weight: var(--uf-font-weight-medium);\n white-space: nowrap;\n cursor: pointer;\n transition:\n background-color var(--uf-duration-fast) ease,\n color var(--uf-duration-fast) ease;\n }\n\n :host([size='sm']) .option {\n padding: 0 var(--uf-space-2);\n font-size: var(--uf-font-size-sm);\n }\n\n :host([size='lg']) .option {\n padding: 0 var(--uf-space-4);\n font-size: var(--uf-font-size-lg);\n }\n\n .option:hover:not(:disabled):not(.selected) {\n background: var(--uf-color-surface-hover);\n color: var(--uf-color-text);\n }\n\n .option.selected {\n background: var(--uf-segmented-control-selected-bg, var(--uf-color-accent));\n color: var(--uf-segmented-control-selected-color, var(--uf-color-on-accent));\n }\n\n .option:focus-visible {\n ${focusRing}\n }\n\n .option:disabled {\n color: var(--uf-color-border-strong);\n cursor: not-allowed;\n }\n\n /* Grey, like disabled fields. */\n .disabled .options {\n border-color: var(--uf-color-border);\n background: var(--uf-color-neutral-fill);\n }\n\n .disabled .option.selected {\n background: var(--uf-color-border-strong);\n color: var(--uf-color-surface);\n }\n `,\n ];\n\n static override properties: PropertyDeclarations = {\n value: { attribute: false },\n defaultValue: { attribute: 'value' },\n label: {},\n hint: {},\n size: { reflect: true },\n };\n\n /** The selected option's value. */\n declare value: string;\n /** Initially selected value, restored on form reset. Set with the `value` attribute. */\n declare defaultValue: string | undefined;\n /** Visible label, also the group's accessible name. */\n declare label: string | undefined;\n /** Help text below the options. */\n declare hint: string | undefined;\n /** Size of the buttons. */\n declare size: FieldSize;\n\n readonly #slots = new HasSlotController(this, 'label', 'hint');\n readonly #id = uniqueId('uf-segmented-control');\n readonly #observer = new MutationObserver(() => this.#readOptions());\n #options: OptionItem[] = [];\n #optionsChanged = false;\n #hasInitialized = false;\n\n constructor() {\n super();\n this.value = '';\n this.size = 'md';\n }\n\n override connectedCallback(): void {\n super.connectedCallback();\n this.#readOptions();\n this.#observer.observe(this, { childList: true, subtree: true, attributes: true, characterData: true });\n }\n\n override disconnectedCallback(): void {\n super.disconnectedCallback();\n this.#observer.disconnect();\n }\n\n #readOptions(): void {\n this.#options = flattenOptions(readItems(this));\n this.#optionsChanged = true;\n this.requestUpdate();\n }\n\n /** The value a reset returns to: the `value` attribute, a `selected` option, or the first enabled one. */\n #initialValue(): string {\n if (this.defaultValue !== undefined && this.defaultValue !== null) return this.defaultValue;\n return (this.#options.find((o) => o.selected) ?? this.#options.find((o) => !o.disabled))?.value ?? '';\n }\n\n override willUpdate(changed: PropertyValues<this>): void {\n if (!changed.has('defaultValue') && !this.#optionsChanged) return;\n this.#optionsChanged = false;\n // Frameworks often connect the element before appending its options: wait for them.\n if (!this.#options.length) return;\n const valid = this.#options.some((o) => o.value === this.value);\n if (!this.#hasInitialized) {\n // A value set before the options were read (e.g. by a framework) wins if it exists.\n if (!(this.value && valid)) this.value = this.#initialValue();\n this.#hasInitialized = true;\n } else if (!valid || changed.has('defaultValue')) {\n this.value = this.#initialValue();\n }\n }\n\n override updated(): void {\n this.syncFormState();\n }\n\n protected syncFormState(): void {\n this.internals.setFormValue(this.value);\n // One option is always selected: nothing to validate.\n this.setValidity({}, '');\n }\n\n protected resetValue(): void {\n this.value = this.#initialValue();\n }\n\n /** @internal */\n formStateRestoreCallback(state: string | null): void {\n this.value = state ?? '';\n }\n\n get #buttons(): HTMLButtonElement[] {\n return [...this.renderRoot.querySelectorAll<HTMLButtonElement>('.option')];\n }\n\n /** Moves focus to the selected option. */\n override focus(options?: FocusOptions): void {\n this.#buttons.find((b) => b.tabIndex === 0)?.focus(options);\n }\n\n #select(option: OptionItem, focus = false): void {\n if (option.disabled || this.isDisabled) return;\n if (focus) this.updateComplete.then(() => this.focus());\n if (option.value === this.value) return;\n this.value = option.value;\n this.markInteracted();\n this.dispatchEvent(new Event('input', { bubbles: true, composed: true }));\n this.emitChange();\n }\n\n #onKeyDown = (event: KeyboardEvent): void => {\n const enabled = this.#options.filter((o) => !o.disabled);\n const index = enabled.findIndex((o) => o.value === this.value);\n const rtl = getComputedStyle(this).direction === 'rtl';\n const next = { ArrowRight: rtl ? -1 : 1, ArrowLeft: rtl ? 1 : -1, ArrowDown: 1, ArrowUp: -1 }[event.key];\n let target: OptionItem | undefined;\n if (next) target = enabled[(index + next + enabled.length) % enabled.length];\n else if (event.key === 'Home') target = enabled[0];\n else if (event.key === 'End') target = enabled[enabled.length - 1];\n if (!target) return;\n event.preventDefault();\n this.#select(target, true);\n };\n\n override render() {\n const ids = { hintId: `${this.#id}-hint`, errorId: `${this.#id}-error` };\n const labelId = `${this.#id}-label`;\n const hasHintSlot = this.#slots.has('hint');\n const hasLabel = Boolean(this.label) || this.#slots.has('label');\n const disabled = this.isDisabled;\n // The selected option takes Tab; with none (no options yet), the first enabled one.\n const focusable = this.#options.find((o) => o.value === this.value && !o.disabled) ?? this.#options.find((o) => !o.disabled);\n\n return html`\n <div\n class=${classMap({ field: true, disabled })}\n part=\"base\"\n role=\"radiogroup\"\n aria-labelledby=${ifDefined(hasLabel ? labelId : undefined)}\n aria-describedby=${ifDefined(describedBy({ ...ids, hint: this.hint, hasHintSlot, error: '' }))}\n aria-disabled=${disabled ? 'true' : 'false'}\n >\n <div id=${labelId} class=\"field-label\" part=\"form-label\" ?hidden=${!hasLabel}>\n <slot name=\"label\">${this.label ?? nothing}</slot>\n </div>\n <div class=\"options\" part=\"options\" @keydown=${this.#onKeyDown}>\n ${this.#options.map((option) => {\n const selected = option.value === this.value;\n return html`<button\n class=${classMap({ option: true, selected })}\n part=${selected ? 'option selected' : 'option'}\n type=\"button\"\n role=\"radio\"\n aria-checked=${selected ? 'true' : 'false'}\n tabindex=${option === focusable ? 0 : -1}\n ?disabled=${disabled || option.disabled}\n @click=${() => this.#select(option)}\n >\n ${option.label}\n </button>`;\n })}\n </div>\n <div id=${ids.hintId} class=\"field-hint\" part=\"hint\" ?hidden=${!(this.hint || hasHintSlot)}>\n <slot name=\"hint\">${this.hint ?? nothing}</slot>\n </div>\n </div>\n `;\n }\n}\n\ndefineElement('uf-segmented-control', UfSegmentedControl);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-segmented-control': UfSegmentedControl;\n }\n}\n",
|
|
890
|
+
"components/segmented-control/segmented-control.ts": "import { css, html, nothing, type PropertyDeclarations, type PropertyValues } from 'lit';\nimport { classMap } from 'lit/directives/class-map.js';\nimport { ifDefined } from 'lit/directives/if-defined.js';\nimport { defineElement } from '../../internal/define.js';\nimport { describedBy, fieldStyles, type FieldSize } from '../../internal/field.js';\nimport { FormControl } from '../../internal/form-control.js';\nimport { flattenOptions, readItems, type OptionItem } from '../../internal/options.js';\nimport { focusRing, hostStyles } from '../../internal/shared.styles.js';\nimport { HasSlotController, uniqueId } from '../../internal/slot.js';\n\n/**\n * A row of buttons for one choice among a few, like \"List / Grid\" or \"Day /\n * Week / Month\". The choices are plain `<option>` children. One is always\n * selected: the `value` attribute, an option marked `selected`, or the first.\n *\n * It's a radio group for assistive tech: arrow keys move and select, Home and\n * End jump to the ends, and it submits its value with a form.\n *\n * @summary Picks one of a few options, side by side.\n * @tag uf-segmented-control\n *\n * @slot - `<option>` elements. `disabled` options can't be picked.\n * @slot label - The label, when you need markup. Overrides `label`.\n * @slot hint - Help text below the options. Overrides `hint`.\n *\n * @event input - The user picked another option.\n * @event change - The user picked another option.\n *\n * @csspart base - The element with `role=\"radiogroup\"`.\n * @csspart form-label - The label.\n * @csspart options - The row of buttons.\n * @csspart option - One button. The selected one also has the part `selected`.\n * @csspart selected - The selected button.\n * @csspart hint - The hint text.\n *\n * @cssprop --uf-segmented-control-bg - Background behind the buttons.\n * @cssprop --uf-segmented-control-selected-bg - Background of the selected button.\n * @cssprop --uf-segmented-control-selected-color - Text color of the selected button.\n * @cssprop --uf-segmented-control-radius - Corner radius of the row.\n */\nexport class UfSegmentedControl extends FormControl {\n static override styles = [\n hostStyles,\n fieldStyles,\n css`\n :host {\n display: inline-block;\n }\n\n .options {\n --_height: var(--uf-size-control-md);\n display: inline-flex;\n gap: 2px;\n padding: 2px;\n border: 1px solid var(--uf-color-border-strong);\n border-radius: var(--uf-segmented-control-radius, var(--uf-radius-control));\n background: var(--uf-segmented-control-bg, var(--uf-color-surface));\n }\n\n :host([size='sm']) .options {\n --_height: var(--uf-size-control-sm);\n }\n\n :host([size='lg']) .options {\n --_height: var(--uf-size-control-lg);\n }\n\n /* Share any extra width when the row is stretched, as in a grid; no effect at its natural width. */\n .option {\n flex: 1 1 auto;\n min-height: calc(var(--_height) - 6px);\n padding: 0 var(--uf-space-3);\n border: 0;\n border-radius: inherit;\n background: transparent;\n color: var(--uf-color-text-muted);\n font: inherit;\n font-size: var(--uf-font-size-md);\n font-weight: var(--uf-font-weight-medium);\n white-space: nowrap;\n cursor: pointer;\n transition:\n background-color var(--uf-duration-fast) ease,\n color var(--uf-duration-fast) ease;\n }\n\n :host([size='sm']) .option {\n padding: 0 var(--uf-space-2);\n font-size: var(--uf-font-size-sm);\n }\n\n :host([size='lg']) .option {\n padding: 0 var(--uf-space-4);\n font-size: var(--uf-font-size-lg);\n }\n\n .option:hover:not(:disabled):not(.selected) {\n background: var(--uf-color-surface-hover);\n color: var(--uf-color-text);\n }\n\n .option.selected {\n background: var(--uf-segmented-control-selected-bg, var(--uf-color-accent));\n color: var(--uf-segmented-control-selected-color, var(--uf-color-on-accent));\n }\n\n .option:focus-visible {\n ${focusRing}\n }\n\n .option:disabled {\n color: var(--uf-color-border-strong);\n cursor: not-allowed;\n }\n\n /* Grey, like disabled fields. */\n .disabled .options {\n border-color: var(--uf-color-border);\n background: var(--uf-color-neutral-fill);\n }\n\n .disabled .option.selected {\n background: var(--uf-color-border-strong);\n color: var(--uf-color-surface);\n }\n `,\n ];\n\n static override properties: PropertyDeclarations = {\n value: { attribute: false },\n defaultValue: { attribute: 'value' },\n label: {},\n hint: {},\n size: { reflect: true },\n };\n\n /** The selected option's value. */\n declare value: string;\n /** Initially selected value, restored on form reset. Set with the `value` attribute. */\n declare defaultValue: string | undefined;\n /** Visible label, also the group's accessible name. */\n declare label: string | undefined;\n /** Help text below the options. */\n declare hint: string | undefined;\n /** Size of the buttons. */\n declare size: FieldSize;\n\n readonly #slots = new HasSlotController(this, 'label', 'hint');\n readonly #id = uniqueId('uf-segmented-control');\n readonly #observer = new MutationObserver(() => this.#readOptions());\n #options: OptionItem[] = [];\n #optionsChanged = false;\n #hasInitialized = false;\n\n constructor() {\n super();\n this.value = '';\n this.size = 'md';\n }\n\n override connectedCallback(): void {\n super.connectedCallback();\n this.#readOptions();\n this.#observer.observe(this, { childList: true, subtree: true, attributes: true, characterData: true });\n }\n\n override disconnectedCallback(): void {\n super.disconnectedCallback();\n this.#observer.disconnect();\n }\n\n #readOptions(): void {\n this.#options = flattenOptions(readItems(this));\n this.#optionsChanged = true;\n this.requestUpdate();\n }\n\n /** The value a reset returns to: the `value` attribute, a `selected` option, or the first enabled one. */\n #initialValue(): string {\n if (this.defaultValue !== undefined && this.defaultValue !== null) return this.defaultValue;\n return (this.#options.find((o) => o.selected) ?? this.#options.find((o) => !o.disabled))?.value ?? '';\n }\n\n override willUpdate(changed: PropertyValues<this>): void {\n if (!changed.has('defaultValue') && !this.#optionsChanged) return;\n this.#optionsChanged = false;\n // Frameworks often connect the element before appending its options: wait for them.\n if (!this.#options.length) return;\n const valid = this.#options.some((o) => o.value === this.value);\n if (!this.#hasInitialized) {\n // A value set before the options were read (e.g. by a framework) wins if it exists.\n if (!(this.value && valid)) this.value = this.#initialValue();\n this.#hasInitialized = true;\n } else if (!valid || changed.has('defaultValue')) {\n this.value = this.#initialValue();\n }\n }\n\n override updated(): void {\n this.syncFormState();\n }\n\n protected syncFormState(): void {\n this.internals.setFormValue(this.value);\n // One option is always selected: nothing to validate.\n this.setValidity({}, '');\n }\n\n protected resetValue(): void {\n this.value = this.#initialValue();\n }\n\n /** @internal */\n formStateRestoreCallback(state: string | null): void {\n this.value = state ?? '';\n }\n\n get #buttons(): HTMLButtonElement[] {\n return [...this.renderRoot.querySelectorAll<HTMLButtonElement>('.option')];\n }\n\n /** Moves focus to the selected option. */\n override focus(options?: FocusOptions): void {\n this.#buttons.find((b) => b.tabIndex === 0)?.focus(options);\n }\n\n #select(option: OptionItem, focus = false): void {\n if (option.disabled || this.isDisabled) return;\n if (focus) this.updateComplete.then(() => this.focus());\n if (option.value === this.value) return;\n this.value = option.value;\n this.markInteracted();\n this.dispatchEvent(new Event('input', { bubbles: true, composed: true }));\n this.emitChange();\n }\n\n #onKeyDown = (event: KeyboardEvent): void => {\n const enabled = this.#options.filter((o) => !o.disabled);\n const index = enabled.findIndex((o) => o.value === this.value);\n const rtl = getComputedStyle(this).direction === 'rtl';\n const next = { ArrowRight: rtl ? -1 : 1, ArrowLeft: rtl ? 1 : -1, ArrowDown: 1, ArrowUp: -1 }[event.key];\n let target: OptionItem | undefined;\n if (next) target = enabled[(index + next + enabled.length) % enabled.length];\n else if (event.key === 'Home') target = enabled[0];\n else if (event.key === 'End') target = enabled[enabled.length - 1];\n if (!target) return;\n event.preventDefault();\n this.#select(target, true);\n };\n\n override render() {\n const ids = { hintId: `${this.#id}-hint`, errorId: `${this.#id}-error` };\n const labelId = `${this.#id}-label`;\n const hasHintSlot = this.#slots.has('hint');\n const hasLabel = Boolean(this.label) || this.#slots.has('label');\n const disabled = this.isDisabled;\n // The selected option takes Tab; with none (no options yet), the first enabled one.\n const focusable = this.#options.find((o) => o.value === this.value && !o.disabled) ?? this.#options.find((o) => !o.disabled);\n\n return html`\n <div\n class=${classMap({ field: true, disabled })}\n part=\"base\"\n role=\"radiogroup\"\n aria-labelledby=${ifDefined(hasLabel ? labelId : undefined)}\n aria-describedby=${ifDefined(describedBy({ ...ids, hint: this.hint, hasHintSlot, error: '' }))}\n aria-disabled=${disabled ? 'true' : 'false'}\n >\n <div id=${labelId} class=\"field-label\" part=\"form-label\" ?hidden=${!hasLabel}>\n <slot name=\"label\">${this.label ?? nothing}</slot>\n </div>\n <div class=\"options\" part=\"options\" @keydown=${this.#onKeyDown}>\n ${this.#options.map((option) => {\n const selected = option.value === this.value;\n return html`<button\n class=${classMap({ option: true, selected })}\n part=${selected ? 'option selected' : 'option'}\n type=\"button\"\n role=\"radio\"\n aria-checked=${selected ? 'true' : 'false'}\n tabindex=${option === focusable ? 0 : -1}\n ?disabled=${disabled || option.disabled}\n @click=${() => this.#select(option)}\n >\n ${option.label}\n </button>`;\n })}\n </div>\n <div id=${ids.hintId} class=\"field-hint\" part=\"hint\" ?hidden=${!(this.hint || hasHintSlot)}>\n <slot name=\"hint\">${this.hint ?? nothing}</slot>\n </div>\n </div>\n `;\n }\n}\n\ndefineElement('uf-segmented-control', UfSegmentedControl);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-segmented-control': UfSegmentedControl;\n }\n}\n",
|
|
891
891
|
"components/select/select.ts": "import { css, html, nothing, type PropertyDeclarations, type PropertyValues } from 'lit';\nimport { classMap } from 'lit/directives/class-map.js';\nimport { ifDefined } from 'lit/directives/if-defined.js';\nimport { live } from 'lit/directives/live.js';\nimport { defineElement } from '../../internal/define.js';\nimport { controlBoxStyles, describedBy, fieldStyles, renderField, type FieldSize } from '../../internal/field.js';\nimport { FormControl } from '../../internal/form-control.js';\nimport { iconSvg, icons } from '../../internal/icons.js';\nimport { hostStyles } from '../../internal/shared.styles.js';\nimport { HasSlotController, uniqueId } from '../../internal/slot.js';\nimport { flattenOptions, readItems, type Item, type OptionItem } from '../../internal/options.js';\n\n/**\n * A dropdown built on the native `<select>`, so it gets the platform's\n * keyboard support, screen reader support and mobile pickers for free.\n * Write options as plain `<option>` and `<optgroup>` children.\n *\n * @summary Lets users pick one option from a dropdown list.\n * @tag uf-select\n *\n * @slot - `<option>` and `<optgroup>` elements. They are mirrored into the native select.\n * @slot label - The label, when you need markup. Overrides `label`.\n * @slot hint - Help text below the field. Overrides `hint`.\n * @slot prefix - An icon before the selected value.\n *\n * @event input - Fired when the selection changes.\n * @event change - Fired when the selection changes.\n *\n * @csspart field - The wrapper around label, control, hint and error.\n * @csspart form-label - The label.\n * @csspart box - The bordered box.\n * @csspart select - The native `<select>`.\n * @csspart chevron - The dropdown arrow.\n * @csspart hint - The hint text.\n * @csspart error - The validation message.\n *\n * @cssprop --uf-field-bg - Background of the box.\n * @cssprop --uf-field-border-color - Border color of the box.\n * @cssprop --uf-field-radius - Corner radius of the box.\n *\n * @cssstate user-invalid - The value is invalid and the user has interacted with the field.\n */\nexport class UfSelect extends FormControl {\n static override styles = [\n hostStyles,\n fieldStyles,\n controlBoxStyles,\n css`\n .box {\n position: relative;\n padding-inline-end: 0;\n }\n\n .native {\n appearance: none;\n min-height: calc(var(--_height) - 2px);\n padding-inline-end: calc(var(--_padding) + 1.25em);\n cursor: pointer;\n }\n\n .native:invalid,\n .native.placeholder {\n color: var(--uf-color-text-muted);\n }\n\n .native option {\n color: var(--uf-color-text);\n background: var(--uf-color-surface-overlay);\n }\n\n .icon {\n position: absolute;\n inset-inline-end: var(--_padding);\n width: 1em;\n height: 1em;\n color: var(--uf-color-text-muted);\n pointer-events: none;\n }\n `,\n ];\n\n static override properties: PropertyDeclarations = {\n value: { attribute: false },\n defaultValue: { attribute: 'value' },\n label: {},\n hint: {},\n placeholder: {},\n size: { reflect: true },\n autocomplete: {},\n };\n\n /** The selected option's value. */\n declare value: string;\n /** Initially selected value, restored on form reset. Set with the `value` attribute. */\n declare defaultValue: string | undefined;\n /** Visible label. */\n declare label: string | undefined;\n /** Help text below the field. */\n declare hint: string | undefined;\n /** Text shown while nothing is selected. */\n declare placeholder: string | undefined;\n /** Size of the field. */\n declare size: FieldSize;\n /** Native `autocomplete` hint. */\n declare autocomplete: AutoFill | undefined;\n\n readonly #slots = new HasSlotController(this, 'label', 'hint');\n readonly #id = uniqueId('uf-select');\n readonly #observer = new MutationObserver(() => this.#readItems());\n #items: Item[] = [];\n #itemsChanged = false;\n #hasInitialized = false;\n\n constructor() {\n super();\n this.value = '';\n this.size = 'md';\n }\n\n override connectedCallback(): void {\n super.connectedCallback();\n this.#readItems();\n this.#observer.observe(this, { childList: true, subtree: true, attributes: true, characterData: true });\n }\n\n override disconnectedCallback(): void {\n super.disconnectedCallback();\n this.#observer.disconnect();\n }\n\n get #select(): HTMLSelectElement | null {\n return this.renderRoot.querySelector('select');\n }\n\n get #options(): OptionItem[] {\n return flattenOptions(this.#items);\n }\n\n /** Mirrors the light-DOM options into the native select. */\n #readItems(): void {\n this.#items = readItems(this);\n this.#itemsChanged = true;\n this.requestUpdate();\n }\n\n /** The value a reset returns to: the `value` attribute, a `selected` option, or the native default. */\n #initialValue(): string {\n if (this.defaultValue !== undefined && this.defaultValue !== null) return this.defaultValue;\n const options = this.#options;\n const selected = options.find((o) => o.selected);\n if (selected) return selected.value;\n if (this.placeholder) return '';\n return options.find((o) => !o.disabled)?.value ?? '';\n }\n\n override willUpdate(changed: PropertyValues<this>): void {\n const defaultChanged = changed.has('defaultValue') || changed.has('placeholder') || this.#itemsChanged;\n if (!defaultChanged) return;\n this.#itemsChanged = false;\n // Frameworks often connect the element before appending its options: wait for them.\n if (!this.#items.length) return;\n const valid = this.#options.some((o) => o.value === this.value);\n if (!this.#hasInitialized) {\n // A value set before the options were read (e.g. by a framework) wins if it exists.\n if (!(this.value && valid)) this.value = this.#initialValue();\n this.#hasInitialized = true;\n } else if (!valid) {\n this.value = this.#initialValue();\n }\n }\n\n override updated(): void {\n this.syncFormState();\n }\n\n protected syncFormState(): void {\n const select = this.#select;\n if (!select) return;\n this.internals.setFormValue(this.value);\n this.setValidityFrom(select);\n }\n\n protected resetValue(): void {\n this.value = this.#initialValue();\n }\n\n /** @internal */\n formStateRestoreCallback(state: string | null): void {\n this.value = state ?? '';\n }\n\n #onChange = (event: Event): void => {\n this.value = (event.target as HTMLSelectElement).value;\n this.markInteracted();\n this.emitChange();\n };\n\n #renderOption(option: OptionItem) {\n return html`<option value=${option.value} ?disabled=${option.disabled} ?selected=${option.value === this.value}>\n ${option.label}\n </option>`;\n }\n\n override render() {\n const ids = { hintId: `${this.#id}-hint`, errorId: `${this.#id}-error` };\n const error = this.showInvalid ? this.validationMessage : '';\n const hasHintSlot = this.#slots.has('hint');\n const showingPlaceholder = Boolean(this.placeholder) && !this.value;\n\n return renderField({\n ...ids,\n controlId: this.#id,\n label: this.label,\n hasLabelSlot: this.#slots.has('label'),\n hint: this.hint,\n hasHintSlot,\n error,\n required: this.required,\n control: html`\n <div class=${classMap({ box: true, disabled: this.isDisabled })} part=\"box\">\n <slot name=\"prefix\"></slot>\n <select\n id=${this.#id}\n class=${classMap({ native: true, placeholder: showingPlaceholder })}\n part=\"select\"\n name=${ifDefined(this.name || undefined)}\n autocomplete=${ifDefined(this.autocomplete)}\n .value=${live(this.value)}\n ?required=${this.required}\n ?disabled=${this.isDisabled}\n aria-invalid=${error ? 'true' : 'false'}\n aria-describedby=${ifDefined(describedBy({ ...ids, hint: this.hint, hasHintSlot, error }))}\n @change=${this.#onChange}\n >\n ${this.placeholder\n ? html`<option value=\"\" disabled hidden ?selected=${!this.value}>${this.placeholder}</option>`\n : nothing}\n ${this.#items.map((item) =>\n item.kind === 'group'\n ? html`<optgroup label=${item.label} ?disabled=${item.disabled}>\n ${item.options.map((o) => this.#renderOption(o))}\n </optgroup>`\n : this.#renderOption(item),\n )}\n </select>\n ${iconSvg(icons['chevron-down'], 'chevron')}\n </div>\n `,\n });\n }\n}\n\ndefineElement('uf-select', UfSelect);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-select': UfSelect;\n }\n}\n",
|
|
892
892
|
"components/skeleton/skeleton.ts": "import { LitElement, css, html, type PropertyDeclarations } from 'lit';\nimport { defineElement } from '../../internal/define.js';\nimport { hostStyles } from '../../internal/shared.styles.js';\n\nexport type SkeletonShape = 'text' | 'rect' | 'circle';\n\n/**\n * A grey placeholder in the shape of content that's still loading: lines of\n * text, a block or a circle. It's decorative, hidden from assistive tech: mark\n * the region that's loading with `aria-busy=\"true\"`, and announce the result\n * when it arrives.\n *\n * Size it with `width` and `height` in CSS; `text` lines take the height of a\n * line of text, and `circle` stays round.\n *\n * @summary Holds the place of content while it loads.\n * @tag uf-skeleton\n *\n * @csspart base - The placeholder, or the wrapper around its lines.\n * @csspart line - One line of a `text` placeholder.\n *\n * @cssprop --uf-skeleton-color - Background of the placeholder.\n * @cssprop --uf-skeleton-highlight - Color of the shimmer that sweeps across it.\n * @cssprop --uf-skeleton-radius - Corner radius of `text` and `rect` placeholders.\n */\nexport class UfSkeleton extends LitElement {\n static override styles = [\n hostStyles,\n css`\n :host {\n --_color: var(--uf-skeleton-color, var(--uf-color-surface-hover));\n /* Toward the text color: lighter in dark mode, darker in light, clearly visible in both. */\n --_highlight: var(--uf-skeleton-highlight, color-mix(in srgb, var(--_color), var(--uf-color-text) 8%));\n display: block;\n }\n\n :host([shape='rect']) {\n height: 6rem;\n }\n\n :host([shape='circle']) {\n display: inline-block;\n width: 2.5rem;\n height: 2.5rem;\n vertical-align: middle;\n }\n\n .base {\n display: grid;\n gap: 0.5em;\n height: 100%;\n }\n\n .block,\n .line {\n border-radius: var(--uf-skeleton-radius, var(--uf-radius-sm));\n /*\n * Three times as wide as the placeholder: the outer thirds are plain, so the\n * loop starts and ends on the plain color and the highlight sweeps through the middle.\n */\n background: linear-gradient(\n /* A slanted band, sweeping from left to right. */\n 110deg,\n var(--_color) 0%,\n var(--_color) 36%,\n var(--_highlight) 50%,\n var(--_color) 64%,\n var(--_color) 100%\n )\n 0 0 / 300% 100%;\n animation: uf-skeleton-shimmer 1.6s ease-in-out infinite;\n }\n\n /* A line of text: as tall as the text around it, a little less than the line height. */\n .line {\n height: 0.9em;\n margin-block: 0.25em;\n }\n\n /* The last of several lines is shorter, like the end of a paragraph. */\n .line.last {\n width: 60%;\n }\n\n :host([shape='circle']) .block {\n border-radius: 50%;\n }\n\n @keyframes uf-skeleton-shimmer {\n from {\n background-position: 100% 0;\n }\n to {\n background-position: 0 0;\n }\n }\n\n /* Still, for people who asked for less motion: the shape alone says \"loading\". */\n @media (prefers-reduced-motion: reduce) {\n .block,\n .line {\n animation: none;\n }\n }\n `,\n ];\n\n static override properties: PropertyDeclarations = {\n shape: { reflect: true },\n lines: { type: Number },\n };\n\n /** `text` (lines of text), `rect` (a block, like an image) or `circle` (like an avatar). */\n declare shape: SkeletonShape;\n /** Number of lines of a `text` placeholder. */\n declare lines: number;\n\n constructor() {\n super();\n this.shape = 'text';\n this.lines = 1;\n }\n\n override connectedCallback(): void {\n super.connectedCallback();\n // A real attribute, so it's hidden for every assistive tech and test tool.\n this.setAttribute('aria-hidden', 'true');\n }\n\n override render() {\n if (this.shape !== 'text') return html`<div class=\"base\" part=\"base\"><div class=\"block\"></div></div>`;\n const count = Math.max(1, Math.floor(this.lines) || 1);\n return html`<div class=\"base\" part=\"base\">\n ${Array.from(\n { length: count },\n (_, i) => html`<div class=${i === count - 1 && count > 1 ? 'line last' : 'line'} part=\"line\"></div>`,\n )}\n </div>`;\n }\n}\n\ndefineElement('uf-skeleton', UfSkeleton);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-skeleton': UfSkeleton;\n }\n}\n",
|
|
893
893
|
"components/slider/slider.ts": "import { css, html, type PropertyDeclarations, type PropertyValues } from 'lit';\nimport { ifDefined } from 'lit/directives/if-defined.js';\nimport { live } from 'lit/directives/live.js';\nimport { defineElement } from '../../internal/define.js';\nimport { describedBy, fieldStyles, renderField, type FieldSize } from '../../internal/field.js';\nimport { FormControl } from '../../internal/form-control.js';\nimport { focusRing, hostStyles } from '../../internal/shared.styles.js';\nimport { HasSlotController, uniqueId } from '../../internal/slot.js';\n\n/**\n * Picks a number in a range by dragging a handle, or with the arrow keys. Built\n * on the native range input, so keyboard, touch and screen readers work as\n * they do everywhere; it submits its value with the form.\n *\n * @summary Lets users pick a number in a range.\n * @tag uf-slider\n *\n * @slot label - The label, when you need markup. Overrides `label`.\n * @slot hint - Help text below the slider. Overrides `hint`.\n *\n * @event input - Fired while the handle moves.\n * @event change - Fired when the user lets go, or after a key press.\n *\n * @csspart field - The wrapper around label, slider, hint and error.\n * @csspart form-label - The label.\n * @csspart value - The current value, when `show-value` is set.\n * @csspart input - The native range `<input>`.\n * @csspart hint - The hint text.\n * @csspart error - The validation message.\n *\n * @cssprop --uf-slider-track-height - Height of the track.\n * @cssprop --uf-slider-track-color - Color of the track's empty part.\n * @cssprop --uf-slider-indicator-color - Color of the track up to the handle.\n * @cssprop --uf-slider-thumb-size - Diameter of the handle.\n */\nexport class UfSlider extends FormControl {\n static override styles = [\n hostStyles,\n fieldStyles,\n css`\n :host {\n --_track: var(--uf-slider-track-height, var(--_track-size, 0.375rem));\n --_thumb: var(--uf-slider-thumb-size, var(--_thumb-size, 1.125rem));\n --_fill-color: var(--uf-slider-indicator-color, var(--uf-color-accent));\n --_track-color: var(--uf-slider-track-color, var(--uf-color-surface-hover));\n }\n\n :host([size='sm']) {\n --_track-size: 0.25rem;\n --_thumb-size: 1rem;\n }\n\n :host([size='lg']) {\n --_track-size: 0.5rem;\n --_thumb-size: 1.375rem;\n }\n\n .value {\n color: var(--uf-color-text-muted);\n font-size: var(--uf-font-size-md);\n font-variant-numeric: tabular-nums;\n }\n\n .native {\n width: 100%;\n height: var(--_thumb);\n margin: 0;\n background: transparent;\n cursor: pointer;\n appearance: none;\n }\n\n .native:focus-visible {\n outline: none;\n }\n\n .native::-webkit-slider-runnable-track {\n height: var(--_track);\n border-radius: var(--uf-radius-control);\n background: linear-gradient(to right, var(--_fill-color) var(--_fill), var(--_track-color) var(--_fill));\n }\n\n .native::-moz-range-track {\n height: var(--_track);\n border-radius: var(--uf-radius-control);\n background: linear-gradient(to right, var(--_fill-color) var(--_fill), var(--_track-color) var(--_fill));\n }\n\n .native::-webkit-slider-thumb {\n width: var(--_thumb);\n height: var(--_thumb);\n margin-top: calc((var(--_track) - var(--_thumb)) / 2);\n border: 2px solid var(--_fill-color);\n border-radius: 50%;\n background: var(--uf-color-surface);\n box-shadow: var(--uf-shadow-sm);\n appearance: none;\n }\n\n .native::-moz-range-thumb {\n width: var(--_thumb);\n height: var(--_thumb);\n border: 2px solid var(--_fill-color);\n border-radius: 50%;\n background: var(--uf-color-surface);\n box-shadow: var(--uf-shadow-sm);\n }\n\n .native:focus-visible::-webkit-slider-thumb {\n ${focusRing}\n }\n\n .native:focus-visible::-moz-range-thumb {\n ${focusRing}\n }\n\n /* Grey, like disabled fields. */\n .native:disabled {\n --_fill-color: var(--uf-color-text-muted);\n --_track-color: var(--uf-color-neutral-fill);\n cursor: not-allowed;\n }\n\n :host([disabled]) .field-label,\n :host([disabled]) .value {\n color: var(--uf-color-text-muted);\n }\n `,\n ];\n\n protected static override formStateProperties: ReadonlySet<PropertyKey> = new Set([\n ...FormControl.formStateProperties,\n 'min',\n 'max',\n 'step',\n ]);\n\n static override properties: PropertyDeclarations = {\n value: { type: Number, attribute: false },\n defaultValue: { type: Number, attribute: 'value' },\n min: { type: Number },\n max: { type: Number },\n step: { type: Number },\n label: {},\n hint: {},\n showValue: { type: Boolean, attribute: 'show-value' },\n size: { reflect: true },\n };\n\n /** Current value. */\n declare value: number;\n /** Initial value, restored on form reset. Set with the `value` attribute. Defaults to the middle of the range, like a native slider. */\n declare defaultValue: number | undefined;\n /** Lowest value. */\n declare min: number;\n /** Highest value. */\n declare max: number;\n /** Granularity: the value moves in steps of this size. */\n declare step: number;\n /** Visible label, also the slider's accessible name. */\n declare label: string | undefined;\n /** Help text below the slider. */\n declare hint: string | undefined;\n /** Shows the current value next to the label. */\n declare showValue: boolean;\n /** Size of the track and handle: `sm`, `md` or `lg`. */\n declare size: FieldSize;\n\n readonly #slots = new HasSlotController(this, 'label', 'hint');\n readonly #id = uniqueId('uf-slider');\n\n constructor() {\n super();\n this.min = 0;\n this.max = 100;\n this.step = 1;\n this.showValue = false;\n this.size = 'md';\n // Not a number yet: the first update puts it in the middle of min and max.\n this.value = Number.NaN;\n }\n\n get #input(): HTMLInputElement | null {\n return this.renderRoot.querySelector('input');\n }\n\n /** The value a native slider would hold: within min and max, on a step. */\n #normalize(value: number | undefined): number {\n const min = this.min;\n const max = Math.max(this.max, min);\n const fallback = min + (max - min) / 2;\n const v = value == null || Number.isNaN(value) ? fallback : value;\n const clamped = Math.min(Math.max(v, min), max);\n const step = this.step > 0 ? this.step : 1;\n const stepped = min + Math.round((clamped - min) / step) * step;\n // Avoid 0.30000000000000004 with decimal steps.\n return Number(Math.min(stepped, max).toFixed(10));\n }\n\n override willUpdate(changed: PropertyValues<this>): void {\n // Like a native input: the value follows the `value` attribute until it is changed.\n if (changed.has('defaultValue') && (!this.hasUpdated || this.value === this.#normalize(changed.get('defaultValue')))) {\n this.value = this.#normalize(this.defaultValue);\n }\n if (changed.has('value') || changed.has('min') || changed.has('max') || changed.has('step')) {\n const normalized = this.#normalize(this.value);\n if (normalized !== this.value) this.value = normalized;\n }\n }\n\n override updated(): void {\n this.syncFormState();\n }\n\n protected syncFormState(): void {\n const input = this.#input;\n if (!input) return;\n this.internals.setFormValue(String(this.value));\n this.setValidityFrom(input);\n }\n\n protected resetValue(): void {\n this.value = this.#normalize(this.defaultValue);\n }\n\n /** @internal */\n formStateRestoreCallback(state: string | null): void {\n this.value = this.#normalize(state == null ? undefined : Number(state));\n }\n\n #onInput = (event: Event): void => {\n this.value = Number((event.target as HTMLInputElement).value);\n };\n\n #onChange = (): void => {\n this.markInteracted();\n this.emitChange();\n };\n\n override render() {\n const ids = { hintId: `${this.#id}-hint`, errorId: `${this.#id}-error` };\n const error = this.showInvalid ? this.validationMessage : '';\n const hasHintSlot = this.#slots.has('hint');\n const range = this.max - this.min;\n const fill = range > 0 ? ((this.value - this.min) / range) * 100 : 0;\n\n return renderField({\n ...ids,\n controlId: this.#id,\n label: this.label,\n hasLabelSlot: this.#slots.has('label'),\n hint: this.hint,\n hasHintSlot,\n error,\n required: false,\n // The native slider announces its value already.\n labelEnd: this.showValue ? html`<span class=\"value\" part=\"value\" aria-hidden=\"true\">${this.value}</span>` : undefined,\n control: html`\n <input\n id=${this.#id}\n class=\"native\"\n part=\"input\"\n type=\"range\"\n style=\"--_fill: ${fill}%\"\n name=${ifDefined(this.name || undefined)}\n min=${this.min}\n max=${this.max}\n step=${this.step}\n .value=${live(String(this.value))}\n ?disabled=${this.isDisabled}\n aria-invalid=${error ? 'true' : 'false'}\n aria-describedby=${ifDefined(describedBy({ ...ids, hint: this.hint, hasHintSlot, error }))}\n @input=${this.#onInput}\n @change=${this.#onChange}\n />\n `,\n });\n }\n}\n\ndefineElement('uf-slider', UfSlider);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-slider': UfSlider;\n }\n}\n",
|
package/skill/unframed/SKILL.md
CHANGED
|
@@ -5,7 +5,7 @@ description: Builds UI with Unframed web components (@unframed/core, @unframed/r
|
|
|
5
5
|
|
|
6
6
|
# Unframed UI
|
|
7
7
|
|
|
8
|
-
Unframed 1.0.0-rc.
|
|
8
|
+
Unframed 1.0.0-rc.1: accessible UI components as standard custom elements (Lit). Every tag starts with `uf-`. They work in plain HTML and every framework; React, Vue and Angular have wrapper packages for typed props, events and form bindings.
|
|
9
9
|
|
|
10
10
|
## Before writing code
|
|
11
11
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# Using Unframed 1.0.0-rc.
|
|
1
|
+
# Using Unframed 1.0.0-rc.1 in each framework
|
|
2
2
|
|
|
3
3
|
## HTML & JavaScript
|
|
4
4
|
|
|
@@ -68,8 +68,8 @@ dialog.addEventListener('uf-hide', () => toast('Welcome aboard!', { variant: 'su
|
|
|
68
68
|
<!doctype html>
|
|
69
69
|
<html lang="en">
|
|
70
70
|
<head>
|
|
71
|
-
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@unframed/tokens@1.0/dist/tokens.css" />
|
|
72
|
-
<script type="module" src="https://cdn.jsdelivr.net/npm/@unframed/core@1.0/+esm"></script>
|
|
71
|
+
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@unframed/tokens@1.0.0-rc.1/dist/tokens.css" />
|
|
72
|
+
<script type="module" src="https://cdn.jsdelivr.net/npm/@unframed/core@1.0.0-rc.1/+esm"></script>
|
|
73
73
|
</head>
|
|
74
74
|
<body>
|
|
75
75
|
<uf-button variant="primary">It works</uf-button>
|