import { beforeEach, describe, expect, it, vi } from 'vitest'; import { FLOATING_PRESENCE_ATTR, FloatingController, floatingPanelsWithin } from '@/utils/floating'; /** * The controller r-select and r-popover both position through. * * jsdom lays nothing out, so the geometry is exercised where it belongs — in * `computePlacement`'s own tests, and in the browser through each component's * e2e specs. What is worth pinning here is the part that is pure state: that * `apply` is the single writer of display and `aria-expanded`, that the four * lifecycle events fire in order, and that a transition already in flight * cannot reach back and undo the one that replaced it. */ const mount = (): { host: HTMLElement; panel: HTMLElement } => { const host = document.createElement('div'); const panel = document.createElement('div'); panel.style.setProperty('display', 'none'); document.body.append(host, panel); return { host, panel }; }; const nextFrame = (): Promise => new Promise((resolve) => requestAnimationFrame(() => resolve())); const controllerFor = (host: HTMLElement, panel: HTMLElement, extra = {}): FloatingController => new FloatingController({ host, panel: () => panel, placement: () => 'bottom', offset: 4, ...extra, }); describe('FloatingController', () => { beforeEach(() => { document.body.innerHTML = ''; }); it('is the only writer of display and aria-expanded, and they agree', () => { const { host, panel } = mount(); const controller = controllerFor(host, panel); controller.apply(true); expect(panel.style.display).toBe('block'); expect(host.getAttribute('aria-expanded')).toBe('true'); controller.apply(false); expect(panel.style.display).toBe('none'); expect(host.getAttribute('aria-expanded')).toBe('false'); }); it('fires show then after-show on open, and hide then after-hide on close', async () => { const { host, panel } = mount(); const controller = controllerFor(host, panel); const seen: string[] = []; for (const name of ['show', 'after-show', 'hide', 'after-hide']) { host.addEventListener(name, () => seen.push(name)); } controller.apply(true); // The entrance class is written a frame after the panel is shown -- the flip // decision needs a laid-out panel -- and only then can anything wait on the // animation, so `after-show` lands one frame behind `show` by design. await nextFrame(); controller.apply(false); expect(seen).toEqual(['show', 'after-show', 'hide', 'after-hide']); }); it('announces the state before the panel finishes animating into it', () => { // `show` is the intent, `after-show` the arrival. Assistive tech should not // have to wait out an animation to be told what happened, which is why // aria-expanded is written up front rather than in the tail. const { host, panel } = mount(); const controller = controllerFor(host, panel); let ariaAtShow: string | null = null; host.addEventListener('show', () => { ariaAtShow = host.getAttribute('aria-expanded'); }); controller.apply(true); expect(ariaAtShow).toBe('true'); }); it('lets a re-open cancel the close that was still finishing', async () => { // The close's tail hides the panel. Without the generation check it would // run anyway and hide a panel that had since been re-opened — the same // class of bug as the swallowed click, one layer down. const { host, panel } = mount(); const controller = controllerFor(host, panel); const afterHide = vi.fn(); host.addEventListener('after-hide', afterHide); controller.apply(true); await nextFrame(); controller.apply(false); controller.apply(true); await nextFrame(); expect(panel.style.display).toBe('block'); // The superseded close must not report completion either. expect(afterHide).toHaveBeenCalledTimes(1); }); it('closing an already-closed panel is a no-op, not a second hide', () => { const { host, panel } = mount(); const controller = controllerFor(host, panel); const hide = vi.fn(); host.addEventListener('hide', hide); controller.apply(false); expect(hide).not.toHaveBeenCalled(); expect(panel.style.display).toBe('none'); }); it('rejects an entrance frame queued before immediate close', async () => { const { host, panel } = mount(); const controller = controllerFor(host, panel); controller.apply(true); controller.apply(false); await nextFrame(); expect(panel.style.display).toBe('none'); expect(panel.hasAttribute('transit')).toBe(false); expect(host.getAttribute('aria-expanded')).toBe('false'); }); it('rejects queued positioning after the controller is destroyed', async () => { const { host, panel } = mount(); const controller = controllerFor(host, panel); controller.apply(true); expect(controller.isPositioned).toBe(true); controller.destroy(); await nextFrame(); expect(panel.hasAttribute('transit')).toBe(false); expect(panel.hasAttribute(FLOATING_PRESENCE_ATTR)).toBe(false); expect(controller.isPositioned).toBe(false); }); it('still reports the state when there is no panel yet', () => { // Components build their panel lazily; the attribute can be set first. const host = document.createElement('div'); document.body.appendChild(host); const controller = new FloatingController({ host, panel: () => null, placement: () => 'bottom' }); controller.apply(true); expect(host.getAttribute('aria-expanded')).toBe('true'); }); it('positions against the anchor when one is given rather than the host', async () => { const { host, panel } = mount(); const anchor = document.createElement('div'); document.body.appendChild(anchor); anchor.getBoundingClientRect = () => ({ top: 100, left: 200, width: 50, height: 20, bottom: 120, right: 250 }) as DOMRect; const controller = controllerFor(host, panel, { anchor: () => anchor }); controller.apply(true); await nextFrame(); controller.position(); // bottom placement, 4px offset: 120 + 4. Left edges align. expect(panel.style.getPropertyValue('--ran-y')).toBe('124px'); expect(panel.style.getPropertyValue('--ran-x')).toBe('200px'); }); it('aligns to the anchor inside a custom container too', async () => { const { host, panel } = mount(); const container = document.createElement('div'); container.id = 'floating-container'; document.body.appendChild(container); container.getBoundingClientRect = () => ({ top: 10, left: 20, width: 500, height: 400, bottom: 410, right: 520 }) as DOMRect; host.getBoundingClientRect = () => ({ top: 100, left: 200, width: 50, height: 20, bottom: 120, right: 250 }) as DOMRect; panel.getBoundingClientRect = () => ({ top: 0, left: 0, width: 120, height: 60, bottom: 60, right: 120 }) as DOMRect; const controller = controllerFor(host, panel, { containerId: () => 'floating-container', placement: () => 'bottom-end', }); controller.apply(true); await nextFrame(); controller.position(); // Trailing edges together: anchor ends at 250, a 120px panel starts at 130, // expressed relative to the container's own left edge (20). expect(panel.style.getPropertyValue('--ran-x')).toBe('110px'); expect(panel.style.getPropertyValue('--ran-y')).toBe('114px'); }); it('positions against the measured panel size when the host box understates it', async () => { // A consumer can widen the painted panel past the host (`::part(dropdown)`), // and that overflow is invisible to the host's rect. const { host, panel } = mount(); host.getBoundingClientRect = () => ({ top: 100, left: 200, width: 50, height: 20, bottom: 120, right: 250 }) as DOMRect; panel.getBoundingClientRect = () => ({ top: 0, left: 0, width: 50, height: 60, bottom: 60, right: 50 }) as DOMRect; const controller = controllerFor(host, panel, { containerId: () => '', placement: () => 'bottom-end', measurePanel: () => ({ width: 200, height: 60 }), }); controller.apply(true); await nextFrame(); controller.position(); // Aligned against 200px, not the 50px the host box reports: 250 - 200. expect(panel.style.getPropertyValue('--ran-x')).toBe('50px'); }); it('follows the anchor while open and stops when closed or destroyed', () => { const { host, panel } = mount(); const controller = controllerFor(host, panel); const add = vi.spyOn(window, 'addEventListener'); const remove = vi.spyOn(window, 'removeEventListener'); controller.apply(true); expect(add.mock.calls.some((c) => c[0] === 'scroll')).toBe(true); expect(add.mock.calls.some((c) => c[0] === 'resize')).toBe(true); controller.apply(false); expect(remove.mock.calls.some((c) => c[0] === 'scroll')).toBe(true); remove.mockClear(); controller.apply(true); controller.destroy(); expect(remove.mock.calls.some((c) => c[0] === 'scroll')).toBe(true); add.mockRestore(); remove.mockRestore(); }); it('does not re-pin the panel when the scroll is inside the panel itself', async () => { // A long select list overflows on the panel. Capture-phase window scroll // still sees those events; treating them like page scroll made the menu // flash on every wheel tick while the pointer stayed put. const { host, panel } = mount(); const controller = controllerFor(host, panel); controller.apply(true); await nextFrame(); const position = vi.spyOn(controller, 'position'); const scroll = new Event('scroll', { bubbles: true }); Object.defineProperty(scroll, 'target', { value: panel }); window.dispatchEvent(scroll); await nextFrame(); expect(position).not.toHaveBeenCalled(); // A page (or outer scroller) scroll still must follow the anchor. const pageScroll = new Event('scroll', { bubbles: true }); Object.defineProperty(pageScroll, 'target', { value: document }); window.dispatchEvent(pageScroll); await nextFrame(); expect(position).toHaveBeenCalled(); position.mockRestore(); }); it('hands the hooks the resolved side and alignment', async () => { const { host, panel } = mount(); const afterPosition = vi.fn(); const beforeMeasure = vi.fn(); const controller = controllerFor(host, panel, { placement: () => 'top-center', beforeMeasure, afterPosition, }); controller.apply(true); await nextFrame(); controller.position(); expect(beforeMeasure).toHaveBeenCalled(); const position = afterPosition.mock.calls.at(-1)?.[0]; expect(position.side).toBe('top'); expect(position.align).toBe('center'); }); it('keeps placing until afterPosition, then opens (Floating UI isPositioned)', () => { const { host, panel } = mount(); const order: string[] = []; const afterPosition = vi.fn(() => { order.push(`afterPosition:presence=${panel.getAttribute(FLOATING_PRESENCE_ATTR)}`); }); const write = panel.setAttribute.bind(panel); vi.spyOn(panel, 'setAttribute').mockImplementation((name, value) => { if (name === 'transit') { order.push(`transit:${value}:presence=${panel.getAttribute(FLOATING_PRESENCE_ATTR)}`); } write(name, value); }); const controller = controllerFor(host, panel, { afterPosition }); controller.apply(true); expect(panel.style.display).toBe('block'); // Open flushes layout and writes in the same turn — placing is only mid-apply. expect(afterPosition).toHaveBeenCalled(); expect(panel.getAttribute(FLOATING_PRESENCE_ATTR)).toBe('open'); expect(panel.style.opacity).toBe(''); expect(panel.style.pointerEvents).toBe(''); expect(controller.isPositioned).toBe(true); expect(order[0]).toBe('afterPosition:presence=placing'); // transit is applied while still placing, then presence flips to open. expect(order[1]).toBe('transit:ran-dropdown-down-in:presence=placing'); }); it('clears presence after close settle and on destroy', async () => { const { host, panel } = mount(); const presenceWrites: string[] = []; const write = panel.setAttribute.bind(panel); vi.spyOn(panel, 'setAttribute').mockImplementation((name, value) => { if (name === FLOATING_PRESENCE_ATTR) presenceWrites.push(value); write(name, value); }); const remove = panel.removeAttribute.bind(panel); vi.spyOn(panel, 'removeAttribute').mockImplementation((name) => { if (name === FLOATING_PRESENCE_ATTR) presenceWrites.push('∅'); remove(name); }); const controller = controllerFor(host, panel); controller.apply(true); expect(presenceWrites).toContain('placing'); await nextFrame(); expect(controller.isPositioned).toBe(true); controller.apply(false); await nextFrame(); expect(presenceWrites).toContain('closing'); expect(panel.getAttribute(FLOATING_PRESENCE_ATTR)).toBe(null); expect(controller.floatingPresence).toBe(null); controller.apply(true); await nextFrame(); controller.destroy(); expect(panel.hasAttribute(FLOATING_PRESENCE_ATTR)).toBe(false); expect(controller.isPositioned).toBe(false); }); it('hides immediately when closed in the same turn as open', async () => { const { host, panel } = mount(); const afterPosition = vi.fn(); const controller = controllerFor(host, panel, { afterPosition }); controller.apply(true); expect(afterPosition).toHaveBeenCalled(); expect(panel.getAttribute(FLOATING_PRESENCE_ATTR)).toBe('open'); controller.apply(false); await nextFrame(); expect(panel.style.display).toBe('none'); expect(controller.isPositioned).toBe(false); expect(panel.hasAttribute('transit')).toBe(false); }); it('closes toward the resolved side after automatic flipping', async () => { const { host, panel } = mount(); const rect = (top: number, height: number) => ({ top, bottom: top + height, left: 20, right: 120, width: 100, height, x: 20, y: top, toJSON() {} }) as DOMRect; vi.spyOn(host, 'getBoundingClientRect').mockReturnValue(rect(window.innerHeight - 30, 20)); vi.spyOn(panel, 'getBoundingClientRect').mockReturnValue(rect(0, 120)); const transit: string[] = []; const write = panel.setAttribute.bind(panel); vi.spyOn(panel, 'setAttribute').mockImplementation((name, value) => { if (name === 'transit') transit.push(value); write(name, value); }); const controller = controllerFor(host, panel); controller.apply(true); await nextFrame(); controller.apply(false); expect(transit).toEqual(['ran-dropdown-up-in', 'ran-dropdown-up-out']); controller.destroy(); }); }); describe('logical floating ownership', () => { it('tracks nested panels across DOM portals and releases only the closing owner', () => { const modal = document.createElement('section'); const first = mount(); const second = mount(); document.body.append(modal); modal.append(first.host); first.panel.append(second.host); const outer = controllerFor(first.host, first.panel); const inner = controllerFor(second.host, second.panel); outer.apply(true); inner.apply(true); expect(floatingPanelsWithin(modal)).toEqual([first.panel, second.panel]); inner.destroy(); expect(floatingPanelsWithin(modal)).toEqual([first.panel]); inner.apply(true); expect(floatingPanelsWithin(modal)).toEqual([first.panel, second.panel]); inner.apply(false); outer.destroy(); expect(floatingPanelsWithin(modal)).toEqual([]); }); });