@joralvmel/cosmos-elements 0.2.0 → 0.4.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.
Files changed (71) hide show
  1. package/README.md +15 -0
  2. package/dist/components/badge/cosm-badge.d.ts +64 -0
  3. package/dist/components/badge/cosm-badge.d.ts.map +1 -0
  4. package/dist/components/badge/cosm-badge.js +162 -0
  5. package/dist/components/badge/cosm-badge.js.map +1 -0
  6. package/dist/components/button/cosm-button.d.ts.map +1 -1
  7. package/dist/components/button/cosm-button.js +2 -0
  8. package/dist/components/button/cosm-button.js.map +1 -1
  9. package/dist/components/calendar/cosm-calendar.d.ts +77 -0
  10. package/dist/components/calendar/cosm-calendar.d.ts.map +1 -0
  11. package/dist/components/calendar/cosm-calendar.js +696 -0
  12. package/dist/components/calendar/cosm-calendar.js.map +1 -0
  13. package/dist/components/checkbox/cosm-checkbox.d.ts +122 -0
  14. package/dist/components/checkbox/cosm-checkbox.d.ts.map +1 -0
  15. package/dist/components/checkbox/cosm-checkbox.js +433 -0
  16. package/dist/components/checkbox/cosm-checkbox.js.map +1 -0
  17. package/dist/components/dialog/cosm-dialog.d.ts +103 -0
  18. package/dist/components/dialog/cosm-dialog.d.ts.map +1 -0
  19. package/dist/components/dialog/cosm-dialog.js +497 -0
  20. package/dist/components/dialog/cosm-dialog.js.map +1 -0
  21. package/dist/components/icon/cosm-icon.d.ts +7 -15
  22. package/dist/components/icon/cosm-icon.d.ts.map +1 -1
  23. package/dist/components/icon/cosm-icon.js +29 -30
  24. package/dist/components/icon/cosm-icon.js.map +1 -1
  25. package/dist/components/icon-button/cosm-icon-button.d.ts +79 -0
  26. package/dist/components/icon-button/cosm-icon-button.d.ts.map +1 -0
  27. package/dist/components/icon-button/cosm-icon-button.js +212 -0
  28. package/dist/components/icon-button/cosm-icon-button.js.map +1 -0
  29. package/dist/components/listbox/cosm-listbox.d.ts +136 -0
  30. package/dist/components/listbox/cosm-listbox.d.ts.map +1 -0
  31. package/dist/components/listbox/cosm-listbox.js +565 -0
  32. package/dist/components/listbox/cosm-listbox.js.map +1 -0
  33. package/dist/components/pagination/cosm-pagination.d.ts +118 -0
  34. package/dist/components/pagination/cosm-pagination.d.ts.map +1 -0
  35. package/dist/components/pagination/cosm-pagination.js +315 -0
  36. package/dist/components/pagination/cosm-pagination.js.map +1 -0
  37. package/dist/components/popover/cosm-popover.d.ts +100 -0
  38. package/dist/components/popover/cosm-popover.d.ts.map +1 -0
  39. package/dist/components/popover/cosm-popover.js +776 -0
  40. package/dist/components/popover/cosm-popover.js.map +1 -0
  41. package/dist/components/radio-group/cosm-radio-group.d.ts +111 -0
  42. package/dist/components/radio-group/cosm-radio-group.d.ts.map +1 -0
  43. package/dist/components/radio-group/cosm-radio-group.js +478 -0
  44. package/dist/components/radio-group/cosm-radio-group.js.map +1 -0
  45. package/dist/components/select/cosm-select.d.ts +126 -0
  46. package/dist/components/select/cosm-select.d.ts.map +1 -0
  47. package/dist/components/select/cosm-select.js +682 -0
  48. package/dist/components/select/cosm-select.js.map +1 -0
  49. package/dist/components/switch/cosm-switch.d.ts +103 -0
  50. package/dist/components/switch/cosm-switch.d.ts.map +1 -0
  51. package/dist/components/switch/cosm-switch.js +359 -0
  52. package/dist/components/switch/cosm-switch.js.map +1 -0
  53. package/dist/components/text-field/cosm-text-field.d.ts +193 -0
  54. package/dist/components/text-field/cosm-text-field.d.ts.map +1 -0
  55. package/dist/components/text-field/cosm-text-field.js +642 -0
  56. package/dist/components/text-field/cosm-text-field.js.map +1 -0
  57. package/dist/components/textarea/cosm-textarea.d.ts +131 -0
  58. package/dist/components/textarea/cosm-textarea.d.ts.map +1 -0
  59. package/dist/components/textarea/cosm-textarea.js +445 -0
  60. package/dist/components/textarea/cosm-textarea.js.map +1 -0
  61. package/dist/custom-elements.json +7605 -78
  62. package/dist/index.d.ts +14 -1
  63. package/dist/index.d.ts.map +1 -1
  64. package/dist/index.js +13 -0
  65. package/dist/index.js.map +1 -1
  66. package/dist/internal/current-page.d.ts +7 -0
  67. package/dist/internal/current-page.d.ts.map +1 -0
  68. package/dist/internal/current-page.js +18 -0
  69. package/dist/internal/current-page.js.map +1 -0
  70. package/llms.md +455 -7
  71. package/package.json +55 -3
