From 66f7e74254cd74b4f58fac1b35a576e94c41099a Mon Sep 17 00:00:00 2001 From: Jan Calanog Date: Thu, 19 Nov 2026 21:16:23 +0100 Subject: [PATCH 1/8] Place API menus with one Floating UI controller so Copy page stays on screen The Copy page menu was an absolutely positioned details panel. On a phone it ran off the right edge, and nothing flipped or shifted it. Copy page, the spec download, the API hub menu and the "more" chip menus are now popovers that floating.ts places beside their button. The popover draws in the top layer, so no ancestor can clip it, and the browser handles click outside and Escape. This deletes the hand-rolled positionMenu in chip-row.ts, the api-menu.ts module that floating.ts generalises, and an unused copy of the page-actions CSS. Co-Authored-By: Claude Sonnet 5.5 --- .../_Partials/_UnionOptions.cshtml | 8 +- .../_Partials/_PageActions.cshtml | 55 +++--- .../_Partials/_SpecDownloadActions.cshtml | 19 +- .../Assets/api-docs.css | 31 +--- .../Assets/api-docs.ts | 6 +- .../Assets/api-examples-carousel.test.ts | 31 ---- .../Assets/api-identity.css | 28 +-- .../Assets/api-menu.test.ts | 114 ------------ .../Assets/api-menu.ts | 104 ----------- .../Assets/api-page-actions.test.ts | 33 ++-- .../Assets/chip-row.ts | 46 +---- src/Elastic.Documentation.Site/Assets/ds.css | 1 + .../Assets/ds/runtime.ts | 2 + .../Assets/floating.css | 30 +++ .../Assets/floating.test.ts | 153 ++++++++++++++++ .../Assets/floating.ts | 144 +++++++++++++++ src/Elastic.Documentation.Site/Assets/main.ts | 4 +- .../Assets/styles.css | 1 + .../Pages/ApiReference/api-reference.css | 172 +----------------- .../Layout/_ApiIdentity.cshtml | 2 +- ...n_CopiesPageAndOpensMarkdown.verified.html | 46 +++-- ...ec_ListsJsonAndYamlDownloads.verified.html | 72 ++++---- ...down_OffersTheDownloadsAlone.verified.html | 42 ++--- ...r_WithoutSpec_HasNoDownloads.verified.html | 46 +++-- ...s_AddsASearchBoxToTheChipRow.verified.html | 4 +- .../api-explorer/synth/copy-page-menu.journey | 19 ++ 26 files changed, 535 insertions(+), 678 deletions(-) delete mode 100644 src/Elastic.Documentation.Site/Assets/api-menu.test.ts delete mode 100644 src/Elastic.Documentation.Site/Assets/api-menu.ts create mode 100644 src/Elastic.Documentation.Site/Assets/floating.css create mode 100644 src/Elastic.Documentation.Site/Assets/floating.test.ts create mode 100644 src/Elastic.Documentation.Site/Assets/floating.ts create mode 100644 tests/Elastic.Documentation.Journeys.Tests/journeys/api-explorer/synth/copy-page-menu.journey diff --git a/src/Elastic.ApiExplorer/Components/PropertyTree/_Partials/_UnionOptions.cshtml b/src/Elastic.ApiExplorer/Components/PropertyTree/_Partials/_UnionOptions.cshtml index 161983f4dd..a434fa27b5 100644 --- a/src/Elastic.ApiExplorer/Components/PropertyTree/_Partials/_UnionOptions.cshtml +++ b/src/Elastic.ApiExplorer/Components/PropertyTree/_Partials/_UnionOptions.cshtml @@ -6,6 +6,7 @@ return; } var menuId = $"{Model.ContainerId}-menu"; + var searchId = $"{Model.ContainerId}-search"; // Chips and menu entries drop the words every variant name shares (bedrock_secrets → bedrock); the full name stays as their tooltip. var chipLabels = Model.UseChips ? ChipLabels.Shorten([.. Model.Variants.Select(static v => v.DisplayName)]) : []; string ChipLabel(int i) => Model.Variants[i].IsArrayVariant ? $"{chipLabels[i]}[]" : chipLabels[i]; @@ -42,12 +43,13 @@ - @* A long list searches from the row itself: typing opens the menu with every match, so nobody has to open it first. *@ + @* A long list searches from the row itself: typing opens the menu with every match, so nobody has to open it first. + The menu then sits under the search box (data-anchor, floating.ts). *@ @if (Model.HasFilter) { - + } -
+
@for (var i = 0; i < Model.Variants.Count; i++) { diff --git a/src/Elastic.ApiExplorer/_Partials/_PageActions.cshtml b/src/Elastic.ApiExplorer/_Partials/_PageActions.cshtml index d4397834e6..e531af8434 100644 --- a/src/Elastic.ApiExplorer/_Partials/_PageActions.cshtml +++ b/src/Elastic.ApiExplorer/_Partials/_PageActions.cshtml @@ -1,5 +1,6 @@ @inherits RazorSlice -@* Copy page with a menu of the page's Markdown and the spec download. A page with no Markdown export gets the download alone. *@ +@* Copy page with a menu of the page's Markdown and the spec download. A page with no Markdown export gets the download alone. + The menu is a popover (top layer), placed beside the chevron by floating.ts. *@ @if (Model.MarkdownUrl is null) { if (Model.Spec is not null) @@ -17,32 +18,30 @@ Copy page - + +
+
diff --git a/src/Elastic.ApiExplorer/_Partials/_SpecDownloadActions.cshtml b/src/Elastic.ApiExplorer/_Partials/_SpecDownloadActions.cshtml index 76494b831a..501398c06d 100644 --- a/src/Elastic.ApiExplorer/_Partials/_SpecDownloadActions.cshtml +++ b/src/Elastic.ApiExplorer/_Partials/_SpecDownloadActions.cshtml @@ -1,15 +1,14 @@ @inherits RazorSlice -@* For a page with no Markdown export, so no Copy page: the spec download is the whole menu. *@ +@* For a page with no Markdown export, so no Copy page: the spec download is the whole menu. Like Copy page's, the menu + is a popover placed beside its button by floating.ts. *@
- + +
+
diff --git a/src/Elastic.Documentation.Site/Assets/api-docs.css b/src/Elastic.Documentation.Site/Assets/api-docs.css index 10d894607d..560b74043d 100644 --- a/src/Elastic.Documentation.Site/Assets/api-docs.css +++ b/src/Elastic.Documentation.Site/Assets/api-docs.css @@ -247,10 +247,9 @@ padding: 0; border-left: 1px solid #cad3e2; border-radius: 0 7px 7px 0; - list-style: none; } -/* No Copy page beside it, so the summary is the whole control. */ +/* No Copy page beside it, so the button is the whole control. */ .api-page-actions-chevron--labeled { width: auto; gap: 8px; @@ -260,10 +259,6 @@ white-space: nowrap; } -.api-page-actions-chevron::-webkit-details-marker { - display: none; -} - .api-page-actions-button:hover, .api-page-actions-chevron:hover { background: #f6f9fc; @@ -292,28 +287,18 @@ height: 12px; } -.api-page-actions details.api-page-actions-dropdown, -.api-page-actions details.nav-select-dropdown { - position: relative; - display: flex; - width: auto; - overflow: visible; -} - -.api-page-actions-dropdown[open] .api-page-actions-chevron-icon, -.api-page-actions-dropdown.is-open .api-page-actions-chevron-icon { +.api-page-actions-chevron[aria-expanded='true'] .api-page-actions-chevron-icon { transform: rotate(180deg); } +/* A popover placed beside the chevron by floating.ts (floating.css). */ .api-page-actions-menu { box-sizing: border-box; - position: absolute; - top: calc(100% + 6px); - right: 0; - z-index: 40; width: max-content; min-width: 196px; - margin: 0; + max-width: calc(100vw - 16px); + max-height: var(--floating-available-height, none); + overflow-y: auto; padding: 8px; background: #fff; border: 0; @@ -3823,12 +3808,12 @@ html:has(.api-page-shell) { fill: currentColor; } -/* Positioned from the "more" button in api-examples-carousel.ts; the popover UA styles centre it otherwise. */ +/* A popover placed under the "more" button, or the row's search box, by floating.ts (floating.css). */ .api-example-menu { box-sizing: border-box; width: max-content; max-width: min(320px, calc(100vw - 16px)); - max-height: min(320px, 50vh); + max-height: min(320px, 50vh, var(--floating-available-height, 100vh)); margin: 0; padding: 4px; overflow: auto; diff --git a/src/Elastic.Documentation.Site/Assets/api-docs.ts b/src/Elastic.Documentation.Site/Assets/api-docs.ts index c6391d1d91..edeab83cac 100644 --- a/src/Elastic.Documentation.Site/Assets/api-docs.ts +++ b/src/Elastic.Documentation.Site/Assets/api-docs.ts @@ -706,10 +706,8 @@ export function initApiPageActions(): void { event.preventDefault() const root = trigger.closest('.api-page-actions') - const dropdown = root?.querySelector( - '.api-page-actions-dropdown' - ) - if (dropdown) dropdown.open = false + const menu = trigger.closest('[popover]') + if (menu?.matches(':popover-open')) menu.hidePopover() void copyPageMarkdown(trigger.dataset.copyPage, root).catch((error) => { console.error(error) }) diff --git a/src/Elastic.Documentation.Site/Assets/api-examples-carousel.test.ts b/src/Elastic.Documentation.Site/Assets/api-examples-carousel.test.ts index 866b7a0a62..2cfd4c8ff8 100644 --- a/src/Elastic.Documentation.Site/Assets/api-examples-carousel.test.ts +++ b/src/Elastic.Documentation.Site/Assets/api-examples-carousel.test.ts @@ -796,37 +796,6 @@ describe('API examples chip overflow', () => { expect(visibleItems()).toEqual(['d', 'e']) }) - - it('keeps the open menu under its button while the page scrolls', async () => { - initApiExamples() - const more = document.querySelector('[data-example-more]')! - const menu = document.querySelector('[data-example-menu]')! - let top = 100 - more.getBoundingClientRect = () => - ({ top, bottom: top + 24, left: 50, width: 80 }) as DOMRect - menu.getBoundingClientRect = () => - ({ width: 200, height: 100 }) as DOMRect - - const toggle = new Event('toggle') as ToggleEvent - Object.defineProperty(toggle, 'newState', { value: 'open' }) - menu.dispatchEvent(toggle) - expect(menu.style.top).toBe('128px') - - const frame = () => - new Promise((resolve) => requestAnimationFrame(resolve)) - top = 40 - window.dispatchEvent(new Event('scroll')) - await frame() - expect(menu.style.top).toBe('68px') - - const close = new Event('toggle') as ToggleEvent - Object.defineProperty(close, 'newState', { value: 'closed' }) - menu.dispatchEvent(close) - top = 10 - window.dispatchEvent(new Event('scroll')) - await frame() - expect(menu.style.top).toBe('68px') - }) }) describe('syncStripHeight', () => { diff --git a/src/Elastic.Documentation.Site/Assets/api-identity.css b/src/Elastic.Documentation.Site/Assets/api-identity.css index a1cc263da6..5b5db667c2 100644 --- a/src/Elastic.Documentation.Site/Assets/api-identity.css +++ b/src/Elastic.Documentation.Site/Assets/api-identity.css @@ -1,7 +1,7 @@ /* * The API identity at the top of the API sidebar: product and version in one trigger and one menu. * Used on API pages in the current layout, so nothing here is scoped to body.navigation-preview. - * The menu is a popover placed by api-menu.ts; the rows reuse .secondary-nav-dropdown-link from + * The menu is a popover placed by floating.ts; the rows reuse .secondary-nav-dropdown-link from * secondary-nav-dropdown.css. */ @@ -109,17 +109,12 @@ background: #eeeff1; } - /* - * Menus. A popover sits in the top layer, so no ancestor can clip it. Floating UI sets - * left/top (api-menu.ts); everything the browser puts on [popover] is reset here. - */ + /* Menus. floating.ts places the popover beside its button (floating.css). */ .api-menu { - position: fixed; - inset: auto; box-sizing: border-box; - min-width: 160px; + min-width: max(160px, var(--floating-anchor-width, 0px)); max-width: min(20rem, calc(100vw - 16px)); - margin: 0; + max-height: max(120px, var(--floating-available-height, 100vh)); padding: 8px; overflow-y: auto; border: 0; @@ -134,21 +129,6 @@ filter: drop-shadow(0 0 2px rgb(43 57 79 / 0.16)) drop-shadow(0 3px 10px rgb(43 57 79 / 0.1)) drop-shadow(0 6px 14px rgb(43 57 79 / 0.06)); - transition: opacity 0.15s ease; - } - /* Hidden until api-menu.ts has placed it, so it never flashes at the wrong spot. */ - .api-menu:not([data-placed]) { - visibility: hidden; - } - @starting-style { - .api-menu:popover-open { - opacity: 0; - } - } - @media (prefers-reduced-motion: reduce) { - .api-menu { - transition: none; - } } /* The version sits beside the name, on its first line. A long name wraps and the version stays put. */ diff --git a/src/Elastic.Documentation.Site/Assets/api-menu.test.ts b/src/Elastic.Documentation.Site/Assets/api-menu.test.ts deleted file mode 100644 index 217429dcdd..0000000000 --- a/src/Elastic.Documentation.Site/Assets/api-menu.test.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { initApiMenus } from './api-menu' -import { autoUpdate, computePosition } from '@floating-ui/dom' -import type { Mock } from 'vitest' - -vi.mock('@floating-ui/dom', () => ({ - autoUpdate: vi.fn(), - computePosition: vi.fn(), - flip: vi.fn(() => 'flip'), - offset: vi.fn(() => 'offset'), - shift: vi.fn(() => 'shift'), - size: vi.fn(() => 'size'), -})) - -const stopTracking = vi.fn() -const hidePopover = vi.fn() - -function toggle(menu: HTMLElement, newState: 'open' | 'closed') { - const event = new Event('toggle') - Object.assign(event, { newState }) - menu.dispatchEvent(event) -} - -/** Floating UI loads on a dynamic import, so let that settle. */ -const settle = () => new Promise((resolve) => setTimeout(resolve, 0)) - -describe('api menus', () => { - beforeAll(() => { - // jsdom has no popover API; initApiMenus only listens where it exists. - Object.assign(HTMLElement.prototype, { - showPopover: vi.fn(), - hidePopover, - }) - initApiMenus() - }) - - beforeEach(() => { - ;(autoUpdate as Mock).mockImplementation( - (_trigger, _menu, update: () => void) => { - update() - return stopTracking - } - ) - ;(computePosition as Mock).mockResolvedValue({ x: 12, y: 34 }) - document.body.innerHTML = ` - - ` - }) - - it('tracks the button and places the menu when it opens', async () => { - const menu = document.getElementById('menu')! - - toggle(menu, 'open') - await settle() - - expect( - document.getElementById('trigger')!.getAttribute('aria-expanded') - ).toBe('true') - expect(autoUpdate).toHaveBeenCalledTimes(1) - expect(computePosition).toHaveBeenCalledWith( - document.getElementById('trigger'), - menu, - expect.objectContaining({ - strategy: 'fixed', - placement: 'bottom-end', - }) - ) - expect(menu.style.left).toBe('12px') - expect(menu.style.top).toBe('34px') - expect(menu.hasAttribute('data-placed')).toBe(true) - }) - - it('stops tracking and hides the menu again when it closes', async () => { - const menu = document.getElementById('menu')! - toggle(menu, 'open') - await settle() - - toggle(menu, 'closed') - - expect(stopTracking).toHaveBeenCalledTimes(1) - expect( - document.getElementById('trigger')!.getAttribute('aria-expanded') - ).toBe('false') - expect(menu.hasAttribute('data-placed')).toBe(false) - }) - - it('does not track a menu that closed while Floating UI was loading', async () => { - const menu = document.getElementById('menu')! - - toggle(menu, 'open') - toggle(menu, 'closed') - await settle() - - expect(autoUpdate).not.toHaveBeenCalled() - expect(menu.hasAttribute('data-placed')).toBe(false) - }) - - it('closes open menus before an htmx swap', async () => { - const menu = document.getElementById('menu')! - toggle(menu, 'open') - await settle() - - document.dispatchEvent(new Event('htmx:beforeSwap')) - - expect(hidePopover).toHaveBeenCalledTimes(1) - }) - - it('ignores popovers that are not API menus', () => { - document.body.innerHTML = '
' - - toggle(document.getElementById('other')!, 'open') - - expect(autoUpdate).not.toHaveBeenCalled() - }) -}) diff --git a/src/Elastic.Documentation.Site/Assets/api-menu.ts b/src/Elastic.Documentation.Site/Assets/api-menu.ts deleted file mode 100644 index 2398a9268c..0000000000 --- a/src/Elastic.Documentation.Site/Assets/api-menu.ts +++ /dev/null @@ -1,104 +0,0 @@ -import type { Placement } from '@floating-ui/dom' - -/** - * Menus on API pages (product, version, spec download). - * - * The `popover` attribute draws the menu in the browser's top layer, so no ancestor's - * overflow, stacking context or z-index can clip it. That attribute also gives click-outside - * dismissal and Escape. Floating UI places it next to its button, flipping and shifting to - * stay on screen; it loads on the first open, so pages without a menu never download it. - * Listeners are delegated on the document, so they survive htmx swaps. - */ - -const MENU = '[popover].api-menu' -const PLACED = 'data-placed' -const VIEWPORT_PADDING = 8 - -type FloatingUi = typeof import('@floating-ui/dom') - -const openMenus = new Set() -const stopTracking = new WeakMap void>() - -function triggerFor(menu: HTMLElement): HTMLElement | null { - if (!menu.id) return null - return document.querySelector( - `[popovertarget="${CSS.escape(menu.id)}"]` - ) -} - -function place(fui: FloatingUi, trigger: HTMLElement, menu: HTMLElement) { - void fui - .computePosition(trigger, menu, { - strategy: 'fixed', - placement: - (menu.dataset.placement as Placement | undefined) ?? - 'bottom-start', - middleware: [ - fui.offset(6), - fui.flip({ padding: VIEWPORT_PADDING }), - fui.shift({ padding: VIEWPORT_PADDING }), - fui.size({ - padding: VIEWPORT_PADDING, - apply({ availableHeight, rects, elements }) { - Object.assign(elements.floating.style, { - minWidth: `${rects.reference.width}px`, - maxHeight: `${Math.max(120, availableHeight)}px`, - }) - }, - }), - ], - }) - .then(({ x, y }) => { - Object.assign(menu.style, { left: `${x}px`, top: `${y}px` }) - // Stays hidden until placed, so it never flashes at the wrong spot. - menu.setAttribute(PLACED, '') - }) -} - -async function track(trigger: HTMLElement, menu: HTMLElement) { - const fui = await import('@floating-ui/dom') - // It may have closed while the module loaded. - if (!openMenus.has(menu)) return - stopTracking.set( - menu, - fui.autoUpdate(trigger, menu, () => place(fui, trigger, menu)) - ) -} - -function untrack(menu: HTMLElement) { - openMenus.delete(menu) - stopTracking.get(menu)?.() - stopTracking.delete(menu) - menu.removeAttribute(PLACED) -} - -function onToggle(event: Event) { - const menu = event.target - if (!(menu instanceof HTMLElement) || !menu.matches(MENU)) return - const trigger = triggerFor(menu) - if (!trigger) return - - const open = (event as ToggleEvent).newState === 'open' - trigger.setAttribute('aria-expanded', String(open)) - untrack(menu) - if (!open) return - - openMenus.add(menu) - void track(trigger, menu) -} - -/** A swap removes the page's menus; close them first so their position tracking is released. */ -function closeOpenMenus() { - for (const menu of openMenus) { - if (menu.isConnected) menu.hidePopover() - } - openMenus.clear() -} - -export function initApiMenus() { - // Without the popover API the menus stay hidden, so there is nothing to place. - if (typeof HTMLElement.prototype.showPopover !== 'function') return - // `toggle` does not bubble, so listen in the capture phase. - document.addEventListener('toggle', onToggle, true) - document.addEventListener('htmx:beforeSwap', closeOpenMenus) -} diff --git a/src/Elastic.Documentation.Site/Assets/api-page-actions.test.ts b/src/Elastic.Documentation.Site/Assets/api-page-actions.test.ts index 89040bc41f..35288ad22a 100644 --- a/src/Elastic.Documentation.Site/Assets/api-page-actions.test.ts +++ b/src/Elastic.Documentation.Site/Assets/api-page-actions.test.ts @@ -7,14 +7,12 @@ function pageActionsMarkup(url: string): string { - + +
+ ` @@ -74,18 +72,25 @@ describe('initApiPageActions', () => { ).toBe('Copy page') }) - it('closes the dropdown when copying from the menu', async () => { - const dropdown = document.querySelector( - '.api-page-actions-dropdown' - )! - expect(dropdown.open).toBe(true) + it('closes the menu when copying from it', async () => { + const menu = document.getElementById('menu')! + // jsdom has no popover API: the menu stands open, as the browser would show it. + menu.hidePopover = vi.fn() + vi.spyOn(menu, 'matches').mockImplementation( + (selector) => selector === ':popover-open' + ) document .querySelector('.api-page-actions-option')! .click() await flushMicrotasks() - expect(dropdown.open).toBe(false) + expect(menu.hidePopover).toHaveBeenCalledTimes(1) expect(writeText).toHaveBeenCalledWith(markdown) + expect( + document + .querySelector('.api-page-actions-label') + ?.textContent?.trim() + ).toBe('Copied!') }) }) diff --git a/src/Elastic.Documentation.Site/Assets/chip-row.ts b/src/Elastic.Documentation.Site/Assets/chip-row.ts index 103dadb9b0..60de24a6a9 100644 --- a/src/Elastic.Documentation.Site/Assets/chip-row.ts +++ b/src/Elastic.Documentation.Site/Assets/chip-row.ts @@ -163,42 +163,15 @@ export function observeChipRow(row: HTMLElement, parts: ChipRowParts): void { const registered: ChipRowParts[] = [] let openMenu: { menu: HTMLElement; anchor: HTMLElement } | null = null -let followQueued = false function partsOf(element: Element): ChipRowParts | undefined { return registered.find((parts) => element.matches(parts.menu)) } -/** Keeps the open menu with its button as the page scrolls or resizes, at most once a frame. */ -function followOpenMenu() { - if (!openMenu || followQueued) return - followQueued = true - requestAnimationFrame(() => { - followQueued = false - if (openMenu) positionMenu(openMenu.menu, openMenu.anchor) - }) -} - -/** Under its anchor (the "more" button, or the row's search box), or above it when there is no room below. Run again on scroll, so the menu stays with its anchor. */ -function positionMenu(menu: HTMLElement, anchorElement: HTMLElement) { - const anchor = anchorElement.getBoundingClientRect() - const size = menu.getBoundingClientRect() - const margin = 8 - const left = Math.max( - margin, - Math.min(anchor.left, window.innerWidth - size.width - margin) - ) - const below = anchor.bottom + 4 - const top = - below + size.height > window.innerHeight - margin && - anchor.top - 4 - size.height > margin - ? anchor.top - 4 - size.height - : below - menu.style.left = `${left}px` - menu.style.top = `${top}px` -} - -/** Opens under the "more" button, or above it when there is no room below, and keeps the button's state in step. */ +/** + * Clears the filter when the menu closes, and moves the focus in when it opens. floating.ts places it under its + * anchor: the "more" button, or the row's search box (`data-anchor`). + */ function onMenuToggle(event: Event) { const menu = event.target as HTMLElement | null const parts = menu && partsOf(menu) @@ -207,7 +180,6 @@ function onMenuToggle(event: Event) { .closest(parts.row) ?.querySelector(parts.more) const open = (event as ToggleEvent).newState === 'open' - more?.setAttribute('aria-expanded', open ? 'true' : 'false') const rowSearch = menu .closest(parts.row) ?.querySelector(`:scope > ${parts.filter}`) @@ -226,7 +198,6 @@ function onMenuToggle(event: Event) { } if (!open || !anchor) return - positionMenu(menu, anchor) // Typing in the row's search box keeps the focus there while the menu fills; opened from the button, the focus moves in. if (rowSearch && document.activeElement === rowSearch) return if (filter) filter.focus() @@ -422,12 +393,10 @@ function onInput(event: Event) { if (!parts) return filterMenu(input as HTMLInputElement, parts) openForSearch(input as HTMLInputElement, parts) - // A menu that opened above its button shrinks as it filters; place it again so it stays against the button. - if (openMenu) positionMenu(openMenu.menu, openMenu.anchor) } /** - * Wires the "more" menus of one kind of chip row: placement, keyboard moves and the filter. Listeners are delegated + * Wires the "more" menus of one kind of chip row: keyboard moves and the filter. Listeners are delegated * from the document and added once, so it is safe to call again after an HTMX swap. */ export function registerChipRows(parts: ChipRowParts): void { @@ -438,11 +407,6 @@ export function registerChipRows(parts: ChipRowParts): void { document.addEventListener('keydown', onKeydown) document.addEventListener('input', onInput) document.addEventListener('pointerdown', onPointerDown) - window.addEventListener('scroll', followOpenMenu, { - capture: true, - passive: true, - }) - window.addEventListener('resize', followOpenMenu) } registered.push(parts) } diff --git a/src/Elastic.Documentation.Site/Assets/ds.css b/src/Elastic.Documentation.Site/Assets/ds.css index 534d2e4542..52be9f54ba 100644 --- a/src/Elastic.Documentation.Site/Assets/ds.css +++ b/src/Elastic.Documentation.Site/Assets/ds.css @@ -97,6 +97,7 @@ @import '../Components/Markdown/Listing/listing.css' layer(ds.components); @import '../Components/Markdown/Image/image.css' layer(ds.components); @import '../Components/Pages/SearchPage/search-page.css' layer(ds.components); +@import './floating.css' layer(ds.components); @import '../Components/Pages/ApiReference/api-reference.css' layer(ds.components); @import '../Components/Pages/ApiReference/api-code.css' layer(ds.components); diff --git a/src/Elastic.Documentation.Site/Assets/ds/runtime.ts b/src/Elastic.Documentation.Site/Assets/ds/runtime.ts index a327f1ee17..588337290a 100644 --- a/src/Elastic.Documentation.Site/Assets/ds/runtime.ts +++ b/src/Elastic.Documentation.Site/Assets/ds/runtime.ts @@ -4,6 +4,7 @@ import { initApiDocs } from '../api-docs' import { initAppliesSwitch } from '../applies-switch' import { initCopyButton } from '../copybutton' +import { initFloating } from '../floating' import { initHighlight, preloadHighlight } from '../hljs' import { initMath } from '../math' import { initMermaid } from '../mermaid' @@ -62,4 +63,5 @@ document.addEventListener('htmx:load', function () { bindCtaClicks() initPrivacyConsent() bindModalEscape() +initFloating() bindHtmxHooks() diff --git a/src/Elastic.Documentation.Site/Assets/floating.css b/src/Elastic.Documentation.Site/Assets/floating.css new file mode 100644 index 0000000000..ecf418853a --- /dev/null +++ b/src/Elastic.Documentation.Site/Assets/floating.css @@ -0,0 +1,30 @@ +/* + * Popovers placed by floating.ts. Floating UI sets left and top; the browser's own [popover] placement + * (centred in the viewport) is reset here. Each menu's CSS reads --floating-anchor-width and + * --floating-available-height to size itself. + */ +[data-floating] { + position: fixed; + inset: auto; + margin: 0; +} + +/* Hidden until floating.ts has placed it, so it never flashes at the wrong spot. */ +[data-floating]:not([data-placed]) { + visibility: hidden; +} + +/* Fades in once placed. */ +[data-floating] { + transition: opacity 0.15s ease; +} +@starting-style { + [data-floating]:popover-open { + opacity: 0; + } +} +@media (prefers-reduced-motion: reduce) { + [data-floating] { + transition: none; + } +} diff --git a/src/Elastic.Documentation.Site/Assets/floating.test.ts b/src/Elastic.Documentation.Site/Assets/floating.test.ts new file mode 100644 index 0000000000..169d30e6c0 --- /dev/null +++ b/src/Elastic.Documentation.Site/Assets/floating.test.ts @@ -0,0 +1,153 @@ +import { initFloating } from './floating' +import { autoUpdate, computePosition } from '@floating-ui/dom' +import type { Mock } from 'vitest' + +vi.mock('@floating-ui/dom', () => ({ + autoUpdate: vi.fn(), + computePosition: vi.fn(), + flip: vi.fn(() => 'flip'), + offset: vi.fn(() => 'offset'), + shift: vi.fn(() => 'shift'), + size: vi.fn(() => 'size'), +})) + +const stopTracking = vi.fn() +const hidePopover = vi.fn() + +function dispatch( + popover: HTMLElement, + type: 'beforetoggle' | 'toggle', + newState: 'open' | 'closed' +) { + const event = new Event(type) + Object.assign(event, { newState }) + popover.dispatchEvent(event) +} + +/** What the browser does when a popover opens or closes. */ +function setOpen(popover: HTMLElement, open: boolean) { + const state = open ? 'open' : 'closed' + dispatch(popover, 'beforetoggle', state) + dispatch(popover, 'toggle', state) +} + +const settle = () => new Promise((resolve) => setTimeout(resolve, 0)) + +describe('floating popovers', () => { + beforeAll(() => { + // jsdom has no popover API; initFloating only listens where it exists. + Object.assign(HTMLElement.prototype, { + showPopover: vi.fn(), + hidePopover, + }) + initFloating() + }) + + beforeEach(() => { + // Releases what the previous test left open, the way a page swap does. + document.dispatchEvent(new Event('htmx:beforeSwap')) + vi.clearAllMocks() + ;(autoUpdate as Mock).mockImplementation( + (_anchor, _floating, update: () => void) => { + update() + return stopTracking + } + ) + ;(computePosition as Mock).mockResolvedValue({ x: 12, y: 34 }) + document.body.innerHTML = ` + + ` + }) + + const menu = () => document.getElementById('menu')! + const trigger = () => document.getElementById('trigger')! + + it('keeps the menu hidden from its first frame until it is placed', () => { + dispatch(menu(), 'beforetoggle', 'open') + + expect(menu().hasAttribute('data-floating')).toBe(true) + expect(menu().hasAttribute('data-placed')).toBe(false) + }) + + it('places the menu beside the button that opens it and follows it', async () => { + setOpen(menu(), true) + await settle() + + expect(trigger().getAttribute('aria-expanded')).toBe('true') + expect(autoUpdate).toHaveBeenCalledTimes(1) + expect(computePosition).toHaveBeenCalledWith( + trigger(), + menu(), + expect.objectContaining({ + strategy: 'fixed', + placement: 'bottom-end', + middleware: ['offset', 'flip', 'shift', 'size'], + }) + ) + expect(menu().style.left).toBe('12px') + expect(menu().style.top).toBe('34px') + expect(menu().hasAttribute('data-placed')).toBe(true) + }) + + it('opens below the start of its button when no placement is given', async () => { + menu().removeAttribute('data-placement') + + setOpen(menu(), true) + await settle() + + expect(computePosition).toHaveBeenCalledWith( + trigger(), + menu(), + expect.objectContaining({ placement: 'bottom-start' }) + ) + }) + + it('anchors to the element data-anchor names instead of the button', async () => { + document.body.insertAdjacentHTML('beforeend', '') + menu().dataset.anchor = 'search' + + setOpen(menu(), true) + await settle() + + expect(computePosition).toHaveBeenCalledWith( + document.getElementById('search'), + menu(), + expect.anything() + ) + }) + + it('stops following and hides the menu again when it closes', async () => { + setOpen(menu(), true) + await settle() + + setOpen(menu(), false) + + expect(stopTracking).toHaveBeenCalledTimes(1) + expect(trigger().getAttribute('aria-expanded')).toBe('false') + expect(menu().hasAttribute('data-placed')).toBe(false) + }) + + it('closes open menus before an htmx swap', async () => { + const matches = vi + .spyOn(menu(), 'matches') + .mockImplementation((selector) => selector === ':popover-open') + setOpen(menu(), true) + await settle() + + document.dispatchEvent(new Event('htmx:beforeSwap')) + + expect(hidePopover).toHaveBeenCalledTimes(1) + expect(stopTracking).toHaveBeenCalledTimes(1) + matches.mockRestore() + }) + + it('leaves alone a popover that has nothing to anchor to', () => { + document.body.innerHTML = '
' + const other = document.getElementById('other')! + + setOpen(other, true) + + expect(other.hasAttribute('data-floating')).toBe(false) + expect(autoUpdate).not.toHaveBeenCalled() + }) +}) diff --git a/src/Elastic.Documentation.Site/Assets/floating.ts b/src/Elastic.Documentation.Site/Assets/floating.ts new file mode 100644 index 0000000000..5f61700a5d --- /dev/null +++ b/src/Elastic.Documentation.Site/Assets/floating.ts @@ -0,0 +1,144 @@ +import { + autoUpdate, + computePosition, + flip, + offset, + shift, + size, + type Placement, +} from '@floating-ui/dom' + +/** + * Places every popover next to the element that opens it. + * + * A menu is a `[popover]` opened by a `[popovertarget]` button. The popover draws it in the top layer, so no + * ancestor's overflow, stacking context or z-index can clip it, and gives click-outside dismissal and Escape. + * Floating UI places it beside its anchor, flipping and shifting to stay on screen, and follows the anchor while + * the menu is open. `data-placement` picks the side (default `bottom-start`); `data-anchor` names the id of an + * anchor other than the button. Listeners are delegated on the document, so they survive htmx swaps. + */ + +const PLACED = 'data-placed' +const FLOATING = 'data-floating' +const VIEWPORT_PADDING = 8 + +const stopTracking = new Map void>() + +function invokers(popover: HTMLElement): HTMLElement[] { + if (!popover.id) return [] + return Array.from( + document.querySelectorAll( + `[popovertarget="${CSS.escape(popover.id)}"]` + ) + ) +} + +function anchorOf(popover: HTMLElement): HTMLElement | null { + const named = popover.dataset.anchor + if (named) return document.getElementById(named) + return invokers(popover)[0] ?? null +} + +/** + * Puts `floating` beside `anchor`. Sets `--floating-anchor-width` and `--floating-available-height` on it, so its + * own CSS decides how wide and tall it may grow. + */ +function place( + anchor: Element, + floating: HTMLElement, + placement: Placement +): Promise { + return computePosition(anchor, floating, { + strategy: 'fixed', + placement, + middleware: [ + offset(6), + flip({ padding: VIEWPORT_PADDING }), + shift({ padding: VIEWPORT_PADDING }), + size({ + padding: VIEWPORT_PADDING, + apply({ availableHeight, rects, elements }) { + elements.floating.style.setProperty( + '--floating-anchor-width', + `${rects.reference.width}px` + ) + elements.floating.style.setProperty( + '--floating-available-height', + `${Math.floor(availableHeight)}px` + ) + }, + }), + ], + }).then(({ x, y }) => { + Object.assign(floating.style, { left: `${x}px`, top: `${y}px` }) + // Hidden until placed (floating.css), so it never flashes at the wrong spot. + floating.setAttribute(PLACED, '') + }) +} + +/** Follows the anchor through scrolling, resizing and the menu's own size changes until `release` is called. */ +function track( + anchor: Element, + floating: HTMLElement, + placement: Placement +): () => void { + return autoUpdate(anchor, floating, () => { + void place(anchor, floating, placement) + }) +} + +function release(popover: HTMLElement) { + stopTracking.get(popover)?.() + stopTracking.delete(popover) + popover.removeAttribute(PLACED) +} + +function placementOf(popover: HTMLElement): Placement { + return ( + (popover.dataset.placement as Placement | undefined) ?? 'bottom-start' + ) +} + +/** Runs before the popover shows, so it is hidden until placed from its first frame. */ +function onBeforeToggle(event: Event) { + const popover = event.target + if (!(popover instanceof HTMLElement) || !popover.hasAttribute('popover')) + return + if ((event as ToggleEvent).newState !== 'open' || !anchorOf(popover)) return + popover.setAttribute(FLOATING, '') +} + +function onToggle(event: Event) { + const popover = event.target + if (!(popover instanceof HTMLElement) || !popover.hasAttribute(FLOATING)) + return + const open = (event as ToggleEvent).newState === 'open' + for (const invoker of invokers(popover)) + invoker.setAttribute('aria-expanded', String(open)) + release(popover) + const anchor = anchorOf(popover) + if (!open || !anchor) return + stopTracking.set(popover, track(anchor, popover, placementOf(popover))) +} + +/** A swap removes the page's popovers; close them first so their tracking is released. */ +function closeAll() { + for (const popover of [...stopTracking.keys()]) { + if (popover.isConnected && popover.matches(':popover-open')) + popover.hidePopover() + release(popover) + } +} + +let initialized = false + +export function initFloating() { + if (initialized) return + // Without the popover API the menus stay hidden, so there is nothing to place. + if (typeof HTMLElement.prototype.showPopover !== 'function') return + initialized = true + // `beforetoggle` and `toggle` do not bubble, so listen in the capture phase. + document.addEventListener('beforetoggle', onBeforeToggle, true) + document.addEventListener('toggle', onToggle, true) + document.addEventListener('htmx:beforeSwap', closeAll) +} diff --git a/src/Elastic.Documentation.Site/Assets/main.ts b/src/Elastic.Documentation.Site/Assets/main.ts index 8810441af5..e01e004697 100644 --- a/src/Elastic.Documentation.Site/Assets/main.ts +++ b/src/Elastic.Documentation.Site/Assets/main.ts @@ -2,11 +2,11 @@ import { initAgentSkillCopy } from './agent-skill' import { bindApiBetaBanner } from './api-beta-banner' import { initApiChromeSync } from './api-chrome-sync' import { initApiDocs } from './api-docs' -import { initApiMenus } from './api-menu' import { changesPageChrome } from './api-navigation' import { initAppliesSwitch } from './applies-switch' import { config } from './config' import { initCopyButton } from './copybutton' +import { initFloating } from './floating' import { initHighlight, preloadHighlight } from './hljs' import { initImageCarousel } from './image-carousel' import { initListing } from './listing' @@ -87,7 +87,7 @@ document.addEventListener('htmx:load', function () { bindCtaClicks() initPrivacyConsent() initSecondaryNav() -initApiMenus() +initFloating() initApiChromeSync() bindApiBetaBanner() bindModalEscape() diff --git a/src/Elastic.Documentation.Site/Assets/styles.css b/src/Elastic.Documentation.Site/Assets/styles.css index fa3a3d05e7..20511fba30 100644 --- a/src/Elastic.Documentation.Site/Assets/styles.css +++ b/src/Elastic.Documentation.Site/Assets/styles.css @@ -28,6 +28,7 @@ @import './modal.css'; @import './secondary-nav.css'; @import './secondary-nav-dropdown.css'; +@import './floating.css'; @import './api-identity.css'; @import './archive.css'; @import './markdown/stepper.css'; diff --git a/src/Elastic.Documentation.Site/Components/Pages/ApiReference/api-reference.css b/src/Elastic.Documentation.Site/Components/Pages/ApiReference/api-reference.css index 2cabd6d953..b5c09f4b8b 100644 --- a/src/Elastic.Documentation.Site/Components/Pages/ApiReference/api-reference.css +++ b/src/Elastic.Documentation.Site/Components/Pages/ApiReference/api-reference.css @@ -169,174 +169,6 @@ ); /* docs h1 mt-6; API headings set margin: 0 */ } -.api-page-actions { - position: relative; - z-index: 6; - flex-shrink: 0; - margin-left: auto; -} - -.api-page-actions-split { - display: inline-flex; - align-items: stretch; - height: 2rem; - overflow: visible; - border: 1px solid var(--color-border-control); - border-radius: 0.5rem; - background: var(--color-surface); - box-shadow: none; - color: var(--color-heading); - font-family: var(--font-body, Inter, ui-sans-serif, system-ui, sans-serif); - font-size: 0.875rem; - line-height: 1.25rem; -} - -.api-page-actions-button, -.api-page-actions-chevron { - margin: 0; - border: 0; - background: transparent; - color: inherit; - font: inherit; - cursor: pointer; -} - -.api-page-actions-button { - display: inline-flex; - align-items: center; - gap: var(--space-2); - padding: 0 var(--space-3); - border-radius: 0.4375rem 0 0 0.4375rem; - white-space: nowrap; -} - -.api-page-actions-chevron { - box-sizing: border-box; - display: inline-flex; - align-items: center; - justify-content: center; - width: 2rem; - padding: 0; - border-left: 1px solid var(--color-border-control); - border-radius: 0 0.4375rem 0.4375rem 0; - list-style: none; -} - -.api-page-actions-chevron::-webkit-details-marker { - display: none; -} - -.api-page-actions-button:hover, -.api-page-actions-chevron:hover { - background: var(--color-surface-sunken); -} - -.api-page-actions-button:focus-visible, -.api-page-actions-chevron:focus-visible, -.api-page-actions-option:focus-visible { - outline: 2px solid var(--color-accent); - outline-offset: -2px; -} - -.api-page-actions-chevron-icon { - display: flex; - align-items: center; - justify-content: center; - width: 0.75rem; - height: 0.75rem; - color: var(--color-text-muted); - transition: transform 0.15s ease; -} - -.api-page-actions-chevron-icon svg { - display: block; - width: 0.75rem; - height: 0.75rem; -} - -.api-page-actions details.api-page-actions-dropdown, -.api-page-actions details.nav-select-dropdown { - position: relative; - display: flex; - width: auto; - overflow: visible; -} - -.api-page-actions-dropdown[open] .api-page-actions-chevron-icon, -.api-page-actions-dropdown.is-open .api-page-actions-chevron-icon { - transform: rotate(180deg); -} - -.api-page-actions-menu { - box-sizing: border-box; - position: absolute; - top: calc(100% + 0.375rem); - right: 0; - z-index: 40; - width: max-content; - min-width: 12.25rem; - margin: 0; - padding: var(--space-2); - background: var(--color-surface); - border: 0; - border-radius: 0.25rem; - filter: drop-shadow( - 0 0 2px color-mix(in oklab, var(--color-text) 16%, transparent) - ) - drop-shadow( - 0 3px 10px color-mix(in oklab, var(--color-text) 10%, transparent) - ) - drop-shadow( - 0 6px 14px color-mix(in oklab, var(--color-text) 6%, transparent) - ); - font-family: var(--font-body, Inter, ui-sans-serif, system-ui, sans-serif); - font-size: 0.875rem; - font-weight: 400; - line-height: 1.25rem; - color: var(--color-heading); -} - -.api-page-actions-icon { - display: block; - flex-shrink: 0; - width: 1rem; - height: 1rem; - color: var(--color-text-muted); -} - -.api-page-actions-option { - display: flex; - align-items: center; - gap: var(--space-2); - width: 100%; - margin: 0; - padding: 0.375rem var(--space-2); - border: 0; - border-radius: 0.25rem; - background: transparent; - font: inherit; - color: var(--color-heading); - text-align: left; - text-decoration: none; - cursor: pointer; -} - -.api-page-actions-option:hover { - background: var(--color-surface-sunken); - color: var(--color-heading); -} - -.markdown-content .api-page-actions a.api-page-actions-option { - color: var(--color-heading); - text-decoration: none; -} - -.markdown-content - .api-page-actions - a.api-page-actions-option[target='_blank']::after { - content: none; -} - .api-pages-nav-toggle { display: inline-flex; align-items: center; @@ -3882,12 +3714,12 @@ html:has(.api-page-shell) { fill: currentColor; } -/* Positioned from the "more" button in api-examples-carousel.ts; the popover UA styles centre it otherwise. */ +/* A popover placed under the "more" button, or the row's search box, by floating.ts (floating.css). */ .api-example-menu { box-sizing: border-box; width: max-content; max-width: min(20rem, calc(100vw - 1rem)); - max-height: min(20rem, 50vh); + max-height: min(20rem, 50vh, var(--floating-available-height, 100vh)); margin: 0; padding: var(--space-1); overflow: auto; diff --git a/src/Elastic.Documentation.Site/Layout/_ApiIdentity.cshtml b/src/Elastic.Documentation.Site/Layout/_ApiIdentity.cshtml index 640cdcb3bd..fa9a705115 100644 --- a/src/Elastic.Documentation.Site/Layout/_ApiIdentity.cshtml +++ b/src/Elastic.Documentation.Site/Layout/_ApiIdentity.cshtml @@ -1,7 +1,7 @@ @using Microsoft.AspNetCore.Html @inherits RazorSlice @* Which API this is, and which version of it: one choice, one menu. The top of the API sidebar. - The menu is a popover (top layer), positioned by api-menu.ts. *@ + The menu is a popover (top layer), positioned by floating.ts. *@ @{ var hasVersions = Model.Versions.Count > 1; var hasProducts = Model.ProductGroups.Count > 0; diff --git a/tests/Elastic.ApiExplorer.Tests/.snapshots/PageActionsRenderingTests/Render_SplitButton_CopiesPageAndOpensMarkdown.verified.html b/tests/Elastic.ApiExplorer.Tests/.snapshots/PageActionsRenderingTests/Render_SplitButton_CopiesPageAndOpensMarkdown.verified.html index d164413fca..cd204a31ab 100644 --- a/tests/Elastic.ApiExplorer.Tests/.snapshots/PageActionsRenderingTests/Render_SplitButton_CopiesPageAndOpensMarkdown.verified.html +++ b/tests/Elastic.ApiExplorer.Tests/.snapshots/PageActionsRenderingTests/Render_SplitButton_CopiesPageAndOpensMarkdown.verified.html @@ -7,29 +7,27 @@ Copy page - + + + diff --git a/tests/Elastic.ApiExplorer.Tests/.snapshots/PageActionsRenderingTests/Render_WithSpec_ListsJsonAndYamlDownloads.verified.html b/tests/Elastic.ApiExplorer.Tests/.snapshots/PageActionsRenderingTests/Render_WithSpec_ListsJsonAndYamlDownloads.verified.html index 151d42136e..6606dddb2d 100644 --- a/tests/Elastic.ApiExplorer.Tests/.snapshots/PageActionsRenderingTests/Render_WithSpec_ListsJsonAndYamlDownloads.verified.html +++ b/tests/Elastic.ApiExplorer.Tests/.snapshots/PageActionsRenderingTests/Render_WithSpec_ListsJsonAndYamlDownloads.verified.html @@ -7,42 +7,40 @@ Copy page - + + + diff --git a/tests/Elastic.ApiExplorer.Tests/.snapshots/PageActionsRenderingTests/Render_WithoutMarkdown_OffersTheDownloadsAlone.verified.html b/tests/Elastic.ApiExplorer.Tests/.snapshots/PageActionsRenderingTests/Render_WithoutMarkdown_OffersTheDownloadsAlone.verified.html index b81fda7026..4357e0ebb8 100644 --- a/tests/Elastic.ApiExplorer.Tests/.snapshots/PageActionsRenderingTests/Render_WithoutMarkdown_OffersTheDownloadsAlone.verified.html +++ b/tests/Elastic.ApiExplorer.Tests/.snapshots/PageActionsRenderingTests/Render_WithoutMarkdown_OffersTheDownloadsAlone.verified.html @@ -1,26 +1,24 @@ diff --git a/tests/Elastic.ApiExplorer.Tests/.snapshots/PageActionsRenderingTests/Render_WithoutSpec_HasNoDownloads.verified.html b/tests/Elastic.ApiExplorer.Tests/.snapshots/PageActionsRenderingTests/Render_WithoutSpec_HasNoDownloads.verified.html index 051aad5b08..1723ad5bba 100644 --- a/tests/Elastic.ApiExplorer.Tests/.snapshots/PageActionsRenderingTests/Render_WithoutSpec_HasNoDownloads.verified.html +++ b/tests/Elastic.ApiExplorer.Tests/.snapshots/PageActionsRenderingTests/Render_WithoutSpec_HasNoDownloads.verified.html @@ -7,29 +7,27 @@ Copy page - + + + diff --git a/tests/Elastic.ApiExplorer.Tests/.snapshots/UnionOptionsRenderingTests/Render_ElevenVariants_AddsASearchBoxToTheChipRow.verified.html b/tests/Elastic.ApiExplorer.Tests/.snapshots/UnionOptionsRenderingTests/Render_ElevenVariants_AddsASearchBoxToTheChipRow.verified.html index 58ac88f9e2..5ce1a9c818 100644 --- a/tests/Elastic.ApiExplorer.Tests/.snapshots/UnionOptionsRenderingTests/Render_ElevenVariants_AddsASearchBoxToTheChipRow.verified.html +++ b/tests/Elastic.ApiExplorer.Tests/.snapshots/UnionOptionsRenderingTests/Render_ElevenVariants_AddsASearchBoxToTheChipRow.verified.html @@ -41,8 +41,8 @@ - -
+ +