From ebf1981e850626ce0e8f37042c39f0ce4304231c Mon Sep 17 00:00:00 2001 From: teodosiah Date: Wed, 25 Nov 2026 16:24:08 +0200 Subject: [PATCH 1/2] feat(overlay): position overlays with native CSS anchor positioning --- CHANGELOG.md | 29 + .../core/src/services/overlay/README.md | 42 +- .../overlay/anchoring/anchor-names.ts | 67 ++ .../overlay/anchoring/anchoring.spec.ts | 254 ++++++++ .../services/overlay/anchoring/anchoring.ts | 67 ++ .../anchoring/native-anchoring.spec.ts | 590 +++++++++++++++++ .../overlay/anchoring/native-engine.ts | 197 ++++++ .../overlay/anchoring/native-overlay.spec.ts | 602 ++++++++++++++++++ .../core/src/services/overlay/overlay.spec.ts | 12 +- .../core/src/services/overlay/overlay.ts | 293 ++++++++- .../src/services/overlay/position/README.md | 21 + .../position/container-position-strategy.ts | 27 +- .../src/services/overlay/scroll/README.md | 24 +- .../overlay/scroll/hide-scroll-strategy.ts | 79 +++ .../core/src/services/overlay/scroll/index.ts | 1 + .../core/src/services/overlay/utilities.ts | 14 + .../core/src/services/public_api.ts | 2 + .../date-range-picker.component.spec.ts | 14 +- .../toggle/toggle.directive.spec.ts | 4 + .../simple-combo.component.spec.ts | 13 +- .../references/setup.md | 3 + src/app/app.config.ts | 8 +- src/app/overlay/overlay.sample.ts | 9 +- 23 files changed, 2331 insertions(+), 41 deletions(-) create mode 100644 projects/igniteui-angular/core/src/services/overlay/anchoring/anchor-names.ts create mode 100644 projects/igniteui-angular/core/src/services/overlay/anchoring/anchoring.spec.ts create mode 100644 projects/igniteui-angular/core/src/services/overlay/anchoring/anchoring.ts create mode 100644 projects/igniteui-angular/core/src/services/overlay/anchoring/native-anchoring.spec.ts create mode 100644 projects/igniteui-angular/core/src/services/overlay/anchoring/native-engine.ts create mode 100644 projects/igniteui-angular/core/src/services/overlay/anchoring/native-overlay.spec.ts create mode 100644 projects/igniteui-angular/core/src/services/overlay/scroll/hide-scroll-strategy.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c6489a7e91..5a50ef03df7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,35 @@ All notable changes for each version of this project will be documented in this file. +## 22.4.0 + +### New Functionality + +- `IgxOverlayService` + - Overlays that use `ConnectedPositioningStrategy`, `AutoPositionStrategy` or `ContainerPositionStrategy` are positioned with native CSS anchor positioning in browsers that support it (Chrome, Edge, Firefox and Safari 26). The browser keeps the content attached to its target while the page scrolls or resizes, with no script running on scroll. Safari 18, subclasses of these strategies, `Point` targets, other strategies and start point/direction combinations such as `Left → Center` keep script positioning. See [Positioning engines](projects/igniteui-angular/core/src/services/overlay/README.md#positioning-engines). + - Added `HideScrollStrategy`, which hides the overlay content while its target is scrolled out of view and shows it again when the target returns. The overlay stays open. + ```typescript + settings.scrollStrategy = new HideScrollStrategy(); + ``` + - Added `provideOverlayAnchoring()`. Add `provideOverlayAnchoring('script')` to the application providers to keep script positioning for every overlay. + ```typescript + bootstrapApplication(AppComponent, { providers: [provideOverlayAnchoring('script')] }); + ``` + +### General + +- `IgxOverlayService` + - **Behavioral changes** with native anchor positioning. `provideOverlayAnchoring('script')` restores the previous behavior. + - Anchored content follows its target on scroll with every scroll strategy, including `NoOpScrollStrategy`. It follows one rendering frame after the scroll, so code that scrolls and measures in the same task sees the previous position. + - `AutoPositionStrategy` content also flips while the overlay is open, when the current side stops fitting. When no side fits, the browser shifts the content into the viewport; the exact position can differ from before. + - Positions are no longer rounded to whole pixels. + - While an overlay is open, its target has an inline `anchor-name` style. + +### Bug Fixes + +- `ContainerPositionStrategy` no longer throws from its `IntersectionObserver` after the overlay is detached (#16988). +- The Excel-style filtering submenu opens on the side the grid requests on every open, in browsers with native anchor positioning. + ## 22.3.0 ### General diff --git a/projects/igniteui-angular/core/src/services/overlay/README.md b/projects/igniteui-angular/core/src/services/overlay/README.md index b4ac2e508df..ae099b70127 100644 --- a/projects/igniteui-angular/core/src/services/overlay/README.md +++ b/projects/igniteui-angular/core/src/services/overlay/README.md @@ -7,10 +7,44 @@ A walk through of how to get started can be found [here](https://www.infragistic - **Popover API Integration**: Uses the HTML Popover API for improved z-index management and automatic top-layer placement - **Flexible Positioning**: Multiple position strategies (global, connected, auto, elastic, container) -- **Scroll Strategies**: Handle scroll behavior with NoOp, Block, Close, and Absolute strategies +- **Native Anchor Positioning**: Connected, auto and container overlays are positioned with CSS anchor positioning where the browser supports it, with no script running on scroll +- **Scroll Strategies**: Handle scroll behavior with NoOp, Block, Close, Absolute and Hide strategies - **Modal Support**: Optional modal backdrop with configurable close-on-outside-click behavior - **Animation Support**: Built-in support for open/close animations +## Positioning engines + +Each time an overlay is shown, the service picks how to position it: + +- **Native** - CSS anchor positioning, resolved by the browser in layout. The content stays attached to its target while the page scrolls or resizes, with every scroll strategy. +- **Script** - the position strategy measures the target and writes pixel offsets, as before 22.4. + +An overlay uses the native engine when the browser supports CSS anchor positioning and one of these applies: + +- The position strategy is exactly `ConnectedPositioningStrategy` or `AutoPositionStrategy` (not a subclass), the target is an `HTMLElement` in the document, in the same document or shadow root as the overlay, and each axis uses one of the pairs listed in the [position strategies README](position/README.md#native-anchor-positioning). +- The position strategy is exactly `ContainerPositionStrategy` and the overlay was attached with it. + +Everything else uses the script engine: `GlobalPositionStrategy`, `ElasticPositionStrategy`, every subclass (for example tooltips), `Point` targets, and browsers without CSS anchor positioning (Safari 18). Chrome, Edge, Firefox and Safari 26 use the native engine. + +Differences under the native engine: + +- Anchored content follows its target on scroll with every scroll strategy, including `NoOpScrollStrategy`. It follows one rendering frame later than the script engine did, so code that scrolls and measures in the same task sees the previous position. +- `AutoPositionStrategy` content can flip while the overlay is open, not only when it is shown. When no side fits, the browser shifts it into the viewport; the exact position can differ from the script engine. +- `ConnectedPositioningStrategy` content never flips or shifts, as before. +- Positions are not rounded to whole pixels. +- While an overlay is open, its target has an inline `anchor-name` style. Values set by the application are kept. +- If the target is removed from the document while the overlay is open, the content loses its position. + +To use the script engine for every overlay, add `provideOverlayAnchoring('script')` to the application providers. It takes effect only in the root environment injector: + +```typescript +import { provideOverlayAnchoring } from 'igniteui-angular/core'; + +bootstrapApplication(AppComponent, { + providers: [provideOverlayAnchoring('script')] +}); +``` + ## Usage ### With igxToggleDirective @@ -138,6 +172,12 @@ this.overlay.show(component, overlaySettings); |createAbsoluteOverlaySettings| Creates overlay settings with global or container position strategy based on a preset position settings |position?, useContainerStrategy?| |createRelativeOverlaySettings| Creates overlay settings with auto, connected or elastic position strategy based on a preset position settings |target, strategy?, position?| +###### Providers + +| Name | Description | Parameters | +|-----------------|---------------------------------------------------------------------------------|------------| +|provideOverlayAnchoring| Selects the positioning engine for every overlay: `'auto'` (default, native where supported) or `'script'`. Root providers only. See [Positioning engines](#positioning-engines). |mode| + ##### Events diff --git a/projects/igniteui-angular/core/src/services/overlay/anchoring/anchor-names.ts b/projects/igniteui-angular/core/src/services/overlay/anchoring/anchor-names.ts new file mode 100644 index 00000000000..680d6b049a6 --- /dev/null +++ b/projects/igniteui-angular/core/src/services/overlay/anchoring/anchor-names.ts @@ -0,0 +1,67 @@ +let counter = 0; + +interface AnchorRecord { + /** Computed `anchor-name` before the element was touched, `''` for `none`. */ + authorValue: string; + /** Inline `anchor-name` before the element was touched, `''` if none. */ + inlineValue: string; + names: string[]; +} + +const records = new WeakMap(); + +/** + * @hidden @internal + * Returns a new, document-unique anchor name. + */ +export function acquireAnchorName(): string { + return `--igx-overlay-anchor-${counter++}`; +} + +/** + * @hidden @internal + * Adds `name` to the element's `anchor-name` list, keeping any author value. + */ +export function addAnchorName(element: HTMLElement, name: string): void { + let record = records.get(element); + if (!record) { + const computed = element.ownerDocument.defaultView + ?.getComputedStyle(element).getPropertyValue('anchor-name').trim() ?? ''; + record = { + authorValue: computed === 'none' ? '' : computed, + inlineValue: element.style.getPropertyValue('anchor-name'), + names: [] + }; + records.set(element, record); + } + if (!record.names.includes(name)) { + record.names.push(name); + } + write(element, record); +} + +/** + * @hidden @internal + * Removes `name` from the element's `anchor-name` list. Restores the author inline value when no names remain. + */ +export function removeAnchorName(element: HTMLElement, name: string): void { + const record = records.get(element); + if (!record) { + return; + } + record.names = record.names.filter(n => n !== name); + if (record.names.length) { + write(element, record); + return; + } + if (record.inlineValue) { + element.style.setProperty('anchor-name', record.inlineValue); + } else { + element.style.removeProperty('anchor-name'); + } + records.delete(element); +} + +function write(element: HTMLElement, record: AnchorRecord): void { + element.style.setProperty('anchor-name', [record.authorValue, ...record.names].filter(Boolean).join(', ')); +} diff --git a/projects/igniteui-angular/core/src/services/overlay/anchoring/anchoring.spec.ts b/projects/igniteui-angular/core/src/services/overlay/anchoring/anchoring.spec.ts new file mode 100644 index 00000000000..b587b687197 --- /dev/null +++ b/projects/igniteui-angular/core/src/services/overlay/anchoring/anchoring.spec.ts @@ -0,0 +1,254 @@ +import { scaleInHorLeft, scaleInHorRight, scaleInVerBottom, scaleInVerTop, fadeIn } from 'igniteui-angular/animations'; +import { afterEach, describe, expect, it } from 'vitest'; +import { HorizontalAlignment as H, PositionSettings, VerticalAlignment as V } from '../utilities'; +import { acquireAnchorName, addAnchorName, removeAnchorName } from './anchor-names'; +import { supportsNativeAnchoring, supportsPositionVisibility } from './anchoring'; +import { + AUTO_FALLBACKS, + connectedDeclarations, + containerDeclarations, + flipAnimation, + isExpressible, + resolveFlippedAxes +} from './native-engine'; + +const HORIZONTAL = [H.Left, H.Center, H.Right]; +const VERTICAL = [V.Top, V.Middle, V.Bottom]; + +const settings = (hs: H, hd: H, vs: V, vd: V, extra: PositionSettings = {}): PositionSettings => ({ + horizontalStartPoint: hs, horizontalDirection: hd, verticalStartPoint: vs, verticalDirection: vd, ...extra +}); + +const asMap = (declarations: ReadonlyArray) => Object.fromEntries(declarations); + +const rect = (left: number, top: number, width: number, height: number) => + ({ left, top, right: left + width, bottom: top + height }); + +describe('Overlay anchoring (pure)', () => { + describe('isExpressible', () => { + const expressible = (start: number, direction: number) => + start === direction || (start !== -0.5 && direction !== -0.5); + + for (const hs of HORIZONTAL) { + for (const hd of HORIZONTAL) { + for (const vs of VERTICAL) { + for (const vd of VERTICAL) { + const expected = expressible(hs, hd) && expressible(vs, vd); + it(`${hs}→${hd}, ${vs}→${vd} is ${expected ? '' : 'not '}expressible`, () => { + expect(isExpressible(settings(hs, hd, vs, vd))).toBe(expected); + }); + } + } + } + } + + it('is false when a value is missing', () => { + expect(isExpressible({ horizontalDirection: H.Right })).toBe(false); + }); + }); + + describe('connectedDeclarations', () => { + const horizontal: [H, H, string, string, string][] = [ + [H.Left, H.Left, 'left', 'normal', 'unsafe right'], + [H.Left, H.Right, 'span-right', 'left', 'unsafe left'], + [H.Center, H.Center, 'span-all', 'anchor-center', 'unsafe anchor-center'], + [H.Right, H.Left, 'span-left', 'right', 'unsafe right'], + [H.Right, H.Right, 'right', 'normal', 'unsafe left'] + ]; + const vertical: [V, V, string, string, string][] = [ + [V.Top, V.Top, 'top', 'normal', 'unsafe end'], + [V.Top, V.Bottom, 'span-bottom', 'self-start', 'unsafe self-start'], + [V.Middle, V.Middle, 'span-all', 'anchor-center', 'unsafe anchor-center'], + [V.Bottom, V.Top, 'span-top', 'self-end', 'unsafe self-end'], + [V.Bottom, V.Bottom, 'bottom', 'normal', 'unsafe start'] + ]; + + for (const [hs, hd, column, hAuto, hConnected] of horizontal) { + for (const [vs, vd, row, vAuto, vConnected] of vertical) { + it(`maps ${hs}→${hd}, ${vs}→${vd} to "${row} ${column}"`, () => { + const s = settings(hs, hd, vs, vd); + const auto = asMap(connectedDeclarations(s, true, '--a', false)); + const connected = asMap(connectedDeclarations(s, false, '--a', false)); + + expect(auto['position-area']).toBe(`${row} ${column}`); + expect(auto['justify-self']).toBe(hAuto); + expect(auto['align-self']).toBe(vAuto); + expect(auto['position-try-fallbacks']).toBe(AUTO_FALLBACKS); + expect(connected['position-area']).toBe(`${row} ${column}`); + expect(connected['justify-self']).toBe(hConnected); + expect(connected['align-self']).toBe(vConnected); + expect(connected['position-try-fallbacks']).toBe('none'); + }); + } + } + + it('writes the fixed base declarations in order', () => { + const declarations = connectedDeclarations(settings(H.Left, H.Right, V.Bottom, V.Bottom), false, '--a', false); + expect(declarations.map(([p]) => p)).toEqual([ + 'position', 'inset', 'margin', 'position-anchor', 'position-area', + 'justify-self', 'align-self', 'position-try-fallbacks', 'position-visibility' + ]); + const map = asMap(declarations); + expect(map.position).toBe('fixed'); + expect(map.inset).toBe('auto'); + expect(map['position-anchor']).toBe('--a'); + expect(map['position-visibility']).toBe('always'); + expect(map.margin).toBe('0px 0px 0px 0px'); + }); + + it('applies the offset as margins on outside axes only', () => { + const bottomBottom = asMap(connectedDeclarations(settings(H.Left, H.Right, V.Bottom, V.Bottom, { offset: 6 }), true, '--a', false)); + expect(bottomBottom.margin).toBe('6px 0px 6px 0px'); + + const rightRight = asMap(connectedDeclarations(settings(H.Right, H.Right, V.Top, V.Bottom, { offset: 4 }), true, '--a', false)); + expect(rightRight.margin).toBe('0px 4px 0px 4px'); + + const centered = asMap(connectedDeclarations(settings(H.Center, H.Center, V.Middle, V.Middle, { offset: 4 }), true, '--a', false)); + expect(centered.margin).toBe('0px 0px 0px 0px'); + }); + + it('writes anchors-visible only when hiding', () => { + const s = settings(H.Left, H.Right, V.Bottom, V.Bottom); + expect(asMap(connectedDeclarations(s, true, '--a', true))['position-visibility']).toBe('anchors-visible'); + expect(asMap(connectedDeclarations(s, true, '--a', false))['position-visibility']).toBe('always'); + }); + }); + + describe('containerDeclarations', () => { + it('anchors all four insets to the container', () => { + expect(asMap(containerDeclarations('--c', false))).toEqual({ + 'position-anchor': '--c', + top: 'anchor(top)', + right: 'anchor(right)', + bottom: 'anchor(bottom)', + left: 'anchor(left)', + 'position-visibility': 'always' + }); + expect(asMap(containerDeclarations('--c', true))['position-visibility']).toBe('anchors-visible'); + }); + }); + + describe('resolveFlippedAxes', () => { + const target = rect(100, 100, 50, 20); // right 150, bottom 120 + + it('detects an unflipped and a flipped vertical outside pair', () => { + const s = settings(H.Left, H.Right, V.Bottom, V.Bottom); + expect(resolveFlippedAxes(s, rect(100, 120, 80, 40), target)).toEqual({ horizontal: false, vertical: false }); + expect(resolveFlippedAxes(s, rect(100, 60, 80, 40), target)).toEqual({ horizontal: false, vertical: true }); + }); + + it('accounts for the offset on outside axes', () => { + const s = settings(H.Left, H.Right, V.Bottom, V.Bottom, { offset: 6 }); + expect(resolveFlippedAxes(s, rect(100, 126, 80, 40), target).vertical).toBe(false); + expect(resolveFlippedAxes(s, rect(100, 54, 80, 40), target).vertical).toBe(true); + }); + + it('detects a flipped horizontal spanning pair', () => { + const s = settings(H.Left, H.Right, V.Bottom, V.Bottom); + // Left → Right flipped is Right → Left: right edges meet. + expect(resolveFlippedAxes(s, rect(70, 120, 80, 40), target).horizontal).toBe(true); + }); + + it('detects both outside axes flipped', () => { + const s = settings(H.Right, H.Right, V.Bottom, V.Bottom); + expect(resolveFlippedAxes(s, rect(20, 60, 80, 40), target)).toEqual({ horizontal: true, vertical: true }); + }); + + it('never flips centered axes', () => { + const s = settings(H.Center, H.Center, V.Middle, V.Middle); + expect(resolveFlippedAxes(s, rect(0, 0, 10, 10), target)).toEqual({ horizontal: false, vertical: false }); + }); + + it('counts a tie as not flipped', () => { + // Content as tall as the space: equally far from both placements. + const s = settings(H.Left, H.Right, V.Bottom, V.Bottom); + expect(resolveFlippedAxes(s, rect(100, 110, 80, 0), target).vertical).toBe(false); + }); + }); + + describe('flipAnimation', () => { + it('reverses vertical animations on a vertical flip only', () => { + expect(flipAnimation(scaleInVerTop, { horizontal: false, vertical: true })).toBe(scaleInVerBottom); + expect(flipAnimation(scaleInVerTop, { horizontal: true, vertical: false })).toBe(scaleInVerTop); + }); + + it('reverses horizontal animations on a horizontal flip only', () => { + expect(flipAnimation(scaleInHorLeft, { horizontal: true, vertical: false })).toBe(scaleInHorRight); + expect(flipAnimation(scaleInHorLeft, { horizontal: false, vertical: true })).toBe(scaleInHorLeft); + }); + + it('keeps animations without a direction and missing animations', () => { + expect(flipAnimation(fadeIn, { horizontal: true, vertical: true })).toBe(fadeIn); + expect(flipAnimation(undefined, { horizontal: true, vertical: true })).toBeUndefined(); + }); + }); + + describe('anchor names', () => { + const elements: HTMLElement[] = []; + const element = () => { + const el = document.createElement('div'); + document.body.appendChild(el); + elements.push(el); + return el; + }; + + afterEach(() => elements.splice(0).forEach(e => e.remove())); + + it('acquires unique names', () => { + const names = new Set([acquireAnchorName(), acquireAnchorName(), acquireAnchorName()]); + expect(names.size).toBe(3); + names.forEach(n => expect(n).toMatch(/^--igx-overlay-anchor-\d+$/)); + }); + + it('adds and removes names, leaving nothing behind', () => { + const el = element(); + addAnchorName(el, '--one'); + addAnchorName(el, '--two'); + addAnchorName(el, '--two'); + expect(el.style.getPropertyValue('anchor-name')).toBe('--one, --two'); + removeAnchorName(el, '--one'); + expect(el.style.getPropertyValue('anchor-name')).toBe('--two'); + removeAnchorName(el, '--two'); + expect(el.getAttribute('style') ?? '').toBe(''); + }); + + it('keeps an author stylesheet value in the list', () => { + const el = element(); + el.id = 'igx-anchor-author'; + const style = document.createElement('style'); + style.textContent = '#igx-anchor-author { anchor-name: --author; }'; + document.head.appendChild(style); + try { + addAnchorName(el, '--one'); + expect(el.style.getPropertyValue('anchor-name')).toBe('--author, --one'); + removeAnchorName(el, '--one'); + expect(el.style.getPropertyValue('anchor-name')).toBe(''); + } finally { + style.remove(); + } + }); + + it('restores an author inline value exactly', () => { + const el = element(); + el.style.setProperty('anchor-name', '--inline'); + addAnchorName(el, '--one'); + expect(el.style.getPropertyValue('anchor-name')).toBe('--inline, --one'); + removeAnchorName(el, '--one'); + expect(el.style.getPropertyValue('anchor-name')).toBe('--inline'); + }); + + it('ignores removing an unknown name', () => { + const el = element(); + expect(() => removeAnchorName(el, '--never')).not.toThrow(); + }); + }); + + describe('feature detection', () => { + it('detects support in this browser and none without a window', () => { + expect(supportsNativeAnchoring(window)).toBe(true); + expect(supportsPositionVisibility(window)).toBe(true); + expect(supportsNativeAnchoring(null)).toBe(false); + expect(supportsPositionVisibility(undefined)).toBe(false); + }); + }); +}); diff --git a/projects/igniteui-angular/core/src/services/overlay/anchoring/anchoring.ts b/projects/igniteui-angular/core/src/services/overlay/anchoring/anchoring.ts new file mode 100644 index 00000000000..9fd642021bb --- /dev/null +++ b/projects/igniteui-angular/core/src/services/overlay/anchoring/anchoring.ts @@ -0,0 +1,67 @@ +import { EnvironmentProviders, InjectionToken, makeEnvironmentProviders } from '@angular/core'; + +/** + * Selects how `IgxOverlayService` positions overlays. + * + * - `'auto'` - native CSS anchor positioning where the browser supports it, script positioning elsewhere. + * - `'script'` - script positioning for every overlay, as before 22.4. + */ +export type OverlayAnchoringMode = 'auto' | 'script'; + +/** @hidden @internal */ +export const IGX_OVERLAY_ANCHORING = new InjectionToken('IGX_OVERLAY_ANCHORING'); + +/** + * Configures how `IgxOverlayService` positions overlays. + * + * With `'auto'` (the default), overlays that use `ConnectedPositioningStrategy`, `AutoPositionStrategy` + * or `ContainerPositionStrategy` are positioned with native CSS anchor positioning where the browser + * supports it. With `'script'`, every overlay is positioned by script, as before 22.4. + * + * Takes effect only in the root environment injector (`bootstrapApplication` / `appConfig.providers`). + * In the providers of a lazy route it has no effect, because the root `IgxOverlayService` already exists. + * + * @param mode `'auto'` or `'script'`. + * @returns Environment providers to add to the application providers. + * + * @example + * ```typescript + * bootstrapApplication(AppComponent, { + * providers: [provideOverlayAnchoring('script')] + * }); + * ``` + */ +export function provideOverlayAnchoring(mode: OverlayAnchoringMode): EnvironmentProviders { + return makeEnvironmentProviders([{ provide: IGX_OVERLAY_ANCHORING, useValue: mode }]); +} + +/** + * @hidden @internal + * Whether the window supports every CSS anchor positioning feature the native engine writes. + */ +export function supportsNativeAnchoring(win: (Window & typeof globalThis) | null | undefined): boolean { + const css = win?.CSS; + if (typeof css?.supports !== 'function') { + return false; + } + return css.supports('anchor-name', '--igx-probe') + && css.supports('position-anchor', '--igx-probe') + && css.supports('position-area', 'bottom span-right') + && css.supports('position-try-fallbacks', 'flip-block, flip-inline') + && css.supports('top', 'anchor(top)') + && css.supports('justify-self', 'anchor-center') + // Connected overlays rely on `unsafe` overflow alignment so that they never shift. + // DISCUSS(#17765): verified in Chromium only. If Firefox 147+ or Safari 26 lack `unsafe anchor-center`, + // this probe turns off the whole native engine there, not only Connected. Alternative: probe it + // separately and let Connected fall back to plain alignment (content could then shift). + && css.supports('justify-self', 'unsafe anchor-center'); +} + +/** + * @hidden @internal + * Whether the window supports `position-visibility: anchors-visible`. + */ +export function supportsPositionVisibility(win: (Window & typeof globalThis) | null | undefined): boolean { + const css = win?.CSS; + return typeof css?.supports === 'function' && css.supports('position-visibility', 'anchors-visible'); +} diff --git a/projects/igniteui-angular/core/src/services/overlay/anchoring/native-anchoring.spec.ts b/projects/igniteui-angular/core/src/services/overlay/anchoring/native-anchoring.spec.ts new file mode 100644 index 00000000000..8034b82783c --- /dev/null +++ b/projects/igniteui-angular/core/src/services/overlay/anchoring/native-anchoring.spec.ts @@ -0,0 +1,590 @@ +import { afterEach, describe, expect, it } from 'vitest'; + +/** + * Gate tests for native CSS anchor positioning in `IgxOverlayService` (#17765). + * + * These tests use no service code. Each test builds the overlay DOM the service creates + * (`div.igx-overlay__wrapper[popover=manual]` > `div.igx-overlay__content`), writes the inline + * declarations that the native engine will write, and measures what the browser does. + * They prove that the browser supports the design, and they stay in the suite as regression + * tests for the browser capabilities the native engine depends on. + * + * The comment above each test says what to change in the design if the test fails. + */ + +const AUTO_FALLBACKS = 'flip-block, flip-inline, flip-block flip-inline'; +/** Native positions are not rounded. */ +const TOLERANCE = 1; + +interface Box { top: number; left: number; width: number; height: number; } + +interface ConnectedOptions { + /** `true` for the `AutoPositionStrategy` fallbacks, `false` for `ConnectedPositioningStrategy`. */ + auto?: boolean; + margin?: string; + visibility?: 'always' | 'anchors-visible'; +} + +let nameCounter = 0; +const createdNodes: HTMLElement[] = []; + +function nextAnchorName(): string { + return `--igx-gate-anchor-${nameCounter++}`; +} + +/** Waits for the given number of animation frames, so that layout and anchor fallbacks resolve. */ +async function frames(count = 2): Promise { + for (let i = 0; i < count; i++) { + await new Promise(resolve => requestAnimationFrame(() => resolve())); + } +} + +function track(element: T, parent: Node): T { + parent.appendChild(element); + if (parent === document.body) { + createdNodes.push(element); + } + return element; +} + +/** Creates a fixed box that acts as an overlay target. */ +function addTarget(box: Box, anchorName: string, parent: Node = document.body): HTMLElement { + const target = document.createElement('div'); + Object.assign(target.style, { + position: 'fixed', + top: `${box.top}px`, + left: `${box.left}px`, + width: `${box.width}px`, + height: `${box.height}px`, + background: 'gold' + }); + target.style.setProperty('anchor-name', anchorName); + return track(target, parent); +} + +/** + * Creates and shows the overlay DOM. `updateSize()` in the service writes an explicit pixel width, + * so the content gets one here too. + */ +function openOverlay( + size: { width: number; height: number }, + declarations: Record, + parent: Node = document.body +): { wrapper: HTMLElement; content: HTMLElement } { + const wrapper = document.createElement('div'); + wrapper.classList.add('igx-overlay__wrapper'); + wrapper.setAttribute('popover', 'manual'); + + const content = document.createElement('div'); + content.classList.add('igx-overlay__content'); + content.style.width = `${size.width}px`; + content.style.height = `${size.height}px`; + content.style.background = 'steelblue'; + for (const [property, value] of Object.entries(declarations)) { + content.style.setProperty(property, value); + } + + wrapper.appendChild(content); + track(wrapper, parent); + wrapper.showPopover(); + return { wrapper, content }; +} + +/** The declarations of the native-connected engine, in the order of §7.4 of the plan. */ +function connected(anchorName: string, area: string, justifySelf: string, alignSelf: string, options: ConnectedOptions = {}) { + return { + 'position': 'fixed', + 'inset': 'auto', + 'margin': options.margin ?? '0px 0px 0px 0px', + 'position-anchor': anchorName, + 'position-area': area, + 'justify-self': justifySelf, + 'align-self': alignSelf, + 'position-try-fallbacks': options.auto ? AUTO_FALLBACKS : 'none', + 'position-visibility': options.visibility ?? 'always' + }; +} + +function expectNear(actual: number, expected: number, label: string): void { + expect(Math.abs(actual - expected), `${label}: ${actual} instead of ${expected}`).toBeLessThanOrEqual(TOLERANCE); +} + +/** `checkVisibility()` and computed styles do not report the `position-visibility` state, so hit-test. */ +function isHitTestable(element: HTMLElement): boolean { + const rect = element.getBoundingClientRect(); + const hit = document.elementFromPoint(rect.left + rect.width / 2, rect.top + rect.height / 2); + return !!hit && element.contains(hit); +} + +describe('Native CSS anchor positioning gate tests', () => { + afterEach(() => { + // Removing an open popover from the document also hides it. + while (createdNodes.length) { + createdNodes.pop()!.remove(); + } + }); + + it('G0 - the test browser supports the final property names', () => { + expect(CSS.supports('anchor-name', '--igx-probe')).toBe(true); + expect(CSS.supports('position-anchor', '--igx-probe')).toBe(true); + expect(CSS.supports('position-area', 'bottom span-right')).toBe(true); + expect(CSS.supports('position-try-fallbacks', 'flip-block, flip-inline')).toBe(true); + expect(CSS.supports('top', 'anchor(top)')).toBe(true); + expect(CSS.supports('justify-self', 'anchor-center')).toBe(true); + expect(CSS.supports('position-visibility', 'anchors-visible')).toBe(true); + }); + + // If it fails: stop. The explicit anchor name design is invalid. Plan B is the implicit anchor + // (`showPopover({ source })`) with the popover moved from the wrapper to the content. + it('G1 - content in the top layer wrapper anchors to a target in the page', async () => { + const name = nextAnchorName(); + const target = addTarget({ top: 100, left: 100, width: 100, height: 30 }, name); + const { content } = openOverlay({ width: 200, height: 150 }, connected(name, 'bottom span-right', 'left', 'normal')); + await frames(); + + const t = target.getBoundingClientRect(); + const c = content.getBoundingClientRect(); + expectNear(c.top, t.bottom, 'content top'); + expectNear(c.left, t.left, 'content left'); + }); + + // If it fails: a target inside `.igx-overlay__content` / `.igx-overlay__content--modal` uses the script engine. + it.each([ + ['the body', false], + ['the outer overlay content', true] + ])('G2 - content anchors to a target inside another open overlay (inner wrapper in %s)', async (_, insideOuter) => { + const outer = openOverlay({ width: 300, height: 200 }, { top: '200px', left: '300px' }); + const name = nextAnchorName(); + const target = document.createElement('div'); + Object.assign(target.style, { position: 'absolute', top: '20px', left: '20px', width: '100px', height: '30px' }); + target.style.setProperty('anchor-name', name); + outer.content.appendChild(target); + + const parent = insideOuter ? outer.content : document.body; + const { content } = openOverlay({ width: 200, height: 150 }, connected(name, 'bottom span-right', 'left', 'normal'), parent); + await frames(); + + const t = target.getBoundingClientRect(); + const c = content.getBoundingClientRect(); + expectNear(c.top, t.bottom, 'content top'); + expectNear(c.left, t.left, 'content left'); + }); + + // If it fails: stop and escalate. + it('G3 - Auto flips above a target near the bottom edge', async () => { + const name = nextAnchorName(); + const target = addTarget({ top: innerHeight - 120, left: 100, width: 100, height: 30 }, name); + const { content } = openOverlay({ width: 200, height: 150 }, + connected(name, 'bottom span-right', 'left', 'normal', { auto: true })); + await frames(); + + const t = target.getBoundingClientRect(); + const c = content.getBoundingClientRect(); + expectNear(c.bottom, t.top, 'content bottom'); + expectNear(c.left, t.left, 'content left'); + }); + + // If it fails: re-run with `justify-self: normal` on spanning pairs. If that passes, change the tables + // in §7.3 to `normal` for spanning pairs. If not, escalate. + it('G4 - Auto flips a spanning pair to the left of a target near the right edge', async () => { + const name = nextAnchorName(); + const target = addTarget({ top: 100, left: innerWidth - 80, width: 60, height: 30 }, name); + const { content } = openOverlay({ width: 200, height: 150 }, + connected(name, 'bottom span-right', 'left', 'normal', { auto: true })); + await frames(); + + const t = target.getBoundingClientRect(); + const c = content.getBoundingClientRect(); + expectNear(c.right, t.right, 'content right (justify-self flipped with the area)'); + expectNear(c.top, t.bottom, 'content top'); + }); + + // Vertical counterpart of G4, for `align-self: self-start` on a spanning row. + it('G4b - Auto flips a spanning row above a target near the bottom edge', async () => { + const name = nextAnchorName(); + const target = addTarget({ top: innerHeight - 100, left: 100, width: 100, height: 60 }, name); + const { content } = openOverlay({ width: 200, height: 150 }, + connected(name, 'span-bottom right', 'normal', 'self-start', { auto: true })); + await frames(); + + const t = target.getBoundingClientRect(); + const c = content.getBoundingClientRect(); + expectNear(c.bottom, t.bottom, 'content bottom (align-self flipped with the area)'); + expectNear(c.left, t.right, 'content left'); + }); + + // If it fails: escalate. + it('G5 - Auto flips both axes for a target in the bottom right corner', async () => { + const name = nextAnchorName(); + const target = addTarget({ top: innerHeight - 70, left: innerWidth - 80, width: 60, height: 30 }, name); + const { content } = openOverlay({ width: 200, height: 150 }, + connected(name, 'bottom span-right', 'left', 'normal', { auto: true })); + await frames(); + + const t = target.getBoundingClientRect(); + const c = content.getBoundingClientRect(); + expectNear(c.right, t.right, 'content right'); + expectNear(c.bottom, t.top, 'content bottom'); + }); + + // Amends §7.3: a centered pair maps to `span-all` with `anchor-center`, not to `center` (see G6b). + // If it fails: Auto overlays with exactly one centered axis use the script engine + // (affects the grid cell error tooltip and the extras tabs menu). + describe('G6 - a centered axis (span-all, anchor-center)', () => { + it('flips the other axis and shifts into the viewport', async () => { + const name = nextAnchorName(); + const target = addTarget({ top: innerHeight - 120, left: 20, width: 40, height: 30 }, name); + const { content } = openOverlay({ width: 200, height: 150 }, + connected(name, 'bottom span-all', 'anchor-center', 'normal', { auto: true })); + await frames(); + + const t = target.getBoundingClientRect(); + const c = content.getBoundingClientRect(); + expectNear(c.bottom, t.top, 'content bottom'); + expect(c.left, `content left: ${c.left}`).toBeGreaterThanOrEqual(-0.5); + }); + + it('stays centered on the target after a horizontal-centered flip', async () => { + const name = nextAnchorName(); + const target = addTarget({ top: innerHeight - 120, left: 600, width: 40, height: 30 }, name); + const { content } = openOverlay({ width: 200, height: 150 }, + connected(name, 'bottom span-all', 'anchor-center', 'normal', { auto: true })); + await frames(); + + const t = target.getBoundingClientRect(); + const c = content.getBoundingClientRect(); + expectNear(c.bottom, t.top, 'content bottom'); + expectNear(c.left + c.width / 2, t.left + t.width / 2, 'horizontal center'); + }); + + it('flips inline for a vertically centered pair near the right edge', async () => { + const name = nextAnchorName(); + const target = addTarget({ top: 300, left: innerWidth - 80, width: 60, height: 30 }, name); + const { content } = openOverlay({ width: 200, height: 150 }, + connected(name, 'span-all right', 'normal', 'anchor-center', { auto: true })); + await frames(); + + const t = target.getBoundingClientRect(); + const c = content.getBoundingClientRect(); + expectNear(c.right, t.left, 'content right'); + expectNear(c.top + c.height / 2, t.top + t.height / 2, 'vertical center'); + }); + }); + + // Informative. Why §7.3 does not use `center`: the `center` area is only as wide as the target, so wider + // content overflows it in every fallback and the browser keeps the base option, shifted over the target. + // If it fails, the browser now flips a `center` area: G6 still holds; this test can go. + it('G6b - a `center` area does not flip content wider than the target', async () => { + const name = nextAnchorName(); + const target = addTarget({ top: innerHeight - 120, left: 600, width: 40, height: 30 }, name); + const { content } = openOverlay({ width: 200, height: 150 }, + connected(name, 'bottom center', 'anchor-center', 'normal', { auto: true })); + await frames(); + + const t = target.getBoundingClientRect(); + const c = content.getBoundingClientRect(); + expect(Math.abs(c.bottom - t.top), 'flipped above the target').toBeGreaterThan(TOLERANCE); + }); + + // Content that fits on neither side of the target: taller than the space above and below it. + const tallContent = () => ({ width: 200, height: innerHeight - 200 }); + const midTarget: Box = { top: 300, left: 100, width: 100, height: 30 }; + + // Measured: with `normal` alignment the browser pushes the content into the viewport on the outside + // axis, for Auto and for Connected. Auto then matches the script engine (which also pushes); + // Connected does not (the script never moves Connected content). Amends §7.3, D13 and §17. + // If it fails: the browser no longer pushes; restore the original G7 wording of the plan. + it.each([ + ['Auto', true], + ['Connected', false] + ])('G7 - %s with normal alignment pushes content that fits on neither side into the viewport', async (_, auto) => { + const name = nextAnchorName(); + const target = addTarget(midTarget, name); + const { content } = openOverlay(tallContent(), connected(name, 'bottom span-right', 'left', 'normal', { auto })); + await frames(); + + const t = target.getBoundingClientRect(); + const c = content.getBoundingClientRect(); + expect(c.top, 'pushed up over the target').toBeLessThan(t.bottom - TOLERANCE); + expectNear(c.bottom, innerHeight, 'content bottom at the viewport edge'); + }); + + // An `unsafe` alignment turns the push off and keeps the flip. Use it if Connected must keep script + // parity (no push), or if Auto must not push on the outside axis. + // If it fails: the push cannot be turned off; only the documentation option of G7 remains. + describe('G7b - unsafe alignment on the outside axis', () => { + it.each([ + ['Auto', true], + ['Connected', false] + ])('%s keeps content that fits on neither side at the target', async (_, auto) => { + const name = nextAnchorName(); + const target = addTarget(midTarget, name); + const { content } = openOverlay(tallContent(), connected(name, 'bottom span-right', 'left', 'unsafe start', { auto })); + await frames(); + + expectNear(content.getBoundingClientRect().top, target.getBoundingClientRect().bottom, 'content top'); + }); + + it('Auto still flips', async () => { + const name = nextAnchorName(); + const target = addTarget({ top: innerHeight - 120, left: 100, width: 100, height: 30 }, name); + const { content } = openOverlay({ width: 200, height: 150 }, + connected(name, 'bottom span-right', 'left', 'unsafe start', { auto: true })); + await frames(); + + expectNear(content.getBoundingClientRect().bottom, target.getBoundingClientRect().top, 'content bottom'); + }); + }); + + // Connected keeps script parity: the script never moves Connected content, so every axis uses an `unsafe` + // alignment and the browser never shifts the content into the viewport. + // If it fails: Connected content can shift; document it in §17 as a behavioral change. + describe('G12 - Connected with unsafe alignment never shifts the content', () => { + it('Top → Top stays above a target when it fits on neither side', async () => { + const name = nextAnchorName(); + const target = addTarget({ top: innerHeight - 330, left: 100, width: 100, height: 30 }, name); + const { content } = openOverlay(tallContent(), connected(name, 'top span-right', 'unsafe left', 'unsafe end')); + await frames(); + + expectNear(content.getBoundingClientRect().bottom, target.getBoundingClientRect().top, 'content bottom'); + }); + + it('Left → Left stays left of a target when it fits on neither side', async () => { + const name = nextAnchorName(); + const target = addTarget({ top: 100, left: 500, width: 100, height: 30 }, name); + const { content } = openOverlay({ width: innerWidth - 500, height: 150 }, + connected(name, 'span-bottom left', 'unsafe right', 'unsafe self-start')); + await frames(); + + expectNear(content.getBoundingClientRect().right, target.getBoundingClientRect().left, 'content right'); + }); + + it('Right → Right stays right of a target when it fits on neither side', async () => { + const name = nextAnchorName(); + const target = addTarget({ top: 100, left: 500, width: 100, height: 30 }, name); + const { content } = openOverlay({ width: innerWidth - 500, height: 150 }, + connected(name, 'span-bottom right', 'unsafe left', 'unsafe self-start')); + await frames(); + + expectNear(content.getBoundingClientRect().left, target.getBoundingClientRect().right, 'content left'); + }); + + it('a spanning axis keeps the edge alignment at the right edge of the viewport', async () => { + const name = nextAnchorName(); + const target = addTarget({ top: 100, left: innerWidth - 80, width: 60, height: 30 }, name); + const { content } = openOverlay({ width: 200, height: 150 }, + connected(name, 'bottom span-right', 'unsafe left', 'unsafe start')); + await frames(); + + expectNear(content.getBoundingClientRect().left, target.getBoundingClientRect().left, 'content left'); + }); + + it('a vertical spanning axis keeps the edge alignment at the bottom of the viewport', async () => { + const name = nextAnchorName(); + const target = addTarget({ top: innerHeight - 100, left: 100, width: 100, height: 60 }, name); + const { content } = openOverlay({ width: 200, height: 150 }, + connected(name, 'span-bottom right', 'unsafe left', 'unsafe self-start')); + await frames(); + + expectNear(content.getBoundingClientRect().top, target.getBoundingClientRect().top, 'content top'); + }); + + it('Right → Left keeps the edge alignment at the left edge of the viewport', async () => { + const name = nextAnchorName(); + const target = addTarget({ top: 100, left: 20, width: 60, height: 30 }, name); + const { content } = openOverlay({ width: 200, height: 150 }, + connected(name, 'bottom span-left', 'unsafe right', 'unsafe start')); + await frames(); + + expectNear(content.getBoundingClientRect().right, target.getBoundingClientRect().right, 'content right'); + }); + + it('Bottom → Top keeps the edge alignment at the top of the viewport', async () => { + const name = nextAnchorName(); + const target = addTarget({ top: 20, left: 100, width: 100, height: 60 }, name); + const { content } = openOverlay({ width: 200, height: 150 }, + connected(name, 'span-top right', 'unsafe left', 'unsafe self-end')); + await frames(); + + expectNear(content.getBoundingClientRect().bottom, target.getBoundingClientRect().bottom, 'content bottom'); + }); + + it('a centered axis stays centered on a target at the left edge', async () => { + const name = nextAnchorName(); + const target = addTarget({ top: 100, left: 20, width: 40, height: 30 }, name); + const { content } = openOverlay({ width: 200, height: 150 }, + connected(name, 'bottom span-all', 'unsafe anchor-center', 'unsafe start')); + await frames(); + + const t = target.getBoundingClientRect(); + const c = content.getBoundingClientRect(); + expectNear(c.left + c.width / 2, t.left + t.width / 2, 'horizontal center'); + }); + + it('both centered axes (span-all span-all) center on the target', async () => { + const name = nextAnchorName(); + const target = addTarget({ top: 200, left: 300, width: 400, height: 300 }, name); + const { content } = openOverlay({ width: 200, height: 150 }, + connected(name, 'span-all span-all', 'unsafe anchor-center', 'unsafe anchor-center')); + await frames(); + + const t = target.getBoundingClientRect(); + const c = content.getBoundingClientRect(); + expectNear(c.left + c.width / 2, t.left + t.width / 2, 'horizontal center'); + expectNear(c.top + c.height / 2, t.top + t.height / 2, 'vertical center'); + }); + }); + + // Auto keeps the safe defaults, so it shifts like the script engine pushes. + it('G13 - Auto with both centered axes (span-all span-all) centers on the target', async () => { + const name = nextAnchorName(); + const target = addTarget({ top: 200, left: 300, width: 400, height: 300 }, name); + const { content } = openOverlay({ width: 200, height: 150 }, + connected(name, 'span-all span-all', 'anchor-center', 'anchor-center', { auto: true })); + await frames(); + + const t = target.getBoundingClientRect(); + const c = content.getBoundingClientRect(); + expectNear(c.left + c.width / 2, t.left + t.width / 2, 'horizontal center'); + expectNear(c.top + c.height / 2, t.top + t.height / 2, 'vertical center'); + }); + + // If it fails: escalate. + it('G8 - an offset becomes a gap on the target side, before and after a flip', async () => { + const options: ConnectedOptions = { auto: true, margin: '6px 0px 6px 0px' }; + const belowName = nextAnchorName(); + const below = addTarget({ top: 100, left: 100, width: 100, height: 30 }, belowName); + const belowOverlay = openOverlay({ width: 200, height: 150 }, connected(belowName, 'bottom span-right', 'left', 'normal', options)); + + const aboveName = nextAnchorName(); + const above = addTarget({ top: innerHeight - 120, left: 400, width: 100, height: 30 }, aboveName); + const aboveOverlay = openOverlay({ width: 200, height: 150 }, connected(aboveName, 'bottom span-right', 'left', 'normal', options)); + await frames(); + + expectNear(belowOverlay.content.getBoundingClientRect().top, below.getBoundingClientRect().bottom + 6, 'top below the target'); + expectNear(aboveOverlay.content.getBoundingClientRect().bottom, above.getBoundingClientRect().top - 6, 'bottom above the target'); + expectNear(aboveOverlay.content.getBoundingClientRect().left, above.getBoundingClientRect().left, 'left above the target'); + }); + + // If it fails: `ContainerPositionStrategy` uses the script engine (agreed fallback); record why here. + it('G9 - a container wrapper covers its container div and follows it on scroll, with no observer', async () => { + const scroller = document.createElement('div'); + Object.assign(scroller.style, { position: 'fixed', top: '100px', left: '100px', width: '400px', height: '300px', overflow: 'auto' }); + track(scroller, document.body); + + const box = document.createElement('div'); + Object.assign(box.style, { position: 'relative', marginTop: '100px', width: '300px', height: '200px' }); + scroller.appendChild(box); + const spacer = document.createElement('div'); + spacer.style.height = '1000px'; + scroller.appendChild(spacer); + + // The div that `insertWrapperInContainer()` creates. + const name = nextAnchorName(); + const container = document.createElement('div'); + Object.assign(container.style, { position: 'absolute', inset: '0', pointerEvents: 'none' }); + container.style.setProperty('anchor-name', name); + box.appendChild(container); + + const wrapper = document.createElement('div'); + wrapper.classList.add('igx-overlay__wrapper'); + wrapper.setAttribute('popover', 'manual'); + const declarations: Record = { + 'position-anchor': name, + 'top': 'anchor(top)', + 'right': 'anchor(right)', + 'bottom': 'anchor(bottom)', + 'left': 'anchor(left)', + 'position-visibility': 'always' + }; + for (const [property, value] of Object.entries(declarations)) { + wrapper.style.setProperty(property, value); + } + container.appendChild(wrapper); + wrapper.showPopover(); + await frames(); + + const expectCovers = (when: string) => { + const d = container.getBoundingClientRect(); + const w = wrapper.getBoundingClientRect(); + expectNear(w.top, d.top, `${when}: top`); + expectNear(w.left, d.left, `${when}: left`); + expectNear(w.width, d.width, `${when}: width`); + expectNear(w.height, d.height, `${when}: height`); + }; + + expectCovers('before scroll'); + const topBefore = container.getBoundingClientRect().top; + + scroller.scrollTop = 50; + await frames(); + + expectNear(container.getBoundingClientRect().top, topBefore - 50, 'the container div moved'); + expectCovers('after scroll'); + }); + + describe('G10 - position-visibility', () => { + /** A target inside a scroll container, low enough that the content stays in the viewport when it is clipped. */ + function setup(visibility: 'always' | 'anchors-visible') { + const scroller = document.createElement('div'); + Object.assign(scroller.style, { position: 'fixed', top: '400px', left: '100px', width: '300px', height: '100px', overflow: 'auto' }); + track(scroller, document.body); + + const name = nextAnchorName(); + const target = document.createElement('div'); + Object.assign(target.style, { marginTop: '10px', width: '100px', height: '30px', background: 'gold' }); + target.style.setProperty('anchor-name', name); + scroller.appendChild(target); + const spacer = document.createElement('div'); + spacer.style.height = '1000px'; + scroller.appendChild(spacer); + + const { content } = openOverlay({ width: 200, height: 60 }, connected(name, 'bottom span-right', 'left', 'normal', { visibility })); + return { scroller, target, content }; + } + + // If it fails: `HideScrollStrategy` always uses the IntersectionObserver fallback. + it('anchors-visible hides the content while the target is fully clipped', async () => { + const { scroller, target, content } = setup('anchors-visible'); + await frames(); + expect(isHitTestable(content), 'visible before scroll').toBe(true); + + // The target ends 20px above the visible area of the scroller. + scroller.scrollTop = 60; + await frames(); + expect(target.getBoundingClientRect().bottom).toBeLessThan(scroller.getBoundingClientRect().top); + expect(isHitTestable(content), 'hidden while the target is clipped').toBe(false); + + scroller.scrollTop = 0; + await frames(); + expect(isHitTestable(content), 'visible again').toBe(true); + }); + + it('always keeps the content visible while the target is fully clipped', async () => { + const { scroller, content } = setup('always'); + await frames(); + + scroller.scrollTop = 60; + await frames(); + expect(isHitTestable(content)).toBe(true); + }); + }); + + // Informative. Proves that the native engine needs the same-tree rule (R3). + // If it fails, the browser resolves anchor names across shadow roots: delete this test. + it('G11 - an anchor name inside a shadow root does not anchor content in the light DOM', async () => { + const host = document.createElement('div'); + track(host, document.body); + const shadowRoot = host.attachShadow({ mode: 'open' }); + + const name = nextAnchorName(); + const target = addTarget({ top: 300, left: 400, width: 100, height: 30 }, name, shadowRoot); + const { content } = openOverlay({ width: 200, height: 150 }, connected(name, 'bottom span-right', 'left', 'normal')); + await frames(); + + const t = target.getBoundingClientRect(); + const c = content.getBoundingClientRect(); + const anchored = Math.abs(c.top - t.bottom) <= TOLERANCE && Math.abs(c.left - t.left) <= TOLERANCE; + expect(anchored).toBe(false); + }); +}); diff --git a/projects/igniteui-angular/core/src/services/overlay/anchoring/native-engine.ts b/projects/igniteui-angular/core/src/services/overlay/anchoring/native-engine.ts new file mode 100644 index 00000000000..7cca8ab8fb2 --- /dev/null +++ b/projects/igniteui-angular/core/src/services/overlay/anchoring/native-engine.ts @@ -0,0 +1,197 @@ +import { AnimationReferenceMetadata } from '@angular/animations'; +import { AnimationUtil } from 'igniteui-angular/animations'; +import { HorizontalAlignment, PositionSettings, VerticalAlignment } from '../utilities'; + +/** @hidden @internal */ +export type OverlayEngine = 'script' | 'native-connected' | 'native-container'; + +/** @hidden @internal Ordered list of inline declarations. */ +export type NativeDeclarations = ReadonlyArray; + +/** @hidden @internal Inline properties the script engine writes on the content element. */ +export const SCRIPT_CONTENT_PROPS = ['top', 'right', 'bottom', 'left', 'transform'] as const; +/** @hidden @internal Inline properties the native engine writes on the content element. */ +export const NATIVE_CONTENT_PROPS = [ + 'position', 'inset', 'margin', 'position-anchor', 'position-area', + 'justify-self', 'align-self', 'position-try-fallbacks', 'position-visibility' +] as const; +/** @hidden @internal Inline properties the script engine writes on the wrapper element. */ +export const SCRIPT_WRAPPER_PROPS = ['top', 'left', 'width', 'height'] as const; +/** @hidden @internal Inline properties the native engine writes on the wrapper element. */ +export const NATIVE_WRAPPER_PROPS = ['position-anchor', 'top', 'right', 'bottom', 'left', 'position-visibility'] as const; + +/** @hidden @internal Fallbacks for `AutoPositionStrategy`: each axis flips independently, then both. */ +export const AUTO_FALLBACKS = 'flip-block, flip-inline, flip-block flip-inline'; + +interface AxisMapping { + /** `position-area` track on this axis. */ + area: string; + /** Self-alignment for Auto: the browser's default overflow alignment may shift the content into view. */ + auto: string; + /** Self-alignment for Connected: `unsafe`, so the content never shifts, as with the script engine. */ + connected: string; + /** The content lies wholly outside the target on this axis; only these axes get `offset`. */ + outside: boolean; +} + +const pairKey = (start: number | undefined, direction: number | undefined) => `${start}|${direction}`; + +const H = HorizontalAlignment; +const V = VerticalAlignment; + +// DISCUSS(#17765): these tables differ from the approved plan (§7.3, D13, Appendix A), following the gate +// tests (option 1): centered pairs use `span-all` instead of `center` (G6, G6b, G13), and Connected uses +// `unsafe` alignment so it never shifts (G7, G12). §15 requires the amended spec to be re-approved. +// +// DISCUSS(#17765): only these 5 pairs per axis go native. Start points default to Left/Bottom, so code that +// sets only a direction (e.g. `horizontalDirection: Center` → `Left → Center`, `verticalDirection: Middle` +// → `Bottom → Middle`) silently stays on the script engine. The drop-down demo's top/bottom/left/right +// placements all do. Decide whether that is acceptable or whether `anchor()` insets should cover the other pairs. + +/** + * Horizontal pairs (`horizontalStartPoint → horizontalDirection`). + * Centered pairs use `span-all`: a `center` track is only as wide as the target, so wider content + * would overflow it on both sides and never flip. + */ +const HORIZONTAL = new Map([ + [pairKey(H.Left, H.Left), { area: 'left', auto: 'normal', connected: 'unsafe right', outside: true }], + [pairKey(H.Left, H.Right), { area: 'span-right', auto: 'left', connected: 'unsafe left', outside: false }], + [pairKey(H.Center, H.Center), { area: 'span-all', auto: 'anchor-center', connected: 'unsafe anchor-center', outside: false }], + [pairKey(H.Right, H.Left), { area: 'span-left', auto: 'right', connected: 'unsafe right', outside: false }], + [pairKey(H.Right, H.Right), { area: 'right', auto: 'normal', connected: 'unsafe left', outside: true }] +]); + +/** Vertical pairs (`verticalStartPoint → verticalDirection`). */ +const VERTICAL = new Map([ + [pairKey(V.Top, V.Top), { area: 'top', auto: 'normal', connected: 'unsafe end', outside: true }], + [pairKey(V.Top, V.Bottom), { area: 'span-bottom', auto: 'self-start', connected: 'unsafe self-start', outside: false }], + [pairKey(V.Middle, V.Middle), { area: 'span-all', auto: 'anchor-center', connected: 'unsafe anchor-center', outside: false }], + [pairKey(V.Bottom, V.Top), { area: 'span-top', auto: 'self-end', connected: 'unsafe self-end', outside: false }], + [pairKey(V.Bottom, V.Bottom), { area: 'bottom', auto: 'normal', connected: 'unsafe start', outside: true }] +]); + +const horizontalOf = (s: PositionSettings) => HORIZONTAL.get(pairKey(s.horizontalStartPoint, s.horizontalDirection)); +const verticalOf = (s: PositionSettings) => VERTICAL.get(pairKey(s.verticalStartPoint, s.verticalDirection)); + +/** + * @hidden @internal + * Whether both axes of the settings map to `position-area`. + */ +export function isExpressible(settings: PositionSettings): boolean { + return !!horizontalOf(settings) && !!verticalOf(settings); +} + +/** + * @hidden @internal + * The inline declarations for a native Connected or Auto overlay content element. + * Call only with expressible settings. + */ +export function connectedDeclarations( + settings: PositionSettings, isAuto: boolean, anchorName: string, hide: boolean +): NativeDeclarations { + const h = horizontalOf(settings)!; + const v = verticalOf(settings)!; + const offset = settings.offset ?? 0; + const mv = v.outside ? offset : 0; + const mh = h.outside ? offset : 0; + return [ + ['position', 'fixed'], + ['inset', 'auto'], + ['margin', `${mv}px ${mh}px ${mv}px ${mh}px`], + ['position-anchor', anchorName], + ['position-area', `${v.area} ${h.area}`], + ['justify-self', isAuto ? h.auto : h.connected], + ['align-self', isAuto ? v.auto : v.connected], + ['position-try-fallbacks', isAuto ? AUTO_FALLBACKS : 'none'], + ['position-visibility', hide ? 'anchors-visible' : 'always'] + ]; +} + +/** + * @hidden @internal + * The inline declarations for a native Container overlay wrapper element. + * + * DISCUSS(#17765): likely obsolete. `vkombov/fix-17986` (#17986, 22.3.1) takes Container overlays out of + * the top layer, so the container clips and scrolls them with no positioning code. Native Container + * (D11, D12, §8.2, PR 3) would then be unnecessary; + */ +export function containerDeclarations(anchorName: string, hide: boolean): NativeDeclarations { + return [ + ['position-anchor', anchorName], + ['top', 'anchor(top)'], + ['right', 'anchor(right)'], + ['bottom', 'anchor(bottom)'], + ['left', 'anchor(left)'], + ['position-visibility', hide ? 'anchors-visible' : 'always'] + ]; +} + +interface Edges { top: number; right: number; bottom: number; left: number } + +/** + * Distance from the content to where the pair would put it, on one axis. + * `start`/`end` are the start point and direction as -1 (left/top) or 0 (right/bottom). + */ +function deviation(start: number, direction: number, content: Edges, target: Edges, offset: number, horizontal: boolean): number { + const [cStart, cEnd, tStart, tEnd] = horizontal + ? [content.left, content.right, target.left, target.right] + : [content.top, content.bottom, target.top, target.bottom]; + const before = start === -1; + const forward = direction === 0; + if (before && !forward) { // Left → Left, Top → Top + return Math.abs(cEnd - (tStart - offset)); + } + if (before && forward) { // Left → Right, Top → Bottom + return Math.abs(cStart - tStart); + } + if (!before && !forward) { // Right → Left, Bottom → Top + return Math.abs(cEnd - tEnd); + } + return Math.abs(cStart - (tEnd + offset)); // Right → Right, Bottom → Bottom +} + +/** Swaps -1 (left/top) and 0 (right/bottom); keeps the center value. */ +const flipValue = (value: number) => value === -1 ? 0 : value === 0 ? -1 : value; + +/** + * @hidden @internal + * Decides per axis whether the browser chose a flipped position option, from the rendered rectangles. + * Centered axes never flip. A tie counts as not flipped. + */ +export function resolveFlippedAxes( + settings: PositionSettings, contentRect: Edges, targetRect: Edges +): { horizontal: boolean; vertical: boolean } { + const offset = settings.offset ?? 0; + const axis = (start: number | undefined, direction: number | undefined, horizontal: boolean, mapping?: AxisMapping) => { + if (start === undefined || direction === undefined || start === -0.5 || direction === -0.5) { + return false; + } + const o = mapping?.outside ? offset : 0; + const configured = deviation(start, direction, contentRect, targetRect, o, horizontal); + const flipped = deviation(flipValue(start), flipValue(direction), contentRect, targetRect, o, horizontal); + return flipped < configured; + }; + return { + horizontal: axis(settings.horizontalStartPoint, settings.horizontalDirection, true, horizontalOf(settings)), + vertical: axis(settings.verticalStartPoint, settings.verticalDirection, false, verticalOf(settings)) + }; +} + +/** + * @hidden @internal + * Reverses an animation on each flipped axis it animates along, as `AutoPositionStrategy` does. + */ +export function flipAnimation( + animation: AnimationReferenceMetadata | null | undefined, + flipped: { horizontal: boolean; vertical: boolean } +): AnimationReferenceMetadata | null | undefined { + const util = AnimationUtil.instance(); + let result = animation; + if (result && flipped.horizontal && util.isHorizontalAnimation(result)) { + result = util.reverseAnimationResolver(result); + } + if (result && flipped.vertical && util.isVerticalAnimation(result)) { + result = util.reverseAnimationResolver(result); + } + return result; +} diff --git a/projects/igniteui-angular/core/src/services/overlay/anchoring/native-overlay.spec.ts b/projects/igniteui-angular/core/src/services/overlay/anchoring/native-overlay.spec.ts new file mode 100644 index 00000000000..244d0c6f13a --- /dev/null +++ b/projects/igniteui-angular/core/src/services/overlay/anchoring/native-overlay.spec.ts @@ -0,0 +1,602 @@ +// DISCUSS(#17765): plan §14.2 puts these tests in a 'Native anchoring' group in overlay.spec.ts. Here they are a +// separate file; overlay.spec.ts runs all its existing groups under both engines (D9). C5 (grid loading overlay, +// snackbar container) is covered by those components' own suites. +import { ElementRef } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { NoopAnimationsModule } from '@angular/platform-browser/animations'; +import { scaleInVerBottom, scaleInVerTop, scaleOutVerBottom, scaleOutVerTop } from 'igniteui-angular/animations'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { IgxOverlayService } from '../overlay'; +import { AutoPositionStrategy } from '../position/auto-position-strategy'; +import { ConnectedPositioningStrategy } from '../position/connected-positioning-strategy'; +import { ContainerPositionStrategy } from '../position/container-position-strategy'; +import { GlobalPositionStrategy } from '../position/global-position-strategy'; +import { AbsoluteScrollStrategy } from '../scroll/absolute-scroll-strategy'; +import { HideScrollStrategy } from '../scroll/hide-scroll-strategy'; +import { NoOpScrollStrategy } from '../scroll/NoOpScrollStrategy'; +import { HorizontalAlignment, OverlaySettings, Point, PositionSettings, Util, VerticalAlignment } from '../utilities'; +import { provideOverlayAnchoring } from './anchoring'; +import { AUTO_FALLBACKS } from './native-engine'; + +const TOLERANCE = 1; +const NO_ANIMATIONS: PositionSettings = { openAnimation: null, closeAnimation: null }; + +const frames = async (count = 2) => { + for (let i = 0; i < count; i++) { + await new Promise(resolve => requestAnimationFrame(() => resolve())); + } +}; + +const expectNear = (actual: number, expected: number) => + expect(Math.abs(actual - expected), `${actual} ≈ ${expected}`).toBeLessThanOrEqual(TOLERANCE); + +const isHitTestable = (element: HTMLElement) => { + const r = element.getBoundingClientRect(); + const hit = document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2); + return !!hit && element.contains(hit); +}; + +/** `position-area` keywords in a fixed order: browsers serialize the row and column in different orders. */ +const sortedArea = (value: string) => value.split(/\s+/).sort().join(' '); +const area = (element: HTMLElement) => sortedArea(element.style.getPropertyValue('position-area')); + +interface Box { top: number; left: number; width: number; height: number } + +describe('igxOverlay native anchoring', () => { + let overlay: IgxOverlayService; + let nodes: HTMLElement[]; + // Restore only our own spies: the global setup keeps a console.warn spy that it asserts on after each test. + const spies: Array<{ mockRestore(): void }> = []; + const spyOn = ((...args: unknown[]) => { + const spy = (vi.spyOn as (...a: unknown[]) => { mockRestore(): void })(...args); + spies.push(spy); + return spy; + }) as typeof vi.spyOn; + + // Engine selection is driven by feature detection, which runs lazily on the first show() of each service. + const realSupports = CSS.supports.bind(CSS) as (property: string, value?: string) => boolean; + /** No CSS anchor positioning: every overlay uses the script engine, as in Safari 18. */ + const useScriptEngine = () => spyOn(CSS, 'supports').mockReturnValue(false); + /** Anchor positioning without `position-visibility`, as in Safari 26.0 and 26.1. */ + const withoutPositionVisibility = () => spyOn(CSS, 'supports').mockImplementation( + ((property: string, value?: string) => property !== 'position-visibility' && + (value === undefined ? realSupports(property) : realSupports(property, value))) as typeof CSS.supports); + + const track = (el: T): T => { + nodes.push(el); + return el; + }; + + /** A fixed-position target at the given viewport box. */ + const addTarget = (box: Box, parent: HTMLElement = document.body) => { + const el = track(document.createElement('div')); + Object.assign(el.style, { + position: 'fixed', top: `${box.top}px`, left: `${box.left}px`, + width: `${box.width}px`, height: `${box.height}px`, background: 'gray' + }); + parent.appendChild(el); + return el; + }; + + /** Element shown in the overlay; in the DOM before attach so its size is known. */ + const addElement = (width = 100, height = 50, parent: HTMLElement = document.body) => { + const el = track(document.createElement('div')); + Object.assign(el.style, { width: `${width}px`, height: `${height}px`, background: 'red' }); + parent.appendChild(el); + return el; + }; + + const content = (id: string): HTMLElement => overlay.getOverlayById(id).elementRef!.nativeElement.parentElement; + + const open = async (element: HTMLElement, settings: OverlaySettings) => { + const id = overlay.attach(new ElementRef(element), { modal: false, closeOnOutsideClick: false, ...settings }); + overlay.show(id); + await frames(); + return id; + }; + + const configure = async (providers: any[] = []) => { + await TestBed.configureTestingModule({ imports: [NoopAnimationsModule], providers }).compileComponents(); + overlay = TestBed.inject(IgxOverlayService); + }; + + beforeEach(() => { + nodes = []; + document.documentElement.scrollTop = 0; + }); + + afterEach(() => { + overlay?.detachAll(); + nodes.forEach(n => n.remove()); + spies.splice(0).forEach(s => s.mockRestore()); + }); + + describe('engine selection', () => { + beforeEach(() => configure()); + + it('N1 - exact Connected and Auto classes go native; subclasses keep the script engine', async () => { + const target = addTarget({ top: 100, left: 100, width: 80, height: 30 }); + for (const Strategy of [ConnectedPositioningStrategy, AutoPositionStrategy]) { + const id = await open(addElement(), { target, positionStrategy: new Strategy(NO_ANIMATIONS) }); + const el = content(id); + expect(overlay.getOverlayById(id).engine).toBe('native-connected'); + expect(el.style.getPropertyValue('position-anchor')).toMatch(/^--igx-overlay-anchor-/); + const r = el.getBoundingClientRect(); + expectNear(r.top, 130); + expectNear(r.left, 100); + overlay.detach(id); + } + + class MyAuto extends AutoPositionStrategy { } + const id = await open(addElement(), { target, positionStrategy: new MyAuto(NO_ANIMATIONS) }); + expect(overlay.getOverlayById(id).engine).toBe('script'); + expect(content(id).style.getPropertyValue('position-anchor')).toBe(''); + expect(content(id).style.top).not.toBe(''); + }); + + it('N2 - Point, detached and SVG targets keep the script engine', async () => { + const point = await open(addElement(), { target: new Point(10, 10), positionStrategy: new ConnectedPositioningStrategy(NO_ANIMATIONS) }); + expect(overlay.getOverlayById(point).engine).toBe('script'); + + const detachedTarget = document.createElement('div'); + const detached = await open(addElement(), { target: detachedTarget, positionStrategy: new ConnectedPositioningStrategy(NO_ANIMATIONS) }); + expect(overlay.getOverlayById(detached).engine).toBe('script'); + + const svg = track(document.createElementNS('http://www.w3.org/2000/svg', 'svg') as unknown as HTMLElement); + document.body.appendChild(svg); + const svgId = await open(addElement(), { target: svg, positionStrategy: new ConnectedPositioningStrategy(NO_ANIMATIONS) }); + expect(overlay.getOverlayById(svgId).engine).toBe('script'); + }); + + it('N3 - a target in a shadow root keeps the script engine', async () => { + const host = track(document.createElement('div')); + document.body.appendChild(host); + const target = addTarget({ top: 100, left: 100, width: 80, height: 30 }, host.attachShadow({ mode: 'open' }) as unknown as HTMLElement); + const id = await open(addElement(), { target, positionStrategy: new ConnectedPositioningStrategy(NO_ANIMATIONS) }); + expect(overlay.getOverlayById(id).engine).toBe('script'); + }); + + it('N3 - a target and overlay in the same shadow root go native', async () => { + const host = track(document.createElement('div')); + document.body.appendChild(host); + // A direct child of a shadow root has no parentElement, and the service would append the overlay to . + const root = document.createElement('div'); + host.attachShadow({ mode: 'open' }).appendChild(root); + const target = addTarget({ top: 100, left: 100, width: 80, height: 30 }, root); + const id = await open(addElement(100, 50, root), { target, positionStrategy: new ConnectedPositioningStrategy(NO_ANIMATIONS) }); + expect(overlay.getOverlayById(id).engine).toBe('native-connected'); + const r = content(id).getBoundingClientRect(); + expectNear(r.top, 130); + expectNear(r.left, 100); + }); + + it('N4 - a pair position-area cannot express keeps the script engine', async () => { + const target = addTarget({ top: 100, left: 100, width: 80, height: 30 }); + const id = await open(addElement(), { + target, + positionStrategy: new ConnectedPositioningStrategy({ + ...NO_ANIMATIONS, horizontalStartPoint: HorizontalAlignment.Center, horizontalDirection: HorizontalAlignment.Left + }) + }); + expect(overlay.getOverlayById(id).engine).toBe('script'); + }); + + it('N6 - no browser support keeps the script engine, detected once per service', async () => { + const supports = spyOn(CSS, 'supports').mockReturnValue(false); + const target = addTarget({ top: 100, left: 100, width: 80, height: 30 }); + const id = await open(addElement(), { target, positionStrategy: new AutoPositionStrategy(NO_ANIMATIONS) }); + expect(overlay.getOverlayById(id).engine).toBe('script'); + const calls = supports.mock.calls.length; + overlay.hide(id); + overlay.show(id); + expect(supports.mock.calls.length).toBe(calls); + }); + + it('N10 - switching from script to native clears script styles and keeps setOffset', async () => { + const target = addTarget({ top: 100, left: 100, width: 80, height: 30 }); + const id = await open(addElement(), { target: new Point(20, 20), positionStrategy: new ConnectedPositioningStrategy(NO_ANIMATIONS) }); + expect(content(id).style.top).not.toBe(''); + overlay.setOffset(id, 10, 20); + overlay.hide(id); + overlay.show(id, { target }); + await frames(); + const el = content(id); + expect(overlay.getOverlayById(id).engine).toBe('native-connected'); + expect(el.style.top).toBe('auto'); + expect(el.style.left).toBe('auto'); + expect(el.style.getPropertyValue('position-anchor')).not.toBe(''); + expect(el.style.transform).toBe('translate(10px, 20px)'); + }); + }); + + describe('provideOverlayAnchoring', () => { + it('N5 - "script" keeps every overlay on the script engine', async () => { + await configure([provideOverlayAnchoring('script')]); + const target = addTarget({ top: 100, left: 100, width: 80, height: 30 }); + const id = await open(addElement(), { target, positionStrategy: new AutoPositionStrategy(NO_ANIMATIONS) }); + expect(overlay.getOverlayById(id).engine).toBe('script'); + expect(content(id).style.getPropertyValue('position-anchor')).toBe(''); + }); + + it('N15 - the script engine writes no native property', async () => { + await configure(); + useScriptEngine(); + const target = addTarget({ top: 100, left: 100, width: 80, height: 30 }); + const id = await open(addElement(), { target, positionStrategy: new AutoPositionStrategy(NO_ANIMATIONS) }); + expect(content(id).getAttribute('style')).not.toMatch(/position-anchor|position-area|anchor-name/); + expect(target.getAttribute('style')).not.toMatch(/anchor-name/); + }); + }); + + describe('connected and auto', () => { + beforeEach(() => configure()); + + it('N7 - anchor-name lives on the target only while the overlay is open', async () => { + const target = addTarget({ top: 100, left: 100, width: 80, height: 30 }); + target.style.setProperty('anchor-name', '--author'); + const a = await open(addElement(), { target, positionStrategy: new ConnectedPositioningStrategy(NO_ANIMATIONS) }); + const b = await open(addElement(), { target, positionStrategy: new AutoPositionStrategy(NO_ANIMATIONS) }); + const nameA = overlay.getOverlayById(a).anchorName; + const nameB = overlay.getOverlayById(b).anchorName; + expect(target.style.getPropertyValue('anchor-name')).toBe(`--author, ${nameA}, ${nameB}`); + + overlay.hide(a); + expect(target.style.getPropertyValue('anchor-name')).toBe(`--author, ${nameB}`); + overlay.hide(b); + expect(target.style.getPropertyValue('anchor-name')).toBe('--author'); + }); + + it('N7 - show with another target moves the anchor name', async () => { + const first = addTarget({ top: 100, left: 100, width: 80, height: 30 }); + const second = addTarget({ top: 300, left: 300, width: 80, height: 30 }); + const id = await open(addElement(), { target: first, positionStrategy: new ConnectedPositioningStrategy(NO_ANIMATIONS) }); + overlay.show(id, { target: second }); + await frames(); + expect(first.style.getPropertyValue('anchor-name')).toBe(''); + expect(second.style.getPropertyValue('anchor-name')).toBe(overlay.getOverlayById(id).anchorName); + expectNear(content(id).getBoundingClientRect().top, 330); + }); + + it('N8 - writes the declarations for the default, Auto, offset and toolbar settings', async () => { + const target = addTarget({ top: 100, left: 100, width: 80, height: 30 }); + const connected = content(await open(addElement(), { target, positionStrategy: new ConnectedPositioningStrategy(NO_ANIMATIONS) })); + expect(area(connected)).toBe(sortedArea('bottom span-right')); + expect(connected.style.getPropertyValue('justify-self')).toBe('unsafe left'); + expect(connected.style.getPropertyValue('align-self')).toBe('unsafe start'); + expect(connected.style.getPropertyValue('position-try-fallbacks')).toBe('none'); + expect(connected.style.getPropertyValue('position-visibility')).toBe('always'); + + const auto = content(await open(addElement(), { target, positionStrategy: new AutoPositionStrategy({ ...NO_ANIMATIONS, offset: 6 }) })); + expect(auto.style.getPropertyValue('justify-self')).toBe('left'); + expect(auto.style.getPropertyValue('position-try-fallbacks')).toBe(AUTO_FALLBACKS); + expect(auto.style.margin).toBe('6px 0px'); + expectNear(auto.getBoundingClientRect().top, 136); + + const toolbar = content(await open(addElement(), { + target, + positionStrategy: new AutoPositionStrategy({ + ...NO_ANIMATIONS, horizontalStartPoint: HorizontalAlignment.Right, horizontalDirection: HorizontalAlignment.Left + }) + })); + expect(area(toolbar)).toBe(sortedArea('bottom span-left')); + expect(toolbar.style.getPropertyValue('justify-self')).toBe('right'); + expectNear(toolbar.getBoundingClientRect().right, 180); + }); + + it('N9 - reposition applies settings changes and never reads layout', async () => { + const target = addTarget({ top: 100, left: 100, width: 80, height: 30 }); + const strategy = new AutoPositionStrategy(NO_ANIMATIONS); + const id = await open(addElement(), { target, positionStrategy: strategy }); + const el = content(id); + const contentRect = spyOn(el, 'getBoundingClientRect'); + const targetRect = spyOn(target, 'getBoundingClientRect'); + + strategy.settings.verticalStartPoint = VerticalAlignment.Top; + strategy.settings.verticalDirection = VerticalAlignment.Top; + overlay.reposition(id); + expect(area(el)).toBe(sortedArea('top span-right')); + expect(contentRect).not.toHaveBeenCalled(); + expect(targetRect).not.toHaveBeenCalled(); + }); + + it('Auto flips above a target near the bottom edge and reverses the animations (N11)', async () => { + const target = addTarget({ top: window.innerHeight - 60, left: 100, width: 80, height: 30 }); + const strategy = new AutoPositionStrategy({ openAnimation: scaleInVerTop, closeAnimation: scaleOutVerTop }); + const id = await open(addElement(100, 200), { target, positionStrategy: strategy }); + const info = overlay.getOverlayById(id); + + expectNear(content(id).getBoundingClientRect().bottom, window.innerHeight - 60); + expect(info.builtOpenAnimation).toBe(scaleInVerBottom); + expect(info.builtCloseAnimation).toBe(scaleOutVerBottom); + expect(strategy.settings.openAnimation).toBe(scaleInVerTop); + expect(strategy.settings.verticalDirection).toBe(VerticalAlignment.Bottom); + }); + + it('N11 - the close animation follows a flip that happened while the overlay was open', async () => { + const target = addTarget({ top: 100, left: 100, width: 80, height: 30 }); + const strategy = new AutoPositionStrategy({ openAnimation: scaleInVerTop, closeAnimation: scaleOutVerTop }); + const id = await open(addElement(100, 200), { target, positionStrategy: strategy }); + const info = overlay.getOverlayById(id); + expect(info.builtCloseAnimation).toBe(scaleOutVerTop); + // Let the open animation finish so hide() resolves the close animation again. + await new Promise(resolve => setTimeout(resolve, 400)); + + target.style.top = `${window.innerHeight - 60}px`; + await frames(); + expectNear(content(id).getBoundingClientRect().bottom, window.innerHeight - 60); + + overlay.hide(id); + expect(info.builtCloseAnimation).toBe(scaleOutVerBottom); + expect(strategy.settings.closeAnimation).toBe(scaleOutVerTop); + }); + + it('Auto flips a spanning pair at the right edge so the right edges meet', async () => { + const target = addTarget({ top: 100, left: window.innerWidth - 90, width: 80, height: 30 }); + const id = await open(addElement(200, 50), { target, positionStrategy: new AutoPositionStrategy(NO_ANIMATIONS) }); + expectNear(content(id).getBoundingClientRect().right, window.innerWidth - 10); + }); + + it('Connected never flips or shifts, as with the script engine', async () => { + const target = addTarget({ top: 100, left: window.innerWidth - 90, width: 80, height: 30 }); + const id = await open(addElement(200, 50), { target, positionStrategy: new ConnectedPositioningStrategy(NO_ANIMATIONS) }); + const r = content(id).getBoundingClientRect(); + expectNear(r.left, window.innerWidth - 90); + expectNear(r.top, 130); + }); + + it('centered pairs stay centered on the target', async () => { + const target = addTarget({ top: 200, left: 300, width: 80, height: 40 }); + const id = await open(addElement(200, 100), { + target, + positionStrategy: new ConnectedPositioningStrategy({ + ...NO_ANIMATIONS, + horizontalStartPoint: HorizontalAlignment.Center, horizontalDirection: HorizontalAlignment.Center, + verticalStartPoint: VerticalAlignment.Middle, verticalDirection: VerticalAlignment.Middle + }) + }); + const r = content(id).getBoundingClientRect(); + expectNear(r.left + r.width / 2, 340); + expectNear(r.top + r.height / 2, 220); + }); + + it('N12 - content follows its target on scroll with NoOpScrollStrategy, without reposition', async () => { + const scroller = track(document.createElement('div')); + Object.assign(scroller.style, { position: 'fixed', top: '50px', left: '50px', width: '300px', height: '300px', overflow: 'auto' }); + const spacer = document.createElement('div'); + spacer.style.height = '2000px'; + const target = document.createElement('div'); + Object.assign(target.style, { position: 'absolute', top: '100px', left: '20px', width: '80px', height: '30px' }); + scroller.append(target, spacer); + document.body.appendChild(scroller); + + const reposition = spyOn(overlay, 'reposition'); + const id = await open(addElement(), { target, positionStrategy: new AutoPositionStrategy(NO_ANIMATIONS), scrollStrategy: new NoOpScrollStrategy() }); + expectNear(content(id).getBoundingClientRect().top, target.getBoundingClientRect().bottom); + + scroller.scrollTop = 50; + await frames(); + expectNear(content(id).getBoundingClientRect().top, target.getBoundingClientRect().bottom); + expect(reposition).not.toHaveBeenCalled(); + }); + + it('N13 - settings changed between shows are honored', async () => { + const target = addTarget({ top: 200, left: 300, width: 80, height: 30 }); + const strategy = new AutoPositionStrategy({ + ...NO_ANIMATIONS, horizontalStartPoint: HorizontalAlignment.Right, horizontalDirection: HorizontalAlignment.Right + }); + const id = await open(addElement(), { target, positionStrategy: strategy }); + expectNear(content(id).getBoundingClientRect().left, 380); + overlay.hide(id); + + strategy.settings.horizontalStartPoint = HorizontalAlignment.Left; + strategy.settings.horizontalDirection = HorizontalAlignment.Left; + overlay.show(id); + await frames(); + expectNear(content(id).getBoundingClientRect().right, 300); + }); + + it('N14 - a target inside another overlay anchors correctly', async () => { + const outerTarget = addTarget({ top: 100, left: 100, width: 80, height: 30 }); + const outerElement = addElement(200, 100); + const innerTarget = document.createElement('button'); + Object.assign(innerTarget.style, { display: 'block', width: '60px', height: '20px', marginTop: '40px' }); + outerElement.appendChild(innerTarget); + await open(outerElement, { target: outerTarget, positionStrategy: new ConnectedPositioningStrategy(NO_ANIMATIONS) }); + + const inner = await open(addElement(), { target: innerTarget, positionStrategy: new ConnectedPositioningStrategy(NO_ANIMATIONS) }); + const t = innerTarget.getBoundingClientRect(); + const r = content(inner).getBoundingClientRect(); + expectNear(r.top, t.bottom); + expectNear(r.left, t.left); + }); + }); + + describe('container', () => { + beforeEach(() => configure()); + + const addHost = () => { + const scroller = track(document.createElement('div')); + Object.assign(scroller.style, { position: 'fixed', top: '40px', left: '40px', width: '400px', height: '300px', overflow: 'auto' }); + const host = document.createElement('div'); + Object.assign(host.style, { position: 'relative', margin: '30px', width: '200px', height: '150px' }); + const spacer = document.createElement('div'); + spacer.style.height = '1000px'; + scroller.append(host, spacer); + document.body.appendChild(scroller); + return { scroller, host }; + }; + + it('C1/C2 - the wrapper covers the container and follows it on scroll, with no observer', async () => { + const { scroller, host } = addHost(); + const observer = spyOn(Util, 'setupIntersectionObserver'); + const id = await open(addElement(50, 20, host), { positionStrategy: new ContainerPositionStrategy(NO_ANIMATIONS) }); + const info = overlay.getOverlayById(id); + const wrapper = info.wrapperElement!; + + expect(info.engine).toBe('native-container'); + expect(observer).not.toHaveBeenCalled(); + expect(info.containerElement!.style.getPropertyValue('anchor-name')).toBe(info.anchorName); + expect(wrapper.classList).toContain('igx-overlay__wrapper--flex-container'); + expect(content(id).classList).toContain('igx-overlay__content--relative'); + expect(wrapper.style.getPropertyValue('top')).toBe('anchor(top)'); + + const check = () => { + const w = wrapper.getBoundingClientRect(); + const c = info.containerElement!.getBoundingClientRect(); + expectNear(w.top, c.top); + expectNear(w.left, c.left); + expectNear(w.width, c.width); + expectNear(w.height, c.height); + }; + check(); + scroller.scrollTop = 60; + await frames(); + check(); + }); + + it('C3 - the script observer does not throw after detach (#16988)', async () => { + useScriptEngine(); + const { host } = addHost(); + let callback: () => void = () => undefined; + spyOn(Util, 'setupIntersectionObserver').mockImplementation((_el, _doc, cb) => { + callback = cb; + return null; + }); + const id = await open(addElement(50, 20, host), { positionStrategy: new ContainerPositionStrategy(NO_ANIMATIONS) }); + expect(overlay.getOverlayById(id).engine).toBe('script'); + overlay.detach(id); + expect(() => callback()).not.toThrow(); + }); + + it('C4 - switching to Container on show after attaching with Global keeps the script engine', async () => { + const { host } = addHost(); + const element = addElement(50, 20, host); + const id = overlay.attach(new ElementRef(element), { modal: false, positionStrategy: new GlobalPositionStrategy(NO_ANIMATIONS) }); + overlay.show(id, { positionStrategy: new ContainerPositionStrategy(NO_ANIMATIONS) }); + await frames(); + const info = overlay.getOverlayById(id); + expect(info.containerElement).toBeUndefined(); + expect(info.engine).toBe('script'); + }); + }); + + describe('HideScrollStrategy', () => { + beforeEach(() => configure()); + + const addScroller = () => { + const scroller = track(document.createElement('div')); + Object.assign(scroller.style, { position: 'fixed', top: '50px', left: '50px', width: '300px', height: '200px', overflow: 'auto' }); + const target = document.createElement('div'); + Object.assign(target.style, { height: '30px', width: '80px', marginTop: '20px', background: 'gray' }); + const spacer = document.createElement('div'); + spacer.style.height = '2000px'; + scroller.append(target, spacer); + document.body.appendChild(scroller); + return { scroller, target }; + }; + + const scrollAndSettle = async (scroller: HTMLElement, top: number) => { + scroller.scrollTop = top; + await frames(3); + }; + + it('H1 - native: hides while the target is scrolled out, without closing', async () => { + const { scroller, target } = addScroller(); + const closed = vi.fn(); + overlay.closed.subscribe(closed); + const id = await open(addElement(), { target, positionStrategy: new AutoPositionStrategy(NO_ANIMATIONS), scrollStrategy: new HideScrollStrategy() }); + const el = content(id); + expect(el.style.getPropertyValue('position-visibility')).toBe('anchors-visible'); + expect(isHitTestable(el)).toBe(true); + + await scrollAndSettle(scroller, 200); + expect(isHitTestable(el)).toBe(false); + expect(overlay.getOverlayById(id).visible).toBe(true); + + await scrollAndSettle(scroller, 0); + expect(isHitTestable(el)).toBe(true); + expect(closed).not.toHaveBeenCalled(); + }); + + it('H2 - native without position-visibility: the observer hides the content', async () => { + withoutPositionVisibility(); + const { scroller, target } = addScroller(); + const id = await open(addElement(), { target, positionStrategy: new AutoPositionStrategy(NO_ANIMATIONS), scrollStrategy: new HideScrollStrategy() }); + const el = content(id); + expect(el.style.getPropertyValue('position-visibility')).toBe('always'); + + await scrollAndSettle(scroller, 200); + expect(el.style.visibility).toBe('hidden'); + await scrollAndSettle(scroller, 0); + expect(el.style.visibility).toBe(''); + }); + + it('H3 - script: repositions like Absolute and hides through the observer', async () => { + useScriptEngine(); + const { scroller, target } = addScroller(); + const reposition = spyOn(overlay, 'reposition'); + const id = await open(addElement(), { target, positionStrategy: new AutoPositionStrategy(NO_ANIMATIONS), scrollStrategy: new HideScrollStrategy() }); + await scrollAndSettle(scroller, 200); + expect(reposition).toHaveBeenCalled(); + expect(content(id).style.visibility).toBe('hidden'); + }); + + it('H4 - a Point target never hides', async () => { + const { scroller } = addScroller(); + const id = await open(addElement(), { target: new Point(60, 60), positionStrategy: new AutoPositionStrategy(NO_ANIMATIONS), scrollStrategy: new HideScrollStrategy() }); + await scrollAndSettle(scroller, 200); + expect(content(id).style.visibility).toBe(''); + }); + + it('H5 - hide and detach clear the hidden state', async () => { + withoutPositionVisibility(); + const { scroller, target } = addScroller(); + const strategy = new HideScrollStrategy(); + const id = await open(addElement(), { target, positionStrategy: new AutoPositionStrategy(NO_ANIMATIONS), scrollStrategy: strategy }); + const el = content(id); + await scrollAndSettle(scroller, 200); + expect(el.style.visibility).toBe('hidden'); + + overlay.hide(id); + expect(el.style.visibility).toBe(''); + + overlay.show(id); + await scrollAndSettle(scroller, 210); + expect(el.style.visibility).toBe('hidden'); + const disconnect = spyOn(IntersectionObserver.prototype, 'disconnect'); + overlay.detach(id); + expect(disconnect).toHaveBeenCalled(); + expect(el.style.visibility).toBe(''); + }); + + it('H6 - replacing the strategy on show clears the hidden state', async () => { + withoutPositionVisibility(); + const { scroller, target } = addScroller(); + const id = await open(addElement(), { target, positionStrategy: new AutoPositionStrategy(NO_ANIMATIONS), scrollStrategy: new HideScrollStrategy() }); + await scrollAndSettle(scroller, 200); + expect(content(id).style.visibility).toBe('hidden'); + overlay.hide(id); + overlay.show(id, { scrollStrategy: new AbsoluteScrollStrategy() }); + await scrollAndSettle(scroller, 210); + expect(content(id).style.visibility).toBe(''); + }); + + it('H7 - Esc closes an overlay whose content is hidden', async () => { + const { scroller, target } = addScroller(); + const id = await open(addElement(), { + target, closeOnEscape: true, + positionStrategy: new AutoPositionStrategy(NO_ANIMATIONS), scrollStrategy: new HideScrollStrategy() + }); + await scrollAndSettle(scroller, 200); + document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })); + expect(overlay.getOverlayById(id).visible).toBe(false); + }); + + it('H8 - Container: native writes anchors-visible on the wrapper', async () => { + const { target: host } = addScroller(); + host.style.position = 'relative'; + const id = await open(addElement(50, 20, host), { positionStrategy: new ContainerPositionStrategy(NO_ANIMATIONS), scrollStrategy: new HideScrollStrategy() }); + expect(overlay.getOverlayById(id).wrapperElement!.style.getPropertyValue('position-visibility')).toBe('anchors-visible'); + }); + }); +}); diff --git a/projects/igniteui-angular/core/src/services/overlay/overlay.spec.ts b/projects/igniteui-angular/core/src/services/overlay/overlay.spec.ts index ceedb0f2b49..50e83dfa863 100644 --- a/projects/igniteui-angular/core/src/services/overlay/overlay.spec.ts +++ b/projects/igniteui-angular/core/src/services/overlay/overlay.spec.ts @@ -11,6 +11,7 @@ import { first } from 'rxjs/operators'; import { UIInteractions, wait } from '../../../../test-utils/ui-interactions.spec'; import { IgxAngularAnimationService } from '../animation/angular-animation-service'; import { IgxOverlayService } from './overlay'; +import { provideOverlayAnchoring } from './anchoring/anchoring'; import { ContainerPositionStrategy } from './position'; import { AutoPositionStrategy } from './position/auto-position-strategy'; import { BaseFitPositionStrategy } from './position/base-fit-position-strategy'; @@ -183,13 +184,19 @@ const formatString = (inputString: string, formatters: any[]) => { return inputString; }; -describe('igxOverlay', () => { +// Every group runs under both positioning engines (D9). The native run is the default in Chromium; the script +// run is what Safari 18 and `provideOverlayAnchoring('script')` get. +describe.each(['script', 'native'] as const)('igxOverlay (%s engine)', (engine) => { const formatters = [ { pattern: /:\s/g, replacement: ':' }, { pattern: /red;/, replacement: 'red' } ]; beforeEach(async () => { UIInteractions.clearOverlay(); + if (engine === 'script') { + // Merged into each group's testing module; groups configure theirs in their own beforeEach. + TestBed.configureTestingModule({ providers: [provideOverlayAnchoring('script')] }); + } }); afterAll(() => { @@ -1137,7 +1144,8 @@ describe('igxOverlay', () => { fixture.componentInstance.hide(); }); - it('#1799 - content div should reposition on window resize.', async () => { + // Mocks Util.getTargetRect, which only the script engine reads. + it.skipIf(engine === 'native')('#1799 - content div should reposition on window resize.', async () => { const rect = { bottom: 50, height: 0, diff --git a/projects/igniteui-angular/core/src/services/overlay/overlay.ts b/projects/igniteui-angular/core/src/services/overlay/overlay.ts index a510be1d24d..3613bccb53d 100644 --- a/projects/igniteui-angular/core/src/services/overlay/overlay.ts +++ b/projects/igniteui-angular/core/src/services/overlay/overlay.ts @@ -15,6 +15,22 @@ import { ElasticPositionStrategy } from './position/elastic-position-strategy'; import { GlobalPositionStrategy } from './position/global-position-strategy'; import { IPositionStrategy } from './position/IPositionStrategy'; import { NoOpScrollStrategy } from './scroll/NoOpScrollStrategy'; +import { HideScrollStrategy } from './scroll/hide-scroll-strategy'; +import { IGX_OVERLAY_ANCHORING, supportsNativeAnchoring, supportsPositionVisibility } from './anchoring/anchoring'; +import { acquireAnchorName, addAnchorName, removeAnchorName } from './anchoring/anchor-names'; +import { + connectedDeclarations, + containerDeclarations, + flipAnimation, + isExpressible, + NATIVE_CONTENT_PROPS, + NATIVE_WRAPPER_PROPS, + NativeDeclarations, + OverlayEngine, + resolveFlippedAxes, + SCRIPT_CONTENT_PROPS, + SCRIPT_WRAPPER_PROPS +} from './anchoring/native-engine'; import { AbsolutePosition, HorizontalAlignment, @@ -44,6 +60,9 @@ export class IgxOverlayService implements OnDestroy { private _zone = inject(NgZone); protected platformUtil = inject(PlatformUtil); private animationService = inject(IgxAngularAnimationService); + private _anchoringMode = inject(IGX_OVERLAY_ANCHORING, { optional: true }) ?? 'auto'; + private _nativeSupported?: boolean; + private _positionVisibilitySupported?: boolean; /** * Emitted just before the overlay content starts to open. @@ -389,6 +408,7 @@ export class IgxOverlayService implements OnDestroy { info.detached = true; this.finishAnimations(info); info.settings!.scrollStrategy!.detach(); + this.releaseAnchor(info); // Dispose position strategy if it has a dispose method if (typeof (info.settings!.positionStrategy as any).dispose === 'function') { (info.settings!.positionStrategy as any).dispose(); @@ -443,8 +463,6 @@ export class IgxOverlayService implements OnDestroy { } } this.updateSize(info); - const openAnimation = info.settings!.positionStrategy!.settings.openAnimation; - const closeAnimation = info.settings!.positionStrategy!.settings.closeAnimation; // Show the overlay using Popover API BEFORE positioning // This ensures the element is in the top layer when position calculations happen if (info.wrapperElement?.isConnected && typeof info.wrapperElement.showPopover === 'function') { @@ -454,18 +472,40 @@ export class IgxOverlayService implements OnDestroy { // Popover API call failed, element may already be showing } } - info.settings!.positionStrategy!.position( - info.elementRef!.nativeElement.parentElement, - { width: info.initialSize!.width, height: info.initialSize!.height }, - this._document, - true, - info.settings!.target); - if (openAnimation !== info.settings!.positionStrategy!.settings.openAnimation || - closeAnimation !== info.settings!.positionStrategy!.settings.closeAnimation){ - this.buildAnimationPlayers(info); + const strategy = info.settings!.positionStrategy!; + const contentElement: HTMLElement = info.elementRef!.nativeElement.parentElement; + const engine = this.resolveEngine(info); + if (info.engine && info.engine !== engine) { + this.switchEngine(info); + } + info.engine = engine; + if (engine === 'script') { + strategy.position( + contentElement, + { width: info.initialSize!.width, height: info.initialSize!.height }, + this._document, + true, + info.settings!.target); + } else { + this.applyNative(info, true); + if (engine === 'native-container') { + (strategy as ContainerPositionStrategy).applyLayout(contentElement); } + } + if (engine === 'native-connected' && strategy.constructor === AutoPositionStrategy) { + this.resolveAnimations(info, 'both'); + } else { + info.resolvedOpenAnimation = info.resolvedCloseAnimation = undefined; + } + this.updateAnimationPlayers(info); + const scrollStrategy = info.settings!.scrollStrategy; + if (scrollStrategy instanceof HideScrollStrategy) { + const anchor = this.getHideAnchor(info); + const useObserver = engine === 'script' || !this.positionVisibilitySupported(); + this._zone.runOutsideAngular(() => scrollStrategy._onShown(anchor, contentElement, useObserver)); + } this.addModalClasses(info); - if (info.settings!.positionStrategy!.settings.openAnimation) { + if (this.getOpenAnimation(info)) { // TODO: should we build players again. This was already done in attach!!! // this.buildAnimationPlayers(info); this.playOpenAnimation(info); @@ -516,6 +556,14 @@ export class IgxOverlayService implements OnDestroy { if (!overlayInfo.visible) { return; } + if (overlayInfo.engine && overlayInfo.engine !== 'script') { + // The browser keeps native overlays in place. Only settings changes need a write. + // DISCUSS(#17765): native content follows a scroll at the next rendering frame, while the script + // engine moved it synchronously in the scroll handler. Code that scrolls and measures in the same + // task sees the old position (the toggle #3636 spec needed a frame wait). Not in plan §17 yet. + this.applyNative(overlayInfo, false); + return; + } const contentElement = overlayInfo.elementRef!.nativeElement.parentElement; const contentElementRect = contentElement.getBoundingClientRect(); overlayInfo.settings.positionStrategy!.position( @@ -601,8 +649,18 @@ export class IgxOverlayService implements OnDestroy { if (eventArgs.cancel) { return; } + if (info.engine === 'native-connected' && + info.settings!.positionStrategy!.constructor === AutoPositionStrategy && + info.visible && + !info.openAnimationPlayer?.hasStarted()) { + // The browser may have flipped the content since show(); close from the side it is on now. + this.resolveAnimations(info, 'close'); + if (this.getCloseAnimation(info) !== info.builtCloseAnimation && !info.closeAnimationPlayer?.hasStarted()) { + this.buildCloseAnimationPlayer(info); + } + } this.removeModalClasses(info); - if (info.settings!.positionStrategy!.settings.closeAnimation) { + if (this.getCloseAnimation(info)) { this.playCloseAnimation(info, event); } else { this.closeDone(info); @@ -723,6 +781,7 @@ export class IgxOverlayService implements OnDestroy { container.style.pointerEvents = 'none'; container.appendChild(info.wrapperElement!); parent.appendChild(container); + info.containerElement = container; } private getWrapperElement(): HTMLElement { @@ -783,6 +842,12 @@ export class IgxOverlayService implements OnDestroy { } } } + // A closed overlay leaves nothing on its target. + this.releaseAnchor(info); + const scrollStrategy = info.settings?.scrollStrategy; + if (scrollStrategy instanceof HideScrollStrategy) { + scrollStrategy._onHidden(); + } if (!info.closeAnimationDetaching) { this.closed.emit({ id: info.id!, componentRef: info.componentRef, event: info.event }); } @@ -890,6 +955,14 @@ export class IgxOverlayService implements OnDestroy { delete info.closeAnimationPlayer; delete (info as any).ngZone; delete info.wrapperElement; + delete info.engine; + delete info.anchorName; + delete info.anchorElement; + delete info.containerElement; + delete info.resolvedOpenAnimation; + delete info.resolvedCloseAnimation; + delete info.builtOpenAnimation; + delete info.builtCloseAnimation; } private playOpenAnimation(info: OverlayInfo) { @@ -1065,7 +1138,7 @@ export class IgxOverlayService implements OnDestroy { if (info.settings!.modal) { const wrapperElement = info.elementRef!.nativeElement.parentElement.parentElement; wrapperElement.classList.remove('igx-overlay__wrapper'); - this.applyAnimationParams(wrapperElement, info.settings!.positionStrategy!.settings.openAnimation); + this.applyAnimationParams(wrapperElement, this.getOpenAnimation(info) ?? undefined); requestAnimationFrame(() => { wrapperElement.classList.add('igx-overlay__wrapper--modal'); }); @@ -1075,29 +1148,207 @@ export class IgxOverlayService implements OnDestroy { private removeModalClasses(info: OverlayInfo) { if (info.settings!.modal) { const wrapperElement = info.elementRef!.nativeElement.parentElement.parentElement; - this.applyAnimationParams(wrapperElement, info.settings!.positionStrategy!.settings.closeAnimation); + this.applyAnimationParams(wrapperElement, this.getCloseAnimation(info) ?? undefined); wrapperElement.classList.remove('igx-overlay__wrapper--modal'); wrapperElement.classList.add('igx-overlay__wrapper'); } } private buildAnimationPlayers(info: OverlayInfo) { - if (info.settings!.positionStrategy!.settings.openAnimation) { - info.openAnimationPlayer = this.animationService - .buildAnimation(info.settings!.positionStrategy!.settings.openAnimation, info.elementRef!.nativeElement); + this.buildOpenAnimationPlayer(info); + this.buildCloseAnimationPlayer(info); + } + + private buildOpenAnimationPlayer(info: OverlayInfo) { + const animation = this.getOpenAnimation(info); + info.builtOpenAnimation = animation; + if (animation) { + info.openAnimationPlayer = this.animationService.buildAnimation(animation, info.elementRef!.nativeElement); info.openAnimationPlayer.animationEnd .pipe(takeUntil(this.destroy$)) .subscribe(() => this.openAnimationDone(info)); } - if (info.settings!.positionStrategy!.settings.closeAnimation) { - info.closeAnimationPlayer = this.animationService - .buildAnimation(info.settings!.positionStrategy!.settings.closeAnimation, info.elementRef!.nativeElement); + } + + private buildCloseAnimationPlayer(info: OverlayInfo) { + const animation = this.getCloseAnimation(info); + info.builtCloseAnimation = animation; + if (animation) { + info.closeAnimationPlayer = this.animationService.buildAnimation(animation, info.elementRef!.nativeElement); info.closeAnimationPlayer.animationEnd .pipe(takeUntil(this.destroy$)) .subscribe(() => this.closeAnimationDone(info)); } } + /** + * Rebuilds the players whose animation changed since they were built (script Auto flip mutates the + * strategy settings; native Auto resolves the animations per show). A running player is kept, + * because the open/close hand-off needs the player that is playing. + */ + private updateAnimationPlayers(info: OverlayInfo) { + if (this.getOpenAnimation(info) !== info.builtOpenAnimation && !info.openAnimationPlayer?.hasStarted()) { + this.buildOpenAnimationPlayer(info); + } + if (this.getCloseAnimation(info) !== info.builtCloseAnimation && !info.closeAnimationPlayer?.hasStarted()) { + this.buildCloseAnimationPlayer(info); + } + } + + private getOpenAnimation(info: OverlayInfo): AnimationReferenceMetadata | null | undefined { + return info.resolvedOpenAnimation !== undefined + ? info.resolvedOpenAnimation + : info.settings!.positionStrategy!.settings.openAnimation; + } + + private getCloseAnimation(info: OverlayInfo): AnimationReferenceMetadata | null | undefined { + return info.resolvedCloseAnimation !== undefined + ? info.resolvedCloseAnimation + : info.settings!.positionStrategy!.settings.closeAnimation; + } + + //#region Native anchoring + + private nativeSupported(): boolean { + return this._nativeSupported ??= supportsNativeAnchoring(this._document.defaultView); + } + + private positionVisibilitySupported(): boolean { + return this._positionVisibilitySupported ??= supportsPositionVisibility(this._document.defaultView); + } + + /** Picks the engine for this show(). Exact class matches only: subclasses keep the script engine. */ + private resolveEngine(info: OverlayInfo): OverlayEngine { + if (this._anchoringMode === 'script' || !this.nativeSupported()) { + return 'script'; + } + const strategy = info.settings!.positionStrategy!; + const ctor = strategy.constructor; + if (ctor === ConnectedPositioningStrategy || ctor === AutoPositionStrategy) { + const target = info.settings!.target; + const content: HTMLElement = info.elementRef!.nativeElement.parentElement; + const HTMLElementCtor = this._document.defaultView?.HTMLElement; + const eligible = !!HTMLElementCtor && target instanceof HTMLElementCtor && + target.isConnected && + target.getRootNode() === content.getRootNode() && + isExpressible(strategy.settings); + return eligible ? 'native-connected' : 'script'; + } + // DISCUSS(#17765): native Container is likely obsolete after #17986 (see containerDeclarations). + if (ctor === ContainerPositionStrategy && info.containerElement?.isConnected) { + return 'native-container'; + } + return 'script'; + } + + /** Clears both engines' inline styles and anchors when an overlay changes engine between shows. */ + private switchEngine(info: OverlayInfo) { + const content: HTMLElement = info.elementRef!.nativeElement.parentElement; + const wrapper = info.wrapperElement!; + for (const prop of [...SCRIPT_CONTENT_PROPS, ...NATIVE_CONTENT_PROPS]) { + content.style.removeProperty(prop); + } + for (const prop of [...SCRIPT_WRAPPER_PROPS, ...NATIVE_WRAPPER_PROPS]) { + wrapper.style.removeProperty(prop); + } + this.releaseAnchor(info); + if (info.engine === 'native-container') { + info.containerElement?.style.removeProperty('anchor-name'); + } + delete info.anchorElement; + info.resolvedOpenAnimation = info.resolvedCloseAnimation = undefined; + if (info.transformX || info.transformY) { + content.style.transform = `translate(${info.transformX}px, ${info.transformY}px)`; + } + } + + /** + * Writes the native declarations from the current settings. Never reads layout, so it is cheap to + * call on every scroll; rewriting unchanged inline values does not invalidate layout. + * + * @param moveAnchor whether the anchor may move to the current target (show only). + */ + private applyNative(info: OverlayInfo, moveAnchor: boolean) { + const name = info.anchorName ??= acquireAnchorName(); + const settings = info.settings!; + const strategy = settings.positionStrategy!; + const hide = settings.scrollStrategy instanceof HideScrollStrategy && this.positionVisibilitySupported(); + let element: HTMLElement; + let declarations: NativeDeclarations; + + if (info.engine === 'native-container') { + if (info.anchorElement !== info.containerElement) { + info.containerElement!.style.setProperty('anchor-name', name); + info.anchorElement = info.containerElement; + } + element = info.wrapperElement!; + declarations = containerDeclarations(name, hide); + } else { + const target = settings.target as HTMLElement; + if (moveAnchor && info.anchorElement !== target) { + if (info.anchorElement) { + removeAnchorName(info.anchorElement, name); + } + addAnchorName(target, name); + info.anchorElement = target; + } + element = info.elementRef!.nativeElement.parentElement; + // D16: always the current settings, never a snapshot. + declarations = connectedDeclarations(strategy.settings, strategy.constructor === AutoPositionStrategy, name, hide); + } + + for (const [property, value] of declarations) { + element.style.setProperty(property, value); + } + } + + /** Removes the overlay's anchor name from its target. Idempotent. */ + private releaseAnchor(info: OverlayInfo) { + if (info.engine === 'native-connected' && info.anchorElement && info.anchorName) { + removeAnchorName(info.anchorElement, info.anchorName); + delete info.anchorElement; + } + } + + /** + * Native Auto: CSS does not report which position option the browser chose, so compare the rendered + * rectangles with the configured and the flipped placement, and reverse the animations of flipped axes. + * Strategy settings are never written. + */ + private resolveAnimations(info: OverlayInfo, which: 'open' | 'close' | 'both') { + if (!info.anchorElement) { + return; + } + const settings = info.settings!.positionStrategy!.settings; + const content: HTMLElement = info.elementRef!.nativeElement.parentElement; + const flipped = resolveFlippedAxes(settings, content.getBoundingClientRect(), info.anchorElement.getBoundingClientRect()); + if (which !== 'close') { + info.resolvedOpenAnimation = flipAnimation(settings.openAnimation, flipped); + } + if (which !== 'open') { + info.resolvedCloseAnimation = flipAnimation(settings.closeAnimation, flipped); + } + } + + /** The element whose visibility controls a `HideScrollStrategy` overlay, if any. */ + private getHideAnchor(info: OverlayInfo): HTMLElement | null { + if (info.engine !== 'script') { + return info.anchorElement ?? null; + } + const strategy = info.settings!.positionStrategy; + if (strategy instanceof ContainerPositionStrategy) { + return info.containerElement ?? null; + } + if (strategy instanceof GlobalPositionStrategy) { + return null; + } + const target = info.settings!.target; + const HTMLElementCtor = this._document.defaultView?.HTMLElement; + return HTMLElementCtor && target instanceof HTMLElementCtor ? target : null; + } + + //#endregion + private openAnimationDone(info: OverlayInfo) { if (!info.openAnimationDetaching) { this.opened.emit({ id: info.id!, componentRef: info.componentRef }); diff --git a/projects/igniteui-angular/core/src/services/overlay/position/README.md b/projects/igniteui-angular/core/src/services/overlay/position/README.md index cb8bb942bad..476b36d073b 100644 --- a/projects/igniteui-angular/core/src/services/overlay/position/README.md +++ b/projects/igniteui-angular/core/src/services/overlay/position/README.md @@ -32,6 +32,27 @@ Position strategies determine where to display the component in the provided Igx |:----------------|:--------------------------|:-------------------------|:-------------------------|:-------------------------|-------------------------| | new Point(0, 0) | HorizontalAlignment.Right | VerticalAlignment.Bottom | HorizontalAlignment.Left | VerticalAlignment.Bottom | { width: 0, height: 0 } | +## Native anchor positioning + +In browsers with CSS anchor positioning, `ConnectedPositioningStrategy`, `AutoPositionStrategy` and `ContainerPositionStrategy` overlays are positioned by the browser instead of by the strategy's `position()` method (see [Positioning engines](../README.md#positioning-engines)). Global and Elastic positioning, and subclasses of any strategy, always use script positioning. + +**Connected and Auto** go native when each axis uses one of these start point → direction pairs: + +| Horizontal | Vertical | +|:-----------|:---------| +| `Left → Left` (before the target) | `Top → Top` (above the target) | +| `Left → Right` (left edges aligned) | `Top → Bottom` (top edges aligned) | +| `Center → Center` (centered) | `Middle → Middle` (centered) | +| `Right → Left` (right edges aligned) | `Bottom → Top` (bottom edges aligned) | +| `Right → Right` (after the target) | `Bottom → Bottom` (below the target) | + +Other pairs, such as `Left → Center`, use script positioning. The start points default to `Left` and `Bottom`, so set them together with the directions, for example `horizontalStartPoint: HorizontalAlignment.Center` with `horizontalDirection: HorizontalAlignment.Center`. The `offset` setting applies to the axes where the content is outside the target (`Left → Left`, `Right → Right`, `Top → Top`, `Bottom → Bottom`), as with script positioning. + +- **Connected** keeps the content where the settings place it, even when it does not fit in the viewport. +- **Auto** flips each axis to the opposite side of the target when the content does not fit, and flips both when needed. The open and close animations are reversed after a flip, as with script positioning. The browser re-evaluates the fit while the overlay is open, and keeps the flipped side until the overlay is shown again. When no side fits, the content is shifted into the viewport. The strategy `settings` are never changed by a flip. + +**Container** anchors the overlay wrapper to the container that the service creates, so the wrapper covers the container and follows it on scroll without an `IntersectionObserver`. + ## Usage ### Container positioning diff --git a/projects/igniteui-angular/core/src/services/overlay/position/container-position-strategy.ts b/projects/igniteui-angular/core/src/services/overlay/position/container-position-strategy.ts index 3cfc53e59b4..f09d4fd1d9d 100644 --- a/projects/igniteui-angular/core/src/services/overlay/position/container-position-strategy.ts +++ b/projects/igniteui-angular/core/src/services/overlay/position/container-position-strategy.ts @@ -6,7 +6,11 @@ import { GlobalPositionStrategy } from './global-position-strategy'; * These are Top/Middle/Bottom for verticalDirection and Left/Center/Right for horizontalDirection */ export class ContainerPositionStrategy extends GlobalPositionStrategy { + // DISCUSS(#17765): `vkombov/fix-17986` (#17986) removes this observer and the top-layer wrapper for + // Container overlays. The #16988 guard and `applyLayout()` below then become unnecessary; this file + // conflicts with that branch. private io: IntersectionObserver | null = null; + private _disposed = false; constructor(settings?: PositionSettings) { super(settings); } @@ -17,6 +21,7 @@ export class ContainerPositionStrategy extends GlobalPositionStrategy { public override position(contentElement: HTMLElement): void { // Set up intersection observer this.io?.disconnect(); + this._disposed = false; const containerElement = contentElement.parentElement!.parentElement; if (!containerElement) { super.position(contentElement); @@ -25,7 +30,11 @@ export class ContainerPositionStrategy extends GlobalPositionStrategy { this.io = Util.setupIntersectionObserver( containerElement, contentElement.ownerDocument, - () => this.updatePosition(contentElement, containerElement) + () => { + if (!this._disposed && contentElement.parentElement) { + this.updatePosition(contentElement, containerElement); + } + } ); this.internalPosition(contentElement, containerElement); } @@ -34,19 +43,31 @@ export class ContainerPositionStrategy extends GlobalPositionStrategy { * Disposes the observer and cleans up references. */ public dispose(): void { + this._disposed = true; this.io?.disconnect(); this.io = null; } - private internalPosition(contentElement: HTMLElement, container: HTMLElement): void { + /** + * @hidden @internal + * Applies the classes and flex alignment that place the content inside the wrapper, + * without sizing the wrapper. Used by the native anchoring engine, which sizes the wrapper with CSS. + * + * @param contentElement The overlay content element. + */ + public applyLayout(contentElement: HTMLElement): void { contentElement.classList.add('igx-overlay__content--relative'); contentElement.parentElement!.classList.add('igx-overlay__wrapper--flex-container'); this.setPosition(contentElement); + } + + private internalPosition(contentElement: HTMLElement, container: HTMLElement): void { + this.applyLayout(contentElement); this.updatePosition(contentElement, container); } private updatePosition(contentElement: HTMLElement, container: HTMLElement): void { - if (!container) + if (!container || !contentElement.parentElement) return; // TODO: consider using new anchor() CSS function when it becomes more widely diff --git a/projects/igniteui-angular/core/src/services/overlay/scroll/README.md b/projects/igniteui-angular/core/src/services/overlay/scroll/README.md index 43693fccd64..7514f423c67 100644 --- a/projects/igniteui-angular/core/src/services/overlay/scroll/README.md +++ b/projects/igniteui-angular/core/src/services/overlay/scroll/README.md @@ -2,11 +2,33 @@ Scroll strategies determines how the scrolling will be handled in the provided IgxOverlayService. A walk through of how to get started can be found [here](https://www.infragistics.com/products/ignite-ui-angular/angular/components/overlay-scroll). -There are four scroll strategies: +There are five scroll strategies: 1) **NoOperation** - does nothing. 2) **Block** - the component do not scroll with the window. The event is canceled. No scrolling happens. 3) **Close** - uses a tolerance and closes an expanded component upon scrolling if the tolerance is exceeded. 4) **Absolute** - scrolls everything. +5) **Hide** - hides the content while its target is scrolled out of view and shows it again when the target returns. The overlay stays open. Otherwise behaves as **Absolute**. + +With [native anchor positioning](../README.md#positioning-engines), anchored content follows its target on scroll with every scroll strategy, including **NoOperation**. + +### Hide scroll strategy + +```typescript +import { AutoPositionStrategy, HideScrollStrategy, OverlaySettings } from 'igniteui-angular/core'; + +const settings: OverlaySettings = { + target: button, + positionStrategy: new AutoPositionStrategy(), + scrollStrategy: new HideScrollStrategy() +}; +``` + +| Situation | Behavior | +|:----------|:---------| +| What is watched | The target for connected, auto and elastic positioning; the container for `ContainerPositionStrategy`. A `Point` target or `GlobalPositionStrategy` has nothing to watch, so the content is never hidden. | +| When the content is hidden | While the watched element is fully clipped by the viewport or a scrolling ancestor. One visible pixel shows the content again. | +| How it is hidden | Visually only. The overlay stays open: `closing` and `closed` are not emitted, and `Esc` and outside clicks still close it. Focus inside the hidden content is lost. | +| Browser | With native anchor positioning, the browser hides the content (`position-visibility: anchors-visible`). Elsewhere, including Safari 26.0 and 26.1, an `IntersectionObserver` hides it, up to one frame later. | ## Usage diff --git a/projects/igniteui-angular/core/src/services/overlay/scroll/hide-scroll-strategy.ts b/projects/igniteui-angular/core/src/services/overlay/scroll/hide-scroll-strategy.ts new file mode 100644 index 00000000000..27cd459eb24 --- /dev/null +++ b/projects/igniteui-angular/core/src/services/overlay/scroll/hide-scroll-strategy.ts @@ -0,0 +1,79 @@ +import { AbsoluteScrollStrategy } from './absolute-scroll-strategy'; + +/** + * Hides the overlay content while its anchor element is scrolled out of view and shows it again + * when the anchor returns. The overlay stays open. Under the script engine it also repositions + * the content on scroll, like `AbsoluteScrollStrategy`. + * + * The anchor element is the overlay target, or the container for `ContainerPositionStrategy`. + * Without an anchor element (a `Point` target, `GlobalPositionStrategy`) it behaves as `AbsoluteScrollStrategy`. + * + * @param scrollContainer Optional element whose scroll events reposition the content under the script engine. + * + * @example + * ```typescript + * const settings: OverlaySettings = { + * target: button, + * positionStrategy: new AutoPositionStrategy(), + * scrollStrategy: new HideScrollStrategy() + * }; + * ``` + */ +// DISCUSS(#17765): Container behavior depends on #17986. Once Container overlays render inside their +// container (not in the top layer), `position-visibility` no longer applies to the wrapper (H8) and the +// container already clips them. Decide whether Hide does anything for Container then. +export class HideScrollStrategy extends AbsoluteScrollStrategy { + private _observer: IntersectionObserver | null = null; + private _content: HTMLElement | null = null; + + constructor(scrollContainer?: HTMLElement) { + super(scrollContainer); + } + + /** + * @hidden @internal + * Called by the overlay service after it positions the content in `show()`. + * + * @param anchor The element whose visibility controls the content, or `null`. + * @param content The overlay content element. + * @param useObserver `false` when the browser hides the content through `position-visibility`. + */ + public _onShown(anchor: HTMLElement | null, content: HTMLElement, useObserver: boolean): void { + this._onHidden(); + const Observer = content.ownerDocument.defaultView?.IntersectionObserver; + if (!anchor || !useObserver || !Observer) { + return; + } + this._content = content; + this._observer = new Observer(entries => { + content.style.visibility = entries[entries.length - 1].isIntersecting ? '' : 'hidden'; + }, { threshold: 0 }); + this._observer.observe(anchor); + } + + /** + * @hidden @internal + * Called by the overlay service when the overlay closes, and by `detach()`. + */ + public _onHidden(): void { + this._observer?.disconnect(); + this._observer = null; + if (this._content) { + this._content.style.visibility = ''; + this._content = null; + } + } + + /** + * Detaches the strategy. + * + * @example + * ```typescript + * settings.scrollStrategy.detach(); + * ``` + */ + public override detach(): void { + this._onHidden(); + super.detach(); + } +} diff --git a/projects/igniteui-angular/core/src/services/overlay/scroll/index.ts b/projects/igniteui-angular/core/src/services/overlay/scroll/index.ts index 77d2b5cab8f..fc92060b813 100644 --- a/projects/igniteui-angular/core/src/services/overlay/scroll/index.ts +++ b/projects/igniteui-angular/core/src/services/overlay/scroll/index.ts @@ -6,4 +6,5 @@ export * from './block-scroll-strategy'; export * from './close-scroll-strategy'; export * from './NoOpScrollStrategy'; export * from './close-scroll-strategy'; +export * from './hide-scroll-strategy'; diff --git a/projects/igniteui-angular/core/src/services/overlay/utilities.ts b/projects/igniteui-angular/core/src/services/overlay/utilities.ts index 71d07262f86..dc9a37bfa0c 100644 --- a/projects/igniteui-angular/core/src/services/overlay/utilities.ts +++ b/projects/igniteui-angular/core/src/services/overlay/utilities.ts @@ -215,6 +215,20 @@ export interface OverlayInfo { event?: Event; wrapperElement?: HTMLElement; size?: string; + /** Engine chosen by the last show(). Undefined before the first show(). */ + engine?: 'script' | 'native-connected' | 'native-container'; + /** Generated anchor name, created on the first native show() and kept until detach(). */ + anchorName?: string; + /** The element that currently carries `anchorName` (target or container div). */ + anchorElement?: HTMLElement; + /** The container div created for ContainerPositionStrategy, if any. */ + containerElement?: HTMLElement; + /** Animations chosen by the native Auto flip check. `undefined` means "use the strategy settings". */ + resolvedOpenAnimation?: AnimationReferenceMetadata | null; + resolvedCloseAnimation?: AnimationReferenceMetadata | null; + /** Animations the current players were built from. */ + builtOpenAnimation?: AnimationReferenceMetadata | null; + builtCloseAnimation?: AnimationReferenceMetadata | null; } /** @hidden */ diff --git a/projects/igniteui-angular/core/src/services/public_api.ts b/projects/igniteui-angular/core/src/services/public_api.ts index f5d80dac755..f9295ade317 100644 --- a/projects/igniteui-angular/core/src/services/public_api.ts +++ b/projects/igniteui-angular/core/src/services/public_api.ts @@ -5,6 +5,8 @@ export * from './animation/animation'; export * from './overlay/overlay'; export * from './overlay/position'; export * from './overlay/scroll'; +export { provideOverlayAnchoring } from './overlay/anchoring/anchoring'; +export type { OverlayAnchoringMode } from './overlay/anchoring/anchoring'; export { AbsolutePosition, ConnectedFit, HorizontalAlignment, OffsetMode, OverlayAnimationEventArgs, OverlayCancelableEventArgs, OverlayClosingEventArgs, OverlayCreateSettings, OverlayEventArgs, OverlaySettings, Point, PositionSettings, RelativePosition, RelativePositionStrategy, Size, VerticalAlignment, Util, diff --git a/projects/igniteui-angular/date-picker/src/date-range-picker/date-range-picker.component.spec.ts b/projects/igniteui-angular/date-picker/src/date-range-picker/date-range-picker.component.spec.ts index f4e150083f3..54282f27781 100644 --- a/projects/igniteui-angular/date-picker/src/date-range-picker/date-range-picker.component.spec.ts +++ b/projects/igniteui-angular/date-picker/src/date-range-picker/date-range-picker.component.spec.ts @@ -14,7 +14,7 @@ import { IgxDateRangeSeparatorDirective, IgxDateRangeStartComponent } from './da import { IgxDateTimeEditorDirective } from '../../../directives/src/directives/date-time-editor/date-time-editor.directive'; import { DateRangeType } from 'igniteui-angular/core'; import { IgxDateRangePickerComponent, IgxDateRangeEndComponent, IGX_DATE_RANGE_PICKER_DIRECTIVES } from './public_api'; -import { AutoPositionStrategy, IgxOverlayService } from 'igniteui-angular/core'; +import { IgxOverlayService } from 'igniteui-angular/core'; import { map, Subject, timer } from 'rxjs'; import { AsyncPipe } from '@angular/common'; import { IgxAngularAnimationService } from 'igniteui-angular/core'; @@ -2028,18 +2028,18 @@ describe('IgxDateRangePicker', () => { fixture = TestBed.createComponent(DateRangeDefaultComponent); fixture.detectChanges(); detectChanges = () => fixture.changeDetectorRef.detectChanges(); - vi.spyOn(AutoPositionStrategy.prototype, 'position'); - dateRange = fixture.componentInstance.dateRange; dateRange.open(); await vi.runAllTimersAsync(); detectChanges(); + // Native anchor positioning: the content is anchored to the input bundle with the Auto fallbacks. const overlayContent = document.getElementsByClassName(CSS_CLASS_OVERLAY_CONTENT)[0] as HTMLElement; - const expectedTarget = dateRange.element.nativeElement.querySelector('.igx-input-group__bundle'); - expect(AutoPositionStrategy.prototype.position).toHaveBeenCalledTimes(1); - expect(AutoPositionStrategy.prototype.position) - .toHaveBeenCalledWith(overlayContent, expect.anything(), document, expect.anything(), expectedTarget); + const expectedTarget = dateRange.element.nativeElement.querySelector('.igx-input-group__bundle') as HTMLElement; + const anchorName = overlayContent.style.getPropertyValue('position-anchor'); + expect(anchorName).toMatch(/^--igx-overlay-anchor-/); + expect(expectedTarget.style.getPropertyValue('anchor-name').split(', ')).toContain(anchorName); + expect(overlayContent.style.getPropertyValue('position-try-fallbacks')).toContain('flip-block'); }); it('Should the weekStart property takes precedence over locale.', async () => { fixture = TestBed.createComponent(DateRangeCustomComponent); diff --git a/projects/igniteui-angular/directives/src/directives/toggle/toggle.directive.spec.ts b/projects/igniteui-angular/directives/src/directives/toggle/toggle.directive.spec.ts index 3a773b2d556..bc90823d41d 100644 --- a/projects/igniteui-angular/directives/src/directives/toggle/toggle.directive.spec.ts +++ b/projects/igniteui-angular/directives/src/directives/toggle/toggle.directive.spec.ts @@ -401,6 +401,10 @@ describe('IgxToggle', () => { document.documentElement.scrollTop += 100; document.dispatchEvent(new Event('scroll')); + // Native anchor positioning applies scroll offsets in the next rendering update. + // DISCUSS(#17765): accepted behavioral change? See the note in IgxOverlayService.reposition(). + await new Promise(resolve => requestAnimationFrame(resolve)); + await new Promise(resolve => requestAnimationFrame(resolve)); toggle = fixture.debugElement.query(By.css('#toggle1')); toggleRect = toggle.nativeElement.getBoundingClientRect(); diff --git a/projects/igniteui-angular/simple-combo/src/simple-combo/simple-combo.component.spec.ts b/projects/igniteui-angular/simple-combo/src/simple-combo/simple-combo.component.spec.ts index fe6aec14711..f24b022a1cd 100644 --- a/projects/igniteui-angular/simple-combo/src/simple-combo/simple-combo.component.spec.ts +++ b/projects/igniteui-angular/simple-combo/src/simple-combo/simple-combo.component.spec.ts @@ -2165,10 +2165,19 @@ describe('IgxSimpleCombo', () => { combo.overlaySettings = newSettings; fixture.detectChanges(); + // Native anchor positioning flips in layout without changing the strategy settings: check the rendered side. + const expectOpenedAbove = () => { + const lists = document.querySelectorAll('.igx-overlay__content .igx-drop-down__list-scroll'); + const listRect = lists[lists.length - 1].closest('.igx-overlay__content')!.getBoundingClientRect(); + const inputRect = fixture.nativeElement.querySelector('igx-input-group').getBoundingClientRect(); + expect(listRect.bottom).toBeLessThanOrEqual(inputRect.bottom + 1); + expect(listRect.top).toBeLessThan(inputRect.top); + }; + combo.open(); fixture.detectChanges(); expect(combo.collapsed).toEqual(false); - expect(combo.overlaySettings.positionStrategy.settings.verticalDirection).toBe(-1); + expectOpenedAbove(); combo.select('Connecticut'); fixture.detectChanges(); @@ -2184,7 +2193,7 @@ describe('IgxSimpleCombo', () => { combo.open(); fixture.detectChanges(); expect(combo.collapsed).toEqual(false); - expect(combo.overlaySettings.positionStrategy.settings.verticalDirection).toBe(-1); + expectOpenedAbove(); combo.dropdown.close(); await fixture.whenStable(); diff --git a/skills/igniteui-angular-components/references/setup.md b/skills/igniteui-angular-components/references/setup.md index a9e769d3d0a..7d8cef1d372 100644 --- a/skills/igniteui-angular-components/references/setup.md +++ b/skills/igniteui-angular-components/references/setup.md @@ -43,6 +43,9 @@ export const appConfig: ApplicationConfig = { | Provider | Package | Required for | |---|---|---| | `provideAnimations()` | `@angular/platform-browser/animations` | **All overlay and animated components** — Dialog, Combo, Select, Dropdown, Date/Time Picker, Snackbar, Toast, Banner, Navigation Drawer, Carousel, Overlay service | +| `provideOverlayAnchoring('script')` | `igniteui-angular/core` | Optional. Keeps script positioning for every overlay instead of native CSS anchor positioning. Root providers only. | + +`HideScrollStrategy` (from `igniteui-angular/core`) hides an overlay while its target is scrolled out of view, without closing it. > **`provideAnimationsAsync()`** lazy-loads the animations module — prefer it for SSR or when optimizing initial bundle size: > ```typescript diff --git a/src/app/app.config.ts b/src/app/app.config.ts index 02532310839..c7c7f3cb6a5 100644 --- a/src/app/app.config.ts +++ b/src/app/app.config.ts @@ -5,7 +5,7 @@ import { provideAnimations } from '@angular/platform-browser/animations'; import { provideClientHydration, withNoIncrementalHydration } from '@angular/platform-browser'; import { provideRouter } from '@angular/router'; import { appRoutes } from './app.routes'; -import { provideIgniteIntl } from 'igniteui-angular/core'; +import { provideIgniteIntl, provideOverlayAnchoring } from 'igniteui-angular/core'; export const appConfig: ApplicationConfig = { providers: [ @@ -18,6 +18,10 @@ export const appConfig: ApplicationConfig = { provideHttpClient(withInterceptorsFromDi(), withFetch()), provideClientHydration(withNoIncrementalHydration()), provideRouter(appRoutes), - provideIgniteIntl() + provideIgniteIntl(), + // Open any demo with ?anchoring=script to compare against the script positioning engine. + ...(new URLSearchParams(globalThis.location?.search ?? '').get('anchoring') === 'script' + ? [provideOverlayAnchoring('script')] + : []) ] }; diff --git a/src/app/overlay/overlay.sample.ts b/src/app/overlay/overlay.sample.ts index 9f45642e710..0264ec66a44 100644 --- a/src/app/overlay/overlay.sample.ts +++ b/src/app/overlay/overlay.sample.ts @@ -11,6 +11,7 @@ import { BlockScrollStrategy, CloseScrollStrategy, NoOpScrollStrategy, + HideScrollStrategy, ElasticPositionStrategy, IgxDragDirective, ContainerPositionStrategy, @@ -65,7 +66,7 @@ export class OverlaySampleComponent implements AfterViewInit { public verticalStartPoint = 'Top'; public positionStrategies = ['Auto', 'Connected', 'Global', 'Container', 'Elastic']; public positionStrategy = 'Global'; - public scrollStrategies = ['Absolute', 'Block', 'Close', 'NoOp']; + public scrollStrategies = ['Absolute', 'Block', 'Close', 'NoOp', 'Hide']; public scrollStrategy = 'NoOp'; public closeOnOutsideClick = true; public modal = true; @@ -177,6 +178,9 @@ export class OverlaySampleComponent implements AfterViewInit { case 'NoOp': this._overlaySettings.scrollStrategy = new NoOpScrollStrategy(); break; + case 'Hide': + this._overlaySettings.scrollStrategy = new HideScrollStrategy(); + break; } } @@ -186,7 +190,8 @@ export class OverlaySampleComponent implements AfterViewInit { Absolute: new AbsoluteScrollStrategy(), Block: new BlockScrollStrategy(), Close: new CloseScrollStrategy(), - NoOp: new NoOpScrollStrategy() + NoOp: new NoOpScrollStrategy(), + Hide: new HideScrollStrategy() }, PositionStrategy: { Auto: new AutoPositionStrategy(), From 75027175e0bd29b955aa037f932f769d9da99586 Mon Sep 17 00:00:00 2001 From: teodosiah Date: Wed, 25 Nov 2026 17:04:27 +0200 Subject: [PATCH 2/2] fix(overlay): write the anchor-visible keyword where supported The CSSWG renamed position-visibility: anchors-visible to anchor-visible. Chrome 157 and Safari 27 ship the new name and serialize the plural legacy alias to it, which broke the exact-value checks in H1 and H8. Detect the supported keyword once per service: anchor-visible, else the older anchors-visible, else none (IntersectionObserver fallback). The tests expect the detected keyword, and a unit test covers the preference with a fake window. Refs #17765 Co-Authored-By: Claude Opus 5.5 --- .../overlay/anchoring/anchoring.spec.ts | 37 ++++++++++++------- .../services/overlay/anchoring/anchoring.ts | 17 +++++++-- .../overlay/anchoring/native-engine.ts | 9 +++-- .../overlay/anchoring/native-overlay.spec.ts | 8 ++-- .../core/src/services/overlay/overlay.ts | 16 +++++--- .../src/services/overlay/scroll/README.md | 2 +- 6 files changed, 57 insertions(+), 32 deletions(-) diff --git a/projects/igniteui-angular/core/src/services/overlay/anchoring/anchoring.spec.ts b/projects/igniteui-angular/core/src/services/overlay/anchoring/anchoring.spec.ts index b587b687197..74587263554 100644 --- a/projects/igniteui-angular/core/src/services/overlay/anchoring/anchoring.spec.ts +++ b/projects/igniteui-angular/core/src/services/overlay/anchoring/anchoring.spec.ts @@ -2,7 +2,7 @@ import { scaleInHorLeft, scaleInHorRight, scaleInVerBottom, scaleInVerTop, fadeI import { afterEach, describe, expect, it } from 'vitest'; import { HorizontalAlignment as H, PositionSettings, VerticalAlignment as V } from '../utilities'; import { acquireAnchorName, addAnchorName, removeAnchorName } from './anchor-names'; -import { supportsNativeAnchoring, supportsPositionVisibility } from './anchoring'; +import { supportsNativeAnchoring, anchorVisibleKeyword } from './anchoring'; import { AUTO_FALLBACKS, connectedDeclarations, @@ -67,8 +67,8 @@ describe('Overlay anchoring (pure)', () => { for (const [vs, vd, row, vAuto, vConnected] of vertical) { it(`maps ${hs}→${hd}, ${vs}→${vd} to "${row} ${column}"`, () => { const s = settings(hs, hd, vs, vd); - const auto = asMap(connectedDeclarations(s, true, '--a', false)); - const connected = asMap(connectedDeclarations(s, false, '--a', false)); + const auto = asMap(connectedDeclarations(s, true, '--a', null)); + const connected = asMap(connectedDeclarations(s, false, '--a', null)); expect(auto['position-area']).toBe(`${row} ${column}`); expect(auto['justify-self']).toBe(hAuto); @@ -83,7 +83,7 @@ describe('Overlay anchoring (pure)', () => { } it('writes the fixed base declarations in order', () => { - const declarations = connectedDeclarations(settings(H.Left, H.Right, V.Bottom, V.Bottom), false, '--a', false); + const declarations = connectedDeclarations(settings(H.Left, H.Right, V.Bottom, V.Bottom), false, '--a', null); expect(declarations.map(([p]) => p)).toEqual([ 'position', 'inset', 'margin', 'position-anchor', 'position-area', 'justify-self', 'align-self', 'position-try-fallbacks', 'position-visibility' @@ -97,26 +97,26 @@ describe('Overlay anchoring (pure)', () => { }); it('applies the offset as margins on outside axes only', () => { - const bottomBottom = asMap(connectedDeclarations(settings(H.Left, H.Right, V.Bottom, V.Bottom, { offset: 6 }), true, '--a', false)); + const bottomBottom = asMap(connectedDeclarations(settings(H.Left, H.Right, V.Bottom, V.Bottom, { offset: 6 }), true, '--a', null)); expect(bottomBottom.margin).toBe('6px 0px 6px 0px'); - const rightRight = asMap(connectedDeclarations(settings(H.Right, H.Right, V.Top, V.Bottom, { offset: 4 }), true, '--a', false)); + const rightRight = asMap(connectedDeclarations(settings(H.Right, H.Right, V.Top, V.Bottom, { offset: 4 }), true, '--a', null)); expect(rightRight.margin).toBe('0px 4px 0px 4px'); - const centered = asMap(connectedDeclarations(settings(H.Center, H.Center, V.Middle, V.Middle, { offset: 4 }), true, '--a', false)); + const centered = asMap(connectedDeclarations(settings(H.Center, H.Center, V.Middle, V.Middle, { offset: 4 }), true, '--a', null)); expect(centered.margin).toBe('0px 0px 0px 0px'); }); - it('writes anchors-visible only when hiding', () => { + it('writes the anchor-visible keyword only when hiding', () => { const s = settings(H.Left, H.Right, V.Bottom, V.Bottom); - expect(asMap(connectedDeclarations(s, true, '--a', true))['position-visibility']).toBe('anchors-visible'); - expect(asMap(connectedDeclarations(s, true, '--a', false))['position-visibility']).toBe('always'); + expect(asMap(connectedDeclarations(s, true, '--a', 'anchor-visible'))['position-visibility']).toBe('anchor-visible'); + expect(asMap(connectedDeclarations(s, true, '--a', null))['position-visibility']).toBe('always'); }); }); describe('containerDeclarations', () => { it('anchors all four insets to the container', () => { - expect(asMap(containerDeclarations('--c', false))).toEqual({ + expect(asMap(containerDeclarations('--c', null))).toEqual({ 'position-anchor': '--c', top: 'anchor(top)', right: 'anchor(right)', @@ -124,7 +124,7 @@ describe('Overlay anchoring (pure)', () => { left: 'anchor(left)', 'position-visibility': 'always' }); - expect(asMap(containerDeclarations('--c', true))['position-visibility']).toBe('anchors-visible'); + expect(asMap(containerDeclarations('--c', 'anchors-visible'))['position-visibility']).toBe('anchors-visible'); }); }); @@ -246,9 +246,18 @@ describe('Overlay anchoring (pure)', () => { describe('feature detection', () => { it('detects support in this browser and none without a window', () => { expect(supportsNativeAnchoring(window)).toBe(true); - expect(supportsPositionVisibility(window)).toBe(true); + expect(['anchor-visible', 'anchors-visible']).toContain(anchorVisibleKeyword(window)); expect(supportsNativeAnchoring(null)).toBe(false); - expect(supportsPositionVisibility(undefined)).toBe(false); + expect(anchorVisibleKeyword(undefined)).toBeNull(); + }); + + it('prefers anchor-visible and falls back to the legacy anchors-visible', () => { + const windowWith = (...keywords: string[]) => ({ + CSS: { supports: (property: string, value: string) => property === 'position-visibility' && keywords.includes(value) } + }) as unknown as Window & typeof globalThis; + expect(anchorVisibleKeyword(windowWith('anchor-visible', 'anchors-visible'))).toBe('anchor-visible'); + expect(anchorVisibleKeyword(windowWith('anchors-visible'))).toBe('anchors-visible'); + expect(anchorVisibleKeyword(windowWith())).toBeNull(); }); }); }); diff --git a/projects/igniteui-angular/core/src/services/overlay/anchoring/anchoring.ts b/projects/igniteui-angular/core/src/services/overlay/anchoring/anchoring.ts index 9fd642021bb..4a885a8204a 100644 --- a/projects/igniteui-angular/core/src/services/overlay/anchoring/anchoring.ts +++ b/projects/igniteui-angular/core/src/services/overlay/anchoring/anchoring.ts @@ -57,11 +57,22 @@ export function supportsNativeAnchoring(win: (Window & typeof globalThis) | null && css.supports('justify-self', 'unsafe anchor-center'); } +/** @hidden @internal The `position-visibility` value that hides content while its anchor is clipped. */ +export type AnchorVisibleKeyword = 'anchor-visible' | 'anchors-visible'; + /** * @hidden @internal - * Whether the window supports `position-visibility: anchors-visible`. + * The `position-visibility` keyword the window supports for hiding content with a clipped anchor, or `null`. + * The CSSWG renamed `anchors-visible` to `anchor-visible` (Chrome 157+, Safari 27+); the plural is a legacy + * alias that browsers serialize to the new name, and the only spelling older browsers know. */ -export function supportsPositionVisibility(win: (Window & typeof globalThis) | null | undefined): boolean { +export function anchorVisibleKeyword(win: (Window & typeof globalThis) | null | undefined): AnchorVisibleKeyword | null { const css = win?.CSS; - return typeof css?.supports === 'function' && css.supports('position-visibility', 'anchors-visible'); + if (typeof css?.supports !== 'function') { + return null; + } + if (css.supports('position-visibility', 'anchor-visible')) { + return 'anchor-visible'; + } + return css.supports('position-visibility', 'anchors-visible') ? 'anchors-visible' : null; } diff --git a/projects/igniteui-angular/core/src/services/overlay/anchoring/native-engine.ts b/projects/igniteui-angular/core/src/services/overlay/anchoring/native-engine.ts index 7cca8ab8fb2..dbceabdedc7 100644 --- a/projects/igniteui-angular/core/src/services/overlay/anchoring/native-engine.ts +++ b/projects/igniteui-angular/core/src/services/overlay/anchoring/native-engine.ts @@ -1,6 +1,7 @@ import { AnimationReferenceMetadata } from '@angular/animations'; import { AnimationUtil } from 'igniteui-angular/animations'; import { HorizontalAlignment, PositionSettings, VerticalAlignment } from '../utilities'; +import type { AnchorVisibleKeyword } from './anchoring'; /** @hidden @internal */ export type OverlayEngine = 'script' | 'native-connected' | 'native-container'; @@ -87,7 +88,7 @@ export function isExpressible(settings: PositionSettings): boolean { * Call only with expressible settings. */ export function connectedDeclarations( - settings: PositionSettings, isAuto: boolean, anchorName: string, hide: boolean + settings: PositionSettings, isAuto: boolean, anchorName: string, hide: AnchorVisibleKeyword | null ): NativeDeclarations { const h = horizontalOf(settings)!; const v = verticalOf(settings)!; @@ -103,7 +104,7 @@ export function connectedDeclarations( ['justify-self', isAuto ? h.auto : h.connected], ['align-self', isAuto ? v.auto : v.connected], ['position-try-fallbacks', isAuto ? AUTO_FALLBACKS : 'none'], - ['position-visibility', hide ? 'anchors-visible' : 'always'] + ['position-visibility', hide ?? 'always'] ]; } @@ -115,14 +116,14 @@ export function connectedDeclarations( * the top layer, so the container clips and scrolls them with no positioning code. Native Container * (D11, D12, §8.2, PR 3) would then be unnecessary; */ -export function containerDeclarations(anchorName: string, hide: boolean): NativeDeclarations { +export function containerDeclarations(anchorName: string, hide: AnchorVisibleKeyword | null): NativeDeclarations { return [ ['position-anchor', anchorName], ['top', 'anchor(top)'], ['right', 'anchor(right)'], ['bottom', 'anchor(bottom)'], ['left', 'anchor(left)'], - ['position-visibility', hide ? 'anchors-visible' : 'always'] + ['position-visibility', hide ?? 'always'] ]; } diff --git a/projects/igniteui-angular/core/src/services/overlay/anchoring/native-overlay.spec.ts b/projects/igniteui-angular/core/src/services/overlay/anchoring/native-overlay.spec.ts index 244d0c6f13a..0b51d506253 100644 --- a/projects/igniteui-angular/core/src/services/overlay/anchoring/native-overlay.spec.ts +++ b/projects/igniteui-angular/core/src/services/overlay/anchoring/native-overlay.spec.ts @@ -15,7 +15,7 @@ import { AbsoluteScrollStrategy } from '../scroll/absolute-scroll-strategy'; import { HideScrollStrategy } from '../scroll/hide-scroll-strategy'; import { NoOpScrollStrategy } from '../scroll/NoOpScrollStrategy'; import { HorizontalAlignment, OverlaySettings, Point, PositionSettings, Util, VerticalAlignment } from '../utilities'; -import { provideOverlayAnchoring } from './anchoring'; +import { anchorVisibleKeyword, provideOverlayAnchoring } from './anchoring'; import { AUTO_FALLBACKS } from './native-engine'; const TOLERANCE = 1; @@ -506,7 +506,7 @@ describe('igxOverlay native anchoring', () => { overlay.closed.subscribe(closed); const id = await open(addElement(), { target, positionStrategy: new AutoPositionStrategy(NO_ANIMATIONS), scrollStrategy: new HideScrollStrategy() }); const el = content(id); - expect(el.style.getPropertyValue('position-visibility')).toBe('anchors-visible'); + expect(el.style.getPropertyValue('position-visibility')).toBe(anchorVisibleKeyword(window)); expect(isHitTestable(el)).toBe(true); await scrollAndSettle(scroller, 200); @@ -592,11 +592,11 @@ describe('igxOverlay native anchoring', () => { expect(overlay.getOverlayById(id).visible).toBe(false); }); - it('H8 - Container: native writes anchors-visible on the wrapper', async () => { + it('H8 - Container: native writes the anchor-visible keyword on the wrapper', async () => { const { target: host } = addScroller(); host.style.position = 'relative'; const id = await open(addElement(50, 20, host), { positionStrategy: new ContainerPositionStrategy(NO_ANIMATIONS), scrollStrategy: new HideScrollStrategy() }); - expect(overlay.getOverlayById(id).wrapperElement!.style.getPropertyValue('position-visibility')).toBe('anchors-visible'); + expect(overlay.getOverlayById(id).wrapperElement!.style.getPropertyValue('position-visibility')).toBe(anchorVisibleKeyword(window)); }); }); }); diff --git a/projects/igniteui-angular/core/src/services/overlay/overlay.ts b/projects/igniteui-angular/core/src/services/overlay/overlay.ts index 3613bccb53d..4b1534f20c2 100644 --- a/projects/igniteui-angular/core/src/services/overlay/overlay.ts +++ b/projects/igniteui-angular/core/src/services/overlay/overlay.ts @@ -16,7 +16,7 @@ import { GlobalPositionStrategy } from './position/global-position-strategy'; import { IPositionStrategy } from './position/IPositionStrategy'; import { NoOpScrollStrategy } from './scroll/NoOpScrollStrategy'; import { HideScrollStrategy } from './scroll/hide-scroll-strategy'; -import { IGX_OVERLAY_ANCHORING, supportsNativeAnchoring, supportsPositionVisibility } from './anchoring/anchoring'; +import { AnchorVisibleKeyword, anchorVisibleKeyword, IGX_OVERLAY_ANCHORING, supportsNativeAnchoring } from './anchoring/anchoring'; import { acquireAnchorName, addAnchorName, removeAnchorName } from './anchoring/anchor-names'; import { connectedDeclarations, @@ -62,7 +62,7 @@ export class IgxOverlayService implements OnDestroy { private animationService = inject(IgxAngularAnimationService); private _anchoringMode = inject(IGX_OVERLAY_ANCHORING, { optional: true }) ?? 'auto'; private _nativeSupported?: boolean; - private _positionVisibilitySupported?: boolean; + private _anchorVisible?: AnchorVisibleKeyword | null; /** * Emitted just before the overlay content starts to open. @@ -501,7 +501,7 @@ export class IgxOverlayService implements OnDestroy { const scrollStrategy = info.settings!.scrollStrategy; if (scrollStrategy instanceof HideScrollStrategy) { const anchor = this.getHideAnchor(info); - const useObserver = engine === 'script' || !this.positionVisibilitySupported(); + const useObserver = engine === 'script' || !this.anchorVisible(); this._zone.runOutsideAngular(() => scrollStrategy._onShown(anchor, contentElement, useObserver)); } this.addModalClasses(info); @@ -1213,8 +1213,12 @@ export class IgxOverlayService implements OnDestroy { return this._nativeSupported ??= supportsNativeAnchoring(this._document.defaultView); } - private positionVisibilitySupported(): boolean { - return this._positionVisibilitySupported ??= supportsPositionVisibility(this._document.defaultView); + /** The supported `position-visibility` hide keyword, or `null`. Detected once per service. */ + private anchorVisible(): AnchorVisibleKeyword | null { + if (this._anchorVisible === undefined) { + this._anchorVisible = anchorVisibleKeyword(this._document.defaultView); + } + return this._anchorVisible; } /** Picks the engine for this show(). Exact class matches only: subclasses keep the script engine. */ @@ -1272,7 +1276,7 @@ export class IgxOverlayService implements OnDestroy { const name = info.anchorName ??= acquireAnchorName(); const settings = info.settings!; const strategy = settings.positionStrategy!; - const hide = settings.scrollStrategy instanceof HideScrollStrategy && this.positionVisibilitySupported(); + const hide = settings.scrollStrategy instanceof HideScrollStrategy ? this.anchorVisible() : null; let element: HTMLElement; let declarations: NativeDeclarations; diff --git a/projects/igniteui-angular/core/src/services/overlay/scroll/README.md b/projects/igniteui-angular/core/src/services/overlay/scroll/README.md index 7514f423c67..38b3183ae66 100644 --- a/projects/igniteui-angular/core/src/services/overlay/scroll/README.md +++ b/projects/igniteui-angular/core/src/services/overlay/scroll/README.md @@ -28,7 +28,7 @@ const settings: OverlaySettings = { | What is watched | The target for connected, auto and elastic positioning; the container for `ContainerPositionStrategy`. A `Point` target or `GlobalPositionStrategy` has nothing to watch, so the content is never hidden. | | When the content is hidden | While the watched element is fully clipped by the viewport or a scrolling ancestor. One visible pixel shows the content again. | | How it is hidden | Visually only. The overlay stays open: `closing` and `closed` are not emitted, and `Esc` and outside clicks still close it. Focus inside the hidden content is lost. | -| Browser | With native anchor positioning, the browser hides the content (`position-visibility: anchors-visible`). Elsewhere, including Safari 26.0 and 26.1, an `IntersectionObserver` hides it, up to one frame later. | +| Browser | With native anchor positioning, the browser hides the content (`position-visibility: anchor-visible`, or the older `anchors-visible` spelling). Elsewhere, including Safari 26.0 and 26.1, an `IntersectionObserver` hides it, up to one frame later. | ## Usage