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