@@ -0,0 +1,776 @@
1
+ import { popoverContract, } from '@joralvmel/cosmos-core';
2
+ import { x } from '@joralvmel/cosmos-icons/x';
3
+ import { css, html, LitElement, nothing } from 'lit';
4
+ import '../icon/cosm-icon.js';
5
+ import '../icon-button/cosm-icon-button.js';
6
+ import { CosmElement } from '../../internal/cosm-element.js';
7
+ import { define } from '../../internal/define.js';
8
+ import { boxSizing, focusRing } from '../../internal/styles.js';
9
+ const styles = css `
10
+ :host {
11
+ display: inline-block;
12
+ color: var(--cosm-fg, oklch(0.24 0.01 268));
13
+ font-family: var(--cosm-font-sans, system-ui, sans-serif);
14
+ }
15
+ .trigger {
16
+ display: inline-flex;
17
+ }
18
+ .panel {
19
+ position: fixed;
20
+ inset: auto;
21
+ margin: 0;
22
+ z-index: var(--cosm-popover-z-index, 1000);
23
+ width: max-content;
24
+ padding: var(--cosm-popover-padding, var(--cosm-space-lg, 1rem));
25
+ border: 1px solid var(--cosm-border-strong, oklch(0.64 0.01 268));
26
+ border-radius: var(--cosm-popover-radius, var(--cosm-radius-md, 0.5rem));
27
+ background: var(--cosm-bg, oklch(0.985 0.007 268));
28
+ color: var(--cosm-fg, oklch(0.24 0.01 268));
29
+ box-shadow: var(--cosm-popover-shadow, var(--cosm-shadow-lg, 0 8px 24px oklch(0 0 0 / 16%)));
30
+ display: flex;
31
+ flex-direction: column;
32
+ overflow: visible;
33
+ }
34
+ .body { min-height: 0; overflow: auto; }
35
+ .close { align-self: flex-end; flex: none; margin-bottom: var(--cosm-space-xs, 0.25rem); }
36
+ .arrow { position: absolute; overflow: visible; pointer-events: none; }
37
+ .panel[hidden] {
38
+ display: none;
39
+ }
40
+ .safe-area-probe {
41
+ position: fixed;
42
+ visibility: hidden;
43
+ pointer-events: none;
44
+ column-gap: var(--cosm-space-sm, 0.5rem);
45
+ padding:
46
+ env(safe-area-inset-top, 0px)
47
+ env(safe-area-inset-right, 0px)
48
+ env(safe-area-inset-bottom, 0px)
49
+ env(safe-area-inset-left, 0px);
50
+ }
51
+ `;
52
+ /**
53
+ * Non-modal content anchored to a consumer-provided trigger. Trigger naming, trigger
54
+ * appearance and panel semantics are supplied by the consumer.
55
+ *
56
+ * @tag cosm-popover
57
+ * @slot trigger - Consumer-supplied keyboard-operable trigger.
58
+ * @slot - Consumer-supplied panel content and semantics.
59
+ * @csspart trigger - Container for the trigger slot.
60
+ * @csspart panel - Non-modal anchored surface.
61
+ * @csspart body - Scrollable content.
62
+ * @csspart close - Optional close IconButton.
63
+ * @csspart arrow - Decorative pointer matching the panel.
64
+ * @fires {CustomEvent<PopoverOpenChangeDetail>} cosm-open-change - Proposes a visibility change.
65
+ * @cssprop --cosm-popover-z-index - Stacking level of the panel.
66
+ * @cssprop --cosm-popover-padding - Panel padding.
67
+ * @cssprop --cosm-popover-radius - Panel corner radius.
68
+ * @cssprop --cosm-popover-shadow - Panel shadow.
69
+ * @remarks Uses the native manual Popover API to escape clipping and transformed ancestors when
70
+ * available. Without that API, it falls back to fixed positioning, which can still be clipped or
71
+ * displaced by ancestor overflow, transforms or containment.
72
+ */
73
+ export class CosmPopover extends CosmElement {
74
+ static shadowRootOptions = {
75
+ ...LitElement.shadowRootOptions,
76
+ delegatesFocus: true,
77
+ };
78
+ static properties = {
79
+ open: { type: Boolean, reflect: true },
80
+ defaultOpen: { type: Boolean, attribute: 'default-open' },
81
+ triggerMode: { attribute: 'trigger-mode' },
82
+ closable: { type: Boolean },
83
+ closeLabel: { attribute: 'close-label' },
84
+ arrow: { type: Boolean },
85
+ closeOnEscape: { type: Boolean, attribute: 'close-on-escape' },
86
+ closeOnOutsidePress: { type: Boolean, attribute: 'close-on-outside-press' },
87
+ side: { reflect: true },
88
+ align: { reflect: true },
89
+ };
90
+ static styles = [boxSizing, focusRing, styles];
91
+ /** Set by adapters to distinguish a bound `open` value from autonomous state. */
92
+ openControlled = false;
93
+ #open = false;
94
+ #writingOpen = false;
95
+ #initialized = false;
96
+ #edited = false;
97
+ #pendingRestoreReason;
98
+ #focusWasInsideBeforeClose = false;
99
+ #openListenersInstalled = false;
100
+ #inTopLayer = false;
101
+ #resizeObserver;
102
+ #triggerAttributes = new Map();
103
+ #hovered = false;
104
+ #focused = false;
105
+ #hoverDismissed = false;
106
+ #hoverTimer;
107
+ #openingReason;
108
+ #themeObserver;
109
+ #pressStartedClosed = false;
110
+ get open() {
111
+ return this.#open;
112
+ }
113
+ set open(value) {
114
+ if (value === undefined) {
115
+ this.openControlled = false;
116
+ return;
117
+ }
118
+ if (!this.#writingOpen)
119
+ this.openControlled = true;
120
+ this.#setOpen(Boolean(value));
121
+ }
122
+ constructor() {
123
+ super();
124
+ const props = popoverContract.props;
125
+ this.defaultOpen = props.defaultOpen.default;
126
+ this.triggerMode = props.triggerMode.default;
127
+ this.closable = props.closable.default;
128
+ this.closeLabel = props.closeLabel.default;
129
+ this.arrow = props.arrow.default;
130
+ this.closeOnEscape = props.closeOnEscape.default;
131
+ this.closeOnOutsidePress = props.closeOnOutsidePress.default;
132
+ this.side = props.side.default;
133
+ this.align = props.align.default;
134
+ this.#setOpen(props.open.default);
135
+ }
136
+ connectedCallback() {
137
+ super.connectedCallback();
138
+ this.addEventListener('click', this.#onHostClick);
139
+ this.addEventListener('pointerdown', this.#onTriggerPointerDown);
140
+ this.addEventListener('pointerover', this.#onPointerOver);
141
+ this.addEventListener('pointerout', this.#onPointerOut);
142
+ this.addEventListener('focusin', this.#onFocusIn);
143
+ this.addEventListener('focusout', this.#onFocusOut);
144
+ document.addEventListener('pointermove', this.#onPointerMove);
145
+ this.#themeObserver = new MutationObserver(() => this.#positionPanel());
146
+ for (let ancestor = this; ancestor; ancestor = ancestor.parentElement) {
147
+ this.#themeObserver.observe(ancestor, {
148
+ attributes: true,
149
+ attributeFilter: ['class', 'style', 'data-theme', 'data-mode'],
150
+ });
151
+ }
152
+ this.#syncTriggerExpanded();
153
+ if (this.open) {
154
+ void this.updateComplete.then(() => {
155
+ if (this.isConnected && this.open) {
156
+ this.#showPanelInTopLayer();
157
+ this.#installOpenListeners();
158
+ this.#positionPanel();
159
+ }
160
+ });
161
+ }
162
+ }
163
+ disconnectedCallback() {
164
+ this.removeEventListener('click', this.#onHostClick);
165
+ this.removeEventListener('pointerdown', this.#onTriggerPointerDown);
166
+ this.removeEventListener('pointerover', this.#onPointerOver);
167
+ this.removeEventListener('pointerout', this.#onPointerOut);
168
+ this.removeEventListener('focusin', this.#onFocusIn);
169
+ this.removeEventListener('focusout', this.#onFocusOut);
170
+ document.removeEventListener('pointermove', this.#onPointerMove);
171
+ clearTimeout(this.#hoverTimer);
172
+ this.#themeObserver?.disconnect();
173
+ this.#hidePanelFromTopLayer();
174
+ this.#removeOpenListeners();
175
+ this.#restoreTriggerAttributes();
176
+ super.disconnectedCallback();
177
+ }
178
+ willUpdate() {
179
+ if (this.closable && !this.closeLabel?.trim()) {
180
+ throw new Error('cosm-popover requires a non-empty closeLabel when closable.');
181
+ }
182
+ if (!this.#initialized) {
183
+ this.#initialized = true;
184
+ if (!this.openControlled && !this.#edited)
185
+ this.#setOpen(this.defaultOpen);
186
+ }
187
+ }
188
+ updated(changed) {
189
+ if (changed.has('open')) {
190
+ this.#syncTriggerExpanded();
191
+ if (this.open) {
192
+ this.#showPanelInTopLayer();
193
+ this.#installOpenListeners();
194
+ this.#positionPanel();
195
+ }
196
+ else {
197
+ this.#hidePanelFromTopLayer();
198
+ this.#removeOpenListeners();
199
+ if (this.#pendingRestoreReason && this.#pendingRestoreReason !== 'outside') {
200
+ this.#restoreFocusToTrigger();
201
+ }
202
+ this.#pendingRestoreReason = undefined;
203
+ this.#focusWasInsideBeforeClose = false;
204
+ }
205
+ }
206
+ if (changed.has('side') ||
207
+ changed.has('align') ||
208
+ changed.has('arrow') ||
209
+ changed.has('closable')) {
210
+ this.#positionPanel();
211
+ }
212
+ if (changed.has('triggerMode')) {
213
+ clearTimeout(this.#hoverTimer);
214
+ this.#hoverDismissed = false;
215
+ }
216
+ }
217
+ /** Requests closure with reason `action` only while the panel is open. */
218
+ requestClose() {
219
+ if (this.open)
220
+ this.#propose(false, 'action');
221
+ }
222
+ #setOpen(value) {
223
+ if (value === this.#open)
224
+ return;
225
+ const previous = this.#open;
226
+ this.#focusWasInsideBeforeClose =
227
+ previous && !value ? this.#isInsidePanel(this.#activeElement()) : false;
228
+ this.#open = value;
229
+ this.requestUpdate('open', previous);
230
+ }
231
+ #commitOpen(value) {
232
+ this.#writingOpen = true;
233
+ this.open = value;
234
+ this.#writingOpen = false;
235
+ }
236
+ #propose(open, reason) {
237
+ if (open === this.open)
238
+ return;
239
+ this.#edited = true;
240
+ if (open) {
241
+ this.#pendingRestoreReason = undefined;
242
+ this.#openingReason = reason === 'hover' || reason === 'focus' ? reason : 'trigger';
243
+ }
244
+ let event;
245
+ if (open) {
246
+ event = new CustomEvent('cosm-open-change', {
247
+ detail: { open: true, reason: this.#openingReason ?? 'trigger' },
248
+ bubbles: true,
249
+ composed: true,
250
+ cancelable: false,
251
+ });
252
+ }
253
+ else {
254
+ let detailPrevented = false;
255
+ const detail = {
256
+ open: false,
257
+ reason,
258
+ get defaultPrevented() {
259
+ return detailPrevented || Boolean(event?.defaultPrevented);
260
+ },
261
+ preventDefault() {
262
+ detailPrevented = true;
263
+ event?.preventDefault();
264
+ },
265
+ };
266
+ event = new CustomEvent('cosm-open-change', {
267
+ detail,
268
+ bubbles: true,
269
+ composed: true,
270
+ cancelable: true,
271
+ });
272
+ }
273
+ // Constructing the event here lets detail.preventDefault() and event.preventDefault()
274
+ // share cancellation state synchronously, including while a wrapper callback is running.
275
+ this.dispatchEvent(event);
276
+ const canceled = event.defaultPrevented;
277
+ if (!open && canceled) {
278
+ this.#pendingRestoreReason = undefined;
279
+ return;
280
+ }
281
+ if (open) {
282
+ if (!this.openControlled)
283
+ this.#commitOpen(true);
284
+ return;
285
+ }
286
+ if (reason !== 'hover' && reason !== 'focus' && this.triggerMode === 'hover') {
287
+ this.#hoverDismissed = this.#hovered || this.#focused;
288
+ clearTimeout(this.#hoverTimer);
289
+ }
290
+ this.#pendingRestoreReason = reason;
291
+ if (!this.openControlled)
292
+ this.#commitOpen(false);
293
+ }
294
+ #onTriggerClick = () => {
295
+ this.#propose(!this.open, 'trigger');
296
+ };
297
+ #onHostClick = (event) => {
298
+ const path = event.composedPath();
299
+ if (this.#triggerSlot()
300
+ ?.assignedElements({ flatten: true })
301
+ .some(element => path.includes(element))) {
302
+ // Touch focus can open hover mode between pointerdown and its resulting click.
303
+ if (this.#pressStartedClosed && this.open && this.#openingReason === 'focus') {
304
+ this.#pressStartedClosed = false;
305
+ return;
306
+ }
307
+ this.#pressStartedClosed = false;
308
+ this.#onTriggerClick();
309
+ }
310
+ };
311
+ #onTriggerPointerDown = (event) => {
312
+ const trigger = this.#triggerElement();
313
+ this.#pressStartedClosed = Boolean(this.triggerMode === 'hover' &&
314
+ !this.open &&
315
+ trigger &&
316
+ event.composedPath().includes(trigger));
317
+ };
318
+ #inside(target) {
319
+ if (!(target instanceof Node))
320
+ return false;
321
+ let node = target;
322
+ while (node) {
323
+ if (node === this || this.contains(node))
324
+ return true;
325
+ const root = node.getRootNode();
326
+ node = root instanceof ShadowRoot ? root.host : null;
327
+ }
328
+ return false;
329
+ }
330
+ #scheduleHoverClose(reason) {
331
+ clearTimeout(this.#hoverTimer);
332
+ if (this.#hovered || this.#focused)
333
+ return;
334
+ this.#hoverDismissed = false;
335
+ if (!this.open || this.triggerMode !== 'hover')
336
+ return;
337
+ this.#hoverTimer = setTimeout(() => {
338
+ if (!this.#hovered && !this.#focused)
339
+ this.#propose(false, reason);
340
+ }, 150);
341
+ }
342
+ #onPointerOver = (event) => {
343
+ if (event.pointerType === 'touch' || this.triggerMode !== 'hover')
344
+ return;
345
+ this.#hovered = true;
346
+ clearTimeout(this.#hoverTimer);
347
+ const trigger = this.#triggerElement();
348
+ if (!this.#hoverDismissed && trigger && event.composedPath().includes(trigger)) {
349
+ this.#propose(true, 'hover');
350
+ }
351
+ };
352
+ #onPointerOut = (event) => {
353
+ if (event.pointerType === 'touch' || this.#inside(event.relatedTarget))
354
+ return;
355
+ this.#hovered = false;
356
+ this.#scheduleHoverClose('hover');
357
+ };
358
+ #inHoverBridge(x, y) {
359
+ const trigger = this.#triggerElement()?.getBoundingClientRect();
360
+ const panel = this.#panel();
361
+ if (!trigger || !panel || !this.open)
362
+ return false;
363
+ const rect = panel.getBoundingClientRect();
364
+ const side = panel.dataset.placement;
365
+ const vertical = side === 'top' || side === 'bottom';
366
+ const start = vertical
367
+ ? side === 'bottom'
368
+ ? trigger.bottom
369
+ : rect.bottom
370
+ : side === 'right'
371
+ ? trigger.right
372
+ : rect.right;
373
+ const end = vertical
374
+ ? side === 'bottom'
375
+ ? rect.top
376
+ : trigger.top
377
+ : side === 'right'
378
+ ? rect.left
379
+ : trigger.left;
380
+ const main = vertical ? y : x;
381
+ if (end <= start || main < start || main > end)
382
+ return false;
383
+ const from = side === 'bottom' || side === 'right' ? trigger : rect;
384
+ const to = from === trigger ? rect : trigger;
385
+ const progress = (main - start) / (end - start);
386
+ const min = vertical ? 'left' : 'top';
387
+ const max = vertical ? 'right' : 'bottom';
388
+ const low = from[min] + (to[min] - from[min]) * progress;
389
+ const high = from[max] + (to[max] - from[max]) * progress;
390
+ const cross = vertical ? x : y;
391
+ return cross >= low - 4 && cross <= high + 4;
392
+ }
393
+ #onPointerMove = (event) => {
394
+ if (event.pointerType === 'touch' || this.triggerMode !== 'hover')
395
+ return;
396
+ this.#hovered =
397
+ event.composedPath().includes(this) || this.#inHoverBridge(event.clientX, event.clientY);
398
+ if (this.#hovered)
399
+ clearTimeout(this.#hoverTimer);
400
+ else
401
+ this.#scheduleHoverClose('hover');
402
+ };
403
+ #onFocusIn = (event) => {
404
+ this.#focused = true;
405
+ clearTimeout(this.#hoverTimer);
406
+ const trigger = this.#triggerElement();
407
+ if (this.triggerMode === 'hover' &&
408
+ !this.#hoverDismissed &&
409
+ trigger &&
410
+ event.composedPath().includes(trigger)) {
411
+ this.#propose(true, 'focus');
412
+ }
413
+ };
414
+ #onFocusOut = (event) => {
415
+ if (this.#inside(event.relatedTarget))
416
+ return;
417
+ this.#focused = false;
418
+ this.#scheduleHoverClose('focus');
419
+ };
420
+ #onTriggerSlotChange = () => {
421
+ this.#syncTriggerExpanded();
422
+ };
423
+ #onKeyDown = (event) => {
424
+ if (this.open && this.closeOnEscape && event.key === 'Escape' && !event.defaultPrevented) {
425
+ event.preventDefault();
426
+ this.#propose(false, 'escape');
427
+ }
428
+ };
429
+ #onDocumentPointerDown = (event) => {
430
+ if (!this.open || !this.closeOnOutsidePress)
431
+ return;
432
+ if (event.composedPath().includes(this))
433
+ return;
434
+ // Do not cancel, stop or redirect the outside interaction.
435
+ this.#propose(false, 'outside');
436
+ };
437
+ #onViewportChange = () => {
438
+ this.#positionPanel();
439
+ };
440
+ #onResize = () => {
441
+ this.#positionPanel();
442
+ };
443
+ #installOpenListeners() {
444
+ if (!this.isConnected || this.#openListenersInstalled)
445
+ return;
446
+ this.#openListenersInstalled = true;
447
+ document.addEventListener('keydown', this.#onKeyDown);
448
+ document.addEventListener('pointerdown', this.#onDocumentPointerDown, true);
449
+ window.addEventListener('resize', this.#onViewportChange);
450
+ window.addEventListener('scroll', this.#onViewportChange, true);
451
+ window.addEventListener('orientationchange', this.#onViewportChange);
452
+ window.visualViewport?.addEventListener('resize', this.#onViewportChange);
453
+ window.visualViewport?.addEventListener('scroll', this.#onViewportChange);
454
+ const trigger = this.#triggerElement();
455
+ const panel = this.#panel();
456
+ if (typeof ResizeObserver !== 'undefined' && trigger && panel) {
457
+ this.#resizeObserver = new ResizeObserver(this.#onResize);
458
+ this.#resizeObserver.observe(trigger);
459
+ this.#resizeObserver.observe(panel);
460
+ }
461
+ }
462
+ #removeOpenListeners() {
463
+ this.#openListenersInstalled = false;
464
+ document.removeEventListener('keydown', this.#onKeyDown);
465
+ document.removeEventListener('pointerdown', this.#onDocumentPointerDown, true);
466
+ window.removeEventListener('resize', this.#onViewportChange);
467
+ window.removeEventListener('scroll', this.#onViewportChange, true);
468
+ window.removeEventListener('orientationchange', this.#onViewportChange);
469
+ window.visualViewport?.removeEventListener('resize', this.#onViewportChange);
470
+ window.visualViewport?.removeEventListener('scroll', this.#onViewportChange);
471
+ this.#resizeObserver?.disconnect();
472
+ this.#resizeObserver = undefined;
473
+ }
474
+ #triggerSlot() {
475
+ return this.renderRoot.querySelector('slot[name="trigger"]');
476
+ }
477
+ #panelSlot() {
478
+ return this.renderRoot.querySelector('.panel slot');
479
+ }
480
+ #panel() {
481
+ return this.renderRoot.querySelector('.panel');
482
+ }
483
+ #showPanelInTopLayer() {
484
+ const panel = this.#panel();
485
+ if (!panel)
486
+ return;
487
+ if (typeof panel.showPopover !== 'function' || typeof panel.hidePopover !== 'function') {
488
+ panel.removeAttribute('popover');
489
+ return;
490
+ }
491
+ if (this.#inTopLayer)
492
+ return;
493
+ panel.showPopover();
494
+ this.#inTopLayer = true;
495
+ }
496
+ #hidePanelFromTopLayer() {
497
+ const panel = this.#panel();
498
+ if (!panel || !this.#inTopLayer || typeof panel.hidePopover !== 'function')
499
+ return;
500
+ if (!panel.isConnected) {
501
+ this.#inTopLayer = false;
502
+ return;
503
+ }
504
+ panel.hidePopover();
505
+ this.#inTopLayer = false;
506
+ }
507
+ #triggerElement() {
508
+ return this.#triggerSlot()?.assignedElements({ flatten: true })[0] ?? null;
509
+ }
510
+ #syncTriggerExpanded() {
511
+ const assigned = this.#triggerSlot()?.assignedElements({ flatten: true }) ?? [];
512
+ const current = new Set(assigned);
513
+ for (const element of assigned) {
514
+ const button = element.shadowRoot?.querySelector('button');
515
+ if (button)
516
+ current.add(button);
517
+ }
518
+ for (const [element, previous] of this.#triggerAttributes) {
519
+ if (!current.has(element)) {
520
+ if (previous === null)
521
+ element.removeAttribute('aria-expanded');
522
+ else
523
+ element.setAttribute('aria-expanded', previous);
524
+ this.#triggerAttributes.delete(element);
525
+ }
526
+ }
527
+ for (const element of current) {
528
+ if (!this.#triggerAttributes.has(element)) {
529
+ this.#triggerAttributes.set(element, element.getAttribute('aria-expanded'));
530
+ }
531
+ element.setAttribute('aria-expanded', String(this.open));
532
+ }
533
+ for (const element of assigned) {
534
+ if (element.localName === 'cosm-icon-button' &&
535
+ 'updateComplete' in element &&
536
+ !element.shadowRoot?.querySelector('button')) {
537
+ void Promise.resolve(element.updateComplete).then(() => {
538
+ if (element.isConnected && this.isConnected)
539
+ this.#syncTriggerExpanded();
540
+ });
541
+ }
542
+ }
543
+ }
544
+ #restoreTriggerAttributes() {
545
+ for (const [element, previous] of this.#triggerAttributes) {
546
+ if (previous === null)
547
+ element.removeAttribute('aria-expanded');
548
+ else
549
+ element.setAttribute('aria-expanded', previous);
550
+ }
551
+ this.#triggerAttributes.clear();
552
+ }
553
+ #focusable(element) {
554
+ if (element.hasAttribute('hidden') || element.closest('[hidden], [inert]'))
555
+ return false;
556
+ if ('disabled' in element && element.disabled)
557
+ return false;
558
+ if (element.getAttribute('aria-disabled') === 'true')
559
+ return false;
560
+ const button = element.shadowRoot?.querySelector('button');
561
+ if (button)
562
+ return !button.disabled;
563
+ return (element.tabIndex >= 0 ||
564
+ (element.hasAttribute('tabindex') && element.tabIndex === -1) ||
565
+ element.matches('a[href], area[href], button, input, select, textarea, summary, iframe'));
566
+ }
567
+ #activeElement() {
568
+ return this.shadowRoot?.activeElement ?? document.activeElement;
569
+ }
570
+ #isInsidePanel(element) {
571
+ if (!element)
572
+ return false;
573
+ const panel = this.#panel();
574
+ if (panel?.contains(element))
575
+ return true;
576
+ return (this.#panelSlot()?.assignedElements({ flatten: true }) ?? []).some(assigned => assigned === element || assigned.contains(element));
577
+ }
578
+ #restoreFocusToTrigger() {
579
+ const active = this.#activeElement();
580
+ const focusWasLostByHiding = this.#focusWasInsideBeforeClose &&
581
+ (active === document.body || active === document.documentElement || active === this);
582
+ if (!this.#isInsidePanel(active) && !focusWasLostByHiding)
583
+ return;
584
+ const trigger = this.#triggerElement();
585
+ if (!trigger?.isConnected || !this.#focusable(trigger))
586
+ return;
587
+ trigger.focus();
588
+ }
589
+ /** Trigger-to-panel distance: the theme `space-sm` token, resolved to pixels by the probe. */
590
+ #gap() {
591
+ const probe = this.renderRoot.querySelector('.safe-area-probe');
592
+ const resolved = probe ? getComputedStyle(probe).columnGap : '';
593
+ const value = resolved.endsWith('px') ? Number.parseFloat(resolved) : Number.NaN;
594
+ return Number.isFinite(value) && value >= 0 ? value : 8;
595
+ }
596
+ #viewportBounds() {
597
+ const viewport = window.visualViewport;
598
+ const left = viewport?.offsetLeft ?? 0;
599
+ const top = viewport?.offsetTop ?? 0;
600
+ const width = viewport?.width ?? window.innerWidth;
601
+ const height = viewport?.height ?? window.innerHeight;
602
+ const probe = this.renderRoot.querySelector('.safe-area-probe');
603
+ const padding = probe ? getComputedStyle(probe) : null;
604
+ const safeTop = Number.parseFloat(padding?.paddingTop ?? '') || 0;
605
+ const safeRight = Number.parseFloat(padding?.paddingRight ?? '') || 0;
606
+ const safeBottom = Number.parseFloat(padding?.paddingBottom ?? '') || 0;
607
+ const safeLeft = Number.parseFloat(padding?.paddingLeft ?? '') || 0;
608
+ return {
609
+ left: left + safeLeft + 8,
610
+ top: top + safeTop + 8,
611
+ right: left + width - safeRight - 8,
612
+ bottom: top + height - safeBottom - 8,
613
+ };
614
+ }
615
+ #coordinates(side, trigger, panelWidth, panelHeight) {
616
+ const rtl = getComputedStyle(this).direction === 'rtl';
617
+ const horizontalAlign = this.align === 'center'
618
+ ? trigger.left + (trigger.width - panelWidth) / 2
619
+ : this.align === 'start'
620
+ ? rtl
621
+ ? trigger.right - panelWidth
622
+ : trigger.left
623
+ : rtl
624
+ ? trigger.left
625
+ : trigger.right - panelWidth;
626
+ const verticalAlign = this.align === 'center'
627
+ ? trigger.top + (trigger.height - panelHeight) / 2
628
+ : this.align === 'start'
629
+ ? trigger.top
630
+ : trigger.bottom - panelHeight;
631
+ const distance = this.#gap() + (this.arrow ? 8 : 0);
632
+ switch (side) {
633
+ case 'top':
634
+ return { left: horizontalAlign, top: trigger.top - panelHeight - distance };
635
+ case 'bottom':
636
+ return { left: horizontalAlign, top: trigger.bottom + distance };
637
+ case 'left':
638
+ return { left: trigger.left - panelWidth - distance, top: verticalAlign };
639
+ case 'right':
640
+ return { left: trigger.right + distance, top: verticalAlign };
641
+ }
642
+ }
643
+ #mainOverflow(side, point, panel, bounds) {
644
+ if (side === 'top' || side === 'bottom') {
645
+ return (Math.max(0, bounds.top - point.top) + Math.max(0, point.top + panel.height - bounds.bottom));
646
+ }
647
+ return (Math.max(0, bounds.left - point.left) + Math.max(0, point.left + panel.width - bounds.right));
648
+ }
649
+ #positionPanel() {
650
+ if (!this.open)
651
+ return;
652
+ const trigger = this.#triggerElement();
653
+ const panel = this.#panel();
654
+ if (!trigger || !panel)
655
+ return;
656
+ const bounds = this.#viewportBounds();
657
+ const availableWidth = Math.max(0, bounds.right - bounds.left);
658
+ const availableHeight = Math.max(0, bounds.bottom - bounds.top);
659
+ panel.style.maxWidth = `${availableWidth}px`;
660
+ panel.style.maxHeight = `${availableHeight}px`;
661
+ const triggerRect = trigger.getBoundingClientRect();
662
+ const panelRect = panel.getBoundingClientRect();
663
+ const opposite = {
664
+ top: 'bottom',
665
+ bottom: 'top',
666
+ left: 'right',
667
+ right: 'left',
668
+ };
669
+ let side = this.side;
670
+ let point = this.#coordinates(side, triggerRect, panelRect.width, panelRect.height);
671
+ // Flip only when the opposite side reduces main-axis overflow; ties keep the request.
672
+ const flippedSide = opposite[side];
673
+ const flippedPoint = this.#coordinates(flippedSide, triggerRect, panelRect.width, panelRect.height);
674
+ if (this.#mainOverflow(flippedSide, flippedPoint, panelRect, bounds) <
675
+ this.#mainOverflow(side, point, panelRect, bounds)) {
676
+ side = flippedSide;
677
+ point = flippedPoint;
678
+ }
679
+ // Then shift within the available viewport/safe-area bounds.
680
+ point.left = Math.min(Math.max(point.left, bounds.left), Math.max(bounds.left, bounds.right - panelRect.width));
681
+ point.top = Math.min(Math.max(point.top, bounds.top), Math.max(bounds.top, bounds.bottom - panelRect.height));
682
+ panel.style.left = `${point.left}px`;
683
+ panel.style.top = `${point.top}px`;
684
+ panel.dataset.placement = side;
685
+ this.#positionArrow(panel, triggerRect, panelRect, point, side, bounds);
686
+ }
687
+ #positionArrow(panel, trigger, rect, point, side, bounds) {
688
+ const arrow = this.renderRoot.querySelector('.arrow');
689
+ if (!arrow)
690
+ return;
691
+ const vertical = side === 'top' || side === 'bottom';
692
+ const center = vertical
693
+ ? trigger.left + trigger.width / 2 - point.left
694
+ : trigger.top + trigger.height / 2 - point.top;
695
+ const computed = getComputedStyle(panel);
696
+ const radius = Math.max(...[
697
+ computed.borderTopLeftRadius,
698
+ computed.borderTopRightRadius,
699
+ computed.borderBottomLeftRadius,
700
+ computed.borderBottomRightRadius,
701
+ ].map(value => Number.parseFloat(value) || 0));
702
+ const size = vertical ? rect.width : rect.height;
703
+ const border = Number.parseFloat(computed.borderTopWidth) || 0;
704
+ const depth = 8;
705
+ const tip = side === 'top'
706
+ ? point.top + rect.height + depth
707
+ : side === 'bottom'
708
+ ? point.top - depth
709
+ : side === 'left'
710
+ ? point.left + rect.width + depth
711
+ : point.left - depth;
712
+ const facing = side === 'top'
713
+ ? tip <= trigger.top
714
+ : side === 'bottom'
715
+ ? tip >= trigger.bottom
716
+ : side === 'left'
717
+ ? tip <= trigger.left
718
+ : tip >= trigger.right;
719
+ const tipWithinBounds = vertical
720
+ ? tip >= bounds.top && tip <= bounds.bottom
721
+ : tip >= bounds.left && tip <= bounds.right;
722
+ arrow.style.display =
723
+ this.arrow && facing && tipWithinBounds && center >= radius + 8 && center <= size - radius - 8
724
+ ? ''
725
+ : 'none';
726
+ arrow.style.height = vertical ? `${8 + border}px` : '16px';
727
+ arrow.style.width = vertical ? '16px' : `${8 + border}px`;
728
+ arrow.style.left = vertical
729
+ ? `${center - 8 - border}px`
730
+ : side === 'right'
731
+ ? `${-8 - border}px`
732
+ : `${rect.width - border * 2}px`;
733
+ arrow.style.top = vertical
734
+ ? side === 'bottom'
735
+ ? `${-8 - border}px`
736
+ : `${rect.height - border * 2}px`
737
+ : `${center - 8 - border}px`;
738
+ const path = arrow.querySelector('path');
739
+ if (!path)
740
+ return;
741
+ path.setAttribute('d', vertical
742
+ ? side === 'bottom'
743
+ ? `M0 ${8 + border} L8 0 L16 ${8 + border}`
744
+ : `M0 0 L8 ${8 + border} L16 0`
745
+ : side === 'right'
746
+ ? `M${8 + border} 0 L0 8 L${8 + border} 16`
747
+ : `M0 0 L${8 + border} 8 L0 16`);
748
+ path.setAttribute('fill', computed.backgroundColor);
749
+ path.setAttribute('stroke', computed.borderTopColor);
750
+ path.setAttribute('stroke-width', String(border));
751
+ }
752
+ render() {
753
+ return html `
754
+ <div
755
+ part="trigger"
756
+ class="trigger"
757
+ aria-expanded=${String(this.open)}
758
+ >
759
+ <slot name="trigger" @slotchange=${this.#onTriggerSlotChange}></slot>
760
+ </div>
761
+ <div part="panel" class="panel" popover="manual" ?hidden=${!this.open} tabindex="-1">
762
+ ${this.arrow ? html `<svg part="arrow" class="arrow" aria-hidden="true" focusable="false"><path /></svg>` : nothing}
763
+ ${this.closable
764
+ ? html `<cosm-icon-button
765
+ part="close" class="close" variant="ghost" tone="neutral" size="sm"
766
+ .label=${this.closeLabel} @cosm-press=${() => this.#propose(false, 'close-button')}
767
+ ><cosm-icon .icon=${x}></cosm-icon></cosm-icon-button>`
768
+ : nothing}
769
+ <div part="body" class="body"><slot></slot></div>
770
+ </div>
771
+ <span class="safe-area-probe" aria-hidden="true"></span>
772
+ `;
773
+ }
774
+ }
775
+ define('cosm-popover', CosmPopover);
776
+ //# sourceMappingURL=cosm-popover.js.map