@unframed/cli 0.8.0 → 0.9.0
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/registry.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version": "0.
|
|
2
|
+
"version": "0.9.0",
|
|
3
3
|
"components": {
|
|
4
4
|
"accordion": {
|
|
5
5
|
"name": "accordion",
|
|
@@ -231,6 +231,32 @@
|
|
|
231
231
|
"lit"
|
|
232
232
|
]
|
|
233
233
|
},
|
|
234
|
+
"date-range-picker": {
|
|
235
|
+
"name": "date-range-picker",
|
|
236
|
+
"entry": "components/date-range-picker/date-range-picker.ts",
|
|
237
|
+
"tag": "uf-date-range-picker",
|
|
238
|
+
"summary": "Lets users type or pick a start and an end date.",
|
|
239
|
+
"files": [
|
|
240
|
+
"components/date-range-picker/date-range-picker.ts"
|
|
241
|
+
],
|
|
242
|
+
"internal": [
|
|
243
|
+
"internal/dates.ts",
|
|
244
|
+
"internal/define.ts",
|
|
245
|
+
"internal/field.ts",
|
|
246
|
+
"internal/form-control.ts",
|
|
247
|
+
"internal/i18n.ts",
|
|
248
|
+
"internal/icons.ts",
|
|
249
|
+
"internal/position.ts",
|
|
250
|
+
"internal/shared.styles.ts",
|
|
251
|
+
"internal/slot.ts"
|
|
252
|
+
],
|
|
253
|
+
"dependencies": [
|
|
254
|
+
"calendar"
|
|
255
|
+
],
|
|
256
|
+
"npm": [
|
|
257
|
+
"lit"
|
|
258
|
+
]
|
|
259
|
+
},
|
|
234
260
|
"dialog": {
|
|
235
261
|
"name": "dialog",
|
|
236
262
|
"entry": "components/dialog/dialog.ts",
|
|
@@ -295,6 +321,28 @@
|
|
|
295
321
|
"lit"
|
|
296
322
|
]
|
|
297
323
|
},
|
|
324
|
+
"file-upload": {
|
|
325
|
+
"name": "file-upload",
|
|
326
|
+
"entry": "components/file-upload/file-upload.ts",
|
|
327
|
+
"tag": "uf-file-upload",
|
|
328
|
+
"summary": "Lets users choose files to upload.",
|
|
329
|
+
"files": [
|
|
330
|
+
"components/file-upload/file-upload.ts"
|
|
331
|
+
],
|
|
332
|
+
"internal": [
|
|
333
|
+
"internal/define.ts",
|
|
334
|
+
"internal/field.ts",
|
|
335
|
+
"internal/form-control.ts",
|
|
336
|
+
"internal/i18n.ts",
|
|
337
|
+
"internal/icons.ts",
|
|
338
|
+
"internal/shared.styles.ts",
|
|
339
|
+
"internal/slot.ts"
|
|
340
|
+
],
|
|
341
|
+
"dependencies": [],
|
|
342
|
+
"npm": [
|
|
343
|
+
"lit"
|
|
344
|
+
]
|
|
345
|
+
},
|
|
298
346
|
"icon": {
|
|
299
347
|
"name": "icon",
|
|
300
348
|
"entry": "components/icon/icon.ts",
|
|
@@ -630,15 +678,15 @@
|
|
|
630
678
|
"components/accordion/accordion.ts": "import { LitElement, css, html, type PropertyDeclarations } from 'lit';\nimport { defineElement } from '../../internal/define.js';\nimport './accordion-item.js';\nimport type { UfAccordionItem } from './accordion-item.js';\n\nexport { UfAccordionItem } from './accordion-item.js';\n\n/**\n * Groups `<uf-accordion-item>`s. By default opening one item closes the\n * others; set `multiple` to let several stay open. Up and Down arrows move\n * between headers, Home and End jump to the first and last.\n *\n * @summary A stack of sections that expand and collapse.\n * @tag uf-accordion\n *\n * @slot - `<uf-accordion-item>` elements.\n *\n * @csspart base - The wrapper around the items.\n */\nexport class UfAccordion extends LitElement {\n static override styles = css`\n :host {\n display: block;\n border-top: 1px solid var(--uf-color-border);\n }\n `;\n\n static override properties: PropertyDeclarations = {\n multiple: { type: Boolean, reflect: true },\n };\n\n /** Allows several items to be open at once. */\n declare multiple: boolean;\n\n constructor() {\n super();\n this.multiple = false;\n this.addEventListener('uf-show', this.#onShow);\n this.addEventListener('keydown', this.#onKeyDown);\n }\n\n get #items(): UfAccordionItem[] {\n return [...this.querySelectorAll<UfAccordionItem>(':scope > uf-accordion-item')];\n }\n\n #onShow = (event: Event): void => {\n if (this.multiple) return;\n const opened = event.target as UfAccordionItem;\n if (opened.parentElement !== this) return;\n for (const item of this.#items) if (item !== opened) item.hide();\n };\n\n #onKeyDown = (event: KeyboardEvent): void => {\n const item = (event.target as Element).closest('uf-accordion-item');\n // Only react to keys on a header, not inside the content.\n if (!item || item.parentElement !== this || event.composedPath()[0] !== item.header) return;\n\n const items = this.#items.filter((i) => !i.disabled);\n const index = items.indexOf(item);\n const target = {\n ArrowDown: items[(index + 1) % items.length],\n ArrowUp: items[(index - 1 + items.length) % items.length],\n Home: items[0],\n End: items[items.length - 1],\n }[event.key];\n if (!target) return;\n event.preventDefault();\n target.focus();\n };\n\n override render() {\n return html`<div part=\"base\"><slot></slot></div>`;\n }\n}\n\ndefineElement('uf-accordion', UfAccordion);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-accordion': UfAccordion;\n }\n}\n",
|
|
631
679
|
"components/accordion/accordion-item.ts": "import { LitElement, css, html, 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\n/**\n * A collapsible section, built on the native `<details>` element: the header\n * is a real disclosure button, and the browser's find-in-page opens a closed\n * item when it contains the match. Use it alone or inside `<uf-accordion>`.\n *\n * @summary A section that expands and collapses.\n * @tag uf-accordion-item\n *\n * @slot - The content.\n * @slot summary - The header, when you need markup. Overrides `summary`.\n *\n * @event uf-show - The item opened.\n * @event uf-hide - The item closed.\n *\n * @csspart base - The native `<details>`.\n * @csspart header - The clickable header (`<summary>`).\n * @csspart chevron - The arrow icon.\n * @csspart content - The content wrapper.\n *\n * @cssprop --uf-accordion-padding - Horizontal padding of header and content.\n */\nexport class UfAccordionItem extends LitElement {\n static override styles = [\n hostStyles,\n css`\n :host {\n --_padding: var(--uf-accordion-padding, var(--uf-space-1));\n display: block;\n border-bottom: 1px solid var(--uf-color-border);\n font-family: var(--uf-font-family-sans);\n font-size: var(--uf-font-size-md);\n color: var(--uf-color-text);\n /* Lets block-size animate to and from auto, where supported. */\n interpolate-size: allow-keywords;\n }\n\n summary {\n display: flex;\n align-items: center;\n gap: var(--uf-space-2);\n padding: var(--uf-space-3) var(--_padding);\n font-weight: var(--uf-font-weight-medium);\n line-height: 1.4;\n cursor: pointer;\n list-style: none;\n user-select: none;\n }\n\n summary::-webkit-details-marker {\n display: none;\n }\n\n summary:hover {\n background: var(--uf-color-accent-tint);\n color: var(--uf-color-on-accent-tint);\n }\n\n summary:focus-visible {\n outline: var(--uf-focus-ring-width) solid var(--uf-color-focus-ring);\n outline-offset: calc(var(--uf-focus-ring-width) * -1);\n }\n\n .summary {\n flex: 1;\n min-width: 0;\n }\n\n .icon {\n flex: none;\n width: 1.125rem;\n height: 1.125rem;\n color: var(--uf-color-text-muted);\n transition: rotate var(--uf-duration-base) ease;\n }\n\n details[open] .icon {\n rotate: 180deg;\n }\n\n .content {\n padding: 0 var(--_padding) var(--uf-space-4);\n line-height: 1.5;\n color: var(--uf-color-text-muted);\n }\n\n details::details-content {\n block-size: 0;\n overflow: clip;\n transition:\n block-size var(--uf-duration-base) ease,\n content-visibility var(--uf-duration-base) allow-discrete;\n }\n\n details[open]::details-content {\n block-size: auto;\n }\n\n :host([disabled]) summary {\n opacity: 0.5;\n cursor: not-allowed;\n }\n\n :host([disabled]) summary:hover {\n background: none;\n color: inherit;\n }\n\n @media (prefers-reduced-motion: reduce) {\n details::details-content,\n .icon {\n transition: none;\n }\n }\n `,\n ];\n\n static override properties: PropertyDeclarations = {\n open: { type: Boolean, reflect: true },\n summary: {},\n disabled: { type: Boolean, reflect: true },\n };\n\n /** Whether the item is expanded. */\n declare open: boolean;\n /** Header text. */\n declare summary: string | undefined;\n /** Prevents the user from toggling the item. */\n declare disabled: boolean;\n\n constructor() {\n super();\n this.open = false;\n this.disabled = false;\n }\n\n get #details(): HTMLDetailsElement | null {\n return this.renderRoot.querySelector('details');\n }\n\n /** The header element, for keyboard navigation between items. */\n get header(): HTMLElement | null {\n return this.renderRoot.querySelector('summary');\n }\n\n /** Expands the item. */\n show(): void {\n this.open = true;\n }\n\n /** Collapses the item. */\n hide(): void {\n this.open = false;\n }\n\n /** Focuses the header. */\n override focus(options?: FocusOptions): void {\n this.header?.focus(options);\n }\n\n override updated(changed: PropertyValues<this>): void {\n const details = this.#details;\n if (details && changed.has('open') && details.open !== this.open) details.open = this.open;\n }\n\n #onSummaryClick = (event: MouseEvent): void => {\n if (this.disabled) event.preventDefault();\n };\n\n /** The last state announced with uf-show / uf-hide. */\n #reported = false;\n\n override firstUpdated(): void {\n this.#reported = this.open;\n }\n\n /** Fires for user clicks, find-in-page and programmatic changes alike. */\n #onToggle = (): void => {\n const open = this.#details!.open;\n this.open = open;\n if (open === this.#reported) return;\n this.#reported = open;\n this.dispatchEvent(new Event(open ? 'uf-show' : 'uf-hide', { bubbles: true, composed: true }));\n };\n\n override render() {\n return html`\n <details part=\"base\" ?open=${this.open} @toggle=${this.#onToggle}>\n <summary part=\"header\" aria-disabled=${this.disabled ? 'true' : 'false'} @click=${this.#onSummaryClick}>\n <span class=\"summary\"><slot name=\"summary\">${this.summary}</slot></span>\n ${iconSvg(icons['chevron-down'], 'chevron')}\n </summary>\n <div class=\"content\" part=\"content\"><slot></slot></div>\n </details>\n `;\n }\n}\n\ndefineElement('uf-accordion-item', UfAccordionItem);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-accordion-item': UfAccordionItem;\n }\n}\n",
|
|
632
680
|
"internal/define.ts": "/**\n * Registers a custom element unless the tag is already taken, so loading the\n * library twice (e.g. two micro-frontends) doesn't throw.\n */\nexport function defineElement(tagName: string, ctor: CustomElementConstructor): void {\n if (!customElements.get(tagName)) customElements.define(tagName, ctor);\n}\n",
|
|
633
|
-
"internal/icons.ts": "import { svg, type SVGTemplateResult } from 'lit';\n\n/** Built-in 24×24 stroke icons, drawn with currentColor. */\nexport const icons = {\n check: svg`<path d=\"M5 12.5l4.5 4.5L19 7.5\" />`,\n minus: svg`<path d=\"M6 12h12\" />`,\n x: svg`<path d=\"M6 6l12 12M18 6L6 18\" />`,\n 'chevron-down': svg`<path d=\"M6 9l6 6 6-6\" />`,\n 'chevron-up': svg`<path d=\"M6 15l6-6 6 6\" />`,\n 'chevron-left': svg`<path d=\"M15 6l-6 6 6 6\" />`,\n 'chevron-right': svg`<path d=\"M9 6l6 6-6 6\" />`,\n plus: svg`<path d=\"M12 5v14M5 12h14\" />`,\n search: svg`<circle cx=\"11\" cy=\"11\" r=\"7\" /><path d=\"M20 20l-4-4\" />`,\n info: svg`<circle cx=\"12\" cy=\"12\" r=\"9\" /><path d=\"M12 11v5M12 8h.01\" />`,\n 'check-circle': svg`<circle cx=\"12\" cy=\"12\" r=\"9\" /><path d=\"M8 12.5l2.5 2.5L16 9.5\" />`,\n 'alert-triangle': svg`<path d=\"M12 4L2.5 20h19L12 4z\" /><path d=\"M12 10v4M12 17h.01\" />`,\n 'alert-circle': svg`<circle cx=\"12\" cy=\"12\" r=\"9\" /><path d=\"M12 7.5v5M12 16h.01\" />`,\n sun: svg`<circle cx=\"12\" cy=\"12\" r=\"4\" /><path d=\"M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4\" />`,\n calendar: svg`<rect x=\"3.5\" y=\"5\" width=\"17\" height=\"15.5\" rx=\"2\" /><path d=\"M3.5 10h17M8 3v4M16 3v4\" />`,\n user: svg`<circle cx=\"12\" cy=\"8\" r=\"4\" /><path d=\"M4 21a8 8 0 0 1 16 0\" />`,\n moon: svg`<path d=\"M20 14.5A8 8 0 0 1 9.5 4a8 8 0 1 0 10.5 10.5z\" />`,\n} satisfies Record<string, SVGTemplateResult>;\n\nexport type BuiltInIconName = keyof typeof icons;\n\n/** Wraps an icon's paths in an `<svg>` element. */\nexport function iconSvg(paths: SVGTemplateResult, part = 'icon') {\n return svg`<svg part=${part} class=\"icon\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\"\n stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\">${paths}</svg>`;\n}\n",
|
|
681
|
+
"internal/icons.ts": "import { svg, type SVGTemplateResult } from 'lit';\n\n/** Built-in 24×24 stroke icons, drawn with currentColor. */\nexport const icons = {\n check: svg`<path d=\"M5 12.5l4.5 4.5L19 7.5\" />`,\n minus: svg`<path d=\"M6 12h12\" />`,\n x: svg`<path d=\"M6 6l12 12M18 6L6 18\" />`,\n 'chevron-down': svg`<path d=\"M6 9l6 6 6-6\" />`,\n 'chevron-up': svg`<path d=\"M6 15l6-6 6 6\" />`,\n 'chevron-left': svg`<path d=\"M15 6l-6 6 6 6\" />`,\n 'chevron-right': svg`<path d=\"M9 6l6 6-6 6\" />`,\n plus: svg`<path d=\"M12 5v14M5 12h14\" />`,\n search: svg`<circle cx=\"11\" cy=\"11\" r=\"7\" /><path d=\"M20 20l-4-4\" />`,\n info: svg`<circle cx=\"12\" cy=\"12\" r=\"9\" /><path d=\"M12 11v5M12 8h.01\" />`,\n 'check-circle': svg`<circle cx=\"12\" cy=\"12\" r=\"9\" /><path d=\"M8 12.5l2.5 2.5L16 9.5\" />`,\n 'alert-triangle': svg`<path d=\"M12 4L2.5 20h19L12 4z\" /><path d=\"M12 10v4M12 17h.01\" />`,\n 'alert-circle': svg`<circle cx=\"12\" cy=\"12\" r=\"9\" /><path d=\"M12 7.5v5M12 16h.01\" />`,\n sun: svg`<circle cx=\"12\" cy=\"12\" r=\"4\" /><path d=\"M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4\" />`,\n calendar: svg`<rect x=\"3.5\" y=\"5\" width=\"17\" height=\"15.5\" rx=\"2\" /><path d=\"M3.5 10h17M8 3v4M16 3v4\" />`,\n user: svg`<circle cx=\"12\" cy=\"8\" r=\"4\" /><path d=\"M4 21a8 8 0 0 1 16 0\" />`,\n moon: svg`<path d=\"M20 14.5A8 8 0 0 1 9.5 4a8 8 0 1 0 10.5 10.5z\" />`,\n upload: svg`<path d=\"M12 15V4M7.5 8.5L12 4l4.5 4.5\" /><path d=\"M4 15v3.5A1.5 1.5 0 0 0 5.5 20h13a1.5 1.5 0 0 0 1.5-1.5V15\" />`,\n file: svg`<path d=\"M13.5 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8.5z\" /><path d=\"M13.5 3v5.5H19\" />`,\n} satisfies Record<string, SVGTemplateResult>;\n\nexport type BuiltInIconName = keyof typeof icons;\n\n/** Wraps an icon's paths in an `<svg>` element. */\nexport function iconSvg(paths: SVGTemplateResult, part = 'icon') {\n return svg`<svg part=${part} class=\"icon\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\"\n stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\">${paths}</svg>`;\n}\n",
|
|
634
682
|
"internal/shared.styles.ts": "import { css } from 'lit';\n\n/** Base styles every component includes. */\nexport const hostStyles = css`\n :host {\n box-sizing: border-box;\n }\n\n :host *,\n :host *::before,\n :host *::after {\n box-sizing: inherit;\n }\n\n :host([hidden]) {\n display: none !important;\n }\n`;\n\n/** Shared keyboard focus ring, driven by the focus tokens. */\nexport const focusRing = css`\n outline: var(--uf-focus-ring-width) solid var(--uf-color-focus-ring);\n outline-offset: var(--uf-focus-ring-offset);\n`;\n",
|
|
635
683
|
"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",
|
|
636
684
|
"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';\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 .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` or `md`. */\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",
|
|
637
685
|
"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",
|
|
638
|
-
"internal/i18n.ts": "import type { ReactiveController, ReactiveControllerHost } from 'lit';\n\n/** Every built-in text, by key. `{page}` is replaced with the page number. */\nexport interface Translations {\n /** Dialog: the close button's accessible name. */\n close: string;\n /** Toast: the dismiss button's accessible name. */\n dismiss: string;\n /** Toaster: the notification region's accessible name, unless `label` is set. */\n notifications: string;\n /** Combobox: the arrow button's accessible name. */\n showOptions: string;\n /** Combobox: shown when the search matches nothing. */\n noResults: string;\n /** Combobox: error when required and empty. */\n selectItem: string;\n /** Combobox: announced while typing when one option matches. */\n oneResult: string;\n /** Combobox: announced while typing; `{count}` is the number of matches. */\n results: `${string}{count}${string}`;\n /** Radio group: error when required and empty. */\n selectOption: string;\n /** Pagination: the navigation's accessible name, unless `label` is set. */\n pagination: string;\n /** Pagination: the previous button's accessible name. */\n previousPage: string;\n /** Pagination: the next button's accessible name. */\n nextPage: string;\n /** Pagination: a page button's accessible name. Must contain `{page}`. */\n page: `${string}{page}${string}`;\n /** Table: shown when there are no rows, unless the `empty` slot is used. */\n noData: string;\n /** Form controls: error for an invalid value that has no message of its own. */\n invalidValue: string;\n /** Date picker: the calendar button's accessible name. */\n chooseDate: string;\n /** Calendar: the previous month button's accessible name. */\n previousMonth: string;\n /** Calendar: the next month button's accessible name. */\n nextMonth: string;\n /** Date picker: error for text that isn't a date; `{example}` is a date in the expected format. */\n invalidDate: `${string}{example}${string}`;\n /** Date picker: error for a date before `min`; `{date}` is the minimum. */\n dateTooEarly: `${string}{date}${string}`;\n /** Date picker: error for a date after `max`; `{date}` is the maximum. */\n dateTooLate: `${string}{date}${string}`;\n /** Date picker: error for a date that `isDateDisabled` rules out. */\n dateUnavailable: string;\n /** Date picker: placeholder letters for day, month and year, in the language's date order. */\n dayPlaceholder: string;\n monthPlaceholder: string;\n yearPlaceholder: string;\n /** Progress: the bar's accessible name, unless `label` is set. */\n progress: string;\n /** Spinner: its accessible name, unless `label` is set. */\n loading: string;\n /** Breadcrumbs: the navigation's accessible name, unless `label` is set. */\n breadcrumb: string;\n}\n\nconst english: Translations = {\n close: 'Close',\n dismiss: 'Dismiss',\n notifications: 'Notifications',\n showOptions: 'Show options',\n noResults: 'No results',\n selectItem: 'Please select an item in the list.',\n oneResult: '1 result',\n results: '{count} results',\n selectOption: 'Please select one of these options.',\n pagination: 'Pagination',\n previousPage: 'Previous page',\n nextPage: 'Next page',\n page: 'Page {page}',\n noData: 'No data',\n invalidValue: 'Invalid value',\n chooseDate: 'Choose date',\n previousMonth: 'Previous month',\n nextMonth: 'Next month',\n invalidDate: 'Enter a date like {example}.',\n dateTooEarly: 'Choose {date} or later.',\n dateTooLate: 'Choose {date} or earlier.',\n dateUnavailable: 'This date is not available.',\n dayPlaceholder: 'dd',\n monthPlaceholder: 'mm',\n yearPlaceholder: 'yyyy',\n progress: 'Progress',\n loading: 'Loading',\n breadcrumb: 'Breadcrumb',\n};\n\n/** Registered translations by lowercase language code; '' applies to every language. */\nconst registered = new Map<string, Partial<Translations>>();\nconst hosts = new Set<ReactiveControllerHost>();\nlet langObserver: MutationObserver | undefined;\n\nconst refreshAll = () => hosts.forEach((host) => host.requestUpdate());\n\n/**\n * Replaces the built-in English text of every component. Pass only the keys\n * you want to change; the rest stay in English. Components already on the page\n * update at once.\n *\n * With a language code, the strings apply where the nearest `lang` attribute\n * matches it (`'pt'` also covers `pt-BR`), so a page can switch language by\n * changing `<html lang>`, or mix languages by section. Without one, they apply\n * everywhere no registered language matches.\n *\n * @example setTranslations({ close: 'Chiudi', page: 'Pagina {page}' }, 'it')\n */\nexport function setTranslations(translations: Partial<Translations>, lang = ''): void {\n const key = lang.toLowerCase();\n registered.set(key, { ...registered.get(key), ...translations });\n refreshAll();\n}\n\n/** Forgets every registered translation. For tests. */\nexport function resetTranslations(): void {\n registered.clear();\n refreshAll();\n}\n\n/** The `lang` that applies to an element: the nearest one, across shadow roots. */\nfunction langOf(element: Element): string {\n let node: Element | null = element;\n while (node) {\n const lang = node.closest('[lang]')?.getAttribute('lang');\n if (lang) return lang.toLowerCase();\n const root = node.getRootNode();\n node = root instanceof ShadowRoot ? root.host : null;\n }\n return '';\n}\n\n/** The text for a key: the element's language, then its base language, then the default, then English. */\nfunction lookup(element: Element, key: keyof Translations): string {\n const lang = langOf(element);\n const candidates = lang ? [lang, lang.split('-')[0], ''] : [''];\n for (const candidate of candidates) {\n const value = registered.get(candidate)?.[key];\n if (value) return value;\n }\n return english[key];\n}\n\n/**\n * Gives a component its built-in text, and re-renders it when translations or\n * the page's `lang` change.\n */\nexport class Translator implements ReactiveController {\n readonly #host: ReactiveControllerHost & HTMLElement;\n\n constructor(host: ReactiveControllerHost & HTMLElement) {\n this.#host = host;\n host.addController(this);\n }\n\n /** The translated text, with `{name}` placeholders filled in. */\n t(key: keyof Translations, values: Record<string, string | number> = {}): string {\n return lookup(this.#host, key).replace(/\\{(\\w+)\\}/g, (match, name: string) => (name in values ? String(values[name]) : match));\n }\n\n hostConnected(): void {\n hosts.add(this.#host);\n if (!langObserver && typeof MutationObserver !== 'undefined') {\n // One observer for the whole document: a `lang` change anywhere re-renders the components.\n langObserver = new MutationObserver(refreshAll);\n langObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['lang'], subtree: true });\n }\n }\n\n /** The language that applies to the component, from the nearest `lang` attribute ('' when none). */\n get lang(): string {\n return langOf(this.#host);\n }\n\n hostDisconnected(): void {\n hosts.delete(this.#host);\n }\n}\n",
|
|
686
|
+
"internal/i18n.ts": "import type { ReactiveController, ReactiveControllerHost } from 'lit';\n\n/** Every built-in text, by key. `{page}` is replaced with the page number. */\nexport interface Translations {\n /** Dialog: the close button's accessible name. */\n close: string;\n /** Toast: the dismiss button's accessible name. */\n dismiss: string;\n /** Toaster: the notification region's accessible name, unless `label` is set. */\n notifications: string;\n /** Combobox: the arrow button's accessible name. */\n showOptions: string;\n /** Combobox: shown when the search matches nothing. */\n noResults: string;\n /** Combobox: error when required and empty. */\n selectItem: string;\n /** Combobox: announced while typing when one option matches. */\n oneResult: string;\n /** Combobox: announced while typing; `{count}` is the number of matches. */\n results: `${string}{count}${string}`;\n /** Radio group: error when required and empty. */\n selectOption: string;\n /** Pagination: the navigation's accessible name, unless `label` is set. */\n pagination: string;\n /** Pagination: the previous button's accessible name. */\n previousPage: string;\n /** Pagination: the next button's accessible name. */\n nextPage: string;\n /** Pagination: a page button's accessible name. Must contain `{page}`. */\n page: `${string}{page}${string}`;\n /** Table: shown when there are no rows, unless the `empty` slot is used. */\n noData: string;\n /** Form controls: error for an invalid value that has no message of its own. */\n invalidValue: string;\n /** Date picker: the calendar button's accessible name. */\n chooseDate: string;\n /** Calendar: the previous month button's accessible name. */\n previousMonth: string;\n /** Calendar: the next month button's accessible name. */\n nextMonth: string;\n /** Date picker: error for text that isn't a date; `{example}` is a date in the expected format. */\n invalidDate: `${string}{example}${string}`;\n /** Date picker: error for a date before `min`; `{date}` is the minimum. */\n dateTooEarly: `${string}{date}${string}`;\n /** Date picker: error for a date after `max`; `{date}` is the maximum. */\n dateTooLate: `${string}{date}${string}`;\n /** Date picker: error for a date that `isDateDisabled` rules out. */\n dateUnavailable: string;\n /** Date picker: placeholder letters for day, month and year, in the language's date order. */\n dayPlaceholder: string;\n monthPlaceholder: string;\n yearPlaceholder: string;\n /** Progress: the bar's accessible name, unless `label` is set. */\n progress: string;\n /** Spinner: its accessible name, unless `label` is set. */\n loading: string;\n /** Breadcrumbs: the navigation's accessible name, unless `label` is set. */\n breadcrumb: string;\n /** File upload: the button, with `multiple`. */\n chooseFiles: string;\n /** File upload: the button, for one file. */\n chooseFile: string;\n /** File upload: next to the button, with `multiple`. */\n dropFiles: string;\n /** File upload: next to the button, for one file. */\n dropFile: string;\n /** File upload: a file's remove button. Must contain `{name}`. */\n removeFile: `${string}{name}${string}`;\n /** File upload: a file over `max-size`. Must contain `{name}`, then `{size}`. */\n fileTooLarge: `${string}{name}${string}{size}${string}`;\n /** File upload: a file `accept` rules out. Must contain `{name}`. */\n fileTypeRejected: `${string}{name}${string}`;\n /** Date range picker: the calendar button's accessible name, and the popup's without a `label`. */\n chooseDates: string;\n /** Date range picker: the start input's accessible name, after the label. */\n startDate: string;\n /** Date range picker: the end input's accessible name, after the label. */\n endDate: string;\n /** Date range picker: error when only one of the two dates is set. */\n rangeIncomplete: string;\n /** Date range picker: error when the end date is before the start date. */\n endBeforeStart: string;\n}\n\nconst english: Translations = {\n close: 'Close',\n dismiss: 'Dismiss',\n notifications: 'Notifications',\n showOptions: 'Show options',\n noResults: 'No results',\n selectItem: 'Please select an item in the list.',\n oneResult: '1 result',\n results: '{count} results',\n selectOption: 'Please select one of these options.',\n pagination: 'Pagination',\n previousPage: 'Previous page',\n nextPage: 'Next page',\n page: 'Page {page}',\n noData: 'No data',\n invalidValue: 'Invalid value',\n chooseDate: 'Choose date',\n previousMonth: 'Previous month',\n nextMonth: 'Next month',\n invalidDate: 'Enter a date like {example}.',\n dateTooEarly: 'Choose {date} or later.',\n dateTooLate: 'Choose {date} or earlier.',\n dateUnavailable: 'This date is not available.',\n dayPlaceholder: 'dd',\n monthPlaceholder: 'mm',\n yearPlaceholder: 'yyyy',\n progress: 'Progress',\n loading: 'Loading',\n breadcrumb: 'Breadcrumb',\n chooseFiles: 'Choose files',\n chooseFile: 'Choose a file',\n dropFiles: 'or drag them here',\n dropFile: 'or drag it here',\n removeFile: 'Remove {name}',\n fileTooLarge: '{name} is larger than {size}.',\n fileTypeRejected: \"{name} isn't an accepted file type.\",\n chooseDates: 'Choose dates',\n startDate: 'Start date',\n endDate: 'End date',\n rangeIncomplete: 'Enter both a start and an end date.',\n endBeforeStart: \"The end date can't be before the start date.\",\n};\n\n/** Registered translations by lowercase language code; '' applies to every language. */\nconst registered = new Map<string, Partial<Translations>>();\nconst hosts = new Set<ReactiveControllerHost>();\nlet langObserver: MutationObserver | undefined;\n\nconst refreshAll = () => hosts.forEach((host) => host.requestUpdate());\n\n/**\n * Replaces the built-in English text of every component. Pass only the keys\n * you want to change; the rest stay in English. Components already on the page\n * update at once.\n *\n * With a language code, the strings apply where the nearest `lang` attribute\n * matches it (`'pt'` also covers `pt-BR`), so a page can switch language by\n * changing `<html lang>`, or mix languages by section. Without one, they apply\n * everywhere no registered language matches.\n *\n * @example setTranslations({ close: 'Chiudi', page: 'Pagina {page}' }, 'it')\n */\nexport function setTranslations(translations: Partial<Translations>, lang = ''): void {\n const key = lang.toLowerCase();\n registered.set(key, { ...registered.get(key), ...translations });\n refreshAll();\n}\n\n/** Forgets every registered translation. For tests. */\nexport function resetTranslations(): void {\n registered.clear();\n refreshAll();\n}\n\n/** The `lang` that applies to an element: the nearest one, across shadow roots. */\nfunction langOf(element: Element): string {\n let node: Element | null = element;\n while (node) {\n const lang = node.closest('[lang]')?.getAttribute('lang');\n if (lang) return lang.toLowerCase();\n const root = node.getRootNode();\n node = root instanceof ShadowRoot ? root.host : null;\n }\n return '';\n}\n\n/** The text for a key: the element's language, then its base language, then the default, then English. */\nfunction lookup(element: Element, key: keyof Translations): string {\n const lang = langOf(element);\n const candidates = lang ? [lang, lang.split('-')[0], ''] : [''];\n for (const candidate of candidates) {\n const value = registered.get(candidate)?.[key];\n if (value) return value;\n }\n return english[key];\n}\n\n/**\n * Gives a component its built-in text, and re-renders it when translations or\n * the page's `lang` change.\n */\nexport class Translator implements ReactiveController {\n readonly #host: ReactiveControllerHost & HTMLElement;\n\n constructor(host: ReactiveControllerHost & HTMLElement) {\n this.#host = host;\n host.addController(this);\n }\n\n /** The translated text, with `{name}` placeholders filled in. */\n t(key: keyof Translations, values: Record<string, string | number> = {}): string {\n return lookup(this.#host, key).replace(/\\{(\\w+)\\}/g, (match, name: string) => (name in values ? String(values[name]) : match));\n }\n\n hostConnected(): void {\n hosts.add(this.#host);\n if (!langObserver && typeof MutationObserver !== 'undefined') {\n // One observer for the whole document: a `lang` change anywhere re-renders the components.\n langObserver = new MutationObserver(refreshAll);\n langObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['lang'], subtree: true });\n }\n }\n\n /** The language that applies to the component, from the nearest `lang` attribute ('' when none). */\n get lang(): string {\n return langOf(this.#host);\n }\n\n hostDisconnected(): void {\n hosts.delete(this.#host);\n }\n}\n",
|
|
639
687
|
"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 // slotchange doesn't fire for a slot that starts empty, so check after the first render too.\n override firstUpdated(): void {\n this.#onLabelChange();\n }\n\n #onLabelChange = (): void => {\n const slot = this.renderRoot.querySelector<HTMLSlotElement>('.label slot');\n const nodes = slot?.assignedNodes({ flatten: true }) ?? [];\n const iconOnly = !nodes.some((n) => n.nodeType === Node.ELEMENT_NODE || n.textContent?.trim());\n if (iconOnly !== this.#iconOnly) {\n this.#iconOnly = iconOnly;\n this.requestUpdate();\n }\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",
|
|
640
688
|
"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 border-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 .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",
|
|
641
|
-
"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 * Use it inline, e.g. for a booking page. For a form field, use\n * `<uf-date-picker>`, which opens 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 it from `value`.\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 *\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 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 };\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\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 constructor() {\n super();\n this.value = '';\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('min') || changed.has('max')) {\n const selected = parseIso(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 (iso === this.value) return;\n this.value = iso;\n this.dispatchEvent(new Event('change', { bubbles: true, composed: true }));\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 } 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\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 selected = iso === this.value;\n const isToday = iso === today;\n const disabled = this.#isDisabled(day);\n const parts = ['day', selected ? 'selected' : '', isToday ? 'today' : ''].filter(Boolean).join(' ');\n return html`<td\n part=${parts}\n class=${classMap({ outside: day.getUTCMonth() !== month.getUTCMonth(), today: isToday })}\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 @focus=${() => {\n if (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",
|
|
689
|
+
"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 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: day.getUTCMonth() !== month.getUTCMonth(),\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 if (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",
|
|
642
690
|
"internal/dates.ts": "// Calendar dates as `YYYY-MM-DD` strings, like `<input type=\"date\">`. They're\n// handled as UTC midnights, so time zones and daylight saving never shift a day.\n\n/** A date as a UTC midnight, or null when the text isn't a real `YYYY-MM-DD` date. */\nexport function parseIso(text: string | null | undefined): Date | null {\n const match = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(text ?? '');\n if (!match) return null;\n const [year, month, day] = match.slice(1).map(Number);\n const date = new Date(Date.UTC(year, month - 1, day));\n // Rejects 2026-02-30 and friends, which Date would roll over.\n return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day ? date : null;\n}\n\nexport function toIso(date: Date): string {\n return date.toISOString().slice(0, 10);\n}\n\n/** Today in the user's time zone, as `YYYY-MM-DD`. */\nexport function todayIso(): string {\n const now = new Date();\n return toIso(new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate())));\n}\n\nexport function addDays(date: Date, days: number): Date {\n return new Date(date.getTime() + days * 86_400_000);\n}\n\n/** The same day `months` later, or the month's last day when it's shorter (Jan 31 + 1 month = Feb 28). */\nexport function addMonths(date: Date, months: number): Date {\n const target = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + months, 1));\n const lastDay = new Date(Date.UTC(target.getUTCFullYear(), target.getUTCMonth() + 1, 0)).getUTCDate();\n target.setUTCDate(Math.min(date.getUTCDate(), lastDay));\n return target;\n}\n\nexport function startOfMonth(date: Date): Date {\n return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), 1));\n}\n\n/** The date clamped between min and max (either may be null). */\nexport function clamp(date: Date, min: Date | null, max: Date | null): Date {\n if (min && date < min) return min;\n if (max && date > max) return max;\n return date;\n}\n\n/** First day of the week for a language: 0 Sunday … 6 Saturday. */\nexport function firstDayOfWeek(lang: string): number {\n try {\n const locale = new Intl.Locale(lang || 'en-US') as Intl.Locale & {\n getWeekInfo?: () => { firstDay: number };\n weekInfo?: { firstDay: number };\n };\n const info = locale.getWeekInfo?.() ?? locale.weekInfo;\n // Intl counts 1 Monday … 7 Sunday.\n if (info) return info.firstDay % 7;\n } catch {\n // An invalid language tag: fall through.\n }\n // Browsers without week info: Sunday in the US and Canada, Monday elsewhere.\n const region = (lang.split('-')[1] ?? (lang === 'en' || !lang ? 'US' : '')).toUpperCase();\n return ['US', 'CA', 'JP', 'BR', 'IL', 'IN'].includes(region) ? 0 : 1;\n}\n\nexport function formatter(lang: string, options: Intl.DateTimeFormatOptions): Intl.DateTimeFormat {\n try {\n return new Intl.DateTimeFormat(lang || undefined, { timeZone: 'UTC', ...options });\n } catch {\n return new Intl.DateTimeFormat(undefined, { timeZone: 'UTC', ...options });\n }\n}\n\n/** The short numeric format of a language, e.g. 14/10/2026 or 10/14/2026. */\nexport function formatShort(date: Date, lang: string): string {\n return formatter(lang, { day: '2-digit', month: '2-digit', year: 'numeric' }).format(date);\n}\n\n/** Order of day, month and year in the language's short format, and its separator. */\nexport function shortPattern(lang: string): { order: ('day' | 'month' | 'year')[]; separator: string } {\n const parts = formatter(lang, { day: '2-digit', month: '2-digit', year: 'numeric' }).formatToParts(new Date(Date.UTC(2026, 11, 31)));\n const order = parts.filter((p) => p.type === 'day' || p.type === 'month' || p.type === 'year').map((p) => p.type as 'day' | 'month' | 'year');\n const separator = parts.find((p) => p.type === 'literal')?.value.trim() || '/';\n return { order: order.length === 3 ? order : ['day', 'month', 'year'], separator };\n}\n\n/**\n * A typed date, in the language's order (14/10/2026, 10.14.26, 14-10-2026…) or\n * as `YYYY-MM-DD`. Any separator works. Two-digit years mean 20xx. Returns null\n * when it isn't a real date.\n */\nexport function parseTyped(text: string, lang: string): Date | null {\n const trimmed = text.trim();\n const iso = parseIso(trimmed);\n if (iso) return iso;\n const numbers = trimmed.split(/[^0-9]+/).filter(Boolean);\n if (numbers.length !== 3) return null;\n const { order } = shortPattern(lang);\n const value = Object.fromEntries(order.map((part, i) => [part, numbers[i]])) as Record<'day' | 'month' | 'year', string>;\n if (value.year.length !== 2 && value.year.length !== 4) return null;\n const year = value.year.length === 2 ? 2000 + Number(value.year) : Number(value.year);\n return parseIso(`${String(year).padStart(4, '0')}-${value.month.padStart(2, '0')}-${value.day.padStart(2, '0')}`);\n}\n",
|
|
643
691
|
"internal/slot.ts": "import type { ReactiveController, ReactiveControllerHost } from 'lit';\n\n/** Re-renders the host when the content of the given named slots changes. */\nexport class HasSlotController implements ReactiveController {\n readonly #host: ReactiveControllerHost & HTMLElement;\n readonly #names: string[];\n\n constructor(host: ReactiveControllerHost & HTMLElement, ...names: string[]) {\n this.#host = host;\n this.#names = names;\n host.addController(this);\n }\n\n /** True when a direct child is assigned to the named slot. */\n has(name: string): boolean {\n return [...this.#host.children].some((child) => child.getAttribute('slot') === name);\n }\n\n hostConnected(): void {\n this.#host.shadowRoot?.addEventListener('slotchange', this.#onSlotChange);\n }\n\n hostDisconnected(): void {\n this.#host.shadowRoot?.removeEventListener('slotchange', this.#onSlotChange);\n }\n\n #onSlotChange = (event: Event): void => {\n const slot = event.target as HTMLSlotElement;\n if (this.#names.includes(slot.name)) this.#host.requestUpdate();\n };\n}\n\nlet counter = 0;\n\n/** A document-unique id, for ARIA references within one tree. */\nexport function uniqueId(prefix = 'uf'): string {\n counter += 1;\n return `${prefix}-${counter}`;\n}\n",
|
|
644
692
|
"components/card/card.ts": "import { LitElement, css, html, type PropertyDeclarations } from 'lit';\nimport { classMap } from 'lit/directives/class-map.js';\nimport { defineElement } from '../../internal/define.js';\nimport { hostStyles } from '../../internal/shared.styles.js';\nimport { HasSlotController } from '../../internal/slot.js';\n\nexport type CardVariant = 'outline' | 'elevated' | 'filled';\nexport type CardOrientation = 'vertical' | 'horizontal';\n\n/**\n * A container that groups related content: an optional image, a header, the\n * content and actions. Empty sections take no space.\n *\n * A card is a plain container for assistive tech. To make a whole card a link,\n * put a link in the header and let it cover the card with CSS, so the card's\n * buttons stay usable.\n *\n * @summary Groups related content and actions.\n * @tag uf-card\n *\n * @slot - The main content.\n * @slot media - An image or video, edge to edge at the top (or the start, when horizontal).\n * @slot header - The title area, e.g. a heading and a subtitle.\n * @slot footer - Actions or details at the bottom.\n *\n * @csspart base - The card.\n * @csspart media - The media wrapper.\n * @csspart header - The header wrapper.\n * @csspart body - The main content wrapper.\n * @csspart footer - The footer wrapper.\n *\n * @cssprop --uf-card-padding - Padding of header, body and footer.\n * @cssprop --uf-card-bg - Background color.\n * @cssprop --uf-card-border-color - Border color.\n * @cssprop --uf-card-radius - Corner radius.\n * @cssprop --uf-card-shadow - Shadow of an elevated card. Defaults to a soft shadow in light mode and an accent glow in dark mode.\n * @cssprop --uf-card-media-width - Width of the media in a horizontal card. Defaults to 40%.\n */\nexport class UfCard extends LitElement {\n static override styles = [\n hostStyles,\n css`\n :host {\n display: block;\n --_padding: var(--uf-card-padding, var(--uf-space-5));\n }\n\n .base {\n display: flex;\n flex-direction: column;\n height: 100%;\n overflow: hidden;\n border: 1px solid var(--uf-card-border-color, var(--uf-color-border));\n border-radius: var(--uf-card-radius, var(--uf-radius-md));\n background: var(--uf-card-bg, var(--uf-color-surface-raised));\n color: var(--uf-color-text);\n font-family: var(--uf-font-family-sans);\n }\n\n /* A shadow in light mode, an accent glow in dark mode (--uf-shadow-raised). */\n :host([variant='elevated']) .base {\n border-color: var(--uf-card-border-color, transparent);\n box-shadow: var(--uf-card-shadow, var(--uf-shadow-raised));\n }\n\n :host([variant='filled']) .base {\n border-color: var(--uf-card-border-color, transparent);\n background: var(--uf-card-bg, var(--uf-color-surface-hover));\n }\n\n .content {\n display: flex;\n flex: 1;\n flex-direction: column;\n min-width: 0;\n }\n\n .media ::slotted(*) {\n display: block;\n width: 100%;\n height: 100%;\n object-fit: cover;\n }\n\n .header,\n .body,\n .footer {\n padding: var(--_padding);\n }\n\n .header {\n padding-bottom: 0;\n }\n\n .body {\n flex: 1;\n }\n\n .footer {\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n gap: var(--uf-space-2);\n padding-top: 0;\n }\n\n /* A body after a header only needs half the gap. */\n .has-header .body {\n padding-top: var(--uf-space-3);\n }\n\n /* Without a body, the header and footer keep their own padding. */\n .no-body .header {\n padding-bottom: var(--_padding);\n }\n .no-body.has-header .footer {\n padding-top: 0;\n }\n\n .empty {\n display: none;\n }\n\n :host([orientation='horizontal']) .base {\n flex-direction: row;\n }\n\n :host([orientation='horizontal']) .media {\n flex: 0 0 var(--uf-card-media-width, 40%);\n }\n `,\n ];\n\n static override properties: PropertyDeclarations = {\n variant: { reflect: true },\n orientation: { reflect: true },\n };\n\n /** `outline` (a border), `elevated` (a shadow, or an accent glow in dark mode) or `filled` (a tinted background). */\n declare variant: CardVariant;\n /** `vertical`, or `horizontal` to put the media beside the content. */\n declare orientation: CardOrientation;\n\n readonly #slots = new HasSlotController(this, 'media', 'header', 'footer', '');\n\n constructor() {\n super();\n this.variant = 'outline';\n this.orientation = 'vertical';\n }\n\n /** True when the default slot has elements or non-blank text. */\n #hasBody(): boolean {\n return [...this.childNodes].some(\n (node) =>\n (node.nodeType === Node.ELEMENT_NODE && !(node as Element).hasAttribute('slot')) ||\n (node.nodeType === Node.TEXT_NODE && node.textContent!.trim() !== ''),\n );\n }\n\n override render() {\n const has = { media: this.#slots.has('media'), header: this.#slots.has('header'), footer: this.#slots.has('footer') };\n const body = this.#hasBody();\n return html`<div class=${classMap({ base: true, 'has-header': has.header, 'no-body': !body })} part=\"base\">\n <div class=${classMap({ media: true, empty: !has.media })} part=\"media\"><slot name=\"media\"></slot></div>\n <div class=\"content\">\n <div class=${classMap({ header: true, empty: !has.header })} part=\"header\"><slot name=\"header\"></slot></div>\n <div class=${classMap({ body: true, empty: !body })} part=\"body\"><slot></slot></div>\n <div class=${classMap({ footer: true, empty: !has.footer })} part=\"footer\"><slot name=\"footer\"></slot></div>\n </div>\n </div>`;\n }\n}\n\ndefineElement('uf-card', UfCard);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-card': UfCard;\n }\n}\n",
|
|
@@ -651,10 +699,12 @@
|
|
|
651
699
|
"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 *\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', { bubbles: true, composed: true }));\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', { bubbles: true, composed: true }));\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",
|
|
652
700
|
"internal/options.ts": "/** An `<option>` read from a component's light DOM. */\nexport interface OptionItem {\n kind: 'option';\n value: string;\n label: string;\n disabled: boolean;\n selected: boolean;\n}\n\n/** An `<optgroup>` and its options. */\nexport interface GroupItem {\n kind: 'group';\n label: string;\n disabled: boolean;\n options: OptionItem[];\n}\n\nexport type Item = OptionItem | GroupItem;\n\nfunction readOption(option: HTMLOptionElement, groupDisabled = false): OptionItem {\n return {\n kind: 'option',\n value: option.value,\n label: option.label || option.textContent?.trim() || '',\n disabled: option.disabled || groupDisabled,\n selected: option.hasAttribute('selected'),\n };\n}\n\n/** Reads the `<option>` and `<optgroup>` children of a host element. */\nexport function readItems(host: Element): Item[] {\n return [...host.children].flatMap((child): Item[] => {\n if (child instanceof HTMLOptionElement) return [readOption(child)];\n if (child instanceof HTMLOptGroupElement) {\n return [\n {\n kind: 'group',\n label: child.label,\n disabled: child.disabled,\n options: [...child.querySelectorAll('option')].map((o) => readOption(o, child.disabled)),\n },\n ];\n }\n return [];\n });\n}\n\n/** All options, with groups flattened. */\nexport function flattenOptions(items: Item[]): OptionItem[] {\n return items.flatMap((item) => (item.kind === 'group' ? item.options : [item]));\n}\n\n/** Calls `onChange` whenever the host's options are added, removed or edited. */\nexport function observeOptions(host: Element, onChange: () => void): MutationObserver {\n const observer = new MutationObserver(onChange);\n observer.observe(host, { childList: true, subtree: true, attributes: true, characterData: true });\n return observer;\n}\n",
|
|
653
701
|
"internal/position.ts": "export type Placement =\n | 'top'\n | 'top-start'\n | 'top-end'\n | 'bottom'\n | 'bottom-start'\n | 'bottom-end'\n | 'left'\n | 'right';\n\nconst VIEWPORT_PADDING = 8;\nconst opposite = { top: 'bottom', bottom: 'top', left: 'right', right: 'left' } as const;\n\n/**\n * Positions a `position: fixed` element (usually in the top layer) next to an\n * anchor. Flips to the opposite side when it doesn't fit, then clamps to the\n * viewport. Returns the side it ended up on.\n */\nexport function positionFloating(\n anchor: Element,\n floating: HTMLElement,\n placement: Placement,\n offset = 8,\n): Placement {\n const a = anchor.getBoundingClientRect();\n const f = floating.getBoundingClientRect();\n const vw = document.documentElement.clientWidth;\n const vh = document.documentElement.clientHeight;\n\n let [side, align] = placement.split('-') as [keyof typeof opposite, 'start' | 'end' | undefined];\n\n const fits = (s: keyof typeof opposite) => {\n if (s === 'top') return a.top - offset - f.height >= VIEWPORT_PADDING;\n if (s === 'bottom') return a.bottom + offset + f.height <= vh - VIEWPORT_PADDING;\n if (s === 'left') return a.left - offset - f.width >= VIEWPORT_PADDING;\n return a.right + offset + f.width <= vw - VIEWPORT_PADDING;\n };\n if (!fits(side) && fits(opposite[side])) side = opposite[side];\n\n let x: number;\n let y: number;\n if (side === 'top' || side === 'bottom') {\n y = side === 'top' ? a.top - offset - f.height : a.bottom + offset;\n x = align === 'start' ? a.left : align === 'end' ? a.right - f.width : a.left + a.width / 2 - f.width / 2;\n } else {\n x = side === 'left' ? a.left - offset - f.width : a.right + offset;\n y = a.top + a.height / 2 - f.height / 2;\n }\n\n x = Math.min(Math.max(x, VIEWPORT_PADDING), vw - f.width - VIEWPORT_PADDING);\n y = Math.min(Math.max(y, VIEWPORT_PADDING), vh - f.height - VIEWPORT_PADDING);\n\n floating.style.left = `${Math.round(x)}px`;\n floating.style.top = `${Math.round(y)}px`;\n return (align ? `${side}-${align}` : side) as Placement;\n}\n\n/** Re-runs `update` on scroll, resize and size changes. Returns a cleanup function. */\nexport function autoUpdate(anchor: Element, floating: HTMLElement, update: () => void): () => void {\n let frame = 0;\n const schedule = () => {\n cancelAnimationFrame(frame);\n frame = requestAnimationFrame(update);\n };\n const observer = new ResizeObserver(schedule);\n observer.observe(anchor);\n observer.observe(floating);\n window.addEventListener('scroll', schedule, { capture: true, passive: true });\n window.addEventListener('resize', schedule, { passive: true });\n update();\n return () => {\n cancelAnimationFrame(frame);\n observer.disconnect();\n window.removeEventListener('scroll', schedule, { capture: true });\n window.removeEventListener('resize', schedule);\n };\n}\n\n",
|
|
654
|
-
"components/date-picker/date-picker.ts": "import { css, html, 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 { formatShort, formatter, parseIso, parseTyped, shortPattern, toIso, todayIso } from '../../internal/dates.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 { autoUpdate, positionFloating } from '../../internal/position.js';\nimport { hostStyles } from '../../internal/shared.styles.js';\nimport { HasSlotController, uniqueId } from '../../internal/slot.js';\nimport '../calendar/calendar.js';\nimport type { UfCalendar } from '../calendar/calendar.js';\n\n/** A browser-translated \"Please fill out this field.\", from a native input that never joins the page. */\nlet requiredMessage: string | undefined;\nfunction valueMissingMessage(): string {\n if (requiredMessage === undefined) {\n const probe = document.createElement('input');\n probe.required = true;\n requiredMessage = probe.validationMessage;\n }\n return requiredMessage;\n}\n\n/**\n * A date field: type a date in the page language's format, or pick one from a\n * calendar. The value is always `YYYY-MM-DD`, like `<input type=\"date\">`, so\n * it's the same in every language and submits with the form.\n *\n * Alt + Down Arrow opens the calendar; Escape closes it.\n *\n * @summary Lets users type or pick a date.\n * @tag uf-date-picker\n *\n * @slot label - The label, when you need markup. Overrides `label`.\n * @slot hint - Help text below the field. Overrides `hint`.\n *\n * @event input - The value changed (a date was typed and committed, or picked).\n * @event change - The value changed (a date was typed and committed, or picked).\n * @event uf-show - The calendar opened.\n * @event uf-hide - The calendar 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 around the input.\n * @csspart input - The text input.\n * @csspart toggle - The calendar button.\n * @csspart popup - The floating panel around the calendar.\n * @csspart calendar - The `<uf-calendar>`.\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 UfDatePicker 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:hover:not(:disabled),\n .toggle.open {\n color: var(--uf-color-accent-strong);\n }\n\n .toggle:focus-visible {\n outline: var(--uf-focus-ring-width) solid var(--uf-color-focus-ring);\n outline-offset: -2px;\n }\n\n .toggle:disabled {\n cursor: not-allowed;\n }\n\n .toggle .icon {\n width: 1.125em;\n height: 1.125em;\n }\n\n .popup {\n position: fixed;\n inset: auto;\n margin: 0;\n padding: var(--uf-space-3);\n border: 1px solid var(--uf-color-border);\n border-radius: var(--uf-radius-md);\n background: var(--uf-color-surface-overlay);\n color: var(--uf-color-text);\n box-shadow: var(--uf-shadow-overlay);\n }\n `,\n ];\n\n protected static override formStateProperties: ReadonlySet<PropertyKey> = new Set([\n ...FormControl.formStateProperties,\n 'min',\n 'max',\n 'isDateDisabled',\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 min: {},\n max: {},\n readonly: { type: Boolean, reflect: true },\n open: { type: Boolean, reflect: true },\n isDateDisabled: { attribute: false },\n };\n\n /** The date, as `YYYY-MM-DD`, or an empty string. */\n declare value: string;\n /** Initial date, restored on form reset. Set with the `value` attribute, as `YYYY-MM-DD`. */\n declare defaultValue: string;\n /** The field's label, also its accessible name. */\n declare label: string | undefined;\n /** Help text below the field. */\n declare hint: string | undefined;\n /** Shown when empty. Defaults to the date format, e.g. dd/mm/yyyy. */\n declare placeholder: string | undefined;\n /** Size: `sm`, `md` or `lg`. */\n declare size: FieldSize;\n /** The earliest allowed date, as `YYYY-MM-DD`. */\n declare min: string | undefined;\n /** The latest allowed date, as `YYYY-MM-DD`. */\n declare max: string | undefined;\n /** Lets the user select the text but not change the date. */\n declare readonly: boolean;\n /** Whether the calendar is open. */\n declare open: boolean;\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\n readonly #slots = new HasSlotController(this, 'label', 'hint');\n readonly #id = uniqueId('uf-date-picker');\n /** What the user typed and hasn't committed yet; null shows the value, formatted. */\n #text: string | null = null;\n /** The committed text isn't a date. */\n #badInput = false;\n #cleanup?: () => void;\n /** Focus was in the calendar when it closed: give it back to the input. */\n #focusWasInside = false;\n /** Between beforetoggle and toggle. */\n #toggling = false;\n\n constructor() {\n super();\n this.value = '';\n this.defaultValue = '';\n this.size = 'md';\n this.readonly = false;\n this.open = false;\n }\n\n get #input(): HTMLInputElement | null {\n return this.renderRoot.querySelector('input');\n }\n\n get #popup(): HTMLElement | null {\n return this.renderRoot.querySelector('.popup');\n }\n\n get #calendar(): UfCalendar | null {\n return this.renderRoot.querySelector('uf-calendar');\n }\n\n /** Opens the calendar. */\n show(): void {\n if (!this.isDisabled && !this.readonly) this.open = true;\n }\n\n /** Closes the calendar. */\n hide(): void {\n this.open = false;\n }\n\n override disconnectedCallback(): void {\n super.disconnectedCallback();\n this.#cleanup?.();\n this.#cleanup = undefined;\n }\n\n override willUpdate(changed: PropertyValues<this>): void {\n if (changed.has('defaultValue') && this.value === (changed.get('defaultValue') ?? '')) {\n this.value = parseIso(this.defaultValue) ? this.defaultValue : '';\n }\n // A value set from code replaces what was typed.\n if (changed.has('value')) {\n this.#text = null;\n this.#badInput = false;\n }\n }\n\n override updated(changed: PropertyValues<this>): void {\n this.syncFormState();\n if (changed.has('open')) this.#syncPopup();\n }\n\n #syncPopup(): void {\n const popup = this.#popup;\n // The browser is opening or closing it already (button, Escape, click outside).\n if (!popup || this.#toggling) return;\n if (this.open && !popup.matches(':popover-open')) {\n popup.showPopover();\n // Positioned in the same task, so it never paints at its default spot.\n this.#startPositioning();\n } else if (!this.open && popup.matches(':popover-open')) {\n popup.hidePopover();\n }\n }\n\n /** Places the popup under the field, and keeps it there on scroll and resize. */\n #startPositioning(): void {\n const popup = this.#popup;\n const box = this.renderRoot.querySelector<HTMLElement>('.box');\n if (!popup || !box || !popup.matches(':popover-open')) return;\n this.#cleanup ??= autoUpdate(box, popup, () => positionFloating(box, popup, 'bottom-start', 4));\n }\n\n /**\n * The popup opened or closed, however it happened: the button (linked with\n * popovertarget, so a click while open closes it instead of reopening),\n * Escape, a click outside, or \\`open\\`.\n */\n #onBeforeToggle = (event: ToggleEvent): void => {\n // Synchronous, so \\`open\\` is right as soon as the popup opens or closes.\n // Lit may render before the browser finishes: #toggling keeps #syncPopup\n // from calling showPopover/hidePopover in the middle, which would cancel\n // the toggle event.\n this.#toggling = true;\n this.open = event.newState === 'open';\n // Opened by the button: the browser shows it after this event, and the\n // toggle event comes a task later, after a paint. An animation frame runs\n // after it's shown and before that paint, so position it there.\n if (event.newState === 'open') requestAnimationFrame(() => this.#startPositioning());\n // Before it hides: afterwards the browser has already moved focus away.\n if (event.newState === 'closed') this.#focusWasInside = Boolean(this.shadowRoot?.activeElement?.closest('.popup'));\n };\n\n #onToggle = (event: ToggleEvent): void => {\n this.#toggling = false;\n if (event.newState === 'open') {\n this.#startPositioning();\n this.#calendar?.updateComplete.then(() => this.#calendar?.focus());\n this.dispatchEvent(new Event('uf-show', { bubbles: true, composed: true }));\n } else {\n this.#cleanup?.();\n this.#cleanup = undefined;\n if (this.#focusWasInside) this.#input?.focus();\n this.#focusWasInside = false;\n this.dispatchEvent(new Event('uf-hide', { bubbles: true, composed: true }));\n }\n };\n\n protected syncFormState(): void {\n const input = this.#input;\n if (!input) return;\n this.internals.setFormValue(this.value);\n const t = this.translator;\n const lang = t.lang;\n const date = parseIso(this.value);\n const min = parseIso(this.min);\n const max = parseIso(this.max);\n const long = (d: Date) => formatter(lang, { day: 'numeric', month: 'long', year: 'numeric' }).format(d);\n\n if (this.#badInput) {\n this.setValidity({ badInput: true }, t.t('invalidDate', { example: formatShort(parseIso(todayIso())!, lang) }), input);\n } else if (this.required && !date) {\n this.setValidity({ valueMissing: true }, valueMissingMessage(), input);\n } else if (date && min && date < min) {\n this.setValidity({ rangeUnderflow: true }, t.t('dateTooEarly', { date: long(min) }), input);\n } else if (date && max && date > max) {\n this.setValidity({ rangeOverflow: true }, t.t('dateTooLate', { date: long(max) }), input);\n } else if (date && this.isDateDisabled?.(this.value)) {\n this.setValidity({ badInput: true }, t.t('dateUnavailable'), input);\n } else {\n this.setValidity({}, '', input);\n }\n }\n\n protected resetValue(): void {\n this.value = parseIso(this.defaultValue) ? this.defaultValue : '';\n }\n\n /** @internal */\n formStateRestoreCallback(state: string | null): void {\n this.value = parseIso(state) ? state! : '';\n }\n\n /** Sets the value from the user, and tells listeners when it changed. */\n #commit(value: string): void {\n const changed = value !== this.value;\n this.value = value;\n this.markInteracted();\n if (changed) {\n this.dispatchEvent(new Event('input', { bubbles: true, composed: true }));\n this.emitChange();\n }\n }\n\n /** Turns the typed text into the value: a date, empty, or invalid. */\n #commitText(): void {\n if (this.#text === null) return;\n const text = this.#text.trim();\n const date = text ? parseTyped(text, this.translator.lang) : null;\n if (!text || date) {\n this.#commit(date ? toIso(date) : '');\n this.#text = null;\n this.#badInput = false;\n } else {\n // Not a date: keep the text so the user can fix it, and report it.\n this.#commit('');\n this.#text = text;\n this.#badInput = true;\n }\n this.syncFormState();\n this.requestUpdate();\n }\n\n #onInput = (event: Event): void => {\n // The value changes when the date is committed, not on every keystroke.\n event.stopPropagation();\n this.#text = (event.target as HTMLInputElement).value;\n };\n\n #onKeyDown = (event: KeyboardEvent): void => {\n if (event.key === 'Enter') this.#commitText();\n else if (event.key === 'ArrowDown' && event.altKey) {\n event.preventDefault();\n this.show();\n }\n };\n\n #onCalendarChange = (event: Event): void => {\n event.stopPropagation();\n this.#commit((event.target as UfCalendar).value);\n this.hide();\n this.#input?.focus();\n };\n\n #placeholder(): string {\n if (this.placeholder !== undefined) return this.placeholder;\n const { order, separator } = shortPattern(this.translator.lang);\n const letters = { day: this.translator.t('dayPlaceholder'), month: this.translator.t('monthPlaceholder'), year: this.translator.t('yearPlaceholder') };\n return order.map((part) => letters[part]).join(separator);\n }\n\n override render() {\n const ids = { hintId: `${this.#id}-hint`, errorId: `${this.#id}-error` };\n const popupId = `${this.#id}-popup`;\n const error = this.showInvalid ? this.validationMessage : '';\n const hasHintSlot = this.#slots.has('hint');\n const date = parseIso(this.value);\n const text = this.#text ?? (date ? formatShort(date, this.translator.lang) : '');\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 <input\n id=${this.#id}\n class=\"native\"\n part=\"input\"\n type=\"text\"\n autocomplete=\"off\"\n .value=${live(text)}\n placeholder=${this.#placeholder()}\n ?readonly=${this.readonly}\n ?disabled=${this.isDisabled}\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 @change=${() => this.#commitText()}\n @keydown=${this.#onKeyDown}\n />\n <button\n class=${classMap({ toggle: true, open: this.open })}\n part=\"toggle\"\n type=\"button\"\n aria-label=${this.translator.t('chooseDate')}\n aria-haspopup=\"dialog\"\n aria-expanded=${this.open ? 'true' : 'false'}\n popovertarget=${popupId}\n ?disabled=${this.isDisabled || this.readonly}\n >\n ${iconSvg(icons.calendar)}\n </button>\n </div>\n <div\n id=${popupId}\n class=\"popup\"\n part=\"popup\"\n popover=\"auto\"\n role=\"dialog\"\n aria-label=${this.label ?? this.translator.t('chooseDate')}\n @beforetoggle=${this.#onBeforeToggle}\n @toggle=${this.#onToggle}\n >\n <uf-calendar\n part=\"calendar\"\n .value=${this.value}\n .min=${this.min}\n .max=${this.max}\n .isDateDisabled=${this.isDateDisabled}\n @change=${this.#onCalendarChange}\n ></uf-calendar>\n </div>\n `,\n });\n }\n}\n\ndefineElement('uf-date-picker', UfDatePicker);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-date-picker': UfDatePicker;\n }\n}\n",
|
|
702
|
+
"components/date-picker/date-picker.ts": "import { css, html, 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 { formatShort, formatter, parseIso, parseTyped, shortPattern, toIso, todayIso } from '../../internal/dates.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 { autoUpdate, positionFloating } from '../../internal/position.js';\nimport { hostStyles } from '../../internal/shared.styles.js';\nimport { HasSlotController, uniqueId } from '../../internal/slot.js';\nimport '../calendar/calendar.js';\nimport type { UfCalendar } from '../calendar/calendar.js';\n\n/** A browser-translated \"Please fill out this field.\", from a native input that never joins the page. */\nlet requiredMessage: string | undefined;\nfunction valueMissingMessage(): string {\n if (requiredMessage === undefined) {\n const probe = document.createElement('input');\n probe.required = true;\n requiredMessage = probe.validationMessage;\n }\n return requiredMessage;\n}\n\n/**\n * A date field: type a date in the page language's format, or pick one from a\n * calendar. The value is always `YYYY-MM-DD`, like `<input type=\"date\">`, so\n * it's the same in every language and submits with the form.\n *\n * Alt + Down Arrow opens the calendar; Escape closes it.\n *\n * @summary Lets users type or pick a date.\n * @tag uf-date-picker\n *\n * @slot label - The label, when you need markup. Overrides `label`.\n * @slot hint - Help text below the field. Overrides `hint`.\n *\n * @event input - The value changed (a date was typed and committed, or picked).\n * @event change - The value changed (a date was typed and committed, or picked).\n * @event uf-show - The calendar opened.\n * @event uf-hide - The calendar 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 around the input.\n * @csspart input - The text input.\n * @csspart toggle - The calendar button.\n * @csspart popup - The floating panel around the calendar.\n * @csspart calendar - The `<uf-calendar>`.\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 UfDatePicker 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:hover:not(:disabled),\n .toggle.open {\n color: var(--uf-color-accent-strong);\n }\n\n .toggle:focus-visible {\n outline: var(--uf-focus-ring-width) solid var(--uf-color-focus-ring);\n outline-offset: -2px;\n }\n\n .toggle:disabled {\n cursor: not-allowed;\n }\n\n .toggle .icon {\n width: 1.125em;\n height: 1.125em;\n }\n\n .popup {\n position: fixed;\n inset: auto;\n margin: 0;\n padding: var(--uf-space-3);\n border: 1px solid var(--uf-color-border);\n border-radius: var(--uf-radius-md);\n background: var(--uf-color-surface-overlay);\n color: var(--uf-color-text);\n box-shadow: var(--uf-shadow-overlay);\n }\n `,\n ];\n\n protected static override formStateProperties: ReadonlySet<PropertyKey> = new Set([\n ...FormControl.formStateProperties,\n 'min',\n 'max',\n 'isDateDisabled',\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 min: {},\n max: {},\n readonly: { type: Boolean, reflect: true },\n open: { type: Boolean, reflect: true },\n isDateDisabled: { attribute: false },\n };\n\n /** The date, as `YYYY-MM-DD`, or an empty string. */\n declare value: string;\n /** Initial date, restored on form reset. Set with the `value` attribute, as `YYYY-MM-DD`. */\n declare defaultValue: string;\n /** The field's label, also its accessible name. */\n declare label: string | undefined;\n /** Help text below the field. */\n declare hint: string | undefined;\n /** Shown when empty. Defaults to the date format, e.g. dd/mm/yyyy. */\n declare placeholder: string | undefined;\n /** Size: `sm`, `md` or `lg`. */\n declare size: FieldSize;\n /** The earliest allowed date, as `YYYY-MM-DD`. */\n declare min: string | undefined;\n /** The latest allowed date, as `YYYY-MM-DD`. */\n declare max: string | undefined;\n /** Lets the user select the text but not change the date. */\n declare readonly: boolean;\n /** Whether the calendar is open. */\n declare open: boolean;\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\n readonly #slots = new HasSlotController(this, 'label', 'hint');\n readonly #id = uniqueId('uf-date-picker');\n /** What the user typed and hasn't committed yet; null shows the value, formatted. */\n #text: string | null = null;\n /** The committed text isn't a date. */\n #badInput = false;\n #cleanup?: () => void;\n /** Focus was in the calendar when it closed: give it back to the input. */\n #focusWasInside = false;\n /** Between beforetoggle and toggle. */\n #toggling = false;\n\n constructor() {\n super();\n this.value = '';\n this.defaultValue = '';\n this.size = 'md';\n this.readonly = false;\n this.open = false;\n }\n\n get #input(): HTMLInputElement | null {\n return this.renderRoot.querySelector('input');\n }\n\n get #popup(): HTMLElement | null {\n return this.renderRoot.querySelector('.popup');\n }\n\n get #calendar(): UfCalendar | null {\n return this.renderRoot.querySelector('uf-calendar');\n }\n\n /** Opens the calendar. */\n show(): void {\n if (!this.isDisabled && !this.readonly) this.open = true;\n }\n\n /** Closes the calendar. */\n hide(): void {\n this.open = false;\n }\n\n override disconnectedCallback(): void {\n super.disconnectedCallback();\n this.#cleanup?.();\n this.#cleanup = undefined;\n }\n\n override willUpdate(changed: PropertyValues<this>): void {\n if (changed.has('defaultValue') && this.value === (changed.get('defaultValue') ?? '')) {\n this.value = parseIso(this.defaultValue) ? this.defaultValue : '';\n }\n // A value set from code replaces what was typed.\n if (changed.has('value')) {\n this.#text = null;\n this.#badInput = false;\n }\n }\n\n override updated(changed: PropertyValues<this>): void {\n this.syncFormState();\n if (changed.has('open')) this.#syncPopup();\n }\n\n #syncPopup(): void {\n const popup = this.#popup;\n // The browser is opening or closing it already (button, Escape, click outside).\n if (!popup || this.#toggling) return;\n if (this.open && !popup.matches(':popover-open')) {\n popup.showPopover();\n // Positioned in the same task, so it never paints at its default spot.\n this.#startPositioning();\n } else if (!this.open && popup.matches(':popover-open')) {\n popup.hidePopover();\n }\n }\n\n /** Places the popup under the field, and keeps it there on scroll and resize. */\n #startPositioning(): void {\n const popup = this.#popup;\n const box = this.renderRoot.querySelector<HTMLElement>('.box');\n if (!popup || !box || !popup.matches(':popover-open')) return;\n this.#cleanup ??= autoUpdate(box, popup, () => positionFloating(box, popup, 'bottom-start', 4));\n }\n\n /**\n * The popup opened or closed, however it happened: the button (linked with\n * popovertarget, so a click while open closes it instead of reopening),\n * Escape, a click outside, or \\`open\\`.\n */\n #onBeforeToggle = (event: ToggleEvent): void => {\n // Synchronous, so \\`open\\` is right as soon as the popup opens or closes.\n // Lit may render before the browser finishes: #toggling keeps #syncPopup\n // from calling showPopover/hidePopover in the middle, which would cancel\n // the toggle event.\n this.#toggling = true;\n this.open = event.newState === 'open';\n // Opened by the button: the browser shows it after this event, and the\n // toggle event comes a task later, after a paint. An animation frame runs\n // after it's shown and before that paint, so position it there.\n if (event.newState === 'open') requestAnimationFrame(() => this.#startPositioning());\n // Before it hides: afterwards the browser has already moved focus away.\n if (event.newState === 'closed') this.#focusWasInside = Boolean(this.shadowRoot?.activeElement?.closest('.popup'));\n };\n\n #onToggle = (event: ToggleEvent): void => {\n this.#toggling = false;\n // Closed (or reopened) from code before the browser finished: catch up now.\n if ((event.newState === 'open') !== this.open) {\n this.#syncPopup();\n return;\n }\n if (event.newState === 'open') {\n this.#startPositioning();\n this.#calendar?.updateComplete.then(() => this.#calendar?.focus());\n this.dispatchEvent(new Event('uf-show', { bubbles: true, composed: true }));\n } else {\n this.#cleanup?.();\n this.#cleanup = undefined;\n if (this.#focusWasInside) this.#input?.focus();\n this.#focusWasInside = false;\n this.dispatchEvent(new Event('uf-hide', { bubbles: true, composed: true }));\n }\n };\n\n protected syncFormState(): void {\n const input = this.#input;\n if (!input) return;\n this.internals.setFormValue(this.value);\n const t = this.translator;\n const lang = t.lang;\n const date = parseIso(this.value);\n const min = parseIso(this.min);\n const max = parseIso(this.max);\n const long = (d: Date) => formatter(lang, { day: 'numeric', month: 'long', year: 'numeric' }).format(d);\n\n if (this.#badInput) {\n this.setValidity({ badInput: true }, t.t('invalidDate', { example: formatShort(parseIso(todayIso())!, lang) }), input);\n } else if (this.required && !date) {\n this.setValidity({ valueMissing: true }, valueMissingMessage(), input);\n } else if (date && min && date < min) {\n this.setValidity({ rangeUnderflow: true }, t.t('dateTooEarly', { date: long(min) }), input);\n } else if (date && max && date > max) {\n this.setValidity({ rangeOverflow: true }, t.t('dateTooLate', { date: long(max) }), input);\n } else if (date && this.isDateDisabled?.(this.value)) {\n this.setValidity({ badInput: true }, t.t('dateUnavailable'), input);\n } else {\n this.setValidity({}, '', input);\n }\n }\n\n protected resetValue(): void {\n this.value = parseIso(this.defaultValue) ? this.defaultValue : '';\n }\n\n /** @internal */\n formStateRestoreCallback(state: string | null): void {\n this.value = parseIso(state) ? state! : '';\n }\n\n /** Sets the value from the user, and tells listeners when it changed. */\n #commit(value: string): void {\n const changed = value !== this.value;\n this.value = value;\n this.markInteracted();\n if (changed) {\n this.dispatchEvent(new Event('input', { bubbles: true, composed: true }));\n this.emitChange();\n }\n }\n\n /** Turns the typed text into the value: a date, empty, or invalid. */\n #commitText(): void {\n if (this.#text === null) return;\n const text = this.#text.trim();\n const date = text ? parseTyped(text, this.translator.lang) : null;\n if (!text || date) {\n this.#commit(date ? toIso(date) : '');\n this.#text = null;\n this.#badInput = false;\n } else {\n // Not a date: keep the text so the user can fix it, and report it.\n this.#commit('');\n this.#text = text;\n this.#badInput = true;\n }\n this.syncFormState();\n this.requestUpdate();\n }\n\n #onInput = (event: Event): void => {\n // The value changes when the date is committed, not on every keystroke.\n event.stopPropagation();\n this.#text = (event.target as HTMLInputElement).value;\n };\n\n #onKeyDown = (event: KeyboardEvent): void => {\n if (event.key === 'Enter') this.#commitText();\n else if (event.key === 'ArrowDown' && event.altKey) {\n event.preventDefault();\n this.show();\n }\n };\n\n #onCalendarChange = (event: Event): void => {\n event.stopPropagation();\n this.#commit((event.target as UfCalendar).value);\n this.hide();\n this.#input?.focus();\n };\n\n #placeholder(): string {\n if (this.placeholder !== undefined) return this.placeholder;\n const { order, separator } = shortPattern(this.translator.lang);\n const letters = { day: this.translator.t('dayPlaceholder'), month: this.translator.t('monthPlaceholder'), year: this.translator.t('yearPlaceholder') };\n return order.map((part) => letters[part]).join(separator);\n }\n\n override render() {\n const ids = { hintId: `${this.#id}-hint`, errorId: `${this.#id}-error` };\n const popupId = `${this.#id}-popup`;\n const error = this.showInvalid ? this.validationMessage : '';\n const hasHintSlot = this.#slots.has('hint');\n const date = parseIso(this.value);\n const text = this.#text ?? (date ? formatShort(date, this.translator.lang) : '');\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 <input\n id=${this.#id}\n class=\"native\"\n part=\"input\"\n type=\"text\"\n autocomplete=\"off\"\n .value=${live(text)}\n placeholder=${this.#placeholder()}\n ?readonly=${this.readonly}\n ?disabled=${this.isDisabled}\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 @change=${() => this.#commitText()}\n @keydown=${this.#onKeyDown}\n />\n <button\n class=${classMap({ toggle: true, open: this.open })}\n part=\"toggle\"\n type=\"button\"\n aria-label=${this.translator.t('chooseDate')}\n aria-haspopup=\"dialog\"\n aria-expanded=${this.open ? 'true' : 'false'}\n popovertarget=${popupId}\n ?disabled=${this.isDisabled || this.readonly}\n >\n ${iconSvg(icons.calendar)}\n </button>\n </div>\n <div\n id=${popupId}\n class=\"popup\"\n part=\"popup\"\n popover=\"auto\"\n role=\"dialog\"\n aria-label=${this.label ?? this.translator.t('chooseDate')}\n @beforetoggle=${this.#onBeforeToggle}\n @toggle=${this.#onToggle}\n >\n <uf-calendar\n part=\"calendar\"\n .value=${this.value}\n .min=${this.min}\n .max=${this.max}\n .isDateDisabled=${this.isDateDisabled}\n @change=${this.#onCalendarChange}\n ></uf-calendar>\n </div>\n `,\n });\n }\n}\n\ndefineElement('uf-date-picker', UfDatePicker);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-date-picker': UfDatePicker;\n }\n}\n",
|
|
703
|
+
"components/date-range-picker/date-range-picker.ts": "import { css, html, 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 { formatShort, formatter, parseIso, parseTyped, shortPattern, toIso, todayIso } from '../../internal/dates.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 { autoUpdate, positionFloating } from '../../internal/position.js';\nimport { hostStyles } from '../../internal/shared.styles.js';\nimport { HasSlotController, uniqueId } from '../../internal/slot.js';\nimport '../calendar/calendar.js';\nimport type { UfCalendar } from '../calendar/calendar.js';\n\ntype End = 'start' | 'end';\n\n/** A browser-translated \"Please fill out this field.\", from a native input that never joins the page. */\nlet requiredMessage: string | undefined;\nfunction valueMissingMessage(): string {\n if (requiredMessage === undefined) {\n const probe = document.createElement('input');\n probe.required = true;\n requiredMessage = probe.validationMessage;\n }\n return requiredMessage;\n}\n\n/** Splits an ISO 8601 interval, `YYYY-MM-DD/YYYY-MM-DD`, into its two valid dates (or empty strings). */\nfunction splitInterval(value: string | null | undefined): [string, string] {\n const [start = '', end = ''] = (value ?? '').split('/');\n return [parseIso(start) ? start : '', parseIso(end) ? end : ''];\n}\n\n/**\n * A date range field: type the start and end dates in the page language's\n * format, or pick both from a calendar. The value is an ISO 8601 interval,\n * `YYYY-MM-DD/YYYY-MM-DD`, the same in every language, and it submits with the\n * form; `start` and `end` hold the two dates.\n *\n * Alt + Down Arrow opens the calendar; Escape closes it.\n *\n * @summary Lets users type or pick a start and an end date.\n * @tag uf-date-range-picker\n *\n * @slot label - The label, when you need markup. Overrides `label`.\n * @slot hint - Help text below the field. Overrides `hint`.\n *\n * @event input - The range changed (a date was typed and committed, or both were picked).\n * @event change - The range changed (a date was typed and committed, or both were picked).\n * @event uf-show - The calendar opened.\n * @event uf-hide - The calendar 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 around the inputs.\n * @csspart start-input - The start date input.\n * @csspart end-input - The end date input.\n * @csspart separator - The dash between the two inputs.\n * @csspart toggle - The calendar button.\n * @csspart popup - The floating panel around the calendar.\n * @csspart calendar - The `<uf-calendar>`.\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 range is invalid and the user has interacted with the field.\n */\nexport class UfDateRangePicker extends FormControl {\n static override styles = [\n hostStyles,\n fieldStyles,\n controlBoxStyles,\n css`\n .box {\n padding-inline-end: 0;\n }\n\n .native {\n width: 0;\n text-align: center;\n }\n\n .separator {\n flex: none;\n color: var(--uf-color-text-muted);\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:hover:not(:disabled),\n .toggle.open {\n color: var(--uf-color-accent-strong);\n }\n\n .toggle:focus-visible {\n outline: var(--uf-focus-ring-width) solid var(--uf-color-focus-ring);\n outline-offset: -2px;\n }\n\n .toggle:disabled {\n cursor: not-allowed;\n }\n\n .toggle .icon {\n width: 1.125em;\n height: 1.125em;\n }\n\n .popup {\n position: fixed;\n inset: auto;\n margin: 0;\n padding: var(--uf-space-3);\n border: 1px solid var(--uf-color-border);\n border-radius: var(--uf-radius-md);\n background: var(--uf-color-surface-overlay);\n color: var(--uf-color-text);\n box-shadow: var(--uf-shadow-overlay);\n }\n `,\n ];\n\n protected static override formStateProperties: ReadonlySet<PropertyKey> = new Set([\n ...FormControl.formStateProperties,\n 'start',\n 'end',\n 'min',\n 'max',\n 'isDateDisabled',\n ]);\n\n static override properties: PropertyDeclarations = {\n value: { attribute: false, noAccessor: true },\n start: { attribute: false },\n end: { attribute: false },\n defaultValue: { attribute: 'value' },\n label: {},\n hint: {},\n placeholder: {},\n size: { reflect: true },\n min: {},\n max: {},\n readonly: { type: Boolean, reflect: true },\n open: { type: Boolean, reflect: true },\n isDateDisabled: { attribute: false },\n };\n\n /** The first date of the range, as `YYYY-MM-DD`, or an empty string. */\n declare start: string;\n /** The last date of the range, as `YYYY-MM-DD`, or an empty string. */\n declare end: string;\n /** Initial range, restored on form reset. Set with the `value` attribute, as `YYYY-MM-DD/YYYY-MM-DD`. */\n declare defaultValue: string;\n /** The field's label, also its accessible name. */\n declare label: string | undefined;\n /** Help text below the field. */\n declare hint: string | undefined;\n /** Shown in both inputs when empty. Defaults to the date format, e.g. dd/mm/yyyy. */\n declare placeholder: string | undefined;\n /** Size: `sm`, `md` or `lg`. */\n declare size: FieldSize;\n /** The earliest allowed date, as `YYYY-MM-DD`. */\n declare min: string | undefined;\n /** The latest allowed date, as `YYYY-MM-DD`. */\n declare max: string | undefined;\n /** Lets the user select the text but not change the dates. */\n declare readonly: boolean;\n /** Whether the calendar is open. */\n declare open: boolean;\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\n readonly #slots = new HasSlotController(this, 'label', 'hint');\n readonly #id = uniqueId('uf-date-range-picker');\n /** What the user typed in each input and hasn't committed yet; null shows the date, formatted. */\n #text: Record<End, string | null> = { start: null, end: null };\n /** The committed text of an input isn't a date. */\n #bad: Record<End, boolean> = { start: false, end: false };\n #cleanup?: () => void;\n #focusWasInside = false;\n #toggling = false;\n\n constructor() {\n super();\n this.start = '';\n this.end = '';\n this.defaultValue = '';\n this.size = 'md';\n this.readonly = false;\n this.open = false;\n }\n\n /** The range as an ISO 8601 interval, `YYYY-MM-DD/YYYY-MM-DD`, or an empty string until both dates are set. */\n get value(): string {\n return this.start && this.end ? `${this.start}/${this.end}` : '';\n }\n\n set value(value: string) {\n const old = this.value;\n [this.start, this.end] = splitInterval(value);\n this.requestUpdate('value', old);\n }\n\n #input(which: End): HTMLInputElement | null {\n return this.renderRoot.querySelector(`[data-end=\"${which}\"]`);\n }\n\n get #popup(): HTMLElement | null {\n return this.renderRoot.querySelector('.popup');\n }\n\n get #calendar(): UfCalendar | null {\n return this.renderRoot.querySelector('uf-calendar');\n }\n\n /** Opens the calendar. */\n show(): void {\n if (!this.isDisabled && !this.readonly) this.open = true;\n }\n\n /** Closes the calendar. */\n hide(): void {\n this.open = false;\n }\n\n override disconnectedCallback(): void {\n super.disconnectedCallback();\n this.#cleanup?.();\n this.#cleanup = undefined;\n }\n\n override willUpdate(changed: PropertyValues<this>): void {\n if (changed.has('defaultValue') && this.value === splitInterval(changed.get('defaultValue')).filter(Boolean).join('/')) {\n [this.start, this.end] = splitInterval(this.defaultValue);\n }\n // Dates set from code replace what was typed.\n for (const which of ['start', 'end'] as const) {\n if (changed.has(which)) {\n this.#text[which] = null;\n this.#bad[which] = false;\n }\n }\n }\n\n override updated(changed: PropertyValues<this>): void {\n this.syncFormState();\n if (changed.has('open')) this.#syncPopup();\n }\n\n #syncPopup(): void {\n const popup = this.#popup;\n if (!popup || this.#toggling) return;\n if (this.open && !popup.matches(':popover-open')) {\n popup.showPopover();\n this.#startPositioning();\n } else if (!this.open && popup.matches(':popover-open')) {\n popup.hidePopover();\n }\n }\n\n #startPositioning(): void {\n const popup = this.#popup;\n const box = this.renderRoot.querySelector<HTMLElement>('.box');\n if (!popup || !box || !popup.matches(':popover-open')) return;\n this.#cleanup ??= autoUpdate(box, popup, () => positionFloating(box, popup, 'bottom-start', 4));\n }\n\n #onBeforeToggle = (event: ToggleEvent): void => {\n // Same as <uf-date-picker>: keeps `open` right at once, and positions the\n // popup before its first paint.\n this.#toggling = true;\n this.open = event.newState === 'open';\n if (event.newState === 'open') requestAnimationFrame(() => this.#startPositioning());\n if (event.newState === 'closed') this.#focusWasInside = Boolean(this.shadowRoot?.activeElement?.closest('.popup'));\n };\n\n #onToggle = (event: ToggleEvent): void => {\n this.#toggling = false;\n // Closed (or reopened) from code before the browser finished: catch up now.\n if ((event.newState === 'open') !== this.open) {\n this.#syncPopup();\n return;\n }\n if (event.newState === 'open') {\n this.#startPositioning();\n this.#calendar?.updateComplete.then(() => this.#calendar?.focus());\n this.dispatchEvent(new Event('uf-show', { bubbles: true, composed: true }));\n } else {\n this.#cleanup?.();\n this.#cleanup = undefined;\n if (this.#focusWasInside) this.#input('start')?.focus();\n this.#focusWasInside = false;\n this.dispatchEvent(new Event('uf-hide', { bubbles: true, composed: true }));\n }\n };\n\n protected syncFormState(): void {\n const startInput = this.#input('start');\n const endInput = this.#input('end');\n if (!startInput || !endInput) return;\n this.internals.setFormValue(this.value);\n const t = this.translator;\n const lang = t.lang;\n const start = parseIso(this.start);\n const end = parseIso(this.end);\n const min = parseIso(this.min);\n const max = parseIso(this.max);\n const long = (d: Date) => formatter(lang, { day: 'numeric', month: 'long', year: 'numeric' }).format(d);\n const example = () => t.t('invalidDate', { example: formatShort(parseIso(todayIso())!, lang) });\n\n if (this.#bad.start || this.#bad.end) {\n this.setValidity({ badInput: true }, example(), this.#bad.start ? startInput : endInput);\n } else if (this.required && !start && !end) {\n this.setValidity({ valueMissing: true }, valueMissingMessage(), startInput);\n } else if (Boolean(start) !== Boolean(end)) {\n this.setValidity({ badInput: true }, t.t('rangeIncomplete'), start ? endInput : startInput);\n } else if (start && end && end < start) {\n this.setValidity({ badInput: true }, t.t('endBeforeStart'), endInput);\n } else if (start && min && start < min) {\n this.setValidity({ rangeUnderflow: true }, t.t('dateTooEarly', { date: long(min) }), startInput);\n } else if (end && max && end > max) {\n this.setValidity({ rangeOverflow: true }, t.t('dateTooLate', { date: long(max) }), endInput);\n } else if (start && this.isDateDisabled?.(this.start)) {\n this.setValidity({ badInput: true }, t.t('dateUnavailable'), startInput);\n } else if (end && this.isDateDisabled?.(this.end)) {\n this.setValidity({ badInput: true }, t.t('dateUnavailable'), endInput);\n } else {\n this.setValidity({}, '', startInput);\n }\n }\n\n protected resetValue(): void {\n [this.start, this.end] = splitInterval(this.defaultValue);\n }\n\n /** @internal */\n formStateRestoreCallback(state: string | null): void {\n [this.start, this.end] = splitInterval(state);\n }\n\n /** Sets the dates from the user, and tells listeners when they changed. */\n #commit(start: string, end: string): void {\n const changed = start !== this.start || end !== this.end;\n this.start = start;\n this.end = end;\n this.markInteracted();\n if (changed) {\n this.dispatchEvent(new Event('input', { bubbles: true, composed: true }));\n this.emitChange();\n }\n }\n\n /** Turns the typed text of one input into its date: a date, empty, or invalid. */\n #commitText(which: End): void {\n const typed = this.#text[which];\n if (typed === null) return;\n const text = typed.trim();\n const date = text ? parseTyped(text, this.translator.lang) : null;\n const iso = date ? toIso(date) : '';\n this.#commit(which === 'start' ? iso : this.start, which === 'end' ? iso : this.end);\n // Not a date: keep the text so the user can fix it, and report it.\n this.#text[which] = text && !date ? text : null;\n this.#bad[which] = Boolean(text && !date);\n this.syncFormState();\n this.requestUpdate();\n }\n\n #onInput = (which: End) => (event: Event) => {\n // The dates change when committed, not on every keystroke.\n event.stopPropagation();\n this.#text[which] = (event.target as HTMLInputElement).value;\n };\n\n #onKeyDown = (which: End) => (event: KeyboardEvent) => {\n if (event.key === 'Enter') this.#commitText(which);\n else if (event.key === 'ArrowDown' && event.altKey) {\n event.preventDefault();\n this.show();\n }\n };\n\n #onCalendarChange = (event: Event): void => {\n event.stopPropagation();\n const calendar = event.target as UfCalendar;\n this.#commit(calendar.start, calendar.end);\n this.hide();\n this.#input('end')?.focus();\n };\n\n #placeholder(): string {\n if (this.placeholder !== undefined) return this.placeholder;\n const { order, separator } = shortPattern(this.translator.lang);\n const letters = { day: this.translator.t('dayPlaceholder'), month: this.translator.t('monthPlaceholder'), year: this.translator.t('yearPlaceholder') };\n return order.map((part) => letters[part]).join(separator);\n }\n\n #renderInput(which: End, ids: { hintId: string; errorId: string }, error: string, hasHintSlot: boolean) {\n const date = parseIso(this[which]);\n const text = this.#text[which] ?? (date ? formatShort(date, this.translator.lang) : '');\n const name = this.translator.t(which === 'start' ? 'startDate' : 'endDate');\n return html`<input\n id=${which === 'start' ? this.#id : `${this.#id}-end`}\n class=\"native\"\n part=${`${which}-input`}\n data-end=${which}\n type=\"text\"\n autocomplete=\"off\"\n .value=${live(text)}\n placeholder=${this.#placeholder()}\n aria-label=${this.label ? `${this.label}, ${name}` : name}\n ?readonly=${this.readonly}\n ?disabled=${this.isDisabled}\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(which)}\n @change=${() => this.#commitText(which)}\n @keydown=${this.#onKeyDown(which)}\n />`;\n }\n\n override render() {\n const ids = { hintId: `${this.#id}-hint`, errorId: `${this.#id}-error` };\n const popupId = `${this.#id}-popup`;\n const error = this.showInvalid ? this.validationMessage : '';\n const hasHintSlot = this.#slots.has('hint');\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 ${this.#renderInput('start', ids, error, hasHintSlot)}\n <span class=\"separator\" part=\"separator\" aria-hidden=\"true\">–</span>\n ${this.#renderInput('end', ids, error, hasHintSlot)}\n <button\n class=${classMap({ toggle: true, open: this.open })}\n part=\"toggle\"\n type=\"button\"\n aria-label=${this.translator.t('chooseDates')}\n aria-haspopup=\"dialog\"\n aria-expanded=${this.open ? 'true' : 'false'}\n popovertarget=${popupId}\n ?disabled=${this.isDisabled || this.readonly}\n >\n ${iconSvg(icons.calendar)}\n </button>\n </div>\n <div\n id=${popupId}\n class=\"popup\"\n part=\"popup\"\n popover=\"auto\"\n role=\"dialog\"\n aria-label=${this.label ?? this.translator.t('chooseDates')}\n @beforetoggle=${this.#onBeforeToggle}\n @toggle=${this.#onToggle}\n >\n <uf-calendar\n part=\"calendar\"\n range\n .start=${live(this.start)}\n .end=${live(this.end)}\n .min=${this.min}\n .max=${this.max}\n .isDateDisabled=${this.isDateDisabled}\n @change=${this.#onCalendarChange}\n ></uf-calendar>\n </div>\n `,\n });\n }\n}\n\ndefineElement('uf-date-range-picker', UfDateRangePicker);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-date-range-picker': UfDateRangePicker;\n }\n}\n",
|
|
655
704
|
"components/dialog/dialog.ts": "import { LitElement, css, html, type PropertyDeclarations, type PropertyValues } from 'lit';\nimport { defineElement } from '../../internal/define.js';\nimport { Translator } from '../../internal/i18n.js';\nimport { iconSvg, icons } from '../../internal/icons.js';\nimport { hostStyles } from '../../internal/shared.styles.js';\nimport { HasSlotController, uniqueId } from '../../internal/slot.js';\n\nexport type DialogCloseSource = 'close-button' | 'escape' | 'backdrop' | 'trigger' | 'method';\n\nexport interface DialogRequestCloseDetail {\n source: DialogCloseSource;\n}\n\nlet scrollLocks = 0;\nlet savedStyles: { overflow: string; paddingRight: string } | undefined;\n\n/**\n * Locks page scroll while any dialog is open. Hiding overflow removes a classic\n * (non-overlay) scrollbar, so the page is padded by its width to avoid a shift.\n * (`scrollbar-gutter: stable` isn't honoured on the root once overflow is hidden.)\n * The width is exposed as `--uf-scrollbar-width` for fixed elements to compensate.\n */\nfunction lockScroll(lock: boolean): void {\n const html = document.documentElement;\n const wasLocked = scrollLocks > 0;\n scrollLocks = Math.max(0, scrollLocks + (lock ? 1 : -1));\n\n if (scrollLocks > 0 && !wasLocked) {\n const scrollbarWidth = window.innerWidth - html.clientWidth;\n savedStyles = { overflow: html.style.overflow, paddingRight: html.style.paddingRight };\n if (scrollbarWidth > 0) {\n const padding = parseFloat(getComputedStyle(html).paddingRight) || 0;\n html.style.paddingRight = `${padding + scrollbarWidth}px`;\n html.style.setProperty('--uf-scrollbar-width', `${scrollbarWidth}px`);\n }\n html.style.overflow = 'hidden';\n } else if (scrollLocks === 0 && wasLocked && savedStyles) {\n html.style.overflow = savedStyles.overflow;\n html.style.paddingRight = savedStyles.paddingRight;\n html.style.removeProperty('--uf-scrollbar-width');\n savedStyles = undefined;\n }\n}\n\n/**\n * A modal dialog built on the native `<dialog>`: it renders in the top layer,\n * traps focus, makes the page inert, and returns focus to the opener on close.\n * Any element inside with `data-dialog=\"close\"` closes it.\n *\n * @summary Shows content in a modal window on top of the page.\n * @tag uf-dialog\n *\n * @slot - The dialog content.\n * @slot label - The title, when you need markup. Overrides `label`.\n * @slot header-actions - Extra buttons next to the close button.\n * @slot footer - Actions at the bottom, usually buttons.\n *\n * @event uf-show - The dialog opened.\n * @event uf-hide - The dialog closed.\n * @event {CustomEvent<DialogRequestCloseDetail>} uf-request-close - The user tried to close the dialog. Call `preventDefault()` to keep it open.\n *\n * @csspart dialog - The native `<dialog>`.\n * @csspart header - The header with title and close button.\n * @csspart title - The title.\n * @csspart close-button - The close button.\n * @csspart body - The content area.\n * @csspart footer - The footer.\n *\n * @cssprop --uf-dialog-bg - Background of the dialog.\n * @cssprop --uf-dialog-width - Width of the dialog. Defaults to `32rem`.\n * @cssprop --uf-dialog-padding - Padding of header, body and footer.\n * @cssprop --uf-dialog-radius - Corner radius.\n * @cssprop --uf-dialog-backdrop - Backdrop color.\n */\nexport class UfDialog extends LitElement {\n static override styles = [\n hostStyles,\n css`\n :host {\n --_padding: var(--uf-dialog-padding, var(--uf-space-5));\n display: contents;\n }\n\n dialog {\n flex-direction: column;\n width: min(var(--uf-dialog-width, 32rem), calc(100vw - 2rem));\n max-height: calc(100dvh - 2rem);\n padding: 0;\n border: 1px solid var(--uf-color-border);\n border-radius: var(--uf-dialog-radius, var(--uf-radius-lg));\n background: var(--uf-dialog-bg, 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-modal);\n overflow: hidden;\n }\n\n dialog[open] {\n display: flex;\n }\n\n dialog::backdrop {\n background: var(--uf-dialog-backdrop, color-mix(in srgb, var(--uf-color-backdrop) 50%, transparent));\n }\n\n /*\n * Keyframe animations rather than transitions on display/overlay: the\n * component keeps the dialog open (modal, in the top layer) until the exit\n * animation ends, so it behaves the same in every browser.\n */\n dialog[open] {\n animation: uf-dialog-in var(--uf-duration-base) ease;\n }\n\n dialog[open]::backdrop {\n animation: uf-fade-in var(--uf-duration-base) ease;\n }\n\n dialog.closing {\n animation: uf-dialog-out var(--uf-duration-base) ease forwards;\n }\n\n dialog.closing::backdrop {\n animation: uf-fade-out var(--uf-duration-base) ease forwards;\n }\n\n @keyframes uf-dialog-in {\n from {\n opacity: 0;\n translate: 0 0.5rem;\n }\n }\n\n @keyframes uf-dialog-out {\n to {\n opacity: 0;\n translate: 0 0.5rem;\n }\n }\n\n @keyframes uf-fade-in {\n from {\n opacity: 0;\n }\n }\n\n @keyframes uf-fade-out {\n to {\n opacity: 0;\n }\n }\n\n @media (prefers-reduced-motion: reduce) {\n dialog[open],\n dialog[open]::backdrop,\n dialog.closing,\n dialog.closing::backdrop {\n animation: none;\n }\n }\n\n .header {\n display: flex;\n align-items: center;\n gap: var(--uf-space-2);\n padding: var(--_padding) var(--_padding) 0;\n }\n\n .title {\n flex: 1;\n margin: 0;\n font-size: var(--uf-font-size-lg);\n font-weight: var(--uf-font-weight-semibold);\n line-height: 1.3;\n }\n\n .close {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: var(--uf-size-control-sm);\n height: var(--uf-size-control-sm);\n margin: calc(var(--uf-space-1) * -1) calc(var(--uf-space-2) * -1) calc(var(--uf-space-1) * -1) 0;\n padding: 0;\n border: 0;\n border-radius: var(--uf-radius-md);\n background: transparent;\n color: var(--uf-color-text-muted);\n cursor: pointer;\n }\n\n .close:hover {\n background: var(--uf-color-surface-hover);\n color: var(--uf-color-text);\n }\n\n .close:focus-visible {\n outline: var(--uf-focus-ring-width) solid var(--uf-color-focus-ring);\n outline-offset: 0;\n }\n\n .close .icon {\n width: 1.125rem;\n height: 1.125rem;\n }\n\n .body {\n flex: 1;\n padding: var(--_padding);\n overflow: auto;\n line-height: 1.5;\n }\n\n .footer {\n display: flex;\n flex-wrap: wrap;\n justify-content: flex-end;\n gap: var(--uf-space-2);\n padding: var(--uf-space-2) var(--_padding) var(--_padding);\n }\n\n [hidden] {\n display: none !important;\n }\n `,\n ];\n\n static override properties: PropertyDeclarations = {\n open: { type: Boolean, reflect: true },\n label: {},\n lightDismiss: { type: Boolean, attribute: 'light-dismiss' },\n withoutHeader: { type: Boolean, attribute: 'without-header' },\n };\n\n /** Whether the dialog is open. */\n declare open: boolean;\n /** Title of the dialog, also its accessible name. */\n declare label: string | undefined;\n /** Closes the dialog when the backdrop is clicked. */\n declare lightDismiss: boolean;\n /** Hides the header. Set `label` anyway, so the dialog keeps an accessible name. */\n declare withoutHeader: boolean;\n\n readonly #slots = new HasSlotController(this, 'footer', 'label');\n readonly #id = uniqueId('uf-dialog');\n readonly #translator = new Translator(this);\n\n constructor() {\n super();\n this.open = false;\n this.lightDismiss = false;\n this.withoutHeader = false;\n this.addEventListener('click', this.#onHostClick);\n }\n\n get #dialog(): HTMLDialogElement | null {\n return this.renderRoot.querySelector('dialog');\n }\n\n /** Opens the dialog. */\n show(): void {\n this.open = true;\n }\n\n /** Closes the dialog, without firing `uf-request-close`. */\n hide(): void {\n this.open = false;\n }\n\n /** Asks to close, as a user action would. Listeners can cancel it. */\n requestClose(source: DialogCloseSource = 'trigger'): void {\n const event = new CustomEvent<DialogRequestCloseDetail>('uf-request-close', {\n bubbles: true,\n composed: true,\n cancelable: true,\n detail: { source },\n });\n if (this.dispatchEvent(event)) this.open = false;\n }\n\n override disconnectedCallback(): void {\n super.disconnectedCallback();\n this.#dialog?.close();\n this.#setScrollLock(false);\n }\n\n /** Each dialog holds at most one scroll lock, however it was closed. */\n #setScrollLock(lock: boolean): void {\n if (lock === this.#scrollLocked) return;\n this.#scrollLocked = lock;\n lockScroll(lock);\n }\n\n #scrollLocked = false;\n\n override updated(changed: PropertyValues<this>): void {\n if (!changed.has('open')) return;\n const dialog = this.#dialog;\n if (!dialog) return;\n\n if (this.open) {\n // Reopened during the exit animation: just cancel the exit.\n if (dialog.classList.contains('closing')) {\n dialog.classList.remove('closing');\n return;\n }\n if (dialog.open) return;\n dialog.showModal();\n this.#setScrollLock(true);\n this.dispatchEvent(new Event('uf-show', { bubbles: true, composed: true }));\n } else if (dialog.open) {\n void this.#animateClose(dialog);\n }\n }\n\n /** Plays the exit animation while the dialog is still modal, then closes it. */\n async #animateClose(dialog: HTMLDialogElement): Promise<void> {\n dialog.classList.add('closing');\n const animations = document.hidden ? [] : dialog.getAnimations({ subtree: true });\n // Animations pause in background tabs; never let that keep the dialog open.\n const longest = Math.max(0, ...animations.map((a) => Number(a.effect?.getComputedTiming().endTime) || 0));\n await Promise.race([\n Promise.allSettled(animations.map((a) => a.finished)),\n new Promise((resolve) => setTimeout(resolve, longest + 50)),\n ]);\n if (this.open || !dialog.classList.contains('closing')) return;\n dialog.classList.remove('closing');\n dialog.close();\n this.#setScrollLock(false);\n this.dispatchEvent(new Event('uf-hide', { bubbles: true, composed: true }));\n }\n\n #onCancel = (event: Event): void => {\n event.preventDefault();\n this.requestClose('escape');\n };\n\n /** Closed by something other than this component, e.g. `<form method=\"dialog\">`. */\n #onClose = (): void => {\n this.#setScrollLock(false);\n if (!this.open) return;\n this.open = false;\n this.dispatchEvent(new Event('uf-hide', { bubbles: true, composed: true }));\n };\n\n #onDialogClick = (event: MouseEvent): void => {\n // The dialog has no padding, so a click whose target is the dialog itself hit the backdrop.\n if (this.lightDismiss && event.target === this.#dialog) this.requestClose('backdrop');\n };\n\n #onHostClick = (event: MouseEvent): void => {\n const closer = event.composedPath().find((el) => el instanceof Element && el.getAttribute('data-dialog') === 'close');\n if (closer && this.open) this.requestClose('trigger');\n };\n\n override render() {\n const titleId = `${this.#id}-title`;\n return html`\n <dialog\n part=\"dialog\"\n aria-labelledby=${titleId}\n @cancel=${this.#onCancel}\n @close=${this.#onClose}\n @click=${this.#onDialogClick}\n >\n <header class=\"header\" part=\"header\" ?hidden=${this.withoutHeader}>\n <h2 id=${titleId} class=\"title\" part=\"title\"><slot name=\"label\">${this.label}</slot></h2>\n <slot name=\"header-actions\"></slot>\n <button class=\"close\" part=\"close-button\" type=\"button\" aria-label=${this.#translator.t('close')} @click=${() => this.requestClose('close-button')}>\n ${iconSvg(icons.x)}\n </button>\n </header>\n <div class=\"body\" part=\"body\"><slot></slot></div>\n <footer class=\"footer\" part=\"footer\" ?hidden=${!this.#slots.has('footer')}>\n <slot name=\"footer\"></slot>\n </footer>\n </dialog>\n `;\n }\n}\n\ndefineElement('uf-dialog', UfDialog);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-dialog': UfDialog;\n }\n}\n",
|
|
656
|
-
"components/drawer/drawer.ts": "import { css, type PropertyDeclarations } from 'lit';\nimport { defineElement } from '../../internal/define.js';\nimport { UfDialog } from '../dialog/dialog.js';\n\nexport type DrawerPlacement = 'start' | 'end' | 'top' | 'bottom';\n\n/**\n * A panel that slides in from an edge of the screen, for navigation, filters or\n * details. It is a modal dialog, so it behaves like `<uf-dialog>`: it traps\n * focus, makes the page inert, closes with Escape, and returns focus to the\n * opener. Any element inside with `data-dialog=\"close\"` closes it.\n *\n * @summary A panel that slides in from an edge of the screen.\n * @tag uf-drawer\n *\n * @slot - The drawer content.\n * @slot label - The title, when you need markup. Overrides `label`.\n * @slot header-actions - Extra buttons next to the close button.\n * @slot footer - Actions at the bottom, usually buttons.\n *\n * @event uf-show - The drawer opened.\n * @event uf-hide - The drawer closed.\n * @event {CustomEvent<DialogRequestCloseDetail>} uf-request-close - The user tried to close the drawer. Call `preventDefault()` to keep it open.\n *\n * @csspart dialog - The native `<dialog>`.\n * @csspart header - The header with title and close button.\n * @csspart title - The title.\n * @csspart close-button - The close button.\n * @csspart body - The content area.\n * @csspart footer - The footer.\n *\n * @cssprop --uf-drawer-size - Width of a side drawer, or height of a top or bottom one. Defaults to `24rem`.\n * @cssprop --uf-dialog-bg - Background of the drawer.\n * @cssprop --uf-dialog-padding - Padding of header, body and footer.\n * @cssprop --uf-dialog-backdrop - Backdrop color.\n */\nexport class UfDrawer extends UfDialog {\n static override styles = [\n ...UfDialog.styles,\n css`\n dialog {\n --_size: min(var(--uf-drawer-size, 24rem), 100vw);\n --_from: 100% 0;\n position: fixed;\n inset: 0 0 0 auto;\n width: var(--_size);\n max-width: 100vw;\n height: 100dvh;\n max-height: 100dvh;\n margin: 0;\n border-width: 0 0 0 1px;\n border-radius: 0;\n }\n\n :host([placement='start']) dialog {\n --_from: -100% 0;\n inset: 0 auto 0 0;\n border-width: 0 1px 0 0;\n }\n\n /* Right-to-left pages: start is on the right, end on the left. */\n :host(:dir(rtl)) dialog {\n --_from: -100% 0;\n inset: 0 auto 0 0;\n border-width: 0 1px 0 0;\n }\n\n :host(:dir(rtl)[placement='start']) dialog {\n --_from: 100% 0;\n inset: 0 0 0 auto;\n border-width: 0 0 0 1px;\n }\n\n :host([placement='top']) dialog,\n :host([placement='bottom']) dialog {\n --_size: min(var(--uf-drawer-size, 24rem), 100dvh);\n width: 100vw;\n height: var(--_size);\n }\n\n :host([placement='top']) dialog {\n --_from: 0 -100%;\n inset: 0 0 auto 0;\n border-width: 0 0 1px 0;\n }\n\n :host([placement='bottom']) dialog {\n --_from: 0 100%;\n inset: auto 0 0 0;\n border-width: 1px 0 0 0;\n }\n\n dialog[open] {\n animation-name: uf-drawer-in;\n }\n\n dialog.closing {\n animation-name: uf-drawer-out;\n }\n\n @keyframes uf-drawer-in {\n from {\n translate: var(--_from);\n }\n }\n\n @keyframes uf-drawer-out {\n to {\n translate: var(--_from);\n }\n }\n `,\n ];\n\n static override properties: PropertyDeclarations = {\n placement: { reflect: true },\n };\n\n /** The edge it slides in from: `start` (left, in left-to-right pages), `end`, `top` or `bottom`. */\n declare placement: DrawerPlacement;\n\n constructor() {\n super();\n this.placement = 'end';\n }\n}\n\ndefineElement('uf-drawer', UfDrawer);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-drawer': UfDrawer;\n }\n}\n",
|
|
705
|
+
"components/drawer/drawer.ts": "import { css, type PropertyDeclarations } from 'lit';\nimport { defineElement } from '../../internal/define.js';\nimport { UfDialog } from '../dialog/dialog.js';\n\nexport type DrawerPlacement = 'start' | 'end' | 'top' | 'bottom';\n\n/**\n * A panel that slides in from an edge of the screen, for navigation, filters or\n * details. It is a modal dialog, so it behaves like `<uf-dialog>`: it traps\n * focus, makes the page inert, closes with Escape, and returns focus to the\n * opener. Any element inside with `data-dialog=\"close\"` closes it.\n *\n * @summary A panel that slides in from an edge of the screen.\n * @tag uf-drawer\n *\n * @slot - The drawer content.\n * @slot label - The title, when you need markup. Overrides `label`.\n * @slot header-actions - Extra buttons next to the close button.\n * @slot footer - Actions at the bottom, usually buttons.\n *\n * @event uf-show - The drawer opened.\n * @event uf-hide - The drawer closed.\n * @event {CustomEvent<DialogRequestCloseDetail>} uf-request-close - The user tried to close the drawer. Call `preventDefault()` to keep it open.\n *\n * @csspart dialog - The native `<dialog>`.\n * @csspart header - The header with title and close button.\n * @csspart title - The title.\n * @csspart close-button - The close button.\n * @csspart body - The content area.\n * @csspart footer - The footer.\n *\n * @cssprop --uf-drawer-size - Width of a side drawer, or height of a top or bottom one. Defaults to `24rem`.\n * @cssprop --uf-drawer-radius - Corner radius of the corners on the open side; the side against the screen edge stays square.\n * @cssprop --uf-dialog-bg - Background of the drawer.\n * @cssprop --uf-dialog-padding - Padding of header, body and footer.\n * @cssprop --uf-dialog-backdrop - Backdrop color.\n */\nexport class UfDrawer extends UfDialog {\n static override styles = [\n ...UfDialog.styles,\n css`\n dialog {\n --_size: min(var(--uf-drawer-size, 24rem), 100vw);\n --_radius: var(--uf-drawer-radius, var(--uf-radius-md));\n --_from: 100% 0;\n position: fixed;\n inset: 0 0 0 auto;\n width: var(--_size);\n max-width: 100vw;\n height: 100dvh;\n max-height: 100dvh;\n margin: 0;\n border-width: 0 0 0 1px;\n border-radius: var(--_radius) 0 0 var(--_radius);\n }\n\n :host([placement='start']) dialog {\n --_from: -100% 0;\n inset: 0 auto 0 0;\n border-width: 0 1px 0 0;\n border-radius: 0 var(--_radius) var(--_radius) 0;\n }\n\n /* Right-to-left pages: start is on the right, end on the left. */\n :host(:dir(rtl)) dialog {\n --_from: -100% 0;\n inset: 0 auto 0 0;\n border-width: 0 1px 0 0;\n border-radius: 0 var(--_radius) var(--_radius) 0;\n }\n\n :host(:dir(rtl)[placement='start']) dialog {\n --_from: 100% 0;\n inset: 0 0 0 auto;\n border-width: 0 0 0 1px;\n border-radius: var(--_radius) 0 0 var(--_radius);\n }\n\n :host([placement='top']) dialog,\n :host([placement='bottom']) dialog {\n --_size: min(var(--uf-drawer-size, 24rem), 100dvh);\n width: 100vw;\n height: var(--_size);\n }\n\n :host([placement='top']) dialog {\n --_from: 0 -100%;\n inset: 0 0 auto 0;\n border-width: 0 0 1px 0;\n border-radius: 0 0 var(--_radius) var(--_radius);\n }\n\n :host([placement='bottom']) dialog {\n --_from: 0 100%;\n inset: auto 0 0 0;\n border-width: 1px 0 0 0;\n border-radius: var(--_radius) var(--_radius) 0 0;\n }\n\n dialog[open] {\n animation-name: uf-drawer-in;\n }\n\n dialog.closing {\n animation-name: uf-drawer-out;\n }\n\n @keyframes uf-drawer-in {\n from {\n translate: var(--_from);\n }\n }\n\n @keyframes uf-drawer-out {\n to {\n translate: var(--_from);\n }\n }\n `,\n ];\n\n static override properties: PropertyDeclarations = {\n placement: { reflect: true },\n };\n\n /** The edge it slides in from: `start` (left, in left-to-right pages), `end`, `top` or `bottom`. */\n declare placement: DrawerPlacement;\n\n constructor() {\n super();\n this.placement = 'end';\n }\n}\n\ndefineElement('uf-drawer', UfDrawer);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-drawer': UfDrawer;\n }\n}\n",
|
|
657
706
|
"components/dropdown/dropdown.ts": "import { css } from 'lit';\nimport { defineElement } from '../../internal/define.js';\nimport { UfPopover } from '../popover/popover.js';\nimport '../menu/menu.js';\nimport type { MenuSelectDetail, UfMenu } from '../menu/menu.js';\n\nexport { UfMenu, UfMenuItem } from '../menu/menu.js';\nexport type { MenuSelectDetail } from '../menu/menu.js';\n\n/**\n * A button that opens a `<uf-menu>`, following the WAI-ARIA menu button\n * pattern: Enter, Space or Down open it on the first item, Up on the last;\n * choosing an item or pressing Escape closes it and returns focus to the button.\n *\n * @summary Opens a menu of actions from a button.\n * @tag uf-dropdown\n *\n * @slot trigger - The button that opens the menu.\n * @slot - A `<uf-menu>`.\n *\n * @event {CustomEvent<MenuSelectDetail>} uf-select - An item was chosen (bubbles up from the menu).\n * @event uf-show - The menu opened.\n * @event uf-hide - The menu closed.\n *\n * @csspart panel - The floating panel around the menu.\n */\nexport class UfDropdown extends UfPopover {\n static override styles = [\n UfPopover.styles,\n css`\n .panel {\n --uf-popover-padding: var(--uf-space-1) 0;\n }\n `,\n ];\n\n #focusLastOnOpen = false;\n\n constructor() {\n super();\n this.addEventListener('uf-select', this.#onSelect as EventListener);\n this.addEventListener('keydown', this.#onKeyDown);\n }\n\n protected override get popupKind(): 'menu' {\n return 'menu';\n }\n\n get #menu(): UfMenu | null {\n return this.querySelector('uf-menu');\n }\n\n protected override afterShow(): void {\n const menu = this.#menu;\n if (this.#focusLastOnOpen) menu?.focusLast();\n else menu?.focusFirst();\n this.#focusLastOnOpen = false;\n }\n\n protected override onTriggerKeyDown(event: KeyboardEvent): void {\n if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return;\n event.preventDefault();\n this.#focusLastOnOpen = event.key === 'ArrowUp';\n if (this.open) this.afterShow();\n else this.show();\n }\n\n #onSelect = (event: CustomEvent<MenuSelectDetail>): void => {\n // Checkbox items stay open so several can be toggled; cancel the event to keep any item open.\n if (event.defaultPrevented || event.detail.item.type === 'checkbox') return;\n this.hide();\n this.trigger?.focus();\n };\n\n #onKeyDown = (event: KeyboardEvent): void => {\n // Tab leaves the menu: close it and let focus move on.\n if (event.key === 'Tab' && this.open && this.focusInPanel) this.hide();\n };\n}\n\ndefineElement('uf-dropdown', UfDropdown);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-dropdown': UfDropdown;\n }\n}\n",
|
|
707
|
+
"components/file-upload/file-upload.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, renderField } from '../../internal/field.js';\nimport { FormControl } from '../../internal/form-control.js';\nimport { iconSvg, icons } from '../../internal/icons.js';\nimport { focusRing, hostStyles } from '../../internal/shared.styles.js';\nimport { HasSlotController, uniqueId } from '../../internal/slot.js';\n\n/** Whether a file matches an `accept` list: extensions (`.pdf`), MIME types (`image/png`) or wildcards (`image/*`). */\nfunction accepts(file: File, accept: string | undefined): boolean {\n const tokens = (accept ?? '')\n .split(',')\n .map((token) => token.trim().toLowerCase())\n .filter(Boolean);\n if (!tokens.length) return true;\n const name = file.name.toLowerCase();\n const type = file.type.toLowerCase();\n return tokens.some((token) =>\n token.startsWith('.') ? name.endsWith(token) : token.endsWith('/*') ? type.startsWith(token.slice(0, -1)) : type === token,\n );\n}\n\n/** A size in the language's format, in bytes, kB, MB or GB. */\nfunction formatSize(bytes: number, lang: string): string {\n const units = ['byte', 'kilobyte', 'megabyte', 'gigabyte'] as const;\n let value = bytes;\n let unit = 0;\n while (value >= 1000 && unit < units.length - 1) {\n value /= 1000;\n unit += 1;\n }\n try {\n return new Intl.NumberFormat(lang || undefined, { style: 'unit', unit: units[unit], unitDisplay: 'short', maximumFractionDigits: unit ? 1 : 0 }).format(value);\n } catch {\n return `${Math.round(value * 10) / 10} ${['B', 'kB', 'MB', 'GB'][unit]}`;\n }\n}\n\n/**\n * Picks files to send with a form: from a button, or by dragging them onto the\n * drop zone. The chosen files are listed with their size and a remove button.\n * Files that don't match `accept` or are larger than `max-size` are refused,\n * with a message saying why. It submits like a native `<input type=\"file\">`.\n *\n * @summary Lets users choose files to upload.\n * @tag uf-file-upload\n *\n * @slot label - The label, when you need markup. Overrides `label`.\n * @slot hint - Help text below the label. Overrides `hint`.\n *\n * @event input - Fired when files are added or removed.\n * @event change - Fired when files are added or removed.\n *\n * @csspart field - The wrapper around label, drop zone, files, hint and error.\n * @csspart form-label - The label.\n * @csspart dropzone - The area files can be dropped on.\n * @csspart button - The button that opens the file picker.\n * @csspart files - The list of chosen files.\n * @csspart file - A chosen file.\n * @csspart remove-button - A file's remove button.\n * @csspart rejected - Why files were refused.\n * @csspart hint - The hint text.\n * @csspart error - The validation message.\n *\n * @cssprop --uf-file-upload-border-color - Border color of the drop zone.\n * @cssprop --uf-file-upload-bg - Background of the drop zone.\n * @cssprop --uf-file-upload-radius - Corner radius of the drop zone. Defaults to the theme's control radius.\n * @cssprop --uf-file-upload-active-color - Border and background tint while files are dragged over.\n *\n * @cssstate user-invalid - Required but empty, after the user interacted.\n */\nexport class UfFileUpload extends FormControl {\n static override styles = [\n hostStyles,\n fieldStyles,\n css`\n .dropzone {\n --_active: var(--uf-file-upload-active-color, var(--uf-color-accent-strong));\n position: relative;\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: var(--uf-space-2);\n padding: var(--uf-space-5) var(--uf-space-4);\n border: 1px solid var(--uf-file-upload-border-color, var(--uf-color-border-strong));\n /* Like the fields: square by default, following the theme's control radius. */\n border-radius: var(--uf-file-upload-radius, var(--uf-radius-control));\n background: var(--uf-file-upload-bg, transparent);\n color: var(--uf-color-text-muted);\n font-size: var(--uf-font-size-sm);\n text-align: center;\n transition:\n border-color var(--uf-duration-fast) ease,\n background-color var(--uf-duration-fast) ease;\n }\n\n .dropzone > .icon {\n width: 1.75rem;\n height: 1.75rem;\n color: var(--uf-color-text-muted);\n }\n\n /* Files dragged over it: an accent border, thicker like a focused field. */\n .dropzone.dragging {\n border-color: var(--_active);\n box-shadow: inset 0 0 0 1px var(--_active);\n background: color-mix(in srgb, var(--_active) 8%, transparent);\n }\n\n /* A 2px error outline, as on the fields. */\n .invalid .dropzone {\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, like disabled fields. */\n .dropzone.disabled {\n border-color: var(--uf-color-border);\n background: var(--uf-color-neutral-fill);\n }\n\n .browse {\n min-height: var(--uf-size-control-sm);\n padding: 0 var(--uf-space-3);\n border: 1px solid var(--uf-color-border-strong);\n border-radius: var(--uf-radius-control);\n background: var(--uf-color-surface);\n color: var(--uf-color-text);\n font: inherit;\n font-weight: var(--uf-font-weight-medium);\n cursor: pointer;\n }\n\n .browse:hover:not(:disabled) {\n border-color: var(--uf-color-accent-strong);\n color: var(--uf-color-accent-strong);\n }\n\n .browse:focus-visible {\n ${focusRing}\n }\n\n .browse:disabled {\n color: var(--uf-color-text-muted);\n cursor: not-allowed;\n }\n\n .native {\n position: absolute;\n width: 1px;\n height: 1px;\n opacity: 0;\n pointer-events: none;\n }\n\n .files {\n display: grid;\n gap: var(--uf-space-1);\n margin: var(--uf-space-2) 0 0;\n padding: 0;\n list-style: none;\n }\n\n .file {\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-1) 0 var(--uf-space-3);\n border: 1px solid var(--uf-color-border);\n border-radius: var(--uf-radius-control);\n font-size: var(--uf-font-size-sm);\n color: var(--uf-color-text);\n }\n\n .file > .icon {\n flex: none;\n width: 1rem;\n height: 1rem;\n color: var(--uf-color-text-muted);\n }\n\n .name {\n flex: 1;\n min-width: 0;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n\n .size {\n flex: none;\n color: var(--uf-color-text-muted);\n font-variant-numeric: tabular-nums;\n }\n\n .remove {\n display: inline-flex;\n flex: none;\n align-items: center;\n justify-content: center;\n width: 1.75rem;\n height: 1.75rem;\n padding: 0;\n border: 0;\n border-radius: var(--uf-radius-sm);\n background: transparent;\n color: var(--uf-color-text-muted);\n cursor: pointer;\n }\n\n .remove:hover:not(:disabled) {\n background: var(--uf-color-surface-hover);\n color: var(--uf-color-text);\n }\n\n .remove:focus-visible {\n ${focusRing}\n }\n\n .remove .icon {\n width: 1rem;\n height: 1rem;\n }\n\n .rejected {\n margin: var(--uf-space-1) 0 0;\n color: var(--uf-color-danger-text);\n font-size: var(--uf-font-size-sm);\n }\n\n .rejected:empty {\n display: none;\n }\n\n [hidden] {\n display: none !important;\n }\n `,\n ];\n\n protected static override formStateProperties: ReadonlySet<PropertyKey> = new Set([...FormControl.formStateProperties, 'files']);\n\n static override properties: PropertyDeclarations = {\n files: { attribute: false },\n label: {},\n hint: {},\n accept: {},\n multiple: { type: Boolean, reflect: true },\n maxSize: { type: Number, attribute: 'max-size' },\n };\n\n /** The chosen files. Set it to `[]` to clear them. */\n declare files: File[];\n /** Visible label. */\n declare label: string | undefined;\n /** Help text, e.g. the accepted types and size. */\n declare hint: string | undefined;\n /** Accepted files, as in a native file input: extensions (`.pdf`), MIME types (`image/png`) or wildcards (`image/*`), comma-separated. */\n declare accept: string | undefined;\n /** Lets users choose more than one file. */\n declare multiple: boolean;\n /** Largest accepted file, in bytes, e.g. `5000000` for 5 MB. */\n declare maxSize: number | undefined;\n\n readonly #slots = new HasSlotController(this, 'label', 'hint');\n readonly #id = uniqueId('uf-file-upload');\n #dragging = false;\n #rejected: string[] = [];\n\n constructor() {\n super();\n this.files = [];\n this.multiple = false;\n }\n\n get #input(): HTMLInputElement | null {\n return this.renderRoot.querySelector('.native');\n }\n\n get #button(): HTMLButtonElement | null {\n return this.renderRoot.querySelector('.browse');\n }\n\n /** Opens the file picker. */\n showPicker(): void {\n if (!this.isDisabled) this.#input?.click();\n }\n\n override willUpdate(changed: PropertyValues<this>): void {\n if (changed.has('multiple') && !this.multiple && this.files.length > 1) this.files = this.files.slice(0, 1);\n }\n\n override updated(): void {\n this.syncFormState();\n }\n\n protected syncFormState(): void {\n if (!this.hasUpdated) return;\n if (this.files.length && this.name) {\n const data = new FormData();\n for (const file of this.files) data.append(this.name, file);\n this.internals.setFormValue(data);\n } else {\n this.internals.setFormValue(null);\n }\n const missing = this.required && !this.files.length;\n this.setValidity({ valueMissing: missing }, missing ? this.#missingMessage() : '', this.#button ?? undefined);\n }\n\n /** The browser's own \"Please select a file\" message, in the user's language. */\n #missingMessage(): string {\n const probe = document.createElement('input');\n probe.type = 'file';\n probe.required = true;\n return probe.validationMessage;\n }\n\n protected resetValue(): void {\n this.files = [];\n this.#rejected = [];\n }\n\n /** Adds files, refusing those that don't fit `accept` and `max-size`. */\n #add(list: FileList | File[]): void {\n const lang = this.translator.lang;\n const rejected: string[] = [];\n const added: File[] = [];\n for (const file of list) {\n if (!accepts(file, this.accept)) rejected.push(this.translator.t('fileTypeRejected', { name: file.name }));\n else if (this.maxSize && file.size > this.maxSize) rejected.push(this.translator.t('fileTooLarge', { name: file.name, size: formatSize(this.maxSize, lang) }));\n else added.push(file);\n }\n this.#rejected = rejected;\n if (added.length) {\n // A new pick replaces the file of a single upload; with `multiple`, files add up (same name and size: kept once).\n const kept = this.multiple ? this.files.filter((f) => !added.some((a) => a.name === f.name && a.size === f.size)) : [];\n this.files = this.multiple ? [...kept, ...added] : added.slice(0, 1);\n this.#changed();\n } else {\n this.requestUpdate();\n }\n }\n\n #remove(index: number): void {\n this.files = this.files.filter((_, i) => i !== index);\n this.#rejected = [];\n this.#changed();\n // Focus moves to the next file's remove button, or the picker button, so it isn't lost.\n void this.updateComplete.then(() => {\n const buttons = this.renderRoot.querySelectorAll<HTMLButtonElement>('.remove');\n (buttons[Math.min(index, buttons.length - 1)] ?? this.#button)?.focus();\n });\n }\n\n #changed(): void {\n this.markInteracted();\n this.dispatchEvent(new Event('input', { bubbles: true, composed: true }));\n this.emitChange();\n }\n\n #onPick = (event: Event): void => {\n event.stopPropagation();\n const input = event.target as HTMLInputElement;\n if (input.files?.length) this.#add(input.files);\n // Cleared, so choosing the same file again still fires `change`.\n input.value = '';\n };\n\n #onDragOver = (event: DragEvent): void => {\n if (this.isDisabled || !event.dataTransfer?.types.includes('Files')) return;\n event.preventDefault();\n event.dataTransfer.dropEffect = 'copy';\n if (!this.#dragging) {\n this.#dragging = true;\n this.requestUpdate();\n }\n };\n\n #onDragLeave = (event: DragEvent): void => {\n if ((event.currentTarget as Element).contains(event.relatedTarget as Node)) return;\n this.#dragging = false;\n this.requestUpdate();\n };\n\n #onDrop = (event: DragEvent): void => {\n event.preventDefault();\n this.#dragging = false;\n if (this.isDisabled || !event.dataTransfer?.files.length) {\n this.requestUpdate();\n return;\n }\n const files = [...event.dataTransfer.files];\n this.#add(this.multiple ? files : files.slice(0, 1));\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 disabled = this.isDisabled;\n const lang = this.translator.lang;\n const choose = this.translator.t(this.multiple ? 'chooseFiles' : 'chooseFile');\n\n return renderField({\n ...ids,\n controlId: `${this.#id}-input`,\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\n class=${classMap({ dropzone: true, dragging: this.#dragging, disabled })}\n part=\"dropzone\"\n @dragover=${this.#onDragOver}\n @dragleave=${this.#onDragLeave}\n @drop=${this.#onDrop}\n >\n ${iconSvg(icons.upload)}\n <button\n class=\"browse\"\n part=\"button\"\n type=\"button\"\n ?disabled=${disabled}\n aria-label=${this.label ? `${choose}: ${this.label}` : choose}\n aria-invalid=${error ? 'true' : 'false'}\n aria-describedby=${ifDefined(describedBy({ ...ids, hint: this.hint, hasHintSlot, error }))}\n @click=${() => this.showPicker()}\n >\n ${choose}\n </button>\n <span>${this.translator.t(this.multiple ? 'dropFiles' : 'dropFile')}</span>\n <input\n id=${`${this.#id}-input`}\n class=\"native\"\n type=\"file\"\n tabindex=\"-1\"\n aria-hidden=\"true\"\n accept=${ifDefined(this.accept)}\n ?multiple=${this.multiple}\n ?disabled=${disabled}\n @change=${this.#onPick}\n @input=${(event: Event) => event.stopPropagation()}\n />\n </div>\n <ul class=\"files\" part=\"files\" ?hidden=${!this.files.length}>\n ${this.files.map(\n (file, i) => html`<li class=\"file\" part=\"file\">\n ${iconSvg(icons.file)}\n <span class=\"name\" title=${file.name}>${file.name}</span>\n <span class=\"size\">${formatSize(file.size, lang)}</span>\n <button\n class=\"remove\"\n part=\"remove-button\"\n type=\"button\"\n ?disabled=${disabled}\n aria-label=${this.translator.t('removeFile', { name: file.name })}\n @click=${() => this.#remove(i)}\n >\n ${iconSvg(icons.x)}\n </button>\n </li>`,\n )}\n </ul>\n <div class=\"rejected\" part=\"rejected\" role=\"status\">${this.#rejected.length ? this.#rejected.join(' ') : nothing}</div>\n `,\n });\n }\n}\n\ndefineElement('uf-file-upload', UfFileUpload);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-file-upload': UfFileUpload;\n }\n}\n",
|
|
658
708
|
"components/icon/icon.ts": "import { LitElement, css, html, nothing, type PropertyDeclarations } from 'lit';\nimport { unsafeSVG } from 'lit/directives/unsafe-svg.js';\nimport { defineElement } from '../../internal/define.js';\nimport { iconSvg, icons, type BuiltInIconName } from '../../internal/icons.js';\n\nconst registry = new Map<string, string>();\nconst instances = new Set<UfIcon>();\n\n/**\n * Registers custom icons by name, as SVG markup. The markup is trusted and\n * inserted as-is, so only register icons from your own code, never user input.\n *\n * @example registerIcons({ heart: '<svg viewBox=\"0 0 24 24\">…</svg>' })\n */\nexport function registerIcons(svgs: Record<string, string>): void {\n for (const [name, markup] of Object.entries(svgs)) registry.set(name, markup);\n for (const icon of instances) icon.requestUpdate();\n}\n\n/**\n * An icon from the built-in set, or one added with `registerIcons()`.\n * Icons are decorative unless you give them a `label`.\n *\n * @summary Shows a small symbol.\n * @tag uf-icon\n *\n * @csspart svg - The `<svg>` element.\n *\n * @cssprop --uf-icon-size - Width and height. Defaults to `1em`, so it follows the font size.\n * @cssprop --uf-icon-stroke-width - Stroke width of built-in icons.\n */\nexport class UfIcon extends LitElement {\n static override styles = css`\n :host {\n display: inline-flex;\n width: var(--uf-icon-size, 1em);\n height: var(--uf-icon-size, 1em);\n flex: none;\n vertical-align: -0.125em;\n }\n\n svg {\n width: 100%;\n height: 100%;\n stroke-width: var(--uf-icon-stroke-width, 2);\n }\n `;\n\n static override properties: PropertyDeclarations = {\n name: { reflect: true },\n label: {},\n };\n\n /** Icon name: a built-in icon or one added with `registerIcons()`. */\n declare name: BuiltInIconName | (string & {});\n /** Accessible label. Without it the icon is hidden from assistive tech. */\n declare label: string | undefined;\n\n constructor() {\n super();\n this.name = '';\n }\n\n override connectedCallback(): void {\n super.connectedCallback();\n instances.add(this);\n }\n\n override disconnectedCallback(): void {\n super.disconnectedCallback();\n instances.delete(this);\n }\n\n override updated(): void {\n if (this.label) {\n this.setAttribute('role', 'img');\n this.setAttribute('aria-label', this.label);\n this.removeAttribute('aria-hidden');\n } else {\n this.removeAttribute('role');\n this.removeAttribute('aria-label');\n this.setAttribute('aria-hidden', 'true');\n }\n }\n\n override render() {\n const custom = registry.get(this.name);\n if (custom) return html`${unsafeSVG(custom)}`;\n const builtIn = icons[this.name as BuiltInIconName];\n return builtIn ? iconSvg(builtIn, 'svg') : nothing;\n }\n}\n\ndefineElement('uf-icon', UfIcon);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-icon': UfIcon;\n }\n}\n",
|
|
659
709
|
"components/input/input.ts": "import { html, 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 { hostStyles } from '../../internal/shared.styles.js';\nimport { HasSlotController, uniqueId } from '../../internal/slot.js';\n\nexport type { FieldSize };\n\nexport type InputType = 'text' | 'email' | 'password' | 'search' | 'tel' | 'url' | 'number' | 'date' | 'time';\n\n/**\n * A single-line text field with a built-in label, hint and validation message.\n *\n * @summary Lets users enter a single line of text.\n * @tag uf-input\n *\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 or text before the input.\n * @slot suffix - An icon or text after the input.\n *\n * @event input - Fired on every keystroke.\n * @event change - Fired when the value is committed (blur or Enter).\n *\n * @csspart field - The wrapper around label, control, hint and error.\n * @csspart form-label - The label.\n * @csspart box - The bordered box around the input.\n * @csspart input - The native `<input>`.\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 UfInput extends FormControl {\n static override styles = [hostStyles, fieldStyles, controlBoxStyles];\n\n protected static override formStateProperties: ReadonlySet<PropertyKey> = new Set([\n ...FormControl.formStateProperties,\n 'type',\n 'readonly',\n 'pattern',\n 'min',\n 'max',\n 'step',\n 'minlength',\n 'maxlength',\n ]);\n\n static override properties: PropertyDeclarations = {\n type: { reflect: true },\n value: { attribute: false },\n defaultValue: { attribute: 'value' },\n label: {},\n hint: {},\n placeholder: {},\n size: { reflect: true },\n readonly: { type: Boolean, reflect: true },\n autocomplete: {},\n inputmode: {},\n pattern: {},\n min: {},\n max: {},\n step: {},\n minlength: { type: Number },\n maxlength: { type: Number },\n };\n\n /** Input type. */\n declare type: InputType;\n /** Current value. */\n declare value: string;\n /** Initial value, restored on form reset. Set with the `value` attribute. */\n declare defaultValue: string;\n /** Visible label. */\n declare label: string | undefined;\n /** Help text below the field. */\n declare hint: string | undefined;\n /** Placeholder text. */\n declare placeholder: string | undefined;\n /** Size of the field. */\n declare size: FieldSize;\n /** Makes the field read-only. */\n declare readonly: boolean;\n /** Native `autocomplete` hint. */\n declare autocomplete: AutoFill | undefined;\n /** Native `inputmode` hint for virtual keyboards. */\n declare inputmode: string | undefined;\n /** Regex the value must match. */\n declare pattern: string | undefined;\n /** Minimum value, for number and date types. */\n declare min: string | undefined;\n /** Maximum value, for number and date types. */\n declare max: string | undefined;\n /** Step, for number and date types. */\n declare step: string | undefined;\n /** Minimum length. */\n declare minlength: number | undefined;\n /** Maximum length. */\n declare maxlength: number | undefined;\n\n readonly #slots = new HasSlotController(this, 'label', 'hint');\n readonly #id = uniqueId('uf-input');\n\n constructor() {\n super();\n this.type = 'text';\n this.value = '';\n this.defaultValue = '';\n this.size = 'md';\n this.readonly = false;\n }\n\n get #input(): HTMLInputElement | null {\n return this.renderRoot.querySelector('input');\n }\n\n /** Selects all text in the field. */\n select(): void {\n this.#input?.select();\n }\n\n override willUpdate(changed: PropertyValues<this>): void {\n // Like a native input: the value follows the `value` attribute until it is edited.\n if (changed.has('defaultValue') && this.value === (changed.get('defaultValue') ?? '')) {\n this.value = this.defaultValue ?? '';\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(this.value);\n this.setValidityFrom(input);\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 #onInput = (event: Event): void => {\n this.value = (event.target as HTMLInputElement).value;\n };\n\n #onChange = (): void => {\n this.markInteracted();\n this.emitChange();\n };\n\n override render() {\n const ids = {\n hintId: `${this.#id}-hint`,\n errorId: `${this.#id}-error`,\n };\n const error = this.showInvalid ? this.validationMessage : '';\n const hasHintSlot = this.#slots.has('hint');\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=${this.type}\n name=${ifDefined(this.name || undefined)}\n .value=${live(this.value)}\n placeholder=${ifDefined(this.placeholder)}\n autocomplete=${ifDefined(this.autocomplete)}\n inputmode=${ifDefined(this.inputmode)}\n pattern=${ifDefined(this.pattern)}\n min=${ifDefined(this.min)}\n max=${ifDefined(this.max)}\n step=${ifDefined(this.step)}\n minlength=${ifDefined(this.minlength)}\n maxlength=${ifDefined(this.maxlength)}\n ?required=${this.required}\n ?readonly=${this.readonly}\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 <slot name=\"suffix\"></slot>\n </div>\n `,\n });\n }\n}\n\ndefineElement('uf-input', UfInput);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-input': UfInput;\n }\n}\n",
|
|
660
710
|
"components/menu/menu.ts": "import { LitElement, css, html, type PropertyDeclarations } from 'lit';\nimport { defineElement } from '../../internal/define.js';\nimport './menu-item.js';\nimport type { UfMenuItem } from './menu-item.js';\n\nexport { UfMenuItem } from './menu-item.js';\n\nexport interface MenuSelectDetail {\n item: UfMenuItem;\n value: string;\n}\n\n/**\n * A list of actions with full keyboard support: arrow keys, Home and End,\n * and typing a letter jumps to the next item starting with it. Use `<hr>`\n * between items for a separator. Usually placed inside `<uf-dropdown>`.\n *\n * @summary A list of actions or options.\n * @tag uf-menu\n *\n * @slot - `<uf-menu-item>` elements and `<hr>` separators.\n *\n * @event {CustomEvent<MenuSelectDetail>} uf-select - An item was chosen. Cancel it to keep a dropdown open.\n */\nexport class UfMenu extends LitElement {\n static override styles = css`\n :host {\n display: block;\n min-width: 10rem;\n outline: none;\n }\n\n ::slotted(hr) {\n height: 1px;\n margin: var(--uf-space-1) 0;\n border: 0;\n background: var(--uf-color-border);\n }\n `;\n\n static override properties: PropertyDeclarations = {\n label: {},\n };\n\n /** Accessible name of the menu. */\n declare label: string | undefined;\n\n #typeahead = '';\n #typeaheadTimer = 0;\n\n constructor() {\n super();\n this.addEventListener('click', this.#onClick);\n this.addEventListener('keydown', this.#onKeyDown);\n }\n\n override connectedCallback(): void {\n super.connectedCallback();\n this.setAttribute('role', 'menu');\n }\n\n override updated(): void {\n if (this.label) this.setAttribute('aria-label', this.label);\n else this.removeAttribute('aria-label');\n this.#alignItems();\n }\n\n /** Reserves the check column on every item when any item is a checkbox. */\n #alignItems(): void {\n const items = [...this.querySelectorAll('uf-menu-item')].filter((i) => i.closest('uf-menu') === this);\n const hasCheckbox = items.some((i) => i.type === 'checkbox');\n for (const item of items) item.toggleAttribute('data-check-space', hasCheckbox);\n }\n\n /** Enabled items that belong to this menu (not to a nested one). */\n get items(): UfMenuItem[] {\n return [...this.querySelectorAll<UfMenuItem>('uf-menu-item')].filter(\n (item) => item.closest('uf-menu') === this && !item.disabled,\n );\n }\n\n /** Focuses the first enabled item. */\n focusFirst(): void {\n this.#focusItem(this.items[0]);\n }\n\n /** Focuses the last enabled item. */\n focusLast(): void {\n const items = this.items;\n this.#focusItem(items[items.length - 1]);\n }\n\n #focusItem(item: UfMenuItem | undefined): void {\n if (!item) return;\n for (const other of this.items) other.tabIndex = other === item ? 0 : -1;\n item.focus();\n }\n\n #activate(item: UfMenuItem): void {\n if (item.disabled) return;\n if (item.type === 'checkbox') item.checked = !item.checked;\n this.dispatchEvent(\n new CustomEvent<MenuSelectDetail>('uf-select', {\n bubbles: true,\n composed: true,\n cancelable: true,\n detail: { item, value: item.value },\n }),\n );\n }\n\n #onClick = (event: MouseEvent): void => {\n const item = (event.target as Element).closest('uf-menu-item');\n if (item && item.closest('uf-menu') === this) this.#activate(item);\n };\n\n #onKeyDown = (event: KeyboardEvent): void => {\n const items = this.items;\n const current = (event.target as Element).closest('uf-menu-item');\n const index = current ? items.indexOf(current) : -1;\n\n switch (event.key) {\n case 'ArrowDown':\n this.#focusItem(items[(index + 1) % items.length]);\n break;\n case 'ArrowUp':\n this.#focusItem(items[(index - 1 + items.length) % items.length]);\n break;\n case 'Home':\n this.#focusItem(items[0]);\n break;\n case 'End':\n this.#focusItem(items[items.length - 1]);\n break;\n case 'Enter':\n case ' ':\n if (current) this.#activate(current);\n break;\n default:\n if (event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) {\n this.#onTypeahead(event.key, items, index);\n break;\n }\n return;\n }\n event.preventDefault();\n };\n\n /** Jumps to the next item whose label starts with the typed characters. */\n #onTypeahead(key: string, items: UfMenuItem[], index: number): void {\n clearTimeout(this.#typeaheadTimer);\n this.#typeaheadTimer = window.setTimeout(() => (this.#typeahead = ''), 500);\n this.#typeahead += key.toLowerCase();\n // Repeating one letter cycles through the items that start with it.\n const search = /^(.)\\1*$/.test(this.#typeahead) ? this.#typeahead[0] : this.#typeahead;\n const ordered = [...items.slice(index + 1), ...items.slice(0, index + 1)];\n const match = ordered.find((item) => item.textContent?.trim().toLowerCase().startsWith(search));\n this.#focusItem(match);\n }\n\n override render() {\n return html`<slot @slotchange=${() => this.#alignItems()}></slot>`;\n }\n}\n\ndefineElement('uf-menu', UfMenu);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-menu': UfMenu;\n }\n}\n",
|
|
@@ -668,12 +718,12 @@
|
|
|
668
718
|
"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 } 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-fill-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, 0.375rem);\n --_thumb: var(--uf-slider-thumb-size, 1.125rem);\n --_fill-color: var(--uf-slider-fill-color, var(--uf-color-accent));\n --_track-color: var(--uf-slider-track-color, var(--uf-color-surface-hover));\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 };\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\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 // 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",
|
|
669
719
|
"components/spinner/spinner.ts": "import { LitElement, css, html, type PropertyDeclarations } from 'lit';\nimport { defineElement } from '../../internal/define.js';\nimport { Translator } from '../../internal/i18n.js';\nimport { hostStyles } from '../../internal/shared.styles.js';\n\nexport type SpinnerSize = 'sm' | 'md' | 'lg';\n\n/**\n * A spinning circle for work in progress whose length isn't known. Screen\n * readers announce it as \"Loading\" (translatable), or as its `label`.\n *\n * @summary Shows that something is loading.\n * @tag uf-spinner\n *\n * @csspart base - The spinner.\n *\n * @cssprop --uf-spinner-size - Diameter. Overrides `size`.\n * @cssprop --uf-spinner-track-color - Color of the circle.\n * @cssprop --uf-spinner-indicator-color - Color of the moving arc.\n */\nexport class UfSpinner extends LitElement {\n static override styles = [\n hostStyles,\n css`\n :host {\n display: inline-flex;\n vertical-align: middle;\n --_size: var(--uf-spinner-size, 1.5rem);\n }\n\n :host([size='sm']) {\n --_size: var(--uf-spinner-size, 1rem);\n }\n\n :host([size='lg']) {\n --_size: var(--uf-spinner-size, 2.5rem);\n }\n\n .base {\n width: var(--_size);\n height: var(--_size);\n border: max(2px, calc(var(--_size) / 10)) solid var(--uf-spinner-track-color, var(--uf-color-surface-hover));\n border-top-color: var(--uf-spinner-indicator-color, var(--uf-color-accent));\n border-radius: 50%;\n animation: uf-spin 0.7s linear infinite;\n }\n\n @keyframes uf-spin {\n to {\n rotate: 360deg;\n }\n }\n\n /* Still turning, so it still says \"working\", but slowly. */\n @media (prefers-reduced-motion: reduce) {\n .base {\n animation-duration: 2s;\n }\n }\n `,\n ];\n\n static override properties: PropertyDeclarations = {\n label: {},\n size: { reflect: true },\n };\n\n /** Accessible name. Defaults to \"Loading\", in the page's language. */\n declare label: string | undefined;\n /** Size: `sm`, `md` or `lg`. */\n declare size: SpinnerSize;\n\n readonly #translator = new Translator(this);\n\n constructor() {\n super();\n this.size = 'md';\n }\n\n override render() {\n return html`<div class=\"base\" part=\"base\" role=\"progressbar\" aria-label=${this.label || this.#translator.t('loading')}></div>`;\n }\n}\n\ndefineElement('uf-spinner', UfSpinner);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-spinner': UfSpinner;\n }\n}\n",
|
|
670
720
|
"components/switch/switch.ts": "import { css, html, type PropertyDeclarations } 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 { describedBy } from '../../internal/field.js';\nimport { hostStyles } from '../../internal/shared.styles.js';\nimport { HasSlotController, uniqueId } from '../../internal/slot.js';\nimport { ToggleControl } from '../../internal/toggle-control.js';\nimport { toggleStyles } from '../../internal/toggle.styles.js';\n\n/**\n * An on/off switch with its label as content. Use it for settings that apply\n * immediately; use a checkbox for choices submitted later with a form.\n *\n * @summary Turns a setting on or off.\n * @tag uf-switch\n *\n * @slot - The label.\n * @slot hint - Help text below the label. Overrides `hint`.\n *\n * @event input - Fired when the state changes.\n * @event change - Fired when the state changes.\n *\n * @csspart base - The `<label>` wrapping control and label.\n * @csspart control - The track.\n * @csspart thumb - The moving knob.\n * @csspart label - The label text.\n * @csspart hint - The hint text.\n * @csspart error - The validation message.\n *\n * @cssprop --uf-switch-width - Width of the track.\n * @cssprop --uf-switch-height - Height of the track.\n * @cssprop --uf-switch-checked-bg - Track color when on.\n * @cssprop --uf-switch-radius - Corner radius of track and thumb. Use `999px` for a pill.\n *\n * @cssstate checked - The switch is on.\n * @cssstate user-invalid - Required but off, after the user interacted.\n */\nexport class UfSwitch extends ToggleControl {\n static override styles = [\n hostStyles,\n toggleStyles,\n css`\n :host {\n --_control-width: var(--uf-switch-width, 2.25rem);\n --_control-height: var(--uf-switch-height, 1.25rem);\n --_thumb: calc(var(--_control-height) - 4px);\n }\n\n .native {\n width: var(--_control-width);\n height: var(--_control-height);\n border-radius: var(--uf-switch-radius, var(--uf-radius-control));\n background: var(--uf-color-border-strong);\n }\n\n .native:checked {\n background: var(--uf-switch-checked-bg, var(--uf-color-accent));\n }\n\n .disabled .native {\n background: var(--uf-color-neutral-fill);\n box-shadow: inset 0 0 0 1px var(--uf-color-border);\n }\n\n .disabled .native:checked {\n background: var(--uf-color-text-muted);\n box-shadow: none;\n }\n\n .disabled .thumb {\n background: var(--uf-color-border-strong);\n box-shadow: none;\n }\n\n .disabled .native:checked + .thumb {\n background: var(--uf-color-surface);\n }\n\n .invalid .native {\n box-shadow: 0 0 0 2px var(--uf-color-danger-text);\n }\n\n .thumb {\n position: absolute;\n top: 2px;\n left: 2px;\n width: var(--_thumb);\n height: var(--_thumb);\n border-radius: var(--uf-switch-radius, var(--uf-radius-control));\n background: var(--uf-palette-neutral-0);\n box-shadow: var(--uf-shadow-sm);\n pointer-events: none;\n transition: translate var(--uf-duration-base) ease;\n }\n\n .native:checked + .thumb {\n translate: calc(var(--_control-width) - var(--_thumb) - 4px) 0;\n }\n\n @media (prefers-reduced-motion: reduce) {\n .thumb {\n transition: none;\n }\n }\n `,\n ];\n\n static override properties: PropertyDeclarations = {\n hint: {},\n };\n\n /** Help text below the label. */\n declare hint: string | undefined;\n\n readonly #slots = new HasSlotController(this, 'hint');\n readonly #id = uniqueId('uf-switch');\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 disabled = this.isDisabled;\n\n return html`\n <label class=${classMap({ root: true, disabled, invalid: Boolean(error) })} part=\"base\">\n <span class=\"control\" part=\"control\">\n <input\n class=\"native\"\n type=\"checkbox\"\n role=\"switch\"\n name=${ifDefined(this.name || undefined)}\n .value=${this.value}\n .checked=${live(this.checked)}\n ?required=${this.required}\n ?disabled=${disabled}\n aria-invalid=${error ? 'true' : 'false'}\n aria-describedby=${ifDefined(describedBy({ ...ids, hint: this.hint, hasHintSlot, error }))}\n @change=${this.onNativeChange}\n />\n <span class=\"thumb\" part=\"thumb\"></span>\n </span>\n <span class=\"label\" part=\"label\"><slot></slot></span>\n </label>\n <div id=${ids.hintId} class=\"hint\" part=\"hint\" ?hidden=${!this.hint && !hasHintSlot}>\n <slot name=\"hint\">${this.hint}</slot>\n </div>\n <div id=${ids.errorId} class=\"error\" part=\"error\" ?hidden=${!error}>${error}</div>\n `;\n }\n}\n\ndefineElement('uf-switch', UfSwitch);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-switch': UfSwitch;\n }\n}\n",
|
|
671
|
-
"components/table/table.ts": "import { LitElement, css, html, nothing, type PropertyDeclarations, type PropertyValues } from 'lit';\nimport { classMap } from 'lit/directives/class-map.js';\nimport { repeat } from 'lit/directives/repeat.js';\nimport { styleMap } from 'lit/directives/style-map.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/** A row of data: column keys to values. */\nexport type TableRow = Record<string, unknown>;\nexport type SortDirection = 'ascending' | 'descending';\nexport type TableDensity = 'comfortable' | 'compact';\n\nexport interface TableColumn<Row extends TableRow = TableRow> {\n /** The row property this column shows, and its id for sorting. */\n key: string;\n /** Header text. */\n label: string;\n /** Lets the user sort by this column. */\n sortable?: boolean;\n /** Text alignment. Use `end` for numbers. Defaults to `start`. */\n align?: 'start' | 'center' | 'end';\n /** Column width, as CSS: `8rem`, `20%`. */\n width?: string;\n /** Cell content from the value: text, or a DOM node such as a badge. Defaults to the value as text. */\n format?: (value: unknown, row: Row) => string | number | Node | null | undefined;\n /** Sort order for two rows, like `Array.prototype.sort`. Defaults to comparing the values. */\n compare?: (a: Row, b: Row) => number;\n}\n\nexport interface TableSortDetail {\n /** Key of the sorted column. */\n key: string;\n direction: SortDirection;\n}\n\nconst collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });\n\n/** Numbers and dates by value, everything else as text; empty values last. */\nfunction compareValues(a: unknown, b: unknown): number {\n const empty = (v: unknown) => v === null || v === undefined || v === '';\n if (empty(a) || empty(b)) return Number(empty(a)) - Number(empty(b));\n if (typeof a === 'number' && typeof b === 'number') return a - b;\n if (a instanceof Date && b instanceof Date) return a.getTime() - b.getTime();\n return collator.compare(String(a), String(b));\n}\n\n/**\n * A table of data, from `columns` and `rows`. Users can sort by the columns\n * marked `sortable`. Rendered as a native `<table>`, so assistive tech reads\n * headers and cells as usual.\n *\n * Set `columns` and `rows` as properties, or as JSON attributes in plain HTML.\n * The table sorts `rows` itself; with `manual-sort` it only shows the order\n * and tells you, so you can sort on the server. Combine it with\n * `<uf-pagination>` for long lists.\n *\n * @summary Shows data in rows and columns, with sorting.\n * @tag uf-table\n *\n * @slot empty - Shown when there are no rows. Defaults to \"No data\", or its translation.\n *\n * @event {CustomEvent<TableSortDetail>} uf-sort - The user sorted by a column.\n *\n * @csspart base - The scroll container around the table.\n * @csspart table - The `<table>`.\n * @csspart header-cell - Every header cell (`<th>`).\n * @csspart sort-button - The button in a sortable header.\n * @csspart row - Every body row.\n * @csspart cell - Every body cell.\n * @csspart empty - The cell shown when there are no rows.\n *\n * @cssprop --uf-table-max-height - Height after which the body scrolls under a sticky header.\n * @cssprop --uf-table-border-color - Border color between rows.\n * @cssprop --uf-table-header-bg - Background of the header row.\n * @cssprop --uf-table-stripe-bg - Background of every other row, with `striped`.\n * @cssprop --uf-table-hover-bg - Background of the row under the pointer.\n */\nexport class UfTable extends LitElement {\n static override styles = [\n hostStyles,\n css`\n :host {\n display: block;\n --_pad-y: var(--uf-space-3);\n --_pad-x: var(--uf-space-4);\n --_border: var(--uf-table-border-color, var(--uf-color-border));\n }\n\n :host([density='compact']) {\n --_pad-y: var(--uf-space-1);\n --_pad-x: var(--uf-space-3);\n }\n\n .base {\n max-height: var(--uf-table-max-height, none);\n overflow: auto;\n border: 1px solid var(--_border);\n border-radius: var(--uf-radius-md);\n }\n\n .base:focus-visible {\n ${focusRing}\n }\n\n table {\n width: 100%;\n border-collapse: separate;\n border-spacing: 0;\n color: var(--uf-color-text);\n font-family: var(--uf-font-family-sans);\n font-size: var(--uf-font-size-sm);\n font-variant-numeric: tabular-nums;\n }\n\n th,\n td {\n padding: var(--_pad-y) var(--_pad-x);\n border-bottom: 1px solid var(--_border);\n text-align: start;\n vertical-align: middle;\n }\n\n tbody tr:last-child td {\n border-bottom: 0;\n }\n\n th {\n position: sticky;\n top: 0;\n z-index: 1;\n background: var(--uf-table-header-bg, var(--uf-color-surface-raised));\n color: var(--uf-color-text-muted);\n font-weight: var(--uf-font-weight-semibold);\n white-space: nowrap;\n }\n\n .align-center {\n text-align: center;\n }\n .align-end {\n text-align: end;\n }\n\n .sort {\n display: inline-flex;\n align-items: center;\n gap: var(--uf-space-1);\n margin: calc(var(--uf-space-1) * -1) calc(var(--uf-space-2) * -1);\n padding: var(--uf-space-1) var(--uf-space-2);\n border: 0;\n border-radius: var(--uf-radius-sm);\n background: none;\n color: inherit;\n font: inherit;\n cursor: pointer;\n }\n\n .sort:hover {\n color: var(--uf-color-text);\n }\n\n .sort:focus-visible {\n ${focusRing}\n }\n\n .sort svg {\n width: 1em;\n height: 1em;\n opacity: 0;\n }\n\n /* A hint on hover and focus, solid when sorted. */\n .sort:hover svg,\n .sort:focus-visible svg {\n opacity: 0.5;\n }\n [aria-sort] .sort {\n color: var(--uf-color-text);\n }\n [aria-sort] .sort svg {\n opacity: 1;\n }\n\n :host([striped]) tbody tr:nth-child(even) td {\n background: var(--uf-table-stripe-bg, var(--uf-color-surface-hover));\n }\n\n tbody tr:hover td {\n background: var(--uf-table-hover-bg, var(--uf-color-accent-tint));\n }\n\n .empty {\n padding: var(--uf-space-6) var(--_pad-x);\n color: var(--uf-color-text-muted);\n text-align: center;\n }\n\n tbody tr.empty-row:hover td {\n background: none;\n }\n `,\n ];\n\n static override properties: PropertyDeclarations = {\n columns: { type: Array },\n rows: { type: Array },\n label: {},\n sortKey: { attribute: 'sort-key', reflect: true },\n sortDirection: { attribute: 'sort-direction', reflect: true },\n manualSort: { type: Boolean, attribute: 'manual-sort' },\n rowKey: { attribute: 'row-key' },\n striped: { type: Boolean, reflect: true },\n density: { reflect: true },\n };\n\n /** The columns, in order. As an attribute, JSON: `[{\"key\": \"name\", \"label\": \"Name\"}]`. */\n declare columns: TableColumn[];\n /** The data, one object per row. As an attribute, JSON: `[{\"name\": \"John\"}]`. */\n declare rows: TableRow[];\n /** Accessible name of the table, e.g. \"Invoices\". */\n declare label: string | undefined;\n /** Key of the column the rows are sorted by. */\n declare sortKey: string | undefined;\n /** Sort order: `ascending` or `descending`. */\n declare sortDirection: SortDirection;\n /** Doesn't sort the rows: only shows the sort and fires `uf-sort`, for sorting on the server. */\n declare manualSort: boolean;\n /** Row property that identifies each row, so rows keep their DOM when the data changes. Defaults to the index. */\n declare rowKey: string | undefined;\n /** Shades every other row. */\n declare striped: boolean;\n /** Row spacing: `comfortable` or `compact`. */\n declare density: TableDensity;\n\n /** The table overflows its container, so it scrolls. */\n #scrollable = false;\n\n readonly #translator = new Translator(this);\n readonly #resizeObserver = new ResizeObserver(() => this.#checkScrollable());\n\n constructor() {\n super();\n this.columns = [];\n this.rows = [];\n this.sortDirection = 'ascending';\n this.manualSort = false;\n this.striped = false;\n this.density = 'comfortable';\n }\n\n override disconnectedCallback(): void {\n super.disconnectedCallback();\n this.#resizeObserver.disconnect();\n }\n\n override firstUpdated(): void {\n const base = this.renderRoot.querySelector('.base')!;\n this.#resizeObserver.observe(base);\n this.#resizeObserver.observe(this.renderRoot.querySelector('table')!);\n }\n\n override updated(changed: PropertyValues<this>): void {\n if (changed.has('rows') || changed.has('columns')) this.#checkScrollable();\n }\n\n /** A scrolling table must be reachable by keyboard, to scroll it. */\n #checkScrollable(): void {\n const base = this.renderRoot.querySelector('.base');\n if (!base) return;\n const scrollable = base.scrollWidth > base.clientWidth || base.scrollHeight > base.clientHeight;\n if (scrollable === this.#scrollable) return;\n this.#scrollable = scrollable;\n this.requestUpdate();\n }\n\n /** The rows in display order. */\n get #sortedRows(): TableRow[] {\n const rows = Array.isArray(this.rows) ? this.rows : [];\n const column = this.columns.find((c) => c.key === this.sortKey);\n if (!column || this.manualSort) return rows;\n const compare = column.compare ?? ((a: TableRow, b: TableRow) => compareValues(a[column.key], b[column.key]));\n const sign = this.sortDirection === 'descending' ? -1 : 1;\n // Stable: equal rows keep their order.\n return [...rows].sort((a, b) => sign * compare(a, b));\n }\n\n #sortBy(column: TableColumn): void {\n const direction: SortDirection = this.sortKey === column.key && this.sortDirection === 'ascending' ? 'descending' : 'ascending';\n this.sortKey = column.key;\n this.sortDirection = direction;\n this.dispatchEvent(\n new CustomEvent<TableSortDetail>('uf-sort', { bubbles: true, composed: true, detail: { key: column.key, direction } }),\n );\n }\n\n #renderHeader(column: TableColumn) {\n const sorted = column.key === this.sortKey;\n const align = { [`align-${column.align ?? 'start'}`]: true };\n return html`<th\n scope=\"col\"\n part=\"header-cell\"\n class=${classMap(align)}\n style=${styleMap({ width: column.width })}\n aria-sort=${sorted && column.sortable ? this.sortDirection : nothing}\n >\n ${column.sortable\n ? html`<button class=\"sort\" part=\"sort-button\" type=\"button\" @click=${() => this.#sortBy(column)}>\n ${column.label}${iconSvg(sorted && this.sortDirection === 'descending' ? icons['chevron-down'] : icons['chevron-up'])}\n </button>`\n : column.label}\n </th>`;\n }\n\n #renderCell(column: TableColumn, row: TableRow) {\n const value = row[column.key];\n const content = column.format ? column.format(value, row) : value;\n return html`<td part=\"cell\" class=${classMap({ [`align-${column.align ?? 'start'}`]: true })}>\n ${content === null || content === undefined ? '' : content instanceof Node ? content : String(content)}\n </td>`;\n }\n\n override render() {\n const columns = Array.isArray(this.columns) ? this.columns : [];\n const rows = this.#sortedRows;\n return html`<div\n class=\"base\"\n part=\"base\"\n tabindex=${this.#scrollable ? '0' : nothing}\n role=${this.#scrollable ? 'region' : nothing}\n aria-label=${this.#scrollable && this.label ? this.label : nothing}\n >\n <table part=\"table\" aria-label=${this.label ?? nothing}>\n <thead>\n <tr>\n ${columns.map((column) => this.#renderHeader(column))}\n </tr>\n </thead>\n <tbody>\n ${rows.length\n ? repeat(\n rows,\n (row, index) => (this.rowKey ? row[this.rowKey] : index),\n (row) => html`<tr part=\"row\">${columns.map((column) => this.#renderCell(column, row))}</tr>`,\n )\n : html`<tr class=\"empty-row\">\n <td class=\"empty\" part=\"empty\" colspan=${Math.max(1, columns.length)}><slot name=\"empty\">${this.#translator.t('noData')}</slot></td>\n </tr>`}\n </tbody>\n </table>\n </div>`;\n }\n}\n\ndefineElement('uf-table', UfTable);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-table': UfTable;\n }\n}\n",
|
|
721
|
+
"components/table/table.ts": "import { LitElement, css, html, nothing, type PropertyDeclarations, type PropertyValues } from 'lit';\nimport { classMap } from 'lit/directives/class-map.js';\nimport { repeat } from 'lit/directives/repeat.js';\nimport { styleMap } from 'lit/directives/style-map.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/** A row of data: column keys to values. */\nexport type TableRow = Record<string, unknown>;\nexport type SortDirection = 'ascending' | 'descending';\nexport type TableDensity = 'comfortable' | 'compact';\n\nexport interface TableColumn<Row extends TableRow = TableRow> {\n /** The row property this column shows, and its id for sorting. */\n key: string;\n /** Header text. */\n label: string;\n /** Lets the user sort by this column. */\n sortable?: boolean;\n /** Text alignment. Use `end` for numbers. Defaults to `start`. */\n align?: 'start' | 'center' | 'end';\n /** Column width, as CSS: `8rem`, `20%`. */\n width?: string;\n /** Cell content from the value: text, or a DOM node such as a badge. Defaults to the value as text. */\n format?: (value: unknown, row: Row) => string | number | Node | null | undefined;\n /** Sort order for two rows, like `Array.prototype.sort`. Defaults to comparing the values. */\n compare?: (a: Row, b: Row) => number;\n}\n\nexport interface TableSortDetail {\n /** Key of the sorted column. */\n key: string;\n direction: SortDirection;\n}\n\nconst collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });\n\n/** Numbers and dates by value, everything else as text; empty values last. */\nfunction compareValues(a: unknown, b: unknown): number {\n const empty = (v: unknown) => v === null || v === undefined || v === '';\n if (empty(a) || empty(b)) return Number(empty(a)) - Number(empty(b));\n if (typeof a === 'number' && typeof b === 'number') return a - b;\n if (a instanceof Date && b instanceof Date) return a.getTime() - b.getTime();\n return collator.compare(String(a), String(b));\n}\n\n/**\n * A table of data, from `columns` and `rows`. Users can sort by the columns\n * marked `sortable`. Rendered as a native `<table>`, so assistive tech reads\n * headers and cells as usual.\n *\n * Set `columns` and `rows` as properties, or as JSON attributes in plain HTML.\n * The table sorts `rows` itself; with `manual-sort` it only shows the order\n * and tells you, so you can sort on the server. Combine it with\n * `<uf-pagination>` for long lists.\n *\n * @summary Shows data in rows and columns, with sorting.\n * @tag uf-table\n *\n * @slot empty - Shown when there are no rows. Defaults to \"No data\", or its translation.\n *\n * @event {CustomEvent<TableSortDetail>} uf-sort - The user sorted by a column.\n *\n * @csspart base - The scroll container around the table.\n * @csspart table - The `<table>`.\n * @csspart header-cell - Every header cell (`<th>`).\n * @csspart sort-button - The button in a sortable header.\n * @csspart row - Every body row.\n * @csspart cell - Every body cell.\n * @csspart empty - The cell shown when there are no rows.\n *\n * @cssprop --uf-table-max-height - Height after which the body scrolls under a sticky header.\n * @cssprop --uf-table-border-color - Border color between rows.\n * @cssprop --uf-table-header-bg - Background of the header row.\n * @cssprop --uf-table-stripe-bg - Background of every other row, with `striped`.\n * @cssprop --uf-table-hover-bg - Background of the row under the pointer.\n */\nexport class UfTable extends LitElement {\n static override styles = [\n hostStyles,\n css`\n :host {\n display: block;\n /* In flex and grid layouts, shrink to the space there is and scroll, instead of overflowing the page. */\n min-width: 0;\n --_pad-y: var(--uf-space-3);\n --_pad-x: var(--uf-space-4);\n --_border: var(--uf-table-border-color, var(--uf-color-border));\n }\n\n :host([density='compact']) {\n --_pad-y: var(--uf-space-1);\n --_pad-x: var(--uf-space-3);\n }\n\n .base {\n max-height: var(--uf-table-max-height, none);\n overflow: auto;\n border: 1px solid var(--_border);\n border-radius: var(--uf-radius-md);\n }\n\n .base:focus-visible {\n ${focusRing}\n }\n\n table {\n width: 100%;\n border-collapse: separate;\n border-spacing: 0;\n color: var(--uf-color-text);\n font-family: var(--uf-font-family-sans);\n font-size: var(--uf-font-size-sm);\n font-variant-numeric: tabular-nums;\n }\n\n th,\n td {\n padding: var(--_pad-y) var(--_pad-x);\n border-bottom: 1px solid var(--_border);\n text-align: start;\n vertical-align: middle;\n }\n\n tbody tr:last-child td {\n border-bottom: 0;\n }\n\n /* Code in cells from \\`format\\`, e.g. an API reference: like inline code in text. */\n td code {\n padding: 0.1em 0.35em;\n border-radius: var(--uf-radius-sm);\n background: var(--uf-color-surface-hover);\n font-family: var(--uf-font-family-mono);\n font-size: 0.875em;\n }\n\n th {\n position: sticky;\n top: 0;\n z-index: 1;\n background: var(--uf-table-header-bg, var(--uf-color-surface-raised));\n color: var(--uf-color-text-muted);\n font-weight: var(--uf-font-weight-semibold);\n white-space: nowrap;\n }\n\n .align-center {\n text-align: center;\n }\n .align-end {\n text-align: end;\n }\n\n .sort {\n display: inline-flex;\n align-items: center;\n gap: var(--uf-space-1);\n margin: calc(var(--uf-space-1) * -1) calc(var(--uf-space-2) * -1);\n padding: var(--uf-space-1) var(--uf-space-2);\n border: 0;\n border-radius: var(--uf-radius-sm);\n background: none;\n color: inherit;\n font: inherit;\n cursor: pointer;\n }\n\n .sort:hover {\n color: var(--uf-color-text);\n }\n\n .sort:focus-visible {\n ${focusRing}\n }\n\n .sort svg {\n width: 1em;\n height: 1em;\n opacity: 0;\n }\n\n /* A hint on hover and focus, solid when sorted. */\n .sort:hover svg,\n .sort:focus-visible svg {\n opacity: 0.5;\n }\n [aria-sort] .sort {\n color: var(--uf-color-text);\n }\n [aria-sort] .sort svg {\n opacity: 1;\n }\n\n :host([striped]) tbody tr:nth-child(even) td {\n background: var(--uf-table-stripe-bg, var(--uf-color-surface-hover));\n }\n\n tbody tr:hover td {\n background: var(--uf-table-hover-bg, var(--uf-color-accent-tint));\n }\n\n .empty {\n padding: var(--uf-space-6) var(--_pad-x);\n color: var(--uf-color-text-muted);\n text-align: center;\n }\n\n tbody tr.empty-row:hover td {\n background: none;\n }\n `,\n ];\n\n static override properties: PropertyDeclarations = {\n columns: { type: Array },\n rows: { type: Array },\n label: {},\n sortKey: { attribute: 'sort-key', reflect: true },\n sortDirection: { attribute: 'sort-direction', reflect: true },\n manualSort: { type: Boolean, attribute: 'manual-sort' },\n rowKey: { attribute: 'row-key' },\n striped: { type: Boolean, reflect: true },\n density: { reflect: true },\n };\n\n /** The columns, in order. As an attribute, JSON: `[{\"key\": \"name\", \"label\": \"Name\"}]`. */\n declare columns: TableColumn[];\n /** The data, one object per row. As an attribute, JSON: `[{\"name\": \"John\"}]`. */\n declare rows: TableRow[];\n /** Accessible name of the table, e.g. \"Invoices\". */\n declare label: string | undefined;\n /** Key of the column the rows are sorted by. */\n declare sortKey: string | undefined;\n /** Sort order: `ascending` or `descending`. */\n declare sortDirection: SortDirection;\n /** Doesn't sort the rows: only shows the sort and fires `uf-sort`, for sorting on the server. */\n declare manualSort: boolean;\n /** Row property that identifies each row, so rows keep their DOM when the data changes. Defaults to the index. */\n declare rowKey: string | undefined;\n /** Shades every other row. */\n declare striped: boolean;\n /** Row spacing: `comfortable` or `compact`. */\n declare density: TableDensity;\n\n /** The table overflows its container, so it scrolls. */\n #scrollable = false;\n\n readonly #translator = new Translator(this);\n readonly #resizeObserver = new ResizeObserver(() => this.#checkScrollable());\n\n constructor() {\n super();\n this.columns = [];\n this.rows = [];\n this.sortDirection = 'ascending';\n this.manualSort = false;\n this.striped = false;\n this.density = 'comfortable';\n }\n\n override disconnectedCallback(): void {\n super.disconnectedCallback();\n this.#resizeObserver.disconnect();\n }\n\n override firstUpdated(): void {\n const base = this.renderRoot.querySelector('.base')!;\n this.#resizeObserver.observe(base);\n this.#resizeObserver.observe(this.renderRoot.querySelector('table')!);\n }\n\n override updated(changed: PropertyValues<this>): void {\n if (changed.has('rows') || changed.has('columns')) this.#checkScrollable();\n }\n\n /** A scrolling table must be reachable by keyboard, to scroll it. */\n #checkScrollable(): void {\n const base = this.renderRoot.querySelector('.base');\n if (!base) return;\n const scrollable = base.scrollWidth > base.clientWidth || base.scrollHeight > base.clientHeight;\n if (scrollable === this.#scrollable) return;\n this.#scrollable = scrollable;\n this.requestUpdate();\n }\n\n /** The rows in display order. */\n get #sortedRows(): TableRow[] {\n const rows = Array.isArray(this.rows) ? this.rows : [];\n const column = this.columns.find((c) => c.key === this.sortKey);\n if (!column || this.manualSort) return rows;\n const compare = column.compare ?? ((a: TableRow, b: TableRow) => compareValues(a[column.key], b[column.key]));\n const sign = this.sortDirection === 'descending' ? -1 : 1;\n // Stable: equal rows keep their order.\n return [...rows].sort((a, b) => sign * compare(a, b));\n }\n\n #sortBy(column: TableColumn): void {\n const direction: SortDirection = this.sortKey === column.key && this.sortDirection === 'ascending' ? 'descending' : 'ascending';\n this.sortKey = column.key;\n this.sortDirection = direction;\n this.dispatchEvent(\n new CustomEvent<TableSortDetail>('uf-sort', { bubbles: true, composed: true, detail: { key: column.key, direction } }),\n );\n }\n\n #renderHeader(column: TableColumn) {\n const sorted = column.key === this.sortKey;\n const align = { [`align-${column.align ?? 'start'}`]: true };\n return html`<th\n scope=\"col\"\n part=\"header-cell\"\n class=${classMap(align)}\n style=${styleMap({ width: column.width })}\n aria-sort=${sorted && column.sortable ? this.sortDirection : nothing}\n >\n ${column.sortable\n ? html`<button class=\"sort\" part=\"sort-button\" type=\"button\" @click=${() => this.#sortBy(column)}>\n ${column.label}${iconSvg(sorted && this.sortDirection === 'descending' ? icons['chevron-down'] : icons['chevron-up'])}\n </button>`\n : column.label}\n </th>`;\n }\n\n #renderCell(column: TableColumn, row: TableRow) {\n const value = row[column.key];\n const content = column.format ? column.format(value, row) : value;\n return html`<td part=\"cell\" class=${classMap({ [`align-${column.align ?? 'start'}`]: true })}>\n ${content === null || content === undefined ? '' : content instanceof Node ? content : String(content)}\n </td>`;\n }\n\n override render() {\n const columns = Array.isArray(this.columns) ? this.columns : [];\n const rows = this.#sortedRows;\n return html`<div\n class=\"base\"\n part=\"base\"\n tabindex=${this.#scrollable ? '0' : nothing}\n role=${this.#scrollable ? 'region' : nothing}\n aria-label=${this.#scrollable && this.label ? this.label : nothing}\n >\n <table part=\"table\" aria-label=${this.label ?? nothing}>\n <thead>\n <tr>\n ${columns.map((column) => this.#renderHeader(column))}\n </tr>\n </thead>\n <tbody>\n ${rows.length\n ? repeat(\n rows,\n (row, index) => (this.rowKey ? row[this.rowKey] : index),\n (row) => html`<tr part=\"row\">${columns.map((column) => this.#renderCell(column, row))}</tr>`,\n )\n : html`<tr class=\"empty-row\">\n <td class=\"empty\" part=\"empty\" colspan=${Math.max(1, columns.length)}><slot name=\"empty\">${this.#translator.t('noData')}</slot></td>\n </tr>`}\n </tbody>\n </table>\n </div>`;\n }\n}\n\ndefineElement('uf-table', UfTable);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-table': UfTable;\n }\n}\n",
|
|
672
722
|
"components/tabs/tabs.ts": "import { LitElement, css, html, type PropertyDeclarations } from 'lit';\nimport { ifDefined } from 'lit/directives/if-defined.js';\nimport { defineElement } from '../../internal/define.js';\nimport { uniqueId } from '../../internal/slot.js';\nimport './tab.js';\nimport type { UfTab, UfTabPanel } from './tab.js';\n\nexport { UfTab, UfTabPanel } from './tab.js';\n\nexport interface TabChangeDetail {\n name: string;\n}\n\n/**\n * Tabs that switch between panels. Arrow keys move between tabs, Home and End\n * jump to the ends, and only the selected tab is in the tab order.\n *\n * @summary Organizes content into panels, one visible at a time.\n * @tag uf-tabs\n *\n * @slot - `<uf-tab>` and `<uf-tab-panel>` elements. Tabs are moved into the tab list automatically.\n * @slot nav - The tab list. You don't need to set this yourself.\n *\n * @event {CustomEvent<TabChangeDetail>} uf-tab-change - The selected tab changed.\n *\n * @csspart tablist - The element with `role=\"tablist\"`.\n * @csspart panels - The wrapper around the panels.\n *\n * @cssprop --uf-tabs-indicator-color - Color of the selected tab's underline.\n */\nexport class UfTabs extends LitElement {\n static override styles = css`\n :host {\n display: block;\n }\n\n .tablist {\n display: flex;\n gap: var(--uf-space-1);\n border-bottom: 1px solid var(--uf-color-border);\n overflow-x: auto;\n scrollbar-width: none;\n }\n\n :host([orientation='vertical']) {\n display: flex;\n gap: var(--uf-space-4);\n }\n\n :host([orientation='vertical']) .tablist {\n flex-direction: column;\n border-bottom: 0;\n border-inline-end: 1px solid var(--uf-color-border);\n overflow: visible;\n }\n\n .panels {\n flex: 1;\n min-width: 0;\n }\n `;\n\n static override properties: PropertyDeclarations = {\n active: { reflect: true },\n activation: { reflect: true },\n orientation: { reflect: true },\n label: {},\n };\n\n /** Name of the selected panel. Defaults to the first enabled tab. */\n declare active: string;\n /** `auto` selects a tab as soon as it gets focus; `manual` waits for Enter or Space. */\n declare activation: 'auto' | 'manual';\n /** Lays the tab list out horizontally or vertically. */\n declare orientation: 'horizontal' | 'vertical';\n /** Accessible name for the tab list. */\n declare label: string | undefined;\n\n readonly #id = uniqueId('uf-tabs');\n\n constructor() {\n super();\n this.active = '';\n this.activation = 'auto';\n this.orientation = 'horizontal';\n this.addEventListener('click', this.#onClick);\n this.addEventListener('keydown', this.#onKeyDown);\n }\n\n get #tabs(): UfTab[] {\n return [...this.querySelectorAll<UfTab>(':scope > uf-tab')];\n }\n\n get #panels(): UfTabPanel[] {\n return [...this.querySelectorAll<UfTabPanel>(':scope > uf-tab-panel')];\n }\n\n /** Selects the tab for the given panel name. */\n select(name: string): void {\n const tab = this.#tabs.find((t) => t.panel === name);\n if (tab && !tab.disabled) this.#activate(tab);\n }\n\n // Picks the active tab before rendering: setting it after (in updated) would\n // render twice, which Lit warns about in development.\n override willUpdate(): void {\n this.#activeTab();\n }\n\n override updated(): void {\n this.#sync();\n }\n\n /** The tab to show: the one for `active`, or the first enabled one. Keeps `active` in step. */\n #activeTab() {\n const enabled = this.#tabs.filter((t) => !t.disabled);\n const activeTab = enabled.find((t) => t.panel === this.active) ?? enabled[0];\n if (activeTab && this.active !== activeTab.panel) this.active = activeTab.panel;\n return activeTab;\n }\n\n /** Wires up roles, ids and visibility on the light-DOM tabs and panels. */\n #sync(): void {\n const tabs = this.#tabs;\n const panels = this.#panels;\n const activeTab = this.#activeTab();\n\n tabs.forEach((tab, i) => {\n tab.slot = 'nav';\n tab.id ||= `${this.#id}-tab-${i}`;\n const panel = panels.find((p) => p.name === tab.panel);\n const selected = tab === activeTab;\n tab.setAttribute('role', 'tab');\n tab.setAttribute('aria-selected', String(selected));\n tab.setAttribute('aria-disabled', String(tab.disabled));\n tab.tabIndex = selected ? 0 : -1;\n if (panel) {\n panel.id ||= `${this.#id}-panel-${i}`;\n tab.setAttribute('aria-controls', panel.id);\n panel.setAttribute('aria-labelledby', tab.id);\n }\n });\n\n for (const panel of panels) {\n panel.setAttribute('role', 'tabpanel');\n panel.tabIndex = 0;\n panel.hidden = panel.name !== activeTab?.panel;\n }\n }\n\n #activate(tab: UfTab): void {\n tab.focus();\n if (tab.panel === this.active) return;\n this.active = tab.panel;\n this.dispatchEvent(\n new CustomEvent<TabChangeDetail>('uf-tab-change', {\n bubbles: true,\n composed: true,\n detail: { name: tab.panel },\n }),\n );\n }\n\n #onClick = (event: MouseEvent): void => {\n const tab = (event.target as Element).closest('uf-tab');\n if (tab?.parentElement === this && !tab.disabled) this.#activate(tab);\n };\n\n #onKeyDown = (event: KeyboardEvent): void => {\n const current = (event.target as Element).closest('uf-tab');\n if (!current || current.parentElement !== this) return;\n\n const tabs = this.#tabs.filter((t) => !t.disabled);\n const index = tabs.indexOf(current);\n const vertical = this.orientation === 'vertical';\n const next = vertical ? 'ArrowDown' : 'ArrowRight';\n const prev = vertical ? 'ArrowUp' : 'ArrowLeft';\n\n let target: UfTab | undefined;\n if (event.key === next) target = tabs[(index + 1) % tabs.length];\n else if (event.key === prev) target = tabs[(index - 1 + tabs.length) % tabs.length];\n else if (event.key === 'Home') target = tabs[0];\n else if (event.key === 'End') target = tabs[tabs.length - 1];\n else if (event.key === 'Enter' || event.key === ' ') {\n event.preventDefault();\n this.#activate(current);\n return;\n }\n if (!target) return;\n\n event.preventDefault();\n if (this.activation === 'auto') this.#activate(target);\n else target.focus();\n };\n\n override render() {\n return html`\n <div\n class=\"tablist\"\n part=\"tablist\"\n role=\"tablist\"\n aria-label=${ifDefined(this.label)}\n aria-orientation=${this.orientation}\n >\n <slot name=\"nav\" @slotchange=${() => this.#sync()}></slot>\n </div>\n <div class=\"panels\" part=\"panels\">\n <slot @slotchange=${() => this.#sync()}></slot>\n </div>\n `;\n }\n}\n\ndefineElement('uf-tabs', UfTabs);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-tabs': UfTabs;\n }\n}\n",
|
|
673
723
|
"components/tabs/tab.ts": "import { LitElement, css, html, type PropertyDeclarations } from 'lit';\nimport { defineElement } from '../../internal/define.js';\n\n/**\n * A tab inside `<uf-tabs>`. Its `panel` names the `<uf-tab-panel>` it shows.\n *\n * @summary A tab in a tab list.\n * @tag uf-tab\n *\n * @slot - The tab label.\n *\n * @csspart base - The tab's inner wrapper.\n *\n * @cssstate active - The tab is selected.\n */\nexport class UfTab extends LitElement {\n static override styles = css`\n :host {\n position: relative;\n display: inline-flex;\n align-items: center;\n gap: var(--uf-space-2);\n padding: var(--uf-space-2) var(--uf-space-3);\n color: var(--uf-color-text-muted);\n font-family: var(--uf-font-family-sans);\n font-size: var(--uf-font-size-md);\n font-weight: var(--uf-font-weight-medium);\n white-space: nowrap;\n cursor: pointer;\n user-select: none;\n outline: none;\n border-radius: var(--uf-radius-sm);\n transition: color var(--uf-duration-fast) ease;\n }\n\n :host(:hover:not([disabled])) {\n color: var(--uf-color-text);\n }\n\n :host([aria-selected='true']) {\n color: var(--uf-color-text);\n }\n\n :host::after {\n content: '';\n position: absolute;\n inset: auto 0 -1px 0;\n height: 2px;\n border-radius: 2px;\n background: var(--uf-tabs-indicator-color, var(--uf-color-accent-strong));\n scale: 0 1;\n transition: scale var(--uf-duration-base) ease;\n }\n\n :host([aria-selected='true'])::after {\n scale: 1 1;\n }\n\n :host(:focus-visible) {\n outline: var(--uf-focus-ring-width) solid var(--uf-color-focus-ring);\n outline-offset: calc(var(--uf-focus-ring-width) * -1);\n }\n\n :host([disabled]) {\n opacity: 0.5;\n cursor: not-allowed;\n }\n\n @media (prefers-reduced-motion: reduce) {\n :host::after {\n transition: none;\n }\n }\n `;\n\n static override properties: PropertyDeclarations = {\n panel: { reflect: true },\n disabled: { type: Boolean, reflect: true },\n };\n\n /** Name of the `<uf-tab-panel>` this tab shows. */\n declare panel: string;\n /** Disables the tab. */\n declare disabled: boolean;\n\n constructor() {\n super();\n this.panel = '';\n this.disabled = false;\n }\n\n override render() {\n return html`<slot part=\"base\"></slot>`;\n }\n}\n\n/**\n * The content shown when its tab is selected.\n *\n * @summary A panel of content inside `<uf-tabs>`.\n * @tag uf-tab-panel\n *\n * @slot - The panel content.\n *\n * @cssprop --uf-tab-panel-padding - Padding around the content.\n */\nexport class UfTabPanel extends LitElement {\n static override styles = css`\n :host {\n display: block;\n padding: var(--uf-tab-panel-padding, var(--uf-space-4) 0);\n outline: none;\n }\n\n :host([hidden]) {\n display: none;\n }\n\n :host(:focus-visible) {\n outline: var(--uf-focus-ring-width) solid var(--uf-color-focus-ring);\n outline-offset: var(--uf-focus-ring-offset);\n border-radius: var(--uf-radius-sm);\n }\n `;\n\n static override properties: PropertyDeclarations = {\n name: { reflect: true },\n };\n\n /** Name the matching tab refers to with `panel`. */\n declare name: string;\n\n constructor() {\n super();\n this.name = '';\n }\n\n override render() {\n return html`<slot></slot>`;\n }\n}\n\ndefineElement('uf-tab', UfTab);\ndefineElement('uf-tab-panel', UfTabPanel);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-tab': UfTab;\n 'uf-tab-panel': UfTabPanel;\n }\n}\n",
|
|
674
724
|
"components/textarea/textarea.ts": "import { css, html, 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 { hostStyles } from '../../internal/shared.styles.js';\nimport { HasSlotController, uniqueId } from '../../internal/slot.js';\n\nexport type TextareaResize = 'none' | 'vertical' | 'auto';\n\n/**\n * A multi-line text field with a built-in label, hint and validation message.\n *\n * @summary Lets users enter multiple lines of text.\n * @tag uf-textarea\n *\n * @slot label - The label, when you need markup. Overrides `label`.\n * @slot hint - Help text below the field. Overrides `hint`.\n *\n * @event input - Fired on every keystroke.\n * @event change - Fired when the value is committed (blur).\n *\n * @csspart field - The wrapper around label, control, hint and error.\n * @csspart form-label - The label.\n * @csspart box - The bordered box around the textarea.\n * @csspart textarea - The native `<textarea>`.\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 UfTextarea extends FormControl {\n static override styles = [\n hostStyles,\n fieldStyles,\n controlBoxStyles,\n css`\n .box {\n align-items: stretch;\n padding-block: var(--uf-space-2);\n }\n\n .native {\n min-height: 3lh;\n line-height: 1.5;\n resize: vertical;\n }\n\n :host([resize='none']) .native {\n resize: none;\n }\n\n /* Grows with its content where supported (field-sizing), otherwise resizable. */\n :host([resize='auto']) .native {\n field-sizing: content;\n resize: none;\n }\n `,\n ];\n\n protected static override formStateProperties: ReadonlySet<PropertyKey> = new Set([\n ...FormControl.formStateProperties,\n 'readonly',\n 'minlength',\n 'maxlength',\n ]);\n\n static override properties: PropertyDeclarations = {\n value: { attribute: false },\n defaultValue: { attribute: 'value' },\n label: {},\n hint: {},\n placeholder: {},\n rows: { type: Number },\n resize: { reflect: true },\n size: { reflect: true },\n readonly: { type: Boolean, reflect: true },\n autocomplete: {},\n minlength: { type: Number },\n maxlength: { type: Number },\n };\n\n /** Current value. */\n declare value: string;\n /** Initial value, restored on form reset. Set with the `value` attribute. */\n declare defaultValue: string;\n /** Visible label. */\n declare label: string | undefined;\n /** Help text below the field. */\n declare hint: string | undefined;\n /** Placeholder text. */\n declare placeholder: string | undefined;\n /** Visible number of lines. */\n declare rows: number;\n /** How the user can resize the field. `auto` grows with the content. */\n declare resize: TextareaResize;\n /** Size of the field. */\n declare size: FieldSize;\n /** Makes the field read-only. */\n declare readonly: boolean;\n /** Native `autocomplete` hint. */\n declare autocomplete: AutoFill | undefined;\n /** Minimum length. */\n declare minlength: number | undefined;\n /** Maximum length. */\n declare maxlength: number | undefined;\n\n readonly #slots = new HasSlotController(this, 'label', 'hint');\n readonly #id = uniqueId('uf-textarea');\n\n constructor() {\n super();\n this.value = '';\n this.defaultValue = '';\n this.rows = 4;\n this.resize = 'vertical';\n this.size = 'md';\n this.readonly = false;\n }\n\n get #textarea(): HTMLTextAreaElement | null {\n return this.renderRoot.querySelector('textarea');\n }\n\n /** Selects all text in the field. */\n select(): void {\n this.#textarea?.select();\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.syncFormState();\n }\n\n protected syncFormState(): void {\n const textarea = this.#textarea;\n if (!textarea) return;\n this.internals.setFormValue(this.value);\n this.setValidityFrom(textarea);\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 #onInput = (event: Event): void => {\n this.value = (event.target as HTMLTextAreaElement).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\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 <textarea\n id=${this.#id}\n class=\"native\"\n part=\"textarea\"\n name=${ifDefined(this.name || undefined)}\n .value=${live(this.value)}\n rows=${this.rows}\n placeholder=${ifDefined(this.placeholder)}\n autocomplete=${ifDefined(this.autocomplete)}\n minlength=${ifDefined(this.minlength)}\n maxlength=${ifDefined(this.maxlength)}\n ?required=${this.required}\n ?readonly=${this.readonly}\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 ></textarea>\n </div>\n `,\n });\n }\n}\n\ndefineElement('uf-textarea', UfTextarea);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-textarea': UfTextarea;\n }\n}\n",
|
|
675
725
|
"components/toast/toast.ts": "import { LitElement, css, html, nothing, type PropertyDeclarations } from 'lit';\nimport { classMap } from 'lit/directives/class-map.js';\nimport { repeat } from 'lit/directives/repeat.js';\nimport { defineElement } from '../../internal/define.js';\nimport { Translator } from '../../internal/i18n.js';\nimport { iconSvg, icons } from '../../internal/icons.js';\n\nexport type ToastVariant = 'neutral' | 'info' | 'success' | 'warning' | 'danger';\nexport type ToasterPlacement = 'top-start' | 'top-center' | 'top-end' | 'bottom-start' | 'bottom-center' | 'bottom-end';\n\nexport interface ToastOptions {\n /** Bold first line. */\n title?: string;\n /** Color and icon. `danger` toasts are announced assertively. */\n variant?: ToastVariant;\n /** Milliseconds before it hides. `0` keeps it until dismissed. Defaults to 5000. */\n duration?: number;\n /** Shows a dismiss button. Defaults to true. */\n closable?: boolean;\n}\n\nexport interface ToastHandle {\n /** Hides the toast now. */\n dismiss(): void;\n}\n\ninterface ToastItem extends Required<Omit<ToastOptions, 'title'>> {\n id: number;\n title?: string;\n message: string;\n leaving: boolean;\n}\n\ninterface Timer {\n handle: number;\n started: number;\n remaining: number;\n}\n\nconst variantIcons = {\n neutral: null,\n info: icons.info,\n success: icons['check-circle'],\n warning: icons['alert-triangle'],\n danger: icons['alert-circle'],\n} as const;\n\nconst MAX_TOASTS = 5;\nconst EXIT_MS = 200;\nlet nextId = 1;\n\n/**\n * The region that shows toasts. You rarely need to add it yourself: `toast()`\n * creates one on first use. Add it to choose a placement, or to hold\n * toasts in a specific place in the DOM.\n *\n * @summary Shows short, temporary notifications.\n * @tag uf-toaster\n *\n * @csspart region - The list holding the toasts.\n * @csspart toast - Each toast.\n * @csspart title - A toast's title.\n * @csspart message - A toast's message.\n * @csspart close-button - A toast's dismiss button.\n *\n * @cssprop --uf-toast-width - Width of each toast.\n * @cssprop --uf-toaster-offset - Distance from the viewport edges.\n */\nexport class UfToaster extends LitElement {\n static override styles = css`\n :host {\n --_offset: var(--uf-toaster-offset, var(--uf-space-4));\n position: fixed;\n inset: auto;\n margin: 0;\n padding: 0;\n border: 0;\n background: transparent;\n overflow: visible;\n width: min(var(--uf-toast-width, 22rem), calc(100vw - 2 * var(--_offset)));\n font-family: var(--uf-font-family-sans);\n }\n\n :host([placement^='top']) {\n top: var(--_offset);\n }\n :host([placement^='bottom']) {\n bottom: var(--_offset);\n }\n :host([placement$='start']) {\n left: var(--_offset);\n }\n :host([placement$='end']) {\n right: var(--_offset);\n }\n :host([placement$='center']) {\n left: 50%;\n translate: -50% 0;\n }\n\n ol {\n display: flex;\n flex-direction: column;\n gap: var(--uf-space-2);\n margin: 0;\n padding: 0;\n list-style: none;\n }\n\n :host([placement^='bottom']) ol {\n flex-direction: column-reverse;\n }\n\n .toast {\n --_bg: var(--uf-color-toast-neutral-bg);\n --_border: var(--uf-color-toast-neutral-border);\n --_text: var(--uf-color-toast-neutral-text);\n display: flex;\n align-items: flex-start;\n gap: var(--uf-space-3);\n padding: var(--uf-space-3) var(--uf-space-3) var(--uf-space-3) var(--uf-space-4);\n border: 1px solid var(--_border);\n border-radius: var(--uf-radius-md);\n background: var(--_bg);\n color: var(--_text);\n font-size: var(--uf-font-size-md);\n line-height: 1.45;\n box-shadow: var(--uf-shadow-md);\n animation: enter var(--uf-duration-base) ease;\n }\n\n .toast.leaving {\n opacity: 0;\n translate: 0 0.25rem;\n transition:\n opacity ${EXIT_MS}ms ease,\n translate ${EXIT_MS}ms ease;\n }\n\n .info {\n --_bg: var(--uf-color-toast-info-bg);\n --_border: var(--uf-color-toast-info-border);\n --_text: var(--uf-color-toast-info-text);\n }\n .success {\n --_bg: var(--uf-color-toast-success-bg);\n --_border: var(--uf-color-toast-success-border);\n --_text: var(--uf-color-toast-success-text);\n }\n .warning {\n --_bg: var(--uf-color-toast-warning-bg);\n --_border: var(--uf-color-toast-warning-border);\n --_text: var(--uf-color-toast-warning-text);\n }\n .danger {\n --_bg: var(--uf-color-toast-danger-bg);\n --_border: var(--uf-color-toast-danger-border);\n --_text: var(--uf-color-toast-danger-text);\n }\n\n .icon {\n flex: none;\n width: 1.125rem;\n height: 1.125rem;\n margin-top: 0.1em;\n color: currentColor;\n }\n\n .content {\n flex: 1;\n min-width: 0;\n padding-block: 0.0625rem;\n }\n\n .title {\n display: block;\n font-weight: var(--uf-font-weight-semibold);\n }\n\n .title + .message {\n margin-top: 0.125rem;\n }\n\n\n .close {\n display: inline-flex;\n flex: none;\n align-items: center;\n justify-content: center;\n width: 1.75rem;\n height: 1.75rem;\n margin: -0.125rem -0.25rem 0 0;\n padding: 0;\n border: 0;\n border-radius: var(--uf-radius-sm);\n background: transparent;\n color: inherit;\n opacity: 0.8;\n cursor: pointer;\n }\n\n .close:hover {\n background: color-mix(in srgb, currentColor 16%, transparent);\n opacity: 1;\n }\n\n .close:focus-visible {\n outline: var(--uf-focus-ring-width) solid var(--uf-color-focus-ring);\n outline-offset: 0;\n }\n\n .close .icon {\n width: 1rem;\n height: 1rem;\n margin: 0;\n color: inherit;\n }\n\n @keyframes enter {\n from {\n opacity: 0;\n translate: 0 0.5rem;\n }\n }\n\n @media (prefers-reduced-motion: reduce) {\n .toast {\n animation: none;\n }\n .toast.leaving {\n transition: none;\n }\n }\n `;\n\n static override properties: PropertyDeclarations = {\n placement: { reflect: true },\n label: {},\n };\n\n /** Corner or edge of the viewport where toasts appear. */\n declare placement: ToasterPlacement;\n /** Accessible name of the notification region. Defaults to \"Notifications\", or its translation. */\n declare label: string | undefined;\n\n #items: ToastItem[] = [];\n readonly #translator = new Translator(this);\n readonly #timers = new Map<number, Timer>();\n\n constructor() {\n super();\n this.placement = 'bottom-end';\n }\n\n override connectedCallback(): void {\n super.connectedCallback();\n // The host itself is a manual popover, so toasts render in the top layer.\n this.popover = 'manual';\n }\n\n override disconnectedCallback(): void {\n super.disconnectedCallback();\n for (const timer of this.#timers.values()) clearTimeout(timer.handle);\n this.#timers.clear();\n }\n\n /** Shows a toast in this region. Prefer the `toast()` function. */\n add(message: string, options: ToastOptions = {}): ToastHandle {\n const item: ToastItem = {\n id: nextId++,\n message,\n title: options.title,\n variant: options.variant ?? 'neutral',\n duration: options.duration ?? 5000,\n closable: options.closable ?? true,\n leaving: false,\n };\n this.#items = [...this.#items, item];\n const overflow = this.#items.filter((i) => !i.leaving).length - MAX_TOASTS;\n if (overflow > 0) this.#items.filter((i) => !i.leaving).slice(0, overflow).forEach((i) => this.dismiss(i.id));\n\n this.#bringToFront();\n if (item.duration > 0) this.#startTimer(item.id, item.duration);\n this.requestUpdate();\n return { dismiss: () => this.dismiss(item.id) };\n }\n\n /** Hides a toast by id. */\n dismiss(id: number): void {\n const item = this.#items.find((i) => i.id === id);\n if (!item || item.leaving) return;\n clearTimeout(this.#timers.get(id)?.handle);\n this.#timers.delete(id);\n item.leaving = true;\n this.requestUpdate();\n\n const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;\n setTimeout(() => {\n this.#items = this.#items.filter((i) => i.id !== id);\n if (!this.#items.length && this.matches(':popover-open')) this.hidePopover();\n this.requestUpdate();\n }, reduced ? 0 : EXIT_MS);\n }\n\n /** Re-shows the popover, so toasts appear above a dialog opened after the last one. */\n #bringToFront(): void {\n if (this.matches(':popover-open')) this.hidePopover();\n this.showPopover();\n }\n\n #startTimer(id: number, ms: number): void {\n this.#timers.set(id, { handle: window.setTimeout(() => this.dismiss(id), ms), started: Date.now(), remaining: ms });\n }\n\n #pause(id: number): void {\n const timer = this.#timers.get(id);\n if (!timer) return;\n clearTimeout(timer.handle);\n timer.remaining -= Date.now() - timer.started;\n }\n\n #resume(id: number): void {\n const timer = this.#timers.get(id);\n if (timer) this.#startTimer(id, Math.max(timer.remaining, 1000));\n }\n\n #renderToast(item: ToastItem) {\n const icon = variantIcons[item.variant];\n return html`\n <li\n class=${classMap({ toast: true, [item.variant]: true, leaving: item.leaving })}\n part=\"toast\"\n role=${item.variant === 'danger' ? 'alert' : nothing}\n @pointerenter=${() => this.#pause(item.id)}\n @pointerleave=${() => this.#resume(item.id)}\n @focusin=${() => this.#pause(item.id)}\n @focusout=${() => this.#resume(item.id)}\n >\n ${icon ? iconSvg(icon) : nothing}\n <div class=\"content\">\n ${item.title ? html`<strong class=\"title\" part=\"title\">${item.title}</strong>` : nothing}\n <div class=\"message\" part=\"message\">${item.message}</div>\n </div>\n ${item.closable\n ? html`<button class=\"close\" part=\"close-button\" type=\"button\" aria-label=${this.#translator.t('dismiss')} @click=${() => this.dismiss(item.id)}>\n ${iconSvg(icons.x)}\n </button>`\n : nothing}\n </li>\n `;\n }\n\n override render() {\n return html`\n <section aria-label=${this.label ?? this.#translator.t('notifications')}>\n <ol part=\"region\" aria-live=\"polite\" aria-relevant=\"additions\">\n ${repeat(this.#items, (item) => item.id, (item) => this.#renderToast(item))}\n </ol>\n </section>\n `;\n }\n}\n\ndefineElement('uf-toaster', UfToaster);\n\n/**\n * Shows a toast. Creates a `<uf-toaster>` on first use. Does nothing on the\n * server, when rendering with SSR.\n *\n * @example toast('Saved', { variant: 'success' })\n */\nexport function toast(message: string, options?: ToastOptions): ToastHandle {\n // On the server (SSR) there is no page to show it on: do nothing.\n if (typeof document === 'undefined') return { dismiss() {} };\n let toaster = document.querySelector('uf-toaster');\n if (toaster) return toaster.add(message, options);\n\n // A live region must exist before content is added to it, or screen readers\n // may skip the first message. Create it now and add the toast a moment later.\n toaster = document.body.appendChild(document.createElement('uf-toaster'));\n let handle: ToastHandle | undefined;\n let dismissed = false;\n setTimeout(() => {\n if (!dismissed) handle = toaster.add(message, options);\n }, 100);\n return {\n dismiss() {\n dismissed = true;\n handle?.dismiss();\n },\n };\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-toaster': UfToaster;\n }\n}\n",
|
|
676
|
-
"components/tooltip/tooltip.ts": "import { LitElement, css, html, type PropertyDeclarations, type PropertyValues } from 'lit';\nimport { defineElement } from '../../internal/define.js';\nimport { autoUpdate, positionFloating, type Placement } from '../../internal/position.js';\n\n/**\n * A short label that appears on hover and keyboard focus. Wrap the element it\n * describes. The text is also set as the trigger's `aria-description` (unless it\n * repeats the trigger's own label), so screen reader users get it too. Don't put\n * interactive content in a tooltip.\n *\n * @summary Shows a short hint for the element it wraps.\n * @tag uf-tooltip\n *\n * @slot - The element the tooltip describes.\n *\n * @csspart body - The tooltip bubble.\n *\n * @cssprop --uf-tooltip-bg - Background color.\n * @cssprop --uf-tooltip-color - Text color.\n * @cssprop --uf-tooltip-max-width - Maximum width.\n */\nexport class UfTooltip extends LitElement {\n static override styles = css`\n :host {\n display: contents;\n }\n\n .body {\n position: fixed;\n inset: auto;\n margin: 0;\n max-width: var(--uf-tooltip-max-width, 18rem);\n padding: var(--uf-space-1) var(--uf-space-2);\n border: 0;\n border-radius: var(--uf-radius
|
|
726
|
+
"components/tooltip/tooltip.ts": "import { LitElement, css, html, type PropertyDeclarations, type PropertyValues } from 'lit';\nimport { defineElement } from '../../internal/define.js';\nimport { autoUpdate, positionFloating, type Placement } from '../../internal/position.js';\n\n/**\n * A short label that appears on hover and keyboard focus. Wrap the element it\n * describes. The text is also set as the trigger's `aria-description` (unless it\n * repeats the trigger's own label), so screen reader users get it too. Don't put\n * interactive content in a tooltip.\n *\n * @summary Shows a short hint for the element it wraps.\n * @tag uf-tooltip\n *\n * @slot - The element the tooltip describes.\n *\n * @csspart body - The tooltip bubble.\n *\n * @cssprop --uf-tooltip-bg - Background color.\n * @cssprop --uf-tooltip-color - Text color.\n * @cssprop --uf-tooltip-max-width - Maximum width.\n * @cssprop --uf-tooltip-radius - Corner radius. Square by default.\n */\nexport class UfTooltip extends LitElement {\n static override styles = css`\n :host {\n display: contents;\n }\n\n .body {\n position: fixed;\n inset: auto;\n margin: 0;\n max-width: var(--uf-tooltip-max-width, 18rem);\n padding: var(--uf-space-1) var(--uf-space-2);\n border: 0;\n border-radius: var(--uf-tooltip-radius, 0);\n background: var(--uf-tooltip-bg, var(--uf-color-text));\n color: var(--uf-tooltip-color, var(--uf-color-surface));\n font-family: var(--uf-font-family-sans);\n font-size: var(--uf-font-size-sm);\n line-height: 1.4;\n overflow: visible;\n opacity: 0;\n transition:\n opacity var(--uf-duration-fast) ease,\n overlay var(--uf-duration-fast) allow-discrete,\n display var(--uf-duration-fast) allow-discrete;\n }\n\n .body:popover-open {\n opacity: 1;\n }\n\n @starting-style {\n .body:popover-open {\n opacity: 0;\n }\n }\n `;\n\n static override properties: PropertyDeclarations = {\n content: {},\n placement: { reflect: true },\n disabled: { type: Boolean, reflect: true },\n delay: { type: Number },\n open: { type: Boolean, reflect: true },\n };\n\n /** The tooltip text. */\n declare content: string;\n /** Preferred side. Flips when there is no room. */\n declare placement: Placement;\n /** Turns the tooltip off. */\n declare disabled: boolean;\n /** Milliseconds to wait on hover before showing. Focus shows it immediately. */\n declare delay: number;\n /** Whether the tooltip is showing. */\n declare open: boolean;\n\n #timer = 0;\n #cleanup?: () => void;\n\n constructor() {\n super();\n this.content = '';\n this.placement = 'top';\n this.disabled = false;\n this.delay = 300;\n this.open = false;\n this.addEventListener('pointerenter', this.#onPointerEnter);\n this.addEventListener('pointerleave', this.#onLeave);\n this.addEventListener('focusin', this.#onFocusIn);\n this.addEventListener('focusout', this.#onLeave);\n }\n\n get #body(): HTMLElement | null {\n return this.renderRoot.querySelector('.body');\n }\n\n get #trigger(): HTMLElement | undefined {\n const slot = this.renderRoot.querySelector<HTMLSlotElement>('slot');\n return slot?.assignedElements()[0] as HTMLElement | undefined;\n }\n\n override connectedCallback(): void {\n super.connectedCallback();\n document.addEventListener('keydown', this.#onKeyDown);\n }\n\n override disconnectedCallback(): void {\n super.disconnectedCallback();\n document.removeEventListener('keydown', this.#onKeyDown);\n clearTimeout(this.#timer);\n this.#cleanup?.();\n }\n\n /** Shows the tooltip, unless it's disabled. */\n show(): void {\n if (!this.disabled) this.open = true;\n }\n\n /** Hides the tooltip. */\n hide(): void {\n clearTimeout(this.#timer);\n this.open = false;\n }\n\n override updated(changed: PropertyValues<this>): void {\n const trigger = this.#trigger;\n if (trigger && changed.has('content')) {\n // Skip when the tooltip repeats the trigger's name (icon buttons), or it's read twice.\n const name = trigger.getAttribute('aria-label') ?? (trigger as HTMLElement & { label?: string }).label;\n if (this.content && this.content !== name) trigger.setAttribute('aria-description', this.content);\n else trigger.removeAttribute('aria-description');\n }\n const body = this.#body;\n if (!changed.has('open') || !body) return;\n\n if (this.open && trigger && !body.matches(':popover-open')) {\n body.showPopover();\n this.#cleanup = autoUpdate(trigger, body, () => positionFloating(trigger, body, this.placement, 6));\n } else if (!this.open && body.matches(':popover-open')) {\n body.hidePopover();\n this.#cleanup?.();\n this.#cleanup = undefined;\n }\n }\n\n #onPointerEnter = (): void => {\n clearTimeout(this.#timer);\n this.#timer = window.setTimeout(() => this.show(), this.delay);\n };\n\n #onFocusIn = (): void => this.show();\n\n #onLeave = (): void => this.hide();\n\n #onKeyDown = (event: KeyboardEvent): void => {\n if (event.key === 'Escape' && this.open) this.hide();\n };\n\n override render() {\n return html`\n <slot @slotchange=${() => this.requestUpdate('content')}></slot>\n <div class=\"body\" part=\"body\" popover=\"manual\" role=\"tooltip\">${this.content}</div>\n `;\n }\n}\n\ndefineElement('uf-tooltip', UfTooltip);\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'uf-tooltip': UfTooltip;\n }\n}\n"
|
|
677
727
|
},
|
|
678
|
-
"tokens": "/* @unframed/tokens — generated by scripts/build.mjs, do not edit. */\n:root {\n --uf-palette-neutral-0: #ffffff;\n --uf-palette-neutral-50: #f7f6f9;\n --uf-palette-neutral-100: #efedf2;\n --uf-palette-neutral-200: #e1dfe6;\n --uf-palette-neutral-300: #c9c6d1;\n --uf-palette-neutral-400: #a29eae;\n --uf-palette-neutral-500: #7c778a;\n --uf-palette-neutral-600: #5d586b;\n --uf-palette-neutral-700: #464155;\n --uf-palette-neutral-750: #373442;\n --uf-palette-neutral-800: #302d38;\n --uf-palette-neutral-825: #28262e;\n --uf-palette-neutral-850: #212026;\n --uf-palette-neutral-900: #19191c;\n --uf-palette-neutral-925: #111312;\n --uf-palette-neutral-950: #0a0b08;\n --uf-palette-accent-50: #f3eefb;\n --uf-palette-accent-100: #e5dbf6;\n --uf-palette-accent-200: #cbb7ee;\n --uf-palette-accent-300: #ad8fe3;\n --uf-palette-accent-400: #9067d6;\n --uf-palette-accent-500: #7b47cc;\n --uf-palette-accent-600: #6930c3;\n --uf-palette-accent-700: #5726a3;\n --uf-palette-accent-800: #461f83;\n --uf-palette-accent-900: #361865;\n --uf-palette-accent-950: #1f0e3b;\n --uf-palette-danger-50: #fcedf0;\n --uf-palette-danger-100: #f8d3db;\n --uf-palette-danger-200: #f0a8b8;\n --uf-palette-danger-300: #e57d93;\n --uf-palette-danger-400: #d4566f;\n --uf-palette-danger-500: #b13650;\n --uf-palette-danger-600: #7c162e;\n --uf-palette-danger-700: #661126;\n --uf-palette-danger-800: #510d1e;\n --uf-palette-danger-900: #3d0a17;\n --uf-palette-danger-950: #24050d;\n --uf-palette-success-50: #f0fdf4;\n --uf-palette-success-100: #dcfce7;\n --uf-palette-success-400: #4ade80;\n --uf-palette-success-500: #22c55e;\n --uf-palette-success-600: #16a34a;\n --uf-palette-success-700: #15803d;\n --uf-palette-success-800: #166534;\n --uf-palette-success-950: #052e16;\n --uf-palette-warning-50: #fffbeb;\n --uf-palette-warning-100: #fef3c7;\n --uf-palette-warning-400: #fbbf24;\n --uf-palette-warning-500: #f59e0b;\n --uf-palette-warning-600: #d97706;\n --uf-palette-warning-700: #b45309;\n --uf-palette-warning-800: #92400e;\n --uf-palette-warning-950: #451a03;\n --uf-palette-info-50: #eef2fc;\n --uf-palette-info-100: #dbe3f8;\n --uf-palette-info-300: #93a8e6;\n --uf-palette-info-400: #6f88db;\n --uf-palette-info-600: #4763c9;\n --uf-palette-info-700: #3a51a8;\n --uf-palette-info-950: #121a36;\n --uf-palette-signal-blue: #4763c9;\n --uf-palette-signal-green: #1f7a66;\n --uf-palette-signal-orange: #f2a65a;\n --uf-palette-signal-orange-ink: #1b1407;\n --uf-font-family-sans: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;\n --uf-font-family-mono: ui-monospace, 'SF Mono', Menlo, Consolas, monospace;\n --uf-font-size-sm: 0.8125rem;\n --uf-font-size-md: 0.875rem;\n --uf-font-size-lg: 1rem;\n --uf-font-weight-regular: 400;\n --uf-font-weight-medium: 500;\n --uf-font-weight-semibold: 600;\n --uf-radius-sm: 4px;\n --uf-radius-md: 8px;\n --uf-radius-lg: 12px;\n --uf-radius-full: 9999px;\n --uf-radius-control: 0px;\n --uf-space-1: 0.25rem;\n --uf-space-2: 0.5rem;\n --uf-space-3: 0.75rem;\n --uf-space-4: 1rem;\n --uf-space-5: 1.25rem;\n --uf-space-6: 1.5rem;\n --uf-size-control-sm: 2rem;\n --uf-size-control-md: 2.5rem;\n --uf-size-control-lg: 3rem;\n --uf-focus-ring-width: 2px;\n --uf-focus-ring-offset: 2px;\n --uf-duration-fast: 120ms;\n --uf-duration-base: 200ms;\n --uf-shadow-sm: 0 1px 2px rgb(0 0 0 / 0.06);\n --uf-shadow-md: 0 4px 12px rgb(0 0 0 / 0.10), 0 1px 3px rgb(0 0 0 / 0.08);\n --uf-shadow-lg: 0 16px 40px rgb(0 0 0 / 0.18), 0 4px 12px rgb(0 0 0 / 0.10);\n}\n\n:root,\n[data-uf-theme='light'] {\n color-scheme: light;\n --uf-color-surface: var(--uf-palette-neutral-0);\n --uf-color-surface-raised: var(--uf-palette-neutral-50);\n --uf-color-surface-overlay: var(--uf-palette-neutral-0);\n --uf-color-surface-hover: var(--uf-palette-neutral-100);\n --uf-color-surface-active: var(--uf-palette-neutral-200);\n --uf-color-text: var(--uf-palette-neutral-925);\n --uf-color-text-muted: var(--uf-palette-neutral-600);\n --uf-color-border: var(--uf-palette-neutral-200);\n --uf-color-border-strong: var(--uf-palette-neutral-500);\n --uf-color-accent: var(--uf-palette-accent-600);\n --uf-color-accent-hover: var(--uf-palette-accent-700);\n --uf-color-accent-active: var(--uf-palette-accent-800);\n --uf-color-accent-strong: var(--uf-palette-accent-600);\n --uf-color-accent-subtle: var(--uf-palette-accent-50);\n --uf-color-on-accent: var(--uf-palette-neutral-0);\n --uf-color-accent-tint: var(--uf-palette-accent-100);\n --uf-color-accent-tint-hover: var(--uf-palette-accent-200);\n --uf-color-accent-tint-active: var(--uf-palette-accent-300);\n --uf-color-on-accent-tint: var(--uf-palette-accent-900);\n --uf-color-neutral-fill: var(--uf-palette-neutral-100);\n --uf-color-danger: var(--uf-palette-danger-500);\n --uf-color-danger-hover: var(--uf-palette-danger-600);\n --uf-color-danger-subtle: var(--uf-palette-danger-50);\n --uf-color-danger-text: var(--uf-palette-danger-500);\n --uf-color-on-danger: var(--uf-palette-neutral-0);\n --uf-color-success: var(--uf-palette-success-700);\n --uf-color-success-subtle: var(--uf-palette-success-50);\n --uf-color-warning: var(--uf-palette-warning-700);\n --uf-color-warning-subtle: var(--uf-palette-warning-50);\n --uf-color-info: var(--uf-palette-info-700);\n --uf-color-info-subtle: var(--uf-palette-info-50);\n --uf-color-focus-ring: var(--uf-palette-accent-600);\n --uf-color-backdrop: var(--uf-palette-neutral-950);\n --uf-color-toast-neutral-bg: var(--uf-palette-neutral-800);\n --uf-color-toast-neutral-border: var(--uf-palette-neutral-800);\n --uf-color-toast-neutral-text: var(--uf-palette-neutral-0);\n --uf-color-toast-info-bg: var(--uf-palette-signal-blue);\n --uf-color-toast-info-border: var(--uf-palette-signal-blue);\n --uf-color-toast-info-text: var(--uf-palette-neutral-0);\n --uf-color-toast-success-bg: var(--uf-palette-signal-green);\n --uf-color-toast-success-border: var(--uf-palette-signal-green);\n --uf-color-toast-success-text: var(--uf-palette-neutral-0);\n --uf-color-toast-warning-bg: var(--uf-palette-signal-orange);\n --uf-color-toast-warning-border: var(--uf-palette-signal-orange);\n --uf-color-toast-warning-text: var(--uf-palette-signal-orange-ink);\n --uf-color-toast-danger-bg: var(--uf-palette-danger-500);\n --uf-color-toast-danger-border: var(--uf-palette-danger-500);\n --uf-color-toast-danger-text: var(--uf-palette-neutral-0);\n --uf-shadow-raised: var(--uf-shadow-md);\n --uf-shadow-overlay: var(--uf-shadow-md);\n --uf-shadow-modal: var(--uf-shadow-lg);\n}\n\n[data-uf-theme='dark'] {\n color-scheme: dark;\n --uf-color-surface: var(--uf-palette-neutral-950);\n --uf-color-surface-raised: var(--uf-palette-neutral-925);\n --uf-color-surface-overlay: var(--uf-palette-neutral-900);\n --uf-color-surface-hover: var(--uf-palette-neutral-850);\n --uf-color-surface-active: var(--uf-palette-neutral-825);\n --uf-color-text: var(--uf-palette-neutral-50);\n --uf-color-text-muted: var(--uf-palette-neutral-400);\n --uf-color-border: var(--uf-palette-neutral-825);\n --uf-color-border-strong: var(--uf-palette-neutral-500);\n --uf-color-accent: var(--uf-palette-accent-600);\n --uf-color-accent-hover: var(--uf-palette-accent-500);\n --uf-color-accent-active: var(--uf-palette-accent-700);\n --uf-color-accent-strong: var(--uf-palette-accent-300);\n --uf-color-accent-subtle: var(--uf-palette-accent-950);\n --uf-color-on-accent: var(--uf-palette-neutral-0);\n --uf-color-accent-tint: var(--uf-palette-accent-800);\n --uf-color-accent-tint-hover: var(--uf-palette-accent-700);\n --uf-color-accent-tint-active: var(--uf-palette-accent-900);\n --uf-color-on-accent-tint: var(--uf-palette-accent-200);\n --uf-color-neutral-fill: var(--uf-palette-neutral-800);\n --uf-color-danger: var(--uf-palette-danger-600);\n --uf-color-danger-hover: var(--uf-palette-danger-500);\n --uf-color-danger-subtle: var(--uf-palette-danger-950);\n --uf-color-danger-text: var(--uf-palette-danger-300);\n --uf-color-on-danger: var(--uf-palette-neutral-0);\n --uf-color-success: var(--uf-palette-success-400);\n --uf-color-success-subtle: var(--uf-palette-success-950);\n --uf-color-warning: var(--uf-palette-warning-400);\n --uf-color-warning-subtle: var(--uf-palette-warning-950);\n --uf-color-info: var(--uf-palette-info-300);\n --uf-color-info-subtle: var(--uf-palette-info-950);\n --uf-color-focus-ring: var(--uf-palette-accent-400);\n --uf-color-backdrop: var(--uf-palette-neutral-950);\n --uf-color-toast-neutral-bg: var(--uf-palette-neutral-750);\n --uf-color-toast-neutral-border: var(--uf-palette-neutral-700);\n --uf-color-toast-neutral-text: var(--uf-palette-neutral-0);\n --uf-color-toast-info-bg: var(--uf-palette-signal-blue);\n --uf-color-toast-info-border: var(--uf-palette-signal-blue);\n --uf-color-toast-info-text: var(--uf-palette-neutral-0);\n --uf-color-toast-success-bg: var(--uf-palette-signal-green);\n --uf-color-toast-success-border: var(--uf-palette-signal-green);\n --uf-color-toast-success-text: var(--uf-palette-neutral-0);\n --uf-color-toast-warning-bg: var(--uf-palette-signal-orange);\n --uf-color-toast-warning-border: var(--uf-palette-signal-orange);\n --uf-color-toast-warning-text: var(--uf-palette-signal-orange-ink);\n --uf-color-toast-danger-bg: var(--uf-palette-danger-600);\n --uf-color-toast-danger-border: var(--uf-palette-danger-600);\n --uf-color-toast-danger-text: var(--uf-palette-neutral-0);\n --uf-shadow-raised: 0 0 0 1px color-mix(in srgb, var(--uf-palette-accent-400) 30%, transparent), 0 12px 32px -8px color-mix(in srgb, var(--uf-palette-accent-600) 55%, transparent);\n --uf-shadow-overlay: 0 0 0 1px color-mix(in srgb, var(--uf-palette-accent-400) 25%, transparent), 0 8px 24px -6px color-mix(in srgb, var(--uf-palette-accent-600) 50%, transparent);\n --uf-shadow-modal: 0 0 0 1px color-mix(in srgb, var(--uf-palette-accent-400) 30%, transparent), 0 24px 64px -12px color-mix(in srgb, var(--uf-palette-accent-600) 60%, transparent);\n}\n\n@media (prefers-color-scheme: dark) {\n :root:not([data-uf-theme='light']) {\n color-scheme: dark;\n --uf-color-surface: var(--uf-palette-neutral-950);\n --uf-color-surface-raised: var(--uf-palette-neutral-925);\n --uf-color-surface-overlay: var(--uf-palette-neutral-900);\n --uf-color-surface-hover: var(--uf-palette-neutral-850);\n --uf-color-surface-active: var(--uf-palette-neutral-825);\n --uf-color-text: var(--uf-palette-neutral-50);\n --uf-color-text-muted: var(--uf-palette-neutral-400);\n --uf-color-border: var(--uf-palette-neutral-825);\n --uf-color-border-strong: var(--uf-palette-neutral-500);\n --uf-color-accent: var(--uf-palette-accent-600);\n --uf-color-accent-hover: var(--uf-palette-accent-500);\n --uf-color-accent-active: var(--uf-palette-accent-700);\n --uf-color-accent-strong: var(--uf-palette-accent-300);\n --uf-color-accent-subtle: var(--uf-palette-accent-950);\n --uf-color-on-accent: var(--uf-palette-neutral-0);\n --uf-color-accent-tint: var(--uf-palette-accent-800);\n --uf-color-accent-tint-hover: var(--uf-palette-accent-700);\n --uf-color-accent-tint-active: var(--uf-palette-accent-900);\n --uf-color-on-accent-tint: var(--uf-palette-accent-200);\n --uf-color-neutral-fill: var(--uf-palette-neutral-800);\n --uf-color-danger: var(--uf-palette-danger-600);\n --uf-color-danger-hover: var(--uf-palette-danger-500);\n --uf-color-danger-subtle: var(--uf-palette-danger-950);\n --uf-color-danger-text: var(--uf-palette-danger-300);\n --uf-color-on-danger: var(--uf-palette-neutral-0);\n --uf-color-success: var(--uf-palette-success-400);\n --uf-color-success-subtle: var(--uf-palette-success-950);\n --uf-color-warning: var(--uf-palette-warning-400);\n --uf-color-warning-subtle: var(--uf-palette-warning-950);\n --uf-color-info: var(--uf-palette-info-300);\n --uf-color-info-subtle: var(--uf-palette-info-950);\n --uf-color-focus-ring: var(--uf-palette-accent-400);\n --uf-color-backdrop: var(--uf-palette-neutral-950);\n --uf-color-toast-neutral-bg: var(--uf-palette-neutral-750);\n --uf-color-toast-neutral-border: var(--uf-palette-neutral-700);\n --uf-color-toast-neutral-text: var(--uf-palette-neutral-0);\n --uf-color-toast-info-bg: var(--uf-palette-signal-blue);\n --uf-color-toast-info-border: var(--uf-palette-signal-blue);\n --uf-color-toast-info-text: var(--uf-palette-neutral-0);\n --uf-color-toast-success-bg: var(--uf-palette-signal-green);\n --uf-color-toast-success-border: var(--uf-palette-signal-green);\n --uf-color-toast-success-text: var(--uf-palette-neutral-0);\n --uf-color-toast-warning-bg: var(--uf-palette-signal-orange);\n --uf-color-toast-warning-border: var(--uf-palette-signal-orange);\n --uf-color-toast-warning-text: var(--uf-palette-signal-orange-ink);\n --uf-color-toast-danger-bg: var(--uf-palette-danger-600);\n --uf-color-toast-danger-border: var(--uf-palette-danger-600);\n --uf-color-toast-danger-text: var(--uf-palette-neutral-0);\n --uf-shadow-raised: 0 0 0 1px color-mix(in srgb, var(--uf-palette-accent-400) 30%, transparent), 0 12px 32px -8px color-mix(in srgb, var(--uf-palette-accent-600) 55%, transparent);\n --uf-shadow-overlay: 0 0 0 1px color-mix(in srgb, var(--uf-palette-accent-400) 25%, transparent), 0 8px 24px -6px color-mix(in srgb, var(--uf-palette-accent-600) 50%, transparent);\n --uf-shadow-modal: 0 0 0 1px color-mix(in srgb, var(--uf-palette-accent-400) 30%, transparent), 0 24px 64px -12px color-mix(in srgb, var(--uf-palette-accent-600) 60%, transparent);\n }\n}\n\n/* Before the components load: no flash of raw content on server-rendered pages. */\n:where(uf-accordion, uf-accordion-item, uf-avatar, uf-badge, uf-breadcrumb-item, uf-breadcrumbs, uf-button, uf-calendar, uf-card, uf-checkbox, uf-checkbox-group, uf-combobox, uf-date-picker, uf-dialog, uf-drawer, uf-dropdown, uf-icon, uf-input, uf-menu, uf-menu-item, uf-pagination, uf-popover, uf-progress, uf-radio, uf-radio-group, uf-select, uf-slider, uf-spinner, uf-switch, uf-tab, uf-tab-panel, uf-table, uf-tabs, uf-textarea, uf-toaster, uf-tooltip):not(:defined) {\n visibility: hidden;\n}\n\n:where(uf-dialog, uf-drawer, uf-toaster, uf-tab-panel):not(:defined),\n:where(uf-dropdown, uf-popover):not(:defined) > :not([slot]),\n:where(uf-select, uf-combobox):not(:defined) > :where(option, optgroup),\nuf-accordion-item:not(:defined):not([open]) > :not([slot]) {\n display: none;\n}\n"
|
|
728
|
+
"tokens": "/* @unframed/tokens — generated by scripts/build.mjs, do not edit. */\n:root {\n --uf-palette-neutral-0: #ffffff;\n --uf-palette-neutral-50: #f7f6f9;\n --uf-palette-neutral-100: #efedf2;\n --uf-palette-neutral-200: #e1dfe6;\n --uf-palette-neutral-300: #c9c6d1;\n --uf-palette-neutral-400: #a29eae;\n --uf-palette-neutral-500: #7c778a;\n --uf-palette-neutral-600: #5d586b;\n --uf-palette-neutral-700: #464155;\n --uf-palette-neutral-750: #373442;\n --uf-palette-neutral-800: #302d38;\n --uf-palette-neutral-825: #28262e;\n --uf-palette-neutral-850: #212026;\n --uf-palette-neutral-900: #19191c;\n --uf-palette-neutral-925: #111312;\n --uf-palette-neutral-950: #0a0b08;\n --uf-palette-accent-50: #f3eefb;\n --uf-palette-accent-100: #e5dbf6;\n --uf-palette-accent-200: #cbb7ee;\n --uf-palette-accent-300: #ad8fe3;\n --uf-palette-accent-400: #9067d6;\n --uf-palette-accent-500: #7b47cc;\n --uf-palette-accent-600: #6930c3;\n --uf-palette-accent-700: #5726a3;\n --uf-palette-accent-800: #461f83;\n --uf-palette-accent-900: #361865;\n --uf-palette-accent-950: #1f0e3b;\n --uf-palette-danger-50: #fcedf0;\n --uf-palette-danger-100: #f8d3db;\n --uf-palette-danger-200: #f0a8b8;\n --uf-palette-danger-300: #e57d93;\n --uf-palette-danger-400: #d4566f;\n --uf-palette-danger-500: #b13650;\n --uf-palette-danger-600: #7c162e;\n --uf-palette-danger-700: #661126;\n --uf-palette-danger-800: #510d1e;\n --uf-palette-danger-900: #3d0a17;\n --uf-palette-danger-950: #24050d;\n --uf-palette-success-50: #f0fdf4;\n --uf-palette-success-100: #dcfce7;\n --uf-palette-success-400: #4ade80;\n --uf-palette-success-500: #22c55e;\n --uf-palette-success-600: #16a34a;\n --uf-palette-success-700: #15803d;\n --uf-palette-success-800: #166534;\n --uf-palette-success-950: #052e16;\n --uf-palette-warning-50: #fffbeb;\n --uf-palette-warning-100: #fef3c7;\n --uf-palette-warning-400: #fbbf24;\n --uf-palette-warning-500: #f59e0b;\n --uf-palette-warning-600: #d97706;\n --uf-palette-warning-700: #b45309;\n --uf-palette-warning-800: #92400e;\n --uf-palette-warning-950: #451a03;\n --uf-palette-info-50: #eef2fc;\n --uf-palette-info-100: #dbe3f8;\n --uf-palette-info-300: #93a8e6;\n --uf-palette-info-400: #6f88db;\n --uf-palette-info-600: #4763c9;\n --uf-palette-info-700: #3a51a8;\n --uf-palette-info-950: #121a36;\n --uf-palette-signal-blue: #4763c9;\n --uf-palette-signal-green: #1f7a66;\n --uf-palette-signal-orange: #f2a65a;\n --uf-palette-signal-orange-ink: #1b1407;\n --uf-font-family-sans: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;\n --uf-font-family-mono: ui-monospace, 'SF Mono', Menlo, Consolas, monospace;\n --uf-font-size-sm: 0.8125rem;\n --uf-font-size-md: 0.875rem;\n --uf-font-size-lg: 1rem;\n --uf-font-weight-regular: 400;\n --uf-font-weight-medium: 500;\n --uf-font-weight-semibold: 600;\n --uf-radius-sm: 4px;\n --uf-radius-md: 8px;\n --uf-radius-lg: 12px;\n --uf-radius-full: 9999px;\n --uf-radius-control: 0px;\n --uf-space-1: 0.25rem;\n --uf-space-2: 0.5rem;\n --uf-space-3: 0.75rem;\n --uf-space-4: 1rem;\n --uf-space-5: 1.25rem;\n --uf-space-6: 1.5rem;\n --uf-size-control-sm: 2rem;\n --uf-size-control-md: 2.5rem;\n --uf-size-control-lg: 3rem;\n --uf-focus-ring-width: 2px;\n --uf-focus-ring-offset: 2px;\n --uf-duration-fast: 120ms;\n --uf-duration-base: 200ms;\n --uf-shadow-sm: 0 1px 2px rgb(0 0 0 / 0.06);\n --uf-shadow-md: 0 4px 12px rgb(0 0 0 / 0.10), 0 1px 3px rgb(0 0 0 / 0.08);\n --uf-shadow-lg: 0 16px 40px rgb(0 0 0 / 0.18), 0 4px 12px rgb(0 0 0 / 0.10);\n}\n\n:root,\n[data-uf-theme='light'] {\n color-scheme: light;\n --uf-color-surface: var(--uf-palette-neutral-0);\n --uf-color-surface-raised: var(--uf-palette-neutral-50);\n --uf-color-surface-overlay: var(--uf-palette-neutral-0);\n --uf-color-surface-hover: var(--uf-palette-neutral-100);\n --uf-color-surface-active: var(--uf-palette-neutral-200);\n --uf-color-text: var(--uf-palette-neutral-925);\n --uf-color-text-muted: var(--uf-palette-neutral-600);\n --uf-color-border: var(--uf-palette-neutral-200);\n --uf-color-border-strong: var(--uf-palette-neutral-500);\n --uf-color-accent: var(--uf-palette-accent-600);\n --uf-color-accent-hover: var(--uf-palette-accent-700);\n --uf-color-accent-active: var(--uf-palette-accent-800);\n --uf-color-accent-strong: var(--uf-palette-accent-600);\n --uf-color-accent-subtle: var(--uf-palette-accent-50);\n --uf-color-on-accent: var(--uf-palette-neutral-0);\n --uf-color-accent-tint: var(--uf-palette-accent-100);\n --uf-color-accent-tint-hover: var(--uf-palette-accent-200);\n --uf-color-accent-tint-active: var(--uf-palette-accent-300);\n --uf-color-on-accent-tint: var(--uf-palette-accent-900);\n --uf-color-neutral-fill: var(--uf-palette-neutral-100);\n --uf-color-danger: var(--uf-palette-danger-500);\n --uf-color-danger-hover: var(--uf-palette-danger-600);\n --uf-color-danger-subtle: var(--uf-palette-danger-50);\n --uf-color-danger-text: var(--uf-palette-danger-500);\n --uf-color-on-danger: var(--uf-palette-neutral-0);\n --uf-color-success: var(--uf-palette-success-700);\n --uf-color-success-subtle: var(--uf-palette-success-50);\n --uf-color-warning: var(--uf-palette-warning-700);\n --uf-color-warning-subtle: var(--uf-palette-warning-50);\n --uf-color-info: var(--uf-palette-info-700);\n --uf-color-info-subtle: var(--uf-palette-info-50);\n --uf-color-focus-ring: var(--uf-palette-accent-600);\n --uf-color-backdrop: var(--uf-palette-neutral-950);\n --uf-color-toast-neutral-bg: var(--uf-palette-neutral-800);\n --uf-color-toast-neutral-border: var(--uf-palette-neutral-800);\n --uf-color-toast-neutral-text: var(--uf-palette-neutral-0);\n --uf-color-toast-info-bg: var(--uf-palette-signal-blue);\n --uf-color-toast-info-border: var(--uf-palette-signal-blue);\n --uf-color-toast-info-text: var(--uf-palette-neutral-0);\n --uf-color-toast-success-bg: var(--uf-palette-signal-green);\n --uf-color-toast-success-border: var(--uf-palette-signal-green);\n --uf-color-toast-success-text: var(--uf-palette-neutral-0);\n --uf-color-toast-warning-bg: var(--uf-palette-signal-orange);\n --uf-color-toast-warning-border: var(--uf-palette-signal-orange);\n --uf-color-toast-warning-text: var(--uf-palette-signal-orange-ink);\n --uf-color-toast-danger-bg: var(--uf-palette-danger-500);\n --uf-color-toast-danger-border: var(--uf-palette-danger-500);\n --uf-color-toast-danger-text: var(--uf-palette-neutral-0);\n --uf-shadow-raised: var(--uf-shadow-md);\n --uf-shadow-overlay: var(--uf-shadow-md);\n --uf-shadow-modal: var(--uf-shadow-lg);\n}\n\n[data-uf-theme='dark'] {\n color-scheme: dark;\n --uf-color-surface: var(--uf-palette-neutral-950);\n --uf-color-surface-raised: var(--uf-palette-neutral-925);\n --uf-color-surface-overlay: var(--uf-palette-neutral-900);\n --uf-color-surface-hover: var(--uf-palette-neutral-850);\n --uf-color-surface-active: var(--uf-palette-neutral-825);\n --uf-color-text: var(--uf-palette-neutral-50);\n --uf-color-text-muted: var(--uf-palette-neutral-400);\n --uf-color-border: var(--uf-palette-neutral-825);\n --uf-color-border-strong: var(--uf-palette-neutral-500);\n --uf-color-accent: var(--uf-palette-accent-600);\n --uf-color-accent-hover: var(--uf-palette-accent-500);\n --uf-color-accent-active: var(--uf-palette-accent-700);\n --uf-color-accent-strong: var(--uf-palette-accent-300);\n --uf-color-accent-subtle: var(--uf-palette-accent-950);\n --uf-color-on-accent: var(--uf-palette-neutral-0);\n --uf-color-accent-tint: var(--uf-palette-accent-800);\n --uf-color-accent-tint-hover: var(--uf-palette-accent-700);\n --uf-color-accent-tint-active: var(--uf-palette-accent-900);\n --uf-color-on-accent-tint: var(--uf-palette-accent-200);\n --uf-color-neutral-fill: var(--uf-palette-neutral-800);\n --uf-color-danger: var(--uf-palette-danger-600);\n --uf-color-danger-hover: var(--uf-palette-danger-500);\n --uf-color-danger-subtle: var(--uf-palette-danger-950);\n --uf-color-danger-text: var(--uf-palette-danger-300);\n --uf-color-on-danger: var(--uf-palette-neutral-0);\n --uf-color-success: var(--uf-palette-success-400);\n --uf-color-success-subtle: var(--uf-palette-success-950);\n --uf-color-warning: var(--uf-palette-warning-400);\n --uf-color-warning-subtle: var(--uf-palette-warning-950);\n --uf-color-info: var(--uf-palette-info-300);\n --uf-color-info-subtle: var(--uf-palette-info-950);\n --uf-color-focus-ring: var(--uf-palette-accent-400);\n --uf-color-backdrop: var(--uf-palette-neutral-950);\n --uf-color-toast-neutral-bg: var(--uf-palette-neutral-750);\n --uf-color-toast-neutral-border: var(--uf-palette-neutral-700);\n --uf-color-toast-neutral-text: var(--uf-palette-neutral-0);\n --uf-color-toast-info-bg: var(--uf-palette-signal-blue);\n --uf-color-toast-info-border: var(--uf-palette-signal-blue);\n --uf-color-toast-info-text: var(--uf-palette-neutral-0);\n --uf-color-toast-success-bg: var(--uf-palette-signal-green);\n --uf-color-toast-success-border: var(--uf-palette-signal-green);\n --uf-color-toast-success-text: var(--uf-palette-neutral-0);\n --uf-color-toast-warning-bg: var(--uf-palette-signal-orange);\n --uf-color-toast-warning-border: var(--uf-palette-signal-orange);\n --uf-color-toast-warning-text: var(--uf-palette-signal-orange-ink);\n --uf-color-toast-danger-bg: var(--uf-palette-danger-600);\n --uf-color-toast-danger-border: var(--uf-palette-danger-600);\n --uf-color-toast-danger-text: var(--uf-palette-neutral-0);\n --uf-shadow-raised: 0 0 0 1px color-mix(in srgb, var(--uf-palette-accent-400) 30%, transparent), 0 12px 32px -8px color-mix(in srgb, var(--uf-palette-accent-600) 55%, transparent);\n --uf-shadow-overlay: 0 0 0 1px color-mix(in srgb, var(--uf-palette-accent-400) 25%, transparent), 0 8px 24px -6px color-mix(in srgb, var(--uf-palette-accent-600) 50%, transparent);\n --uf-shadow-modal: 0 0 0 1px color-mix(in srgb, var(--uf-palette-accent-400) 30%, transparent), 0 24px 64px -12px color-mix(in srgb, var(--uf-palette-accent-600) 60%, transparent);\n}\n\n@media (prefers-color-scheme: dark) {\n :root:not([data-uf-theme='light']) {\n color-scheme: dark;\n --uf-color-surface: var(--uf-palette-neutral-950);\n --uf-color-surface-raised: var(--uf-palette-neutral-925);\n --uf-color-surface-overlay: var(--uf-palette-neutral-900);\n --uf-color-surface-hover: var(--uf-palette-neutral-850);\n --uf-color-surface-active: var(--uf-palette-neutral-825);\n --uf-color-text: var(--uf-palette-neutral-50);\n --uf-color-text-muted: var(--uf-palette-neutral-400);\n --uf-color-border: var(--uf-palette-neutral-825);\n --uf-color-border-strong: var(--uf-palette-neutral-500);\n --uf-color-accent: var(--uf-palette-accent-600);\n --uf-color-accent-hover: var(--uf-palette-accent-500);\n --uf-color-accent-active: var(--uf-palette-accent-700);\n --uf-color-accent-strong: var(--uf-palette-accent-300);\n --uf-color-accent-subtle: var(--uf-palette-accent-950);\n --uf-color-on-accent: var(--uf-palette-neutral-0);\n --uf-color-accent-tint: var(--uf-palette-accent-800);\n --uf-color-accent-tint-hover: var(--uf-palette-accent-700);\n --uf-color-accent-tint-active: var(--uf-palette-accent-900);\n --uf-color-on-accent-tint: var(--uf-palette-accent-200);\n --uf-color-neutral-fill: var(--uf-palette-neutral-800);\n --uf-color-danger: var(--uf-palette-danger-600);\n --uf-color-danger-hover: var(--uf-palette-danger-500);\n --uf-color-danger-subtle: var(--uf-palette-danger-950);\n --uf-color-danger-text: var(--uf-palette-danger-300);\n --uf-color-on-danger: var(--uf-palette-neutral-0);\n --uf-color-success: var(--uf-palette-success-400);\n --uf-color-success-subtle: var(--uf-palette-success-950);\n --uf-color-warning: var(--uf-palette-warning-400);\n --uf-color-warning-subtle: var(--uf-palette-warning-950);\n --uf-color-info: var(--uf-palette-info-300);\n --uf-color-info-subtle: var(--uf-palette-info-950);\n --uf-color-focus-ring: var(--uf-palette-accent-400);\n --uf-color-backdrop: var(--uf-palette-neutral-950);\n --uf-color-toast-neutral-bg: var(--uf-palette-neutral-750);\n --uf-color-toast-neutral-border: var(--uf-palette-neutral-700);\n --uf-color-toast-neutral-text: var(--uf-palette-neutral-0);\n --uf-color-toast-info-bg: var(--uf-palette-signal-blue);\n --uf-color-toast-info-border: var(--uf-palette-signal-blue);\n --uf-color-toast-info-text: var(--uf-palette-neutral-0);\n --uf-color-toast-success-bg: var(--uf-palette-signal-green);\n --uf-color-toast-success-border: var(--uf-palette-signal-green);\n --uf-color-toast-success-text: var(--uf-palette-neutral-0);\n --uf-color-toast-warning-bg: var(--uf-palette-signal-orange);\n --uf-color-toast-warning-border: var(--uf-palette-signal-orange);\n --uf-color-toast-warning-text: var(--uf-palette-signal-orange-ink);\n --uf-color-toast-danger-bg: var(--uf-palette-danger-600);\n --uf-color-toast-danger-border: var(--uf-palette-danger-600);\n --uf-color-toast-danger-text: var(--uf-palette-neutral-0);\n --uf-shadow-raised: 0 0 0 1px color-mix(in srgb, var(--uf-palette-accent-400) 30%, transparent), 0 12px 32px -8px color-mix(in srgb, var(--uf-palette-accent-600) 55%, transparent);\n --uf-shadow-overlay: 0 0 0 1px color-mix(in srgb, var(--uf-palette-accent-400) 25%, transparent), 0 8px 24px -6px color-mix(in srgb, var(--uf-palette-accent-600) 50%, transparent);\n --uf-shadow-modal: 0 0 0 1px color-mix(in srgb, var(--uf-palette-accent-400) 30%, transparent), 0 24px 64px -12px color-mix(in srgb, var(--uf-palette-accent-600) 60%, transparent);\n }\n}\n\n/* Before the components load: no flash of raw content on server-rendered pages. */\n:where(uf-accordion, uf-accordion-item, uf-avatar, uf-badge, uf-breadcrumb-item, uf-breadcrumbs, uf-button, uf-calendar, uf-card, uf-checkbox, uf-checkbox-group, uf-combobox, uf-date-picker, uf-date-range-picker, uf-dialog, uf-drawer, uf-dropdown, uf-file-upload, uf-icon, uf-input, uf-menu, uf-menu-item, uf-pagination, uf-popover, uf-progress, uf-radio, uf-radio-group, uf-select, uf-slider, uf-spinner, uf-switch, uf-tab, uf-tab-panel, uf-table, uf-tabs, uf-textarea, uf-toaster, uf-tooltip):not(:defined) {\n visibility: hidden;\n}\n\n:where(uf-dialog, uf-drawer, uf-toaster, uf-tab-panel):not(:defined),\n:where(uf-dropdown, uf-popover):not(:defined) > :not([slot]),\n:where(uf-select, uf-combobox):not(:defined) > :where(option, optgroup),\nuf-accordion-item:not(:defined):not([open]) > :not([slot]) {\n display: none;\n}\n"
|
|
679
729
|
}
|