From 169c9542f5ede9b7a127c52009d003d49c4f8467 Mon Sep 17 00:00:00 2001 From: Joseph Pender Date: Fri, 4 Dec 2026 11:31:06 -0600 Subject: [PATCH 1/6] Starting on DisplayFeatures polyfill --- cli/src/declarations.ts | 16 ++ core/display-features.ts | 238 ++++++++++++++++++++++++ core/package.json | 2 +- core/rollup.bridge.config.js | 83 ++++++--- core/src/tests/display-features.spec.ts | 190 +++++++++++++++++++ ios/Capacitor.podspec | 2 +- 6 files changed, 499 insertions(+), 32 deletions(-) create mode 100644 core/display-features.ts create mode 100644 core/src/tests/display-features.spec.ts diff --git a/cli/src/declarations.ts b/cli/src/declarations.ts index dbd94509d..ba756a968 100644 --- a/cli/src/declarations.ts +++ b/cli/src/declarations.ts @@ -94,6 +94,22 @@ export interface CapacitorConfig { */ forceCordovaInclusion?: boolean; + displayFeatures?: { + /** + * Whether to inject the Device Posture and Viewport Segments polyfill. + * + * When enabled, `navigator.devicePosture`, `window.viewport.segments` + * and the `--device-posture`, `--horizontal-viewport-segments`, + * `--vertical-viewport-segments` and `--viewport-segment-*` CSS + * variables are provided from native fold data, replacing any built-in + * implementation in the web view. + * + * @since 9.1.0 + * @default true + */ + polyfill?: boolean; + }; + android?: { /** * Specify a custom path to the native Android project. diff --git a/core/display-features.ts b/core/display-features.ts new file mode 100644 index 000000000..c0a13e5ef --- /dev/null +++ b/core/display-features.ts @@ -0,0 +1,238 @@ +/** + * Note: When making changes to this file, run `npm run build:nativebridge` + * afterwards to build the display-features.js files to the android and iOS projects. + */ + +type DevicePostureType = 'continuous' | 'folded'; + +interface SegmentRect { + left: number; + top: number; + width: number; + height: number; +} + +interface DisplayFeaturesState { + posture: DevicePostureType; + segments: SegmentRect[]; +} + +interface DisplayFeaturesUpdate { + posture?: unknown; + segments?: unknown; +} + +export interface DisplayFeaturesWindow extends Window { + __osDisplayFeatures?: { update: (update: DisplayFeaturesUpdate) => void }; + __osDisplayFeaturesNative?: { getState?: () => string | null | undefined }; + viewport?: object; +} + +const isPosture = (value: unknown): value is DevicePostureType => value === 'continuous' || value === 'folded'; + +const isSegment = (value: any): value is SegmentRect => + value !== null && + typeof value === 'object' && + [value.left, value.top, value.width, value.height].every((n) => typeof n === 'number' && Number.isFinite(n)) && + value.left >= 0 && + value.top >= 0 && + value.width > 0 && + value.height > 0; + +const parseSegments = (value: unknown): SegmentRect[] | null => { + if (!Array.isArray(value) || value.length < 1 || value.length > 2 || !value.every(isSegment)) { + return null; + } + return value + .map(({ left, top, width, height }: SegmentRect) => ({ left, top, width, height })) + .sort((a, b) => a.left - b.left || a.top - b.top); +}; + +const segmentsEqual = (a: SegmentRect[], b: SegmentRect[]): boolean => + a.length === b.length && + a.every((s, i) => s.left === b[i].left && s.top === b[i].top && s.width === b[i].width && s.height === b[i].height); + +const segmentIndices = (segments: SegmentRect[]): [number, number][] => + segments.length === 2 && segments[1].left > segments[0].left + ? [ + [0, 0], + [1, 0], + ] + : segments.map((_, i): [number, number] => [0, i]); + +const cssVariables = (state: DisplayFeaturesState): Map => { + const vars = new Map(); + const indices = segmentIndices(state.segments); + vars.set('--device-posture', state.posture); + vars.set('--horizontal-viewport-segments', String(Math.max(...indices.map(([x]) => x)) + 1)); + vars.set('--vertical-viewport-segments', String(Math.max(...indices.map(([, y]) => y)) + 1)); + if (state.segments.length > 1) { + state.segments.forEach((s, i) => { + const suffix = `${indices[i][0]}-${indices[i][1]}`; + vars.set(`--viewport-segment-top-${suffix}`, `${s.top}px`); + vars.set(`--viewport-segment-left-${suffix}`, `${s.left}px`); + vars.set(`--viewport-segment-bottom-${suffix}`, `${s.top + s.height}px`); + vars.set(`--viewport-segment-right-${suffix}`, `${s.left + s.width}px`); + vars.set(`--viewport-segment-width-${suffix}`, `${s.width}px`); + vars.set(`--viewport-segment-height-${suffix}`, `${s.height}px`); + }); + } + return vars; +}; + +const readNativeState = (win: DisplayFeaturesWindow): DisplayFeaturesUpdate => { + const getState = win.__osDisplayFeaturesNative?.getState; + if (typeof getState !== 'function') { + return {}; + } + try { + const json = getState.call(win.__osDisplayFeaturesNative); + const parsed = json ? JSON.parse(json) : null; + return parsed !== null && typeof parsed === 'object' ? parsed : {}; + } catch (e) { + console.warn('Display Features: unable to read initial state from native', e); + return {}; + } +}; + +const initDisplayFeatures = (win: DisplayFeaturesWindow): void => { + if (win.__osDisplayFeatures || win.top !== win) { + return; + } + + const initial = readNativeState(win); + const state: DisplayFeaturesState = { + posture: isPosture(initial.posture) ? initial.posture : 'continuous', + segments: parseSegments(initial.segments) ?? [{ left: 0, top: 0, width: win.innerWidth, height: win.innerHeight }], + }; + + class DevicePosture extends EventTarget { + private changeHandler: ((this: DevicePosture, ev: Event) => any) | null = null; + private changeHandlerRegistered = false; + + get type(): DevicePostureType { + return state.posture; + } + + get onchange(): ((this: DevicePosture, ev: Event) => any) | null { + return this.changeHandler; + } + + set onchange(handler: ((this: DevicePosture, ev: Event) => any) | null) { + this.changeHandler = typeof handler === 'function' ? handler : null; + if (this.changeHandler && !this.changeHandlerRegistered) { + this.changeHandlerRegistered = true; + this.addEventListener('change', (ev) => this.changeHandler?.call(this, ev)); + } + } + } + + const devicePosture = new DevicePosture(); + const getSegments = (): DOMRect[] => state.segments.map((s) => new DOMRect(s.left, s.top, s.width, s.height)); + + try { + Object.defineProperty(win.navigator, 'devicePosture', { + configurable: true, + enumerable: true, + get: () => devicePosture, + }); + if (win.viewport && typeof win.viewport === 'object') { + Object.defineProperty(win.viewport, 'segments', { configurable: true, enumerable: true, get: getSegments }); + } else { + const viewport = {}; + Object.defineProperty(viewport, 'segments', { configurable: true, enumerable: true, get: getSegments }); + Object.defineProperty(win, 'viewport', { configurable: true, enumerable: true, value: viewport }); + } + } catch (e) { + console.warn('Display Features: unable to install the polyfill', e); + return; + } + + const appliedVariables = new Set(); + const applyCssVariables = () => { + const style = win.document.documentElement.style; + const vars = cssVariables(state); + appliedVariables.forEach((name) => { + if (!vars.has(name)) { + style.removeProperty(name); + appliedVariables.delete(name); + } + }); + vars.forEach((value, name) => { + style.setProperty(name, value); + appliedVariables.add(name); + }); + }; + + let announcedPosture = state.posture; + let resizePending = false; + let eventsQueued = false; + const queueEvents = () => { + if (eventsQueued) { + return; + } + eventsQueued = true; + win.setTimeout(() => { + eventsQueued = false; + if (state.posture !== announcedPosture) { + announcedPosture = state.posture; + devicePosture.dispatchEvent(new Event('change')); + } + if (resizePending) { + resizePending = false; + win.dispatchEvent(new Event('resize')); + } + }, 0); + }; + + let pending: DisplayFeaturesState | null = null; + const apply = (next: DisplayFeaturesState) => { + if (win.document.visibilityState === 'hidden') { + pending = next; + return; + } + pending = null; + const postureChanged = next.posture !== state.posture; + const segmentsChanged = !segmentsEqual(next.segments, state.segments); + if (!postureChanged && !segmentsChanged) { + return; + } + state.posture = next.posture; + state.segments = next.segments; + applyCssVariables(); + resizePending = resizePending || segmentsChanged; + queueEvents(); + }; + + win.document.addEventListener('visibilitychange', () => { + if (pending && win.document.visibilityState !== 'hidden') { + apply(pending); + } + }); + + win.__osDisplayFeatures = { + update: (update: DisplayFeaturesUpdate) => { + if (update === null || typeof update !== 'object') { + return; + } + const base = pending ?? state; + apply({ + posture: isPosture(update.posture) ? update.posture : base.posture, + segments: parseSegments(update.segments) ?? base.segments, + }); + }, + }; + + if (win.document.documentElement) { + applyCssVariables(); + } else { + win.document.addEventListener('DOMContentLoaded', applyCssVariables, { once: true }); + } +}; + +if (typeof window !== 'undefined') { + initDisplayFeatures(window as DisplayFeaturesWindow); +} + +// Export only for tests +export { initDisplayFeatures }; diff --git a/core/package.json b/core/package.json index 7eb991ee4..c8d0a9b72 100644 --- a/core/package.json +++ b/core/package.json @@ -26,7 +26,7 @@ "unpkg": "dist/capacitor.js", "scripts": { "build": "npm run clean && npm run docgen && npm run transpile && npm run rollup", - "build:nativebridge": "tsc native-bridge.ts --target es2017 --moduleResolution node --outDir build && rollup --config rollup.bridge.config.js", + "build:nativebridge": "tsc native-bridge.ts display-features.ts --target es2017 --moduleResolution node --outDir build && rollup --config rollup.bridge.config.js", "clean": "rimraf dist", "docgen": "docgen --api CapacitorCookiesPlugin --output-readme cookies.md && docgen --api CapacitorHttpPlugin --output-readme http.md && docgen --api SystemBarsPlugin --output-readme system-bars.md", "prepublishOnly": "npm run build", diff --git a/core/rollup.bridge.config.js b/core/rollup.bridge.config.js index d741e5dcc..a0649f561 100644 --- a/core/rollup.bridge.config.js +++ b/core/rollup.bridge.config.js @@ -5,33 +5,56 @@ const banner = ` /* Generated File. Do not edit. */ `; -export default { - input: 'build/native-bridge.js', - output: [ - { - file: '../android/capacitor/src/main/assets/native-bridge.js', - format: 'iife', - name: 'nativeBridge', - preferConst: true, - banner, - sourcemap: false, - }, - { - file: '../ios/Sources/Capacitor/assets/native-bridge.js', - format: 'iife', - name: 'nativeBridge', - preferConst: true, - banner, - sourcemap: false, - }, - ], - // Remove any references to module.exports or exports.__esModule by replacing them with unused variables - plugins: [ - replace({ - 'module.exports': 'dummy', - 'exports.__esModule': 'dummy', - 'exports.initBridge': 'dummy', - preventAssignment: false, - }), - ], -}; +export default [ + { + input: 'build/native-bridge.js', + output: [ + { + file: '../android/capacitor/src/main/assets/native-bridge.js', + format: 'iife', + name: 'nativeBridge', + preferConst: true, + banner, + sourcemap: false, + }, + { + file: '../ios/Sources/Capacitor/assets/native-bridge.js', + format: 'iife', + name: 'nativeBridge', + preferConst: true, + banner, + sourcemap: false, + }, + ], + // Remove any references to module.exports or exports.__esModule by replacing them with unused variables + plugins: [ + replace({ + 'module.exports': 'dummy', + 'exports.__esModule': 'dummy', + 'exports.initBridge': 'dummy', + preventAssignment: false, + }), + ], + }, + { + input: 'build/display-features.js', + output: [ + { + file: '../android/capacitor/src/main/assets/display-features.js', + format: 'iife', + name: '__osDisplayFeaturesPolyfill', + preferConst: true, + banner, + sourcemap: false, + }, + { + file: '../ios/Sources/Capacitor/assets/display-features.js', + format: 'iife', + name: '__osDisplayFeaturesPolyfill', + preferConst: true, + banner, + sourcemap: false, + }, + ], + }, +]; diff --git a/core/src/tests/display-features.spec.ts b/core/src/tests/display-features.spec.ts new file mode 100644 index 000000000..1498b7184 --- /dev/null +++ b/core/src/tests/display-features.spec.ts @@ -0,0 +1,190 @@ +/** + * @jest-environment jsdom + */ + +import type { DisplayFeaturesWindow } from '../../display-features'; +import { initDisplayFeatures } from '../../display-features'; + +const win = window as DisplayFeaturesWindow; +const nav = navigator as any; +const style = () => document.documentElement.style; + +const vertical = [ + { left: 420, top: 0, width: 400, height: 800 }, + { left: 0, top: 0, width: 400, height: 800 }, +]; + +const install = (nativeState?: unknown) => { + delete win.__osDisplayFeatures; + delete win.__osDisplayFeaturesNative; + if (nativeState !== undefined) { + win.__osDisplayFeaturesNative = { getState: () => JSON.stringify(nativeState) }; + } + initDisplayFeatures(win); +}; + +const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); + +const setVisibility = (state: 'visible' | 'hidden') => { + Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => state }); + document.dispatchEvent(new Event('visibilitychange')); +}; + +describe('display features polyfill', () => { + beforeAll(() => { + (globalThis as any).DOMRect ??= class { + constructor( + public x: number, + public y: number, + public width: number, + public height: number, + ) {} + }; + }); + + beforeEach(() => { + document.documentElement.removeAttribute('style'); + setVisibility('visible'); + install(); + }); + + afterEach(flush); + + it('is a no-op when installed twice', () => { + const posture = nav.devicePosture; + initDisplayFeatures(win); + expect(nav.devicePosture).toBe(posture); + }); + + it('defaults to continuous with one segment covering the viewport', () => { + expect(nav.devicePosture.type).toBe('continuous'); + const segments = (win.viewport as any).segments; + expect(segments).toHaveLength(1); + expect(segments[0]).toMatchObject({ x: 0, y: 0, width: win.innerWidth, height: win.innerHeight }); + expect(style().getPropertyValue('--device-posture')).toBe('continuous'); + expect(style().getPropertyValue('--horizontal-viewport-segments')).toBe('1'); + expect(style().getPropertyValue('--vertical-viewport-segments')).toBe('1'); + expect(style().getPropertyValue('--viewport-segment-width-0-0')).toBe(''); + }); + + it('reads the initial state from native and sorts segments', () => { + install({ posture: 'folded', segments: vertical }); + expect(nav.devicePosture.type).toBe('folded'); + expect((win.viewport as any).segments.map((s: DOMRect) => s.x)).toEqual([0, 420]); + expect(style().getPropertyValue('--horizontal-viewport-segments')).toBe('2'); + expect(style().getPropertyValue('--viewport-segment-width-1-0')).toBe('400px'); + expect(style().getPropertyValue('--viewport-segment-right-1-0')).toBe('820px'); + }); + + it('falls back when native returns invalid state', () => { + install({ posture: 'bent', segments: [{ left: 0, top: 0, width: -1, height: 10 }] }); + expect(nav.devicePosture.type).toBe('continuous'); + expect((win.viewport as any).segments[0].width).toBe(win.innerWidth); + }); + + it('indexes stacked segments on the y axis', () => { + win.__osDisplayFeatures?.update({ + segments: [ + { left: 0, top: 420, width: 800, height: 400 }, + { left: 0, top: 0, width: 800, height: 400 }, + ], + }); + expect(style().getPropertyValue('--vertical-viewport-segments')).toBe('2'); + expect(style().getPropertyValue('--horizontal-viewport-segments')).toBe('1'); + expect(style().getPropertyValue('--viewport-segment-top-0-1')).toBe('420px'); + expect(style().getPropertyValue('--viewport-segment-bottom-0-1')).toBe('820px'); + }); + + it('removes segment variables when returning to one segment', () => { + win.__osDisplayFeatures?.update({ segments: vertical }); + win.__osDisplayFeatures?.update({ segments: [{ left: 0, top: 0, width: 820, height: 800 }] }); + expect(style().getPropertyValue('--viewport-segment-width-0-0')).toBe(''); + expect(style().getPropertyValue('--viewport-segment-width-1-0')).toBe(''); + expect(style().getPropertyValue('--horizontal-viewport-segments')).toBe('1'); + }); + + it('returns a fresh snapshot on each read', () => { + const before = (win.viewport as any).segments; + win.__osDisplayFeatures?.update({ segments: vertical }); + expect(before).toHaveLength(1); + expect((win.viewport as any).segments).toHaveLength(2); + }); + + it('ignores invalid fields and keeps the rest', () => { + win.__osDisplayFeatures?.update({ posture: 'folded', segments: 'nope' }); + expect(nav.devicePosture.type).toBe('folded'); + expect((win.viewport as any).segments).toHaveLength(1); + }); + + it('dispatches change then resize asynchronously, after state is applied', async () => { + const events: string[] = []; + nav.devicePosture.addEventListener('change', () => + events.push(`change:${nav.devicePosture.type}:${style().getPropertyValue('--device-posture')}`), + ); + nav.devicePosture.onchange = () => events.push('onchange'); + const onResize = () => events.push(`resize:${(win.viewport as any).segments.length}`); + win.addEventListener('resize', onResize); + + win.__osDisplayFeatures?.update({ posture: 'folded', segments: vertical }); + expect(events).toEqual([]); + await flush(); + expect(events).toEqual(['change:folded:folded', 'onchange', 'resize:2']); + win.removeEventListener('resize', onResize); + }); + + it('fires nothing when the values do not change', async () => { + const listener = jest.fn(); + nav.devicePosture.addEventListener('change', listener); + win.addEventListener('resize', listener); + win.__osDisplayFeatures?.update({ posture: 'continuous' }); + await flush(); + expect(listener).not.toHaveBeenCalled(); + win.removeEventListener('resize', listener); + }); + + it('fires resize but not change when only segments change', async () => { + const change = jest.fn(); + const resize = jest.fn(); + nav.devicePosture.addEventListener('change', change); + win.addEventListener('resize', resize); + win.__osDisplayFeatures?.update({ segments: vertical }); + await flush(); + expect(change).not.toHaveBeenCalled(); + expect(resize).toHaveBeenCalledTimes(1); + win.removeEventListener('resize', resize); + }); + + it('defers updates while hidden and applies them when visible', async () => { + const change = jest.fn(); + nav.devicePosture.addEventListener('change', change); + setVisibility('hidden'); + win.__osDisplayFeatures?.update({ posture: 'folded' }); + win.__osDisplayFeatures?.update({ segments: vertical }); + await flush(); + expect(nav.devicePosture.type).toBe('continuous'); + expect(change).not.toHaveBeenCalled(); + + setVisibility('visible'); + expect(nav.devicePosture.type).toBe('folded'); + expect((win.viewport as any).segments).toHaveLength(2); + await flush(); + expect(change).toHaveBeenCalledTimes(1); + }); + + it('replaces only segments on an existing viewport object', () => { + const existing = { segments: [] as DOMRect[], other: 'kept' }; + Object.defineProperty(win, 'viewport', { configurable: true, value: existing }); + install(); + expect(win.viewport).toBe(existing); + expect((existing as any).other).toBe('kept'); + expect(existing.segments).toHaveLength(1); + }); + + it('replaces a built-in navigator.devicePosture', () => { + const builtIn = { type: 'folded' }; + Object.defineProperty(navigator, 'devicePosture', { configurable: true, value: builtIn }); + install(); + expect(nav.devicePosture).not.toBe(builtIn); + expect(nav.devicePosture.type).toBe('continuous'); + }); +}); diff --git a/ios/Capacitor.podspec b/ios/Capacitor.podspec index dc007ed70..9d9c7b088 100644 --- a/ios/Capacitor.podspec +++ b/ios/Capacitor.podspec @@ -23,7 +23,7 @@ Pod::Spec.new do |s| # SPM-only shim; CocoaPods generates the real Capacitor-Swift.h for the mixed-language module. s.exclude_files = ["#{prefix}Sources/CapacitorObjCShims/include/Capacitor/Capacitor-Swift.h"] s.module_map = "#{prefix}Sources/CapacitorObjCShims/Capacitor.modulemap" - s.resources = ["#{prefix}Sources/Capacitor/assets/native-bridge.js"] + s.resources = ["#{prefix}Sources/Capacitor/assets/native-bridge.js", "#{prefix}Sources/Capacitor/assets/display-features.js"] s.resource_bundles = { 'Capacitor' => ["#{prefix}Sources/Capacitor/PrivacyInfo.xcprivacy"] } s.swift_version = '5.7' end From 472c6b8c60eee3de65c89ca9288dcbaf5ac2551c Mon Sep 17 00:00:00 2001 From: Joseph Pender Date: Fri, 4 Dec 2026 11:31:37 -0600 Subject: [PATCH 2/6] building Android display features functionality --- android-template/variables.gradle | 1 + android/capacitor/build.gradle | 3 + .../src/main/assets/display-features.js | 210 ++++++++++++++++++ .../main/java/com/getcapacitor/Bridge.java | 26 ++- .../main/java/com/getcapacitor/CapConfig.java | 20 ++ .../com/getcapacitor/DisplayFeatures.java | 100 +++++++++ .../getcapacitor/DisplayFeaturesState.java | 109 +++++++++ .../main/java/com/getcapacitor/JSExport.java | 4 + .../com/getcapacitor/ConfigReadingTest.java | 2 + .../DisplayFeaturesStateTest.java | 90 ++++++++ .../src/test/resources/configs/hierarchy.json | 3 + 11 files changed, 567 insertions(+), 1 deletion(-) create mode 100644 android/capacitor/src/main/assets/display-features.js create mode 100644 android/capacitor/src/main/java/com/getcapacitor/DisplayFeatures.java create mode 100644 android/capacitor/src/main/java/com/getcapacitor/DisplayFeaturesState.java create mode 100644 android/capacitor/src/test/java/com/getcapacitor/DisplayFeaturesStateTest.java diff --git a/android-template/variables.gradle b/android-template/variables.gradle index eb5879721..c2c02bf2a 100644 --- a/android-template/variables.gradle +++ b/android-template/variables.gradle @@ -9,6 +9,7 @@ ext { androidxFragmentVersion = '1.9.1' coreSplashScreenVersion = '1.2.0' androidxWebkitVersion = '1.17.1' + androidxWindowVersion = '1.5.1' junitVersion = '4.13.2' androidxJunitVersion = '1.3.0' androidxEspressoCoreVersion = '3.7.0' diff --git a/android/capacitor/build.gradle b/android/capacitor/build.gradle index bda6371fd..ca35f5f32 100644 --- a/android/capacitor/build.gradle +++ b/android/capacitor/build.gradle @@ -5,6 +5,7 @@ ext { androidxCoreVersion = rootProject.hasProperty('androidxCoreVersion') ? rootProject.ext.androidxCoreVersion : '1.19.1' androidxFragmentVersion = rootProject.hasProperty('androidxFragmentVersion') ? rootProject.ext.androidxFragmentVersion : '1.9.1' androidxWebkitVersion = rootProject.hasProperty('androidxWebkitVersion') ? rootProject.ext.androidxWebkitVersion : '1.17.1' + androidxWindowVersion = rootProject.hasProperty('androidxWindowVersion') ? rootProject.ext.androidxWindowVersion : '1.5.1' junitVersion = rootProject.hasProperty('junitVersion') ? rootProject.ext.junitVersion : '4.13.2' androidxJunitVersion = rootProject.hasProperty('androidxJunitVersion') ? rootProject.ext.androidxJunitVersion : '1.3.0' androidxEspressoCoreVersion = rootProject.hasProperty('androidxEspressoCoreVersion') ? rootProject.ext.androidxEspressoCoreVersion : '3.7.0' @@ -76,6 +77,8 @@ dependencies { implementation "androidx.fragment:fragment:$androidxFragmentVersion" implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion" implementation "androidx.webkit:webkit:$androidxWebkitVersion" + implementation "androidx.window:window:$androidxWindowVersion" + implementation "androidx.window:window-java:$androidxWindowVersion" testImplementation "junit:junit:$junitVersion" androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion" androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion" diff --git a/android/capacitor/src/main/assets/display-features.js b/android/capacitor/src/main/assets/display-features.js new file mode 100644 index 000000000..ca98d7ead --- /dev/null +++ b/android/capacitor/src/main/assets/display-features.js @@ -0,0 +1,210 @@ + +/*! Capacitor: https://capacitorjs.com/ - MIT License */ +/* Generated File. Do not edit. */ + +var __osDisplayFeaturesPolyfill = (function (exports) { + 'use strict'; + + /** + * Note: When making changes to this file, run `npm run build:nativebridge` + * afterwards to build the display-features.js files to the android and iOS projects. + */ + const isPosture = (value) => value === 'continuous' || value === 'folded'; + const isSegment = (value) => value !== null && + typeof value === 'object' && + [value.left, value.top, value.width, value.height].every((n) => typeof n === 'number' && Number.isFinite(n)) && + value.left >= 0 && + value.top >= 0 && + value.width > 0 && + value.height > 0; + const parseSegments = (value) => { + if (!Array.isArray(value) || value.length < 1 || value.length > 2 || !value.every(isSegment)) { + return null; + } + return value + .map(({ left, top, width, height }) => ({ left, top, width, height })) + .sort((a, b) => a.left - b.left || a.top - b.top); + }; + const segmentsEqual = (a, b) => a.length === b.length && + a.every((s, i) => s.left === b[i].left && s.top === b[i].top && s.width === b[i].width && s.height === b[i].height); + const segmentIndices = (segments) => segments.length === 2 && segments[1].left > segments[0].left + ? [ + [0, 0], + [1, 0], + ] + : segments.map((_, i) => [0, i]); + const cssVariables = (state) => { + const vars = new Map(); + const indices = segmentIndices(state.segments); + vars.set('--device-posture', state.posture); + vars.set('--horizontal-viewport-segments', String(Math.max(...indices.map(([x]) => x)) + 1)); + vars.set('--vertical-viewport-segments', String(Math.max(...indices.map(([, y]) => y)) + 1)); + if (state.segments.length > 1) { + state.segments.forEach((s, i) => { + const suffix = `${indices[i][0]}-${indices[i][1]}`; + vars.set(`--viewport-segment-top-${suffix}`, `${s.top}px`); + vars.set(`--viewport-segment-left-${suffix}`, `${s.left}px`); + vars.set(`--viewport-segment-bottom-${suffix}`, `${s.top + s.height}px`); + vars.set(`--viewport-segment-right-${suffix}`, `${s.left + s.width}px`); + vars.set(`--viewport-segment-width-${suffix}`, `${s.width}px`); + vars.set(`--viewport-segment-height-${suffix}`, `${s.height}px`); + }); + } + return vars; + }; + const readNativeState = (win) => { + var _a; + const getState = (_a = win.__osDisplayFeaturesNative) === null || _a === void 0 ? void 0 : _a.getState; + if (typeof getState !== 'function') { + return {}; + } + try { + const json = getState.call(win.__osDisplayFeaturesNative); + const parsed = json ? JSON.parse(json) : null; + return parsed !== null && typeof parsed === 'object' ? parsed : {}; + } + catch (e) { + console.warn('Display Features: unable to read initial state from native', e); + return {}; + } + }; + const initDisplayFeatures = (win) => { + var _a; + if (win.__osDisplayFeatures || win.top !== win) { + return; + } + const initial = readNativeState(win); + const state = { + posture: isPosture(initial.posture) ? initial.posture : 'continuous', + segments: (_a = parseSegments(initial.segments)) !== null && _a !== void 0 ? _a : [{ left: 0, top: 0, width: win.innerWidth, height: win.innerHeight }], + }; + class DevicePosture extends EventTarget { + constructor() { + super(...arguments); + this.changeHandler = null; + this.changeHandlerRegistered = false; + } + get type() { + return state.posture; + } + get onchange() { + return this.changeHandler; + } + set onchange(handler) { + this.changeHandler = typeof handler === 'function' ? handler : null; + if (this.changeHandler && !this.changeHandlerRegistered) { + this.changeHandlerRegistered = true; + this.addEventListener('change', (ev) => { var _a; return (_a = this.changeHandler) === null || _a === void 0 ? void 0 : _a.call(this, ev); }); + } + } + } + const devicePosture = new DevicePosture(); + const getSegments = () => state.segments.map((s) => new DOMRect(s.left, s.top, s.width, s.height)); + try { + Object.defineProperty(win.navigator, 'devicePosture', { + configurable: true, + enumerable: true, + get: () => devicePosture, + }); + if (win.viewport && typeof win.viewport === 'object') { + Object.defineProperty(win.viewport, 'segments', { configurable: true, enumerable: true, get: getSegments }); + } + else { + const viewport = {}; + Object.defineProperty(viewport, 'segments', { configurable: true, enumerable: true, get: getSegments }); + Object.defineProperty(win, 'viewport', { configurable: true, enumerable: true, value: viewport }); + } + } + catch (e) { + console.warn('Display Features: unable to install the polyfill', e); + return; + } + const appliedVariables = new Set(); + const applyCssVariables = () => { + const style = win.document.documentElement.style; + const vars = cssVariables(state); + appliedVariables.forEach((name) => { + if (!vars.has(name)) { + style.removeProperty(name); + appliedVariables.delete(name); + } + }); + vars.forEach((value, name) => { + style.setProperty(name, value); + appliedVariables.add(name); + }); + }; + let announcedPosture = state.posture; + let resizePending = false; + let eventsQueued = false; + const queueEvents = () => { + if (eventsQueued) { + return; + } + eventsQueued = true; + win.setTimeout(() => { + eventsQueued = false; + if (state.posture !== announcedPosture) { + announcedPosture = state.posture; + devicePosture.dispatchEvent(new Event('change')); + } + if (resizePending) { + resizePending = false; + win.dispatchEvent(new Event('resize')); + } + }, 0); + }; + let pending = null; + const apply = (next) => { + if (win.document.visibilityState === 'hidden') { + pending = next; + return; + } + pending = null; + const postureChanged = next.posture !== state.posture; + const segmentsChanged = !segmentsEqual(next.segments, state.segments); + if (!postureChanged && !segmentsChanged) { + return; + } + state.posture = next.posture; + state.segments = next.segments; + applyCssVariables(); + resizePending = resizePending || segmentsChanged; + queueEvents(); + }; + win.document.addEventListener('visibilitychange', () => { + if (pending && win.document.visibilityState !== 'hidden') { + apply(pending); + } + }); + win.__osDisplayFeatures = { + update: (update) => { + var _a; + if (update === null || typeof update !== 'object') { + return; + } + const base = pending !== null && pending !== void 0 ? pending : state; + apply({ + posture: isPosture(update.posture) ? update.posture : base.posture, + segments: (_a = parseSegments(update.segments)) !== null && _a !== void 0 ? _a : base.segments, + }); + }, + }; + if (win.document.documentElement) { + applyCssVariables(); + } + else { + win.document.addEventListener('DOMContentLoaded', applyCssVariables, { once: true }); + } + }; + if (typeof window !== 'undefined') { + initDisplayFeatures(window); + } + + exports.initDisplayFeatures = initDisplayFeatures; + + Object.defineProperty(exports, '__esModule', { value: true }); + + return exports; + +})({}); diff --git a/android/capacitor/src/main/java/com/getcapacitor/Bridge.java b/android/capacitor/src/main/java/com/getcapacitor/Bridge.java index d9299d460..d29812d1d 100644 --- a/android/capacitor/src/main/java/com/getcapacitor/Bridge.java +++ b/android/capacitor/src/main/java/com/getcapacitor/Bridge.java @@ -103,6 +103,7 @@ public class Bridge { // A reference to the containing Fragment if used private final Fragment fragment; private WebViewLocalServer localServer; + private DisplayFeatures displayFeatures; private String localUrl; private String appUrl; private String appUrlConfig; @@ -224,8 +225,11 @@ private void loadWebView() { // Start the local web server JSInjector injector = getJSInjector(); + String allowedOrigin = Uri.parse(appUrl).buildUpon().path(null).fragment(null).clearQuery().build().toString(); + if (config.isDisplayFeaturesPolyfillEnabled()) { + installDisplayFeatures(allowedOrigin); + } if (WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) { - String allowedOrigin = Uri.parse(appUrl).buildUpon().path(null).fragment(null).clearQuery().build().toString(); try { WebViewCompat.addDocumentStartJavaScript(webView, injector.getScriptString(), Collections.singleton(allowedOrigin)); injector = null; @@ -968,6 +972,20 @@ private JSInjector getJSInjector() { return null; } + private void installDisplayFeatures(String allowedOrigin) { + if (WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) { + try { + String script = JSExport.getDisplayFeaturesJS(context); + WebViewCompat.addDocumentStartJavaScript(webView, script, Collections.singleton(allowedOrigin)); + displayFeatures = new DisplayFeatures(context, webView); + } catch (JSExportException | IllegalArgumentException ex) { + Logger.error("Unable to install the Display Features polyfill", ex); + } + } else { + Logger.warn("Display Features polyfill not installed: this WebView does not support document start scripts"); + } + } + /** * Inject JavaScript from an external file before the WebView loads. * @param path relative to public folder @@ -1245,6 +1263,9 @@ public void onRestart() { * Handle onStart lifecycle event and notify the plugins */ public void onStart() { + if (displayFeatures != null) { + displayFeatures.start(); + } for (PluginHandle plugin : plugins.values()) { plugin.getInstance().handleOnStart(); } @@ -1272,6 +1293,9 @@ public void onPause() { * Handle onStop lifecycle event and notify the plugins */ public void onStop() { + if (displayFeatures != null) { + displayFeatures.stop(); + } for (PluginHandle plugin : plugins.values()) { plugin.getInstance().handleOnStop(); } diff --git a/android/capacitor/src/main/java/com/getcapacitor/CapConfig.java b/android/capacitor/src/main/java/com/getcapacitor/CapConfig.java index 305d61e59..41442e253 100644 --- a/android/capacitor/src/main/java/com/getcapacitor/CapConfig.java +++ b/android/capacitor/src/main/java/com/getcapacitor/CapConfig.java @@ -55,6 +55,9 @@ public class CapConfig { private boolean zoomableWebView = false; private boolean resolveServiceWorkerRequests = true; + // Display Features Config + private boolean displayFeaturesPolyfill = true; + // Embedded private String startPath; @@ -161,6 +164,9 @@ private CapConfig(Builder builder) { this.zoomableWebView = builder.zoomableWebView; this.resolveServiceWorkerRequests = builder.resolveServiceWorkerRequests; + // Display Features Config + this.displayFeaturesPolyfill = builder.displayFeaturesPolyfill; + // Embedded this.startPath = builder.startPath; @@ -288,6 +294,8 @@ private void deserializeConfig(@Nullable Context context) { JSONUtils.getBoolean(configJSON, "initialFocus", initialFocus) ); + displayFeaturesPolyfill = JSONUtils.getBoolean(configJSON, "displayFeatures.polyfill", displayFeaturesPolyfill); + // Plugins pluginsConfiguration = deserializePluginsConfig(JSONUtils.getObject(configJSON, "plugins")); } @@ -377,6 +385,10 @@ public boolean isInitialFocus() { return initialFocus; } + public boolean isDisplayFeaturesPolyfillEnabled() { + return displayFeaturesPolyfill; + } + public boolean isUsingLegacyBridge() { return useLegacyBridge; } @@ -464,6 +476,9 @@ public static class Builder { private boolean zoomableWebView = false; private boolean resolveServiceWorkerRequests = true; + // Display Features Config + private boolean displayFeaturesPolyfill = true; + // Embedded private String startPath = null; @@ -586,5 +601,10 @@ public Builder setInitialFocus(boolean focus) { this.initialFocus = focus; return this; } + + public Builder setDisplayFeaturesPolyfill(boolean enabled) { + this.displayFeaturesPolyfill = enabled; + return this; + } } } diff --git a/android/capacitor/src/main/java/com/getcapacitor/DisplayFeatures.java b/android/capacitor/src/main/java/com/getcapacitor/DisplayFeatures.java new file mode 100644 index 000000000..bf80eefa6 --- /dev/null +++ b/android/capacitor/src/main/java/com/getcapacitor/DisplayFeatures.java @@ -0,0 +1,100 @@ +package com.getcapacitor; + +import android.app.Activity; +import android.graphics.Rect; +import android.view.View; +import android.webkit.JavascriptInterface; +import android.webkit.WebView; +import androidx.core.content.ContextCompat; +import androidx.core.util.Consumer; +import androidx.window.java.layout.WindowInfoTrackerCallbackAdapter; +import androidx.window.layout.DisplayFeature; +import androidx.window.layout.FoldingFeature; +import androidx.window.layout.WindowInfoTracker; +import androidx.window.layout.WindowLayoutInfo; + +class DisplayFeatures { + + static final String NATIVE_INTERFACE_NAME = "__osDisplayFeaturesNative"; + + private final Activity activity; + private final WebView webView; + private final WindowInfoTrackerCallbackAdapter windowInfoTracker; + private final Consumer layoutInfoListener = this::onWindowLayoutInfo; + private final View.OnLayoutChangeListener webViewLayoutListener = (v, l, t, r, b, oldL, oldT, oldR, oldB) -> refresh(); + + private FoldingFeature foldingFeature; + private volatile String state; + + DisplayFeatures(Activity activity, WebView webView) { + this.activity = activity; + this.webView = webView; + this.windowInfoTracker = new WindowInfoTrackerCallbackAdapter(WindowInfoTracker.getOrCreate(activity)); + this.state = compute().toJson(); + webView.addJavascriptInterface(this, NATIVE_INTERFACE_NAME); + webView.addOnLayoutChangeListener(webViewLayoutListener); + } + + @JavascriptInterface + public String getState() { + return state; + } + + void start() { + windowInfoTracker.addWindowLayoutInfoListener(activity, ContextCompat.getMainExecutor(activity), layoutInfoListener); + } + + void stop() { + windowInfoTracker.removeWindowLayoutInfoListener(layoutInfoListener); + } + + private void onWindowLayoutInfo(WindowLayoutInfo layoutInfo) { + foldingFeature = null; + for (DisplayFeature feature : layoutInfo.getDisplayFeatures()) { + if (feature instanceof FoldingFeature) { + foldingFeature = (FoldingFeature) feature; + break; + } + } + refresh(); + } + + private void refresh() { + String next = compute().toJson(); + if (next.equals(state)) { + return; + } + state = next; + webView.evaluateJavascript("window.__osDisplayFeatures && window.__osDisplayFeatures.update(" + next + ")", null); + } + + private DisplayFeaturesState compute() { + int[] location = new int[2]; + webView.getLocationInWindow(location); + float density = activity.getResources().getDisplayMetrics().density; + return DisplayFeaturesState.compute( + toFold(foldingFeature), + location[0], + location[1], + webView.getWidth(), + webView.getHeight(), + density + ); + } + + private static DisplayFeaturesState.Fold toFold(FoldingFeature feature) { + if (feature == null) { + return null; + } + Rect bounds = feature.getBounds(); + return new DisplayFeaturesState.Fold( + bounds.left, + bounds.top, + bounds.right, + bounds.bottom, + feature.getOrientation() == FoldingFeature.Orientation.VERTICAL, + feature.isSeparating(), + feature.getState() == FoldingFeature.State.HALF_OPENED + ); + } +} diff --git a/android/capacitor/src/main/java/com/getcapacitor/DisplayFeaturesState.java b/android/capacitor/src/main/java/com/getcapacitor/DisplayFeaturesState.java new file mode 100644 index 000000000..5eb5a9a8e --- /dev/null +++ b/android/capacitor/src/main/java/com/getcapacitor/DisplayFeaturesState.java @@ -0,0 +1,109 @@ +package com.getcapacitor; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +final class DisplayFeaturesState { + + static final String CONTINUOUS = "continuous"; + static final String FOLDED = "folded"; + + static final class Fold { + + final int left; + final int top; + final int right; + final int bottom; + final boolean vertical; + final boolean separating; + final boolean halfOpened; + + Fold(int left, int top, int right, int bottom, boolean vertical, boolean separating, boolean halfOpened) { + this.left = left; + this.top = top; + this.right = right; + this.bottom = bottom; + this.vertical = vertical; + this.separating = separating; + this.halfOpened = halfOpened; + } + } + + static final class Segment { + + final double left; + final double top; + final double width; + final double height; + + Segment(double left, double top, double width, double height) { + this.left = left; + this.top = top; + this.width = width; + this.height = height; + } + } + + final String posture; + final List segments; + + private DisplayFeaturesState(String posture, List segments) { + this.posture = posture; + this.segments = Collections.unmodifiableList(segments); + } + + /** + * Computes the posture and the WebView's viewport segments. + * + * @param fold the window's folding feature in window px, or null if there is none + * @param webLeft the WebView's left edge in window px + * @param webTop the WebView's top edge in window px + * @param webWidth the WebView's width in px + * @param webHeight the WebView's height in px + * @param density the display density used to convert px to CSS px + */ + static DisplayFeaturesState compute(Fold fold, int webLeft, int webTop, int webWidth, int webHeight, float density) { + String posture = fold != null && fold.halfOpened ? FOLDED : CONTINUOUS; + int webRight = webLeft + webWidth; + int webBottom = webTop + webHeight; + List segments = new ArrayList<>(); + + if (fold != null && fold.separating && fold.vertical && fold.left > webLeft && fold.right < webRight) { + segments.add(toCss(webLeft, webTop, fold.left, webBottom, webLeft, webTop, density)); + segments.add(toCss(fold.right, webTop, webRight, webBottom, webLeft, webTop, density)); + } else if (fold != null && fold.separating && !fold.vertical && fold.top > webTop && fold.bottom < webBottom) { + segments.add(toCss(webLeft, webTop, webRight, fold.top, webLeft, webTop, density)); + segments.add(toCss(webLeft, fold.bottom, webRight, webBottom, webLeft, webTop, density)); + } else { + segments.add(toCss(webLeft, webTop, webRight, webBottom, webLeft, webTop, density)); + } + + return new DisplayFeaturesState(posture, segments); + } + + private static Segment toCss(int left, int top, int right, int bottom, int originLeft, int originTop, float density) { + return new Segment((left - originLeft) / density, (top - originTop) / density, (right - left) / density, (bottom - top) / density); + } + + String toJson() { + try { + JSONArray segmentsJson = new JSONArray(); + for (Segment segment : segments) { + segmentsJson.put( + new JSONObject() + .put("left", segment.left) + .put("top", segment.top) + .put("width", segment.width) + .put("height", segment.height) + ); + } + return new JSONObject().put("posture", posture).put("segments", segmentsJson).toString(); + } catch (JSONException e) { + throw new IllegalStateException("Unable to serialize display features state", e); + } + } +} diff --git a/android/capacitor/src/main/java/com/getcapacitor/JSExport.java b/android/capacitor/src/main/java/com/getcapacitor/JSExport.java index 04f22ebb1..74d9c736d 100644 --- a/android/capacitor/src/main/java/com/getcapacitor/JSExport.java +++ b/android/capacitor/src/main/java/com/getcapacitor/JSExport.java @@ -163,6 +163,10 @@ public static String getBridgeJS(Context context) throws JSExportException { return getFilesContent(context, "native-bridge.js"); } + static String getDisplayFeaturesJS(Context context) throws JSExportException { + return getFilesContent(context, "display-features.js"); + } + private static String generateMethodJS(PluginHandle plugin, PluginMethodHandle method) { List lines = new ArrayList<>(); diff --git a/android/capacitor/src/test/java/com/getcapacitor/ConfigReadingTest.java b/android/capacitor/src/test/java/com/getcapacitor/ConfigReadingTest.java index 61597b24e..9841a9d25 100644 --- a/android/capacitor/src/test/java/com/getcapacitor/ConfigReadingTest.java +++ b/android/capacitor/src/test/java/com/getcapacitor/ConfigReadingTest.java @@ -64,6 +64,7 @@ public void flat() { assertEquals("#ffffff", config.getBackgroundColor()); assertFalse(config.isLoggingEnabled()); assertEquals(1, config.getPluginConfiguration("SplashScreen").getInt("launchShowDuration", 0)); + assertTrue(config.isDisplayFeaturesPolyfillEnabled()); } catch (IOException e) { fail(); } @@ -79,6 +80,7 @@ public void hierarchy() { assertEquals("level 2 append", config.getAppendedUserAgentString()); assertEquals("#000000", config.getBackgroundColor()); assertFalse(config.isLoggingEnabled()); + assertFalse(config.isDisplayFeaturesPolyfillEnabled()); } catch (IOException e) { fail(); } diff --git a/android/capacitor/src/test/java/com/getcapacitor/DisplayFeaturesStateTest.java b/android/capacitor/src/test/java/com/getcapacitor/DisplayFeaturesStateTest.java new file mode 100644 index 000000000..e427c953e --- /dev/null +++ b/android/capacitor/src/test/java/com/getcapacitor/DisplayFeaturesStateTest.java @@ -0,0 +1,90 @@ +package com.getcapacitor; + +import static org.junit.Assert.assertEquals; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.Test; + +public class DisplayFeaturesStateTest { + + private static final double DELTA = 0.0001; + + private static void assertSegment(DisplayFeaturesState.Segment segment, double left, double top, double width, double height) { + assertEquals(left, segment.left, DELTA); + assertEquals(top, segment.top, DELTA); + assertEquals(width, segment.width, DELTA); + assertEquals(height, segment.height, DELTA); + } + + @Test + public void noFoldIsContinuousWithOneSegment() { + DisplayFeaturesState state = DisplayFeaturesState.compute(null, 0, 0, 1080, 2400, 2f); + assertEquals(DisplayFeaturesState.CONTINUOUS, state.posture); + assertEquals(1, state.segments.size()); + assertSegment(state.segments.get(0), 0, 0, 540, 1200); + } + + @Test + public void halfOpenedVerticalFoldSplitsLeftAndRight() { + DisplayFeaturesState.Fold fold = new DisplayFeaturesState.Fold(1000, 0, 1040, 2000, true, true, true); + DisplayFeaturesState state = DisplayFeaturesState.compute(fold, 0, 0, 2040, 2000, 2f); + assertEquals(DisplayFeaturesState.FOLDED, state.posture); + assertEquals(2, state.segments.size()); + assertSegment(state.segments.get(0), 0, 0, 500, 1000); + assertSegment(state.segments.get(1), 520, 0, 500, 1000); + } + + @Test + public void halfOpenedHorizontalFoldSplitsTopAndBottom() { + DisplayFeaturesState.Fold fold = new DisplayFeaturesState.Fold(0, 1000, 2000, 1000, false, true, true); + DisplayFeaturesState state = DisplayFeaturesState.compute(fold, 0, 0, 2000, 2000, 1f); + assertEquals(DisplayFeaturesState.FOLDED, state.posture); + assertSegment(state.segments.get(0), 0, 0, 2000, 1000); + assertSegment(state.segments.get(1), 0, 1000, 2000, 1000); + } + + @Test + public void flatNonSeparatingFoldIsOneSegment() { + DisplayFeaturesState.Fold fold = new DisplayFeaturesState.Fold(1000, 0, 1000, 2000, true, false, false); + DisplayFeaturesState state = DisplayFeaturesState.compute(fold, 0, 0, 2000, 2000, 1f); + assertEquals(DisplayFeaturesState.CONTINUOUS, state.posture); + assertEquals(1, state.segments.size()); + } + + @Test + public void flatSeparatingFoldIsContinuousWithTwoSegments() { + DisplayFeaturesState.Fold fold = new DisplayFeaturesState.Fold(1000, 0, 1040, 2000, true, true, false); + DisplayFeaturesState state = DisplayFeaturesState.compute(fold, 0, 0, 2040, 2000, 1f); + assertEquals(DisplayFeaturesState.CONTINUOUS, state.posture); + assertEquals(2, state.segments.size()); + } + + @Test + public void foldOutsideWebViewIsOneSegment() { + DisplayFeaturesState.Fold fold = new DisplayFeaturesState.Fold(1000, 0, 1040, 2000, true, true, true); + DisplayFeaturesState state = DisplayFeaturesState.compute(fold, 1040, 0, 1000, 2000, 1f); + assertEquals(1, state.segments.size()); + assertSegment(state.segments.get(0), 0, 0, 1000, 2000); + } + + @Test + public void segmentsAreRelativeToWebViewOrigin() { + DisplayFeaturesState.Fold fold = new DisplayFeaturesState.Fold(1000, 0, 1040, 2000, true, true, true); + DisplayFeaturesState state = DisplayFeaturesState.compute(fold, 200, 100, 1640, 1900, 2f); + assertSegment(state.segments.get(0), 0, 0, 400, 950); + assertSegment(state.segments.get(1), 420, 0, 400, 950); + } + + @Test + public void toJsonMatchesPolyfillShape() throws JSONException { + DisplayFeaturesState state = DisplayFeaturesState.compute(null, 0, 0, 100, 200, 1f); + JSONObject json = new JSONObject(state.toJson()); + assertEquals("continuous", json.getString("posture")); + JSONArray segments = json.getJSONArray("segments"); + assertEquals(1, segments.length()); + assertEquals(100, segments.getJSONObject(0).getDouble("width"), DELTA); + assertEquals(200, segments.getJSONObject(0).getDouble("height"), DELTA); + } +} diff --git a/android/capacitor/src/test/resources/configs/hierarchy.json b/android/capacitor/src/test/resources/configs/hierarchy.json index 4a39921b5..107b6129f 100644 --- a/android/capacitor/src/test/resources/configs/hierarchy.json +++ b/android/capacitor/src/test/resources/configs/hierarchy.json @@ -6,6 +6,9 @@ "overrideUserAgent": "level 1 override", "appendUserAgent": "level 1 append", "backgroundColor": "#ffffff", + "displayFeatures": { + "polyfill": false + }, "android": { "overrideUserAgent": "level 2 override", "appendUserAgent": "level 2 append", From a27a80d03af03b6a9578f73750590f323be60032 Mon Sep 17 00:00:00 2001 From: Joseph Pender Date: Fri, 4 Dec 2026 11:31:58 -0600 Subject: [PATCH 3/6] building iOS display features functionality --- .prettierignore | 2 + .../Capacitor/CAPInstanceDescriptor.swift | 3 + ios/Sources/Capacitor/CapacitorBridge.swift | 7 + ios/Sources/Capacitor/DisplayFeatures.swift | 86 +++++++ .../Capacitor/DisplayFeaturesState.swift | 39 ++++ ios/Sources/Capacitor/JSExport.swift | 17 ++ .../Capacitor/assets/display-features.js | 210 ++++++++++++++++++ .../CapacitorObjC/CAPInstanceConfiguration.m | 2 + .../CapacitorObjC/CAPInstanceDescriptor.m | 1 + .../Capacitor/CAPInstanceConfiguration.h | 1 + .../include/Capacitor/CAPInstanceDescriptor.h | 5 + .../CapacitorTests/ConfigurationTests.swift | 2 + .../CapacitorTests/DisplayFeaturesTests.swift | 59 +++++ .../Resources/configurations/hierarchy.json | 3 + 14 files changed, 437 insertions(+) create mode 100644 ios/Sources/Capacitor/DisplayFeatures.swift create mode 100644 ios/Sources/Capacitor/DisplayFeaturesState.swift create mode 100644 ios/Sources/Capacitor/assets/display-features.js create mode 100644 ios/Tests/CapacitorTests/DisplayFeaturesTests.swift diff --git a/.prettierignore b/.prettierignore index bc26e5194..c5853f77b 100644 --- a/.prettierignore +++ b/.prettierignore @@ -3,6 +3,8 @@ core/types cli/assets dist android/capacitor/src/main/assets/native-bridge.js +android/capacitor/src/main/assets/display-features.js ios/Sources/Capacitor/assets/native-bridge.js +ios/Sources/Capacitor/assets/display-features.js ios/Frameworks/Capacitor.xcframework/ios-arm64_x86_64-simulator/Capacitor.framework/native-bridge.js ios/Frameworks/Capacitor.xcframework/ios-arm64/Capacitor.framework/native-bridge.js diff --git a/ios/Sources/Capacitor/CAPInstanceDescriptor.swift b/ios/Sources/Capacitor/CAPInstanceDescriptor.swift index f2a606715..32519c806 100644 --- a/ios/Sources/Capacitor/CAPInstanceDescriptor.swift +++ b/ios/Sources/Capacitor/CAPInstanceDescriptor.swift @@ -127,6 +127,9 @@ internal extension InstanceDescriptor { if let initialFocus = (config[keyPath: "ios.initialFocus"] as? Bool) ?? (config[keyPath: "initialFocus"] as? Bool) { hasInitialFocus = initialFocus } + if let polyfill = config[keyPath: "displayFeatures.polyfill"] as? Bool { + displayFeaturesPolyfillEnabled = polyfill + } if let startPath = (config[keyPath: "server.appStartPath"] as? String) { appStartPath = startPath } diff --git a/ios/Sources/Capacitor/CapacitorBridge.swift b/ios/Sources/Capacitor/CapacitorBridge.swift index 116d8fa0e..d1a074071 100644 --- a/ios/Sources/Capacitor/CapacitorBridge.swift +++ b/ios/Sources/Capacitor/CapacitorBridge.swift @@ -118,6 +118,7 @@ open class CapacitorBridge: NSObject, CAPBridgeProtocol { private var cordovaIsPresent = false private var injectMiscFiles: [String] = [] private var canInjectJS: Bool = true + private var displayFeatures: DisplayFeatures? // Background dispatch queue for plugin calls open private(set) var dispatchQueue = DispatchQueue(label: "bridge") @@ -171,6 +172,12 @@ open class CapacitorBridge: NSObject, CAPBridgeProtocol { self.webViewDelegationHandler.bridge = self self.webViewAssetHandler.setConfiguration(configuration) + if configuration.displayFeaturesPolyfillEnabled { + JSExport.exportDisplayFeaturesJS(userContentController: webViewDelegationHandler.contentController) + if let webView { + displayFeatures = DisplayFeatures(webView: webView) + } + } exportCoreJS(localUrl: configuration.localURL.absoluteString) registerPlugins() setupListeners() diff --git a/ios/Sources/Capacitor/DisplayFeatures.swift b/ios/Sources/Capacitor/DisplayFeatures.swift new file mode 100644 index 000000000..51b219580 --- /dev/null +++ b/ios/Sources/Capacitor/DisplayFeatures.swift @@ -0,0 +1,86 @@ +import WebKit + +internal class DisplayFeatures { + private weak var webView: WKWebView? + private var observation: NSKeyValueObservation? + private var tracker: UIView? + private var division: CGRect? + private var lastState: DisplayFeaturesState? + + init(webView: WKWebView) { + self.webView = webView + observation = webView.layer.observe(\.bounds) { [weak self] _, _ in + DispatchQueue.main.async { + self?.refresh() + } + } + trackDivision(in: webView) + } + + deinit { + observation?.invalidate() + tracker?.removeFromSuperview() + } + + private func trackDivision(in webView: WKWebView) { + #if canImport(UIKit, _version: 9127.1) + if #available(iOS 27.1, *) { + let tracker = ReservedRegionTracker(frame: webView.bounds) + tracker.onChange = { [weak self] division in + DispatchQueue.main.async { + self?.division = division + self?.refresh() + } + } + webView.addSubview(tracker) + self.tracker = tracker + } + #endif + } + + private func refresh() { + guard let webView else { + return + } + let state = DisplayFeaturesState.compute(bounds: webView.bounds.size, division: division) + guard state != lastState else { + return + } + lastState = state + webView.evaluateJavaScript(state.updateScript) + } +} + +#if canImport(UIKit, _version: 9127.1) +// UIKit has no change notification for reserved regions; +// it re-runs updateConstraints() when a region read there changes. +@available(iOS 27.1, *) +private final class ReservedRegionTracker: UIView { + var onChange: ((CGRect?) -> Void)? + private var division: CGRect? + + override static var requiresConstraintBasedLayout: Bool { + true + } + + override init(frame: CGRect) { + super.init(frame: frame) + isUserInteractionEnabled = false + backgroundColor = .clear + autoresizingMask = [.flexibleWidth, .flexibleHeight] + } + + required init?(coder: NSCoder) { + nil + } + + override func updateConstraints() { + let next = reservedRegions(kind: .division).first?.frame + if next != division { + division = next + onChange?(next) + } + super.updateConstraints() + } +} +#endif diff --git a/ios/Sources/Capacitor/DisplayFeaturesState.swift b/ios/Sources/Capacitor/DisplayFeaturesState.swift new file mode 100644 index 000000000..2537dbf0c --- /dev/null +++ b/ios/Sources/Capacitor/DisplayFeaturesState.swift @@ -0,0 +1,39 @@ +import CoreGraphics + +internal struct DisplayFeaturesState: Equatable { + static let continuous = "continuous" + static let folded = "folded" + + let posture: String + let segments: [CGRect] + + static func compute(bounds: CGSize, division: CGRect?) -> DisplayFeaturesState { + let whole = CGRect(origin: .zero, size: bounds) + guard let division else { + return DisplayFeaturesState(posture: continuous, segments: [whole]) + } + + if division.height > division.width && division.minX > 0 && division.maxX < bounds.width { + return DisplayFeaturesState(posture: folded, segments: [ + CGRect(x: 0, y: 0, width: division.minX, height: bounds.height), + CGRect(x: division.maxX, y: 0, width: bounds.width - division.maxX, height: bounds.height) + ]) + } + if division.width >= division.height && division.minY > 0 && division.maxY < bounds.height { + return DisplayFeaturesState(posture: folded, segments: [ + CGRect(x: 0, y: 0, width: bounds.width, height: division.minY), + CGRect(x: 0, y: division.maxY, width: bounds.width, height: bounds.height - division.maxY) + ]) + } + return DisplayFeaturesState(posture: folded, segments: [whole]) + } + + var updateScript: String { + let segmentList = segments.map { segment in + "{ left: \(Double(segment.minX)), top: \(Double(segment.minY)), " + + "width: \(Double(segment.width)), height: \(Double(segment.height)) }" + } + let update = "{ posture: '\(posture)', segments: [\(segmentList.joined(separator: ", "))] }" + return "window.__osDisplayFeatures && window.__osDisplayFeatures.update(\(update))" + } +} diff --git a/ios/Sources/Capacitor/JSExport.swift b/ios/Sources/Capacitor/JSExport.swift index d8133a369..9c7f2a7b7 100644 --- a/ios/Sources/Capacitor/JSExport.swift +++ b/ios/Sources/Capacitor/JSExport.swift @@ -39,6 +39,23 @@ internal class JSExport { } } + static func exportDisplayFeaturesJS(userContentController: WKUserContentController) { + #if SWIFT_PACKAGE + let jsUrl = Bundle.module.url(forResource: "display-features", withExtension: "js", subdirectory: "assets") + #else + let jsUrl = Bundle(for: Self.self).url(forResource: "display-features", withExtension: "js") + #endif + guard let jsUrl else { + CAPLog.print("ERROR: display-features.js not found. Display Features polyfill will not be installed.") + return + } + do { + try self.injectFile(fileURL: jsUrl, userContentController: userContentController) + } catch { + CAPLog.print("ERROR: Unable to read display-features.js. Display Features polyfill will not be installed.") + } + } + static func exportMiscFileJS(paths: [String], userContentController: WKUserContentController) { for path in paths { if let miscJSFilePath = Bundle.main.url(forResource: "public/\(path.replacingOccurrences(of: ".js", with: ""))", withExtension: "js") { diff --git a/ios/Sources/Capacitor/assets/display-features.js b/ios/Sources/Capacitor/assets/display-features.js new file mode 100644 index 000000000..ca98d7ead --- /dev/null +++ b/ios/Sources/Capacitor/assets/display-features.js @@ -0,0 +1,210 @@ + +/*! Capacitor: https://capacitorjs.com/ - MIT License */ +/* Generated File. Do not edit. */ + +var __osDisplayFeaturesPolyfill = (function (exports) { + 'use strict'; + + /** + * Note: When making changes to this file, run `npm run build:nativebridge` + * afterwards to build the display-features.js files to the android and iOS projects. + */ + const isPosture = (value) => value === 'continuous' || value === 'folded'; + const isSegment = (value) => value !== null && + typeof value === 'object' && + [value.left, value.top, value.width, value.height].every((n) => typeof n === 'number' && Number.isFinite(n)) && + value.left >= 0 && + value.top >= 0 && + value.width > 0 && + value.height > 0; + const parseSegments = (value) => { + if (!Array.isArray(value) || value.length < 1 || value.length > 2 || !value.every(isSegment)) { + return null; + } + return value + .map(({ left, top, width, height }) => ({ left, top, width, height })) + .sort((a, b) => a.left - b.left || a.top - b.top); + }; + const segmentsEqual = (a, b) => a.length === b.length && + a.every((s, i) => s.left === b[i].left && s.top === b[i].top && s.width === b[i].width && s.height === b[i].height); + const segmentIndices = (segments) => segments.length === 2 && segments[1].left > segments[0].left + ? [ + [0, 0], + [1, 0], + ] + : segments.map((_, i) => [0, i]); + const cssVariables = (state) => { + const vars = new Map(); + const indices = segmentIndices(state.segments); + vars.set('--device-posture', state.posture); + vars.set('--horizontal-viewport-segments', String(Math.max(...indices.map(([x]) => x)) + 1)); + vars.set('--vertical-viewport-segments', String(Math.max(...indices.map(([, y]) => y)) + 1)); + if (state.segments.length > 1) { + state.segments.forEach((s, i) => { + const suffix = `${indices[i][0]}-${indices[i][1]}`; + vars.set(`--viewport-segment-top-${suffix}`, `${s.top}px`); + vars.set(`--viewport-segment-left-${suffix}`, `${s.left}px`); + vars.set(`--viewport-segment-bottom-${suffix}`, `${s.top + s.height}px`); + vars.set(`--viewport-segment-right-${suffix}`, `${s.left + s.width}px`); + vars.set(`--viewport-segment-width-${suffix}`, `${s.width}px`); + vars.set(`--viewport-segment-height-${suffix}`, `${s.height}px`); + }); + } + return vars; + }; + const readNativeState = (win) => { + var _a; + const getState = (_a = win.__osDisplayFeaturesNative) === null || _a === void 0 ? void 0 : _a.getState; + if (typeof getState !== 'function') { + return {}; + } + try { + const json = getState.call(win.__osDisplayFeaturesNative); + const parsed = json ? JSON.parse(json) : null; + return parsed !== null && typeof parsed === 'object' ? parsed : {}; + } + catch (e) { + console.warn('Display Features: unable to read initial state from native', e); + return {}; + } + }; + const initDisplayFeatures = (win) => { + var _a; + if (win.__osDisplayFeatures || win.top !== win) { + return; + } + const initial = readNativeState(win); + const state = { + posture: isPosture(initial.posture) ? initial.posture : 'continuous', + segments: (_a = parseSegments(initial.segments)) !== null && _a !== void 0 ? _a : [{ left: 0, top: 0, width: win.innerWidth, height: win.innerHeight }], + }; + class DevicePosture extends EventTarget { + constructor() { + super(...arguments); + this.changeHandler = null; + this.changeHandlerRegistered = false; + } + get type() { + return state.posture; + } + get onchange() { + return this.changeHandler; + } + set onchange(handler) { + this.changeHandler = typeof handler === 'function' ? handler : null; + if (this.changeHandler && !this.changeHandlerRegistered) { + this.changeHandlerRegistered = true; + this.addEventListener('change', (ev) => { var _a; return (_a = this.changeHandler) === null || _a === void 0 ? void 0 : _a.call(this, ev); }); + } + } + } + const devicePosture = new DevicePosture(); + const getSegments = () => state.segments.map((s) => new DOMRect(s.left, s.top, s.width, s.height)); + try { + Object.defineProperty(win.navigator, 'devicePosture', { + configurable: true, + enumerable: true, + get: () => devicePosture, + }); + if (win.viewport && typeof win.viewport === 'object') { + Object.defineProperty(win.viewport, 'segments', { configurable: true, enumerable: true, get: getSegments }); + } + else { + const viewport = {}; + Object.defineProperty(viewport, 'segments', { configurable: true, enumerable: true, get: getSegments }); + Object.defineProperty(win, 'viewport', { configurable: true, enumerable: true, value: viewport }); + } + } + catch (e) { + console.warn('Display Features: unable to install the polyfill', e); + return; + } + const appliedVariables = new Set(); + const applyCssVariables = () => { + const style = win.document.documentElement.style; + const vars = cssVariables(state); + appliedVariables.forEach((name) => { + if (!vars.has(name)) { + style.removeProperty(name); + appliedVariables.delete(name); + } + }); + vars.forEach((value, name) => { + style.setProperty(name, value); + appliedVariables.add(name); + }); + }; + let announcedPosture = state.posture; + let resizePending = false; + let eventsQueued = false; + const queueEvents = () => { + if (eventsQueued) { + return; + } + eventsQueued = true; + win.setTimeout(() => { + eventsQueued = false; + if (state.posture !== announcedPosture) { + announcedPosture = state.posture; + devicePosture.dispatchEvent(new Event('change')); + } + if (resizePending) { + resizePending = false; + win.dispatchEvent(new Event('resize')); + } + }, 0); + }; + let pending = null; + const apply = (next) => { + if (win.document.visibilityState === 'hidden') { + pending = next; + return; + } + pending = null; + const postureChanged = next.posture !== state.posture; + const segmentsChanged = !segmentsEqual(next.segments, state.segments); + if (!postureChanged && !segmentsChanged) { + return; + } + state.posture = next.posture; + state.segments = next.segments; + applyCssVariables(); + resizePending = resizePending || segmentsChanged; + queueEvents(); + }; + win.document.addEventListener('visibilitychange', () => { + if (pending && win.document.visibilityState !== 'hidden') { + apply(pending); + } + }); + win.__osDisplayFeatures = { + update: (update) => { + var _a; + if (update === null || typeof update !== 'object') { + return; + } + const base = pending !== null && pending !== void 0 ? pending : state; + apply({ + posture: isPosture(update.posture) ? update.posture : base.posture, + segments: (_a = parseSegments(update.segments)) !== null && _a !== void 0 ? _a : base.segments, + }); + }, + }; + if (win.document.documentElement) { + applyCssVariables(); + } + else { + win.document.addEventListener('DOMContentLoaded', applyCssVariables, { once: true }); + } + }; + if (typeof window !== 'undefined') { + initDisplayFeatures(window); + } + + exports.initDisplayFeatures = initDisplayFeatures; + + Object.defineProperty(exports, '__esModule', { value: true }); + + return exports; + +})({}); diff --git a/ios/Sources/CapacitorObjC/CAPInstanceConfiguration.m b/ios/Sources/CapacitorObjC/CAPInstanceConfiguration.m index 7a3c187ac..dcb6d90c2 100644 --- a/ios/Sources/CapacitorObjC/CAPInstanceConfiguration.m +++ b/ios/Sources/CapacitorObjC/CAPInstanceConfiguration.m @@ -47,6 +47,7 @@ - (instancetype)initWithDescriptor:(CAPInstanceDescriptor *)descriptor isDebug:( _pluginConfigurations = descriptor.pluginConfigurations; _isWebDebuggable = descriptor.isWebDebuggable; _hasInitialFocus = descriptor.hasInitialFocus; + _displayFeaturesPolyfillEnabled = descriptor.displayFeaturesPolyfillEnabled; _legacyConfig = descriptor.legacyConfig; // construct the necessary URLs _localURL = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"%@://%@", descriptor.urlScheme, descriptor.urlHostname]]; @@ -78,6 +79,7 @@ - (instancetype)initWithConfiguration:(CAPInstanceConfiguration*)configuration a _handleApplicationNotifications = configuration.handleApplicationNotifications; _isWebDebuggable = configuration.isWebDebuggable; _hasInitialFocus = configuration.hasInitialFocus; + _displayFeaturesPolyfillEnabled = configuration.displayFeaturesPolyfillEnabled; _contentInsetAdjustmentBehavior = configuration.contentInsetAdjustmentBehavior; // we don't care about internal usage of deprecated APIs and the framework should build cleanly #pragma clang diagnostic push diff --git a/ios/Sources/CapacitorObjC/CAPInstanceDescriptor.m b/ios/Sources/CapacitorObjC/CAPInstanceDescriptor.m index ef8679535..b5c3faa3f 100644 --- a/ios/Sources/CapacitorObjC/CAPInstanceDescriptor.m +++ b/ios/Sources/CapacitorObjC/CAPInstanceDescriptor.m @@ -50,6 +50,7 @@ - (void)_setDefaultsWithAppLocation:(NSURL*)location { _handleApplicationNotifications = YES; _isWebDebuggable = NO; _hasInitialFocus = YES; + _displayFeaturesPolyfillEnabled = YES; _contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever; _appLocation = location; _limitsNavigationsToAppBoundDomains = FALSE; diff --git a/ios/Sources/CapacitorObjC/include/Capacitor/CAPInstanceConfiguration.h b/ios/Sources/CapacitorObjC/include/Capacitor/CAPInstanceConfiguration.h index 5401ddd9d..843e82e34 100644 --- a/ios/Sources/CapacitorObjC/include/Capacitor/CAPInstanceConfiguration.h +++ b/ios/Sources/CapacitorObjC/include/Capacitor/CAPInstanceConfiguration.h @@ -22,6 +22,7 @@ NS_SWIFT_NAME(InstanceConfiguration) @property (nonatomic, readonly) BOOL handleApplicationNotifications; @property (nonatomic, readonly) BOOL isWebDebuggable; @property (nonatomic, readonly) BOOL hasInitialFocus; +@property (nonatomic, readonly) BOOL displayFeaturesPolyfillEnabled; @property (nonatomic, readonly) BOOL cordovaDeployDisabled DEPRECATED_MSG_ATTRIBUTE("Always false. The Cordova configuration is not read."); @property (nonatomic, readonly) UIScrollViewContentInsetAdjustmentBehavior contentInsetAdjustmentBehavior; @property (nonatomic, readonly, nonnull) NSURL *appLocation; diff --git a/ios/Sources/CapacitorObjC/include/Capacitor/CAPInstanceDescriptor.h b/ios/Sources/CapacitorObjC/include/Capacitor/CAPInstanceDescriptor.h index 49b6c1968..a110b8b86 100644 --- a/ios/Sources/CapacitorObjC/include/Capacitor/CAPInstanceDescriptor.h +++ b/ios/Sources/CapacitorObjC/include/Capacitor/CAPInstanceDescriptor.h @@ -108,6 +108,11 @@ NS_SWIFT_NAME(InstanceDescriptor) @discussion Defaults to @c true. Set by @c ios.initialFocus in the configuration file. */ @property (nonatomic, assign) BOOL hasInitialFocus; +/** + @brief Whether to inject the Device Posture and Viewport Segments polyfill. + @discussion Defaults to @c true. Set by @c displayFeatures.polyfill in the configuration file. + */ +@property (nonatomic, assign) BOOL displayFeaturesPolyfillEnabled; /** @brief How the web view will inset its content diff --git a/ios/Tests/CapacitorTests/ConfigurationTests.swift b/ios/Tests/CapacitorTests/ConfigurationTests.swift index e55c8c586..9a7a6cb77 100644 --- a/ios/Tests/CapacitorTests/ConfigurationTests.swift +++ b/ios/Tests/CapacitorTests/ConfigurationTests.swift @@ -60,6 +60,7 @@ struct ConfigurationTests { #expect(descriptor.loggingBehavior == .debug) #expect(descriptor.allowLinkPreviews == true) #expect(descriptor.contentInsetAdjustmentBehavior == .never) + #expect(descriptor.displayFeaturesPolyfillEnabled == true) } @Test func deprecatedParsing() throws { @@ -92,6 +93,7 @@ struct ConfigurationTests { #expect(descriptor.loggingBehavior == .none) #expect(descriptor.scrollingEnabled == false) #expect(descriptor.contentInsetAdjustmentBehavior == .scrollableAxes) + #expect(descriptor.displayFeaturesPolyfillEnabled == false) } @Test func serverParsing() throws { diff --git a/ios/Tests/CapacitorTests/DisplayFeaturesTests.swift b/ios/Tests/CapacitorTests/DisplayFeaturesTests.swift new file mode 100644 index 000000000..d897cd8e6 --- /dev/null +++ b/ios/Tests/CapacitorTests/DisplayFeaturesTests.swift @@ -0,0 +1,59 @@ +import CoreGraphics +import Testing +import WebKit +@testable import Capacitor + +struct DisplayFeaturesTests { + private let bounds = CGSize(width: 800, height: 1000) + + @Test @MainActor func exportsPolyfillAtDocumentStart() { + let contentController = WKUserContentController() + Capacitor.JSExport.exportDisplayFeaturesJS(userContentController: contentController) + let script = contentController.userScripts.first + #expect(contentController.userScripts.count == 1) + #expect(script?.injectionTime == .atDocumentStart) + #expect(script?.source.contains("__osDisplayFeatures") == true) + } + + @Test func noDivisionIsOneContinuousSegment() { + let state = DisplayFeaturesState.compute(bounds: bounds, division: nil) + #expect(state.posture == "continuous") + #expect(state.segments == [CGRect(x: 0, y: 0, width: 800, height: 1000)]) + } + + @Test func verticalDivisionSplitsSideBySide() { + let state = DisplayFeaturesState.compute(bounds: bounds, division: CGRect(x: 390, y: 0, width: 20, height: 1000)) + #expect(state.posture == "folded") + #expect(state.segments == [ + CGRect(x: 0, y: 0, width: 390, height: 1000), + CGRect(x: 410, y: 0, width: 390, height: 1000) + ]) + } + + @Test func horizontalDivisionSplitsStacked() { + let state = DisplayFeaturesState.compute(bounds: bounds, division: CGRect(x: 0, y: 490, width: 800, height: 20)) + #expect(state.posture == "folded") + #expect(state.segments == [ + CGRect(x: 0, y: 0, width: 800, height: 490), + CGRect(x: 0, y: 510, width: 800, height: 490) + ]) + } + + @Test(arguments: [ + CGRect(x: -10, y: 0, width: 20, height: 1000), + CGRect(x: 790, y: 0, width: 20, height: 1000), + CGRect(x: 0, y: 990, width: 800, height: 20) + ]) + func divisionAtAnEdgeIsFoldedWithOneSegment(division: CGRect) { + let state = DisplayFeaturesState.compute(bounds: bounds, division: division) + #expect(state.posture == "folded") + #expect(state.segments == [CGRect(x: 0, y: 0, width: 800, height: 1000)]) + } + + @Test func updateScriptSerializesEverySegment() { + let state = DisplayFeaturesState.compute(bounds: bounds, division: CGRect(x: 390.5, y: 0, width: 19, height: 1000)) + #expect(state.updateScript == "window.__osDisplayFeatures && window.__osDisplayFeatures.update(" + + "{ posture: 'folded', segments: [{ left: 0.0, top: 0.0, width: 390.5, height: 1000.0 }, " + + "{ left: 409.5, top: 0.0, width: 390.5, height: 1000.0 }] })") + } +} diff --git a/ios/Tests/CapacitorTests/Resources/configurations/hierarchy.json b/ios/Tests/CapacitorTests/Resources/configurations/hierarchy.json index 54d5b9bb4..ecc1be015 100644 --- a/ios/Tests/CapacitorTests/Resources/configurations/hierarchy.json +++ b/ios/Tests/CapacitorTests/Resources/configurations/hierarchy.json @@ -7,6 +7,9 @@ "appendUserAgent": "level 1 append", "backgroundColor": "#ffffff", "loggingBehavior": "none", + "displayFeatures": { + "polyfill": false + }, "ios": { "overrideUserAgent": "level 2 override", "appendUserAgent": "level 2 append", From 107a9ad5455b2a2fa397b72bdc976154dee88b16 Mon Sep 17 00:00:00 2001 From: Joseph Pender Date: Fri, 4 Dec 2026 11:45:34 -0600 Subject: [PATCH 4/6] save display features state into document-start script --- ios/Sources/Capacitor/CapacitorBridge.swift | 9 +- ios/Sources/Capacitor/DisplayFeatures.swift | 53 ++++++++++-- .../Capacitor/DisplayFeaturesState.swift | 27 ++++-- ios/Sources/Capacitor/JSExport.swift | 12 +-- .../CapacitorTests/DisplayFeaturesTests.swift | 84 +++++++++++++++---- 5 files changed, 143 insertions(+), 42 deletions(-) diff --git a/ios/Sources/Capacitor/CapacitorBridge.swift b/ios/Sources/Capacitor/CapacitorBridge.swift index d1a074071..e0edeff44 100644 --- a/ios/Sources/Capacitor/CapacitorBridge.swift +++ b/ios/Sources/Capacitor/CapacitorBridge.swift @@ -172,11 +172,10 @@ open class CapacitorBridge: NSObject, CAPBridgeProtocol { self.webViewDelegationHandler.bridge = self self.webViewAssetHandler.setConfiguration(configuration) - if configuration.displayFeaturesPolyfillEnabled { - JSExport.exportDisplayFeaturesJS(userContentController: webViewDelegationHandler.contentController) - if let webView { - displayFeatures = DisplayFeatures(webView: webView) - } + if configuration.displayFeaturesPolyfillEnabled, let webView, let polyfill = JSExport.displayFeaturesJS() { + displayFeatures = DisplayFeatures(webView: webView, + userContentController: webViewDelegationHandler.contentController, + polyfill: polyfill) } exportCoreJS(localUrl: configuration.localURL.absoluteString) registerPlugins() diff --git a/ios/Sources/Capacitor/DisplayFeatures.swift b/ios/Sources/Capacitor/DisplayFeatures.swift index 51b219580..2aa99c090 100644 --- a/ios/Sources/Capacitor/DisplayFeatures.swift +++ b/ios/Sources/Capacitor/DisplayFeatures.swift @@ -2,13 +2,20 @@ import WebKit internal class DisplayFeatures { private weak var webView: WKWebView? + private weak var userContentController: WKUserContentController? + private let polyfill: String + private var script: WKUserScript? private var observation: NSKeyValueObservation? private var tracker: UIView? private var division: CGRect? - private var lastState: DisplayFeaturesState? + private var state: DisplayFeaturesState - init(webView: WKWebView) { + init(webView: WKWebView, userContentController: WKUserContentController, polyfill: String) { self.webView = webView + self.userContentController = userContentController + self.polyfill = polyfill + state = DisplayFeaturesState.compute(bounds: webView.bounds.size, division: nil) + installScript() observation = webView.layer.observe(\.bounds) { [weak self] _, _ in DispatchQueue.main.async { self?.refresh() @@ -42,18 +49,39 @@ internal class DisplayFeatures { guard let webView else { return } - let state = DisplayFeaturesState.compute(bounds: webView.bounds.size, division: division) - guard state != lastState else { + let next = DisplayFeaturesState.compute(bounds: webView.bounds.size, division: division) + guard next != state else { return } - lastState = state + state = next + installScript() webView.evaluateJavaScript(state.updateScript) } + + // WKWebView has no synchronous bridge, so getState() is baked into the document-start script, which is + // swapped on every change. WKUserContentController cannot remove a single script, so the rest are re-added in order. + private func installScript() { + guard let userContentController else { + return + } + let next = WKUserScript(source: state.documentStartScript(polyfill: polyfill), injectionTime: .atDocumentStart, forMainFrameOnly: true) + if let script { + // userScripts is bridged lazily from a live array that removeAllUserScripts() empties, so copy it first. + let scripts = userContentController.userScripts.map { $0 } + userContentController.removeAllUserScripts() + for existing in scripts { + userContentController.addUserScript(existing === script ? next : existing) + } + } else { + userContentController.addUserScript(next) + } + script = next + } } #if canImport(UIKit, _version: 9127.1) // UIKit has no change notification for reserved regions; -// it re-runs updateConstraints() when a region read there changes. +// it re-runs updateConstraints() and layoutSubviews() when a region read there changes. @available(iOS 27.1, *) private final class ReservedRegionTracker: UIView { var onChange: ((CGRect?) -> Void)? @@ -75,12 +103,21 @@ private final class ReservedRegionTracker: UIView { } override func updateConstraints() { - let next = reservedRegions(kind: .division).first?.frame + readDivision() + super.updateConstraints() + } + + override func layoutSubviews() { + super.layoutSubviews() + readDivision() + } + + private func readDivision() { + let next = reservedRegions(kind: .division).first.map { $0.frame.inset(by: $0.margins) } if next != division { division = next onChange?(next) } - super.updateConstraints() } } #endif diff --git a/ios/Sources/Capacitor/DisplayFeaturesState.swift b/ios/Sources/Capacitor/DisplayFeaturesState.swift index 2537dbf0c..1aa3324f3 100644 --- a/ios/Sources/Capacitor/DisplayFeaturesState.swift +++ b/ios/Sources/Capacitor/DisplayFeaturesState.swift @@ -1,4 +1,4 @@ -import CoreGraphics +import Foundation internal struct DisplayFeaturesState: Equatable { static let continuous = "continuous" @@ -28,12 +28,25 @@ internal struct DisplayFeaturesState: Equatable { return DisplayFeaturesState(posture: folded, segments: [whole]) } - var updateScript: String { - let segmentList = segments.map { segment in - "{ left: \(Double(segment.minX)), top: \(Double(segment.minY)), " - + "width: \(Double(segment.width)), height: \(Double(segment.height)) }" + var json: String { + let object: [String: Any] = [ + "posture": posture, + "segments": segments.map { segment in + ["left": Double(segment.minX), "top": Double(segment.minY), "width": Double(segment.width), "height": Double(segment.height)] + } + ] + guard let data = try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]), + let json = String(data: data, encoding: .utf8) else { + return "null" } - let update = "{ posture: '\(posture)', segments: [\(segmentList.joined(separator: ", "))] }" - return "window.__osDisplayFeatures && window.__osDisplayFeatures.update(\(update))" + return json + } + + var updateScript: String { + "window.__osDisplayFeatures && window.__osDisplayFeatures.update(\(json))" + } + + func documentStartScript(polyfill: String) -> String { + "window.__osDisplayFeaturesNative = { getState: function () { return JSON.stringify(\(json)); } };\n\(polyfill)" } } diff --git a/ios/Sources/Capacitor/JSExport.swift b/ios/Sources/Capacitor/JSExport.swift index 9c7f2a7b7..e769e55e9 100644 --- a/ios/Sources/Capacitor/JSExport.swift +++ b/ios/Sources/Capacitor/JSExport.swift @@ -39,21 +39,17 @@ internal class JSExport { } } - static func exportDisplayFeaturesJS(userContentController: WKUserContentController) { + static func displayFeaturesJS() -> String? { #if SWIFT_PACKAGE let jsUrl = Bundle.module.url(forResource: "display-features", withExtension: "js", subdirectory: "assets") #else let jsUrl = Bundle(for: Self.self).url(forResource: "display-features", withExtension: "js") #endif - guard let jsUrl else { - CAPLog.print("ERROR: display-features.js not found. Display Features polyfill will not be installed.") - return - } - do { - try self.injectFile(fileURL: jsUrl, userContentController: userContentController) - } catch { + guard let jsUrl, let source = try? String(contentsOf: jsUrl, encoding: .utf8) else { CAPLog.print("ERROR: Unable to read display-features.js. Display Features polyfill will not be installed.") + return nil } + return source } static func exportMiscFileJS(paths: [String], userContentController: WKUserContentController) { diff --git a/ios/Tests/CapacitorTests/DisplayFeaturesTests.swift b/ios/Tests/CapacitorTests/DisplayFeaturesTests.swift index d897cd8e6..841bca790 100644 --- a/ios/Tests/CapacitorTests/DisplayFeaturesTests.swift +++ b/ios/Tests/CapacitorTests/DisplayFeaturesTests.swift @@ -3,18 +3,9 @@ import Testing import WebKit @testable import Capacitor -struct DisplayFeaturesTests { +struct DisplayFeaturesStateTests { private let bounds = CGSize(width: 800, height: 1000) - @Test @MainActor func exportsPolyfillAtDocumentStart() { - let contentController = WKUserContentController() - Capacitor.JSExport.exportDisplayFeaturesJS(userContentController: contentController) - let script = contentController.userScripts.first - #expect(contentController.userScripts.count == 1) - #expect(script?.injectionTime == .atDocumentStart) - #expect(script?.source.contains("__osDisplayFeatures") == true) - } - @Test func noDivisionIsOneContinuousSegment() { let state = DisplayFeaturesState.compute(bounds: bounds, division: nil) #expect(state.posture == "continuous") @@ -30,6 +21,15 @@ struct DisplayFeaturesTests { ]) } + @Test func zeroWidthDivisionSplitsSideBySide() { + let state = DisplayFeaturesState.compute(bounds: bounds, division: CGRect(x: 400, y: 0, width: 0, height: 1000)) + #expect(state.posture == "folded") + #expect(state.segments == [ + CGRect(x: 0, y: 0, width: 400, height: 1000), + CGRect(x: 400, y: 0, width: 400, height: 1000) + ]) + } + @Test func horizontalDivisionSplitsStacked() { let state = DisplayFeaturesState.compute(bounds: bounds, division: CGRect(x: 0, y: 490, width: 800, height: 20)) #expect(state.posture == "folded") @@ -50,10 +50,66 @@ struct DisplayFeaturesTests { #expect(state.segments == [CGRect(x: 0, y: 0, width: 800, height: 1000)]) } - @Test func updateScriptSerializesEverySegment() { + @Test func jsonListsEverySegment() { let state = DisplayFeaturesState.compute(bounds: bounds, division: CGRect(x: 390.5, y: 0, width: 19, height: 1000)) - #expect(state.updateScript == "window.__osDisplayFeatures && window.__osDisplayFeatures.update(" - + "{ posture: 'folded', segments: [{ left: 0.0, top: 0.0, width: 390.5, height: 1000.0 }, " - + "{ left: 409.5, top: 0.0, width: 390.5, height: 1000.0 }] })") + #expect(state.json == #"{"posture":"folded","segments":[{"height":1000,"left":0,"top":0,"width":390.5},"# + + #"{"height":1000,"left":409.5,"top":0,"width":390.5}]}"#) + #expect(state.updateScript == "window.__osDisplayFeatures && window.__osDisplayFeatures.update(\(state.json))") + } + + @Test func documentStartScriptSeedsGetStateBeforeThePolyfill() { + let state = DisplayFeaturesState.compute(bounds: bounds, division: nil) + let script = state.documentStartScript(polyfill: "polyfill();") + #expect(script == "window.__osDisplayFeaturesNative = { getState: function () { return JSON.stringify(\(state.json)); } };" + + "\npolyfill();") + } +} + +@MainActor +struct DisplayFeaturesTests { + private let contentController = WKUserContentController() + private let webView: WKWebView + + init() { + let configuration = WKWebViewConfiguration() + configuration.userContentController = contentController + webView = WKWebView(frame: CGRect(x: 0, y: 0, width: 400, height: 800), configuration: configuration) + } + + @Test func readsThePolyfillFromTheBundle() { + #expect(JSExport.displayFeaturesJS()?.contains("__osDisplayFeatures") == true) + } + + @Test func installsSeededPolyfillInTheTopFrameAtDocumentStart() throws { + let features = DisplayFeatures(webView: webView, userContentController: contentController, polyfill: "polyfill();") + let script = try #require(contentController.userScripts.first) + #expect(contentController.userScripts.count == 1) + #expect(script.injectionTime == .atDocumentStart) + #expect(script.isForMainFrameOnly) + #expect(script.source.contains(#""width":400"#)) + #expect(script.source.hasSuffix("polyfill();")) + withExtendedLifetime(features) {} + } + + @Test func resizeSwapsTheScriptInPlace() async throws { + let before = WKUserScript(source: "before();", injectionTime: .atDocumentStart, forMainFrameOnly: true) + let after = WKUserScript(source: "after();", injectionTime: .atDocumentEnd, forMainFrameOnly: true) + contentController.addUserScript(before) + let features = DisplayFeatures(webView: webView, userContentController: contentController, polyfill: "polyfill();") + contentController.addUserScript(after) + + webView.frame = CGRect(x: 0, y: 0, width: 600, height: 800) + await withCheckedContinuation { continuation in + DispatchQueue.main.async { continuation.resume() } + } + + let scripts = contentController.userScripts + #expect(scripts.count == 3) + #expect(scripts.first === before) + #expect(scripts.last === after) + let seeded = try #require(scripts.dropFirst().first) + #expect(seeded.source.contains(#""width":600"#)) + #expect(seeded.isForMainFrameOnly) + withExtendedLifetime(features) {} } } From d3a6ef2cddba4d14cdd5f118cad9183b3f151163 Mon Sep 17 00:00:00 2001 From: Joseph Pender Date: Fri, 4 Dec 2026 15:49:15 -0600 Subject: [PATCH 5/6] extend display features polyfill to same-origin child frames --- .../src/main/assets/display-features.js | 38 +++++++++++---- core/display-features.ts | 38 ++++++++++++--- core/src/tests/display-features.spec.ts | 48 +++++++++++++++++++ ios/Sources/Capacitor/DisplayFeatures.swift | 4 +- .../Capacitor/assets/display-features.js | 38 +++++++++++---- 5 files changed, 142 insertions(+), 24 deletions(-) diff --git a/android/capacitor/src/main/assets/display-features.js b/android/capacitor/src/main/assets/display-features.js index ca98d7ead..c943d97b2 100644 --- a/android/capacitor/src/main/assets/display-features.js +++ b/android/capacitor/src/main/assets/display-features.js @@ -68,15 +68,28 @@ var __osDisplayFeaturesPolyfill = (function (exports) { return {}; } }; - const initDisplayFeatures = (win) => { + const sameOriginParent = (win) => { var _a; - if (win.__osDisplayFeatures || win.top !== win) { + const parent = (_a = win.frameElement) === null || _a === void 0 ? void 0 : _a.ownerDocument.defaultView; + return (parent === null || parent === void 0 ? void 0 : parent.__osDisplayFeatures) ? parent : null; + }; + const initDisplayFeatures = (win) => { + var _a, _b; + if (win.__osDisplayFeatures) { return; } - const initial = readNativeState(win); + const isTopFrame = win.parent === win; + const parent = isTopFrame ? null : sameOriginParent(win); + if (!isTopFrame && !parent) { + return; + } + const viewportSegment = () => ({ left: 0, top: 0, width: win.innerWidth, height: win.innerHeight }); + const initial = parent + ? { posture: (_a = parent.navigator.devicePosture) === null || _a === void 0 ? void 0 : _a.type } + : readNativeState(win); const state = { posture: isPosture(initial.posture) ? initial.posture : 'continuous', - segments: (_a = parseSegments(initial.segments)) !== null && _a !== void 0 ? _a : [{ left: 0, top: 0, width: win.innerWidth, height: win.innerHeight }], + segments: (_b = (parent ? null : parseSegments(initial.segments))) !== null && _b !== void 0 ? _b : [viewportSegment()], }; class DevicePosture extends EventTarget { constructor() { @@ -99,7 +112,7 @@ var __osDisplayFeaturesPolyfill = (function (exports) { } } const devicePosture = new DevicePosture(); - const getSegments = () => state.segments.map((s) => new DOMRect(s.left, s.top, s.width, s.height)); + const getSegments = () => (isTopFrame ? state.segments : [viewportSegment()]).map((s) => new DOMRect(s.left, s.top, s.width, s.height)); try { Object.defineProperty(win.navigator, 'devicePosture', { configurable: true, @@ -177,6 +190,13 @@ var __osDisplayFeaturesPolyfill = (function (exports) { apply(pending); } }); + const forwardToFrames = (posture) => { + win.document.querySelectorAll('iframe, frame').forEach((element) => { + var _a, _b; + const frame = (_a = element.contentDocument) === null || _a === void 0 ? void 0 : _a.defaultView; + (_b = frame === null || frame === void 0 ? void 0 : frame.__osDisplayFeatures) === null || _b === void 0 ? void 0 : _b.update({ posture }); + }); + }; win.__osDisplayFeatures = { update: (update) => { var _a; @@ -184,10 +204,12 @@ var __osDisplayFeaturesPolyfill = (function (exports) { return; } const base = pending !== null && pending !== void 0 ? pending : state; - apply({ + const next = { posture: isPosture(update.posture) ? update.posture : base.posture, - segments: (_a = parseSegments(update.segments)) !== null && _a !== void 0 ? _a : base.segments, - }); + segments: (_a = (isTopFrame ? parseSegments(update.segments) : null)) !== null && _a !== void 0 ? _a : base.segments, + }; + apply(next); + forwardToFrames(next.posture); }, }; if (win.document.documentElement) { diff --git a/core/display-features.ts b/core/display-features.ts index c0a13e5ef..115529943 100644 --- a/core/display-features.ts +++ b/core/display-features.ts @@ -95,15 +95,28 @@ const readNativeState = (win: DisplayFeaturesWindow): DisplayFeaturesUpdate => { } }; +const sameOriginParent = (win: DisplayFeaturesWindow): DisplayFeaturesWindow | null => { + const parent = win.frameElement?.ownerDocument.defaultView as DisplayFeaturesWindow | null | undefined; + return parent?.__osDisplayFeatures ? parent : null; +}; + const initDisplayFeatures = (win: DisplayFeaturesWindow): void => { - if (win.__osDisplayFeatures || win.top !== win) { + if (win.__osDisplayFeatures) { + return; + } + const isTopFrame = win.parent === win; + const parent = isTopFrame ? null : sameOriginParent(win); + if (!isTopFrame && !parent) { return; } - const initial = readNativeState(win); + const viewportSegment = (): SegmentRect => ({ left: 0, top: 0, width: win.innerWidth, height: win.innerHeight }); + const initial: DisplayFeaturesUpdate = parent + ? { posture: (parent.navigator as Navigator & { devicePosture?: { type?: unknown } }).devicePosture?.type } + : readNativeState(win); const state: DisplayFeaturesState = { posture: isPosture(initial.posture) ? initial.posture : 'continuous', - segments: parseSegments(initial.segments) ?? [{ left: 0, top: 0, width: win.innerWidth, height: win.innerHeight }], + segments: (parent ? null : parseSegments(initial.segments)) ?? [viewportSegment()], }; class DevicePosture extends EventTarget { @@ -128,7 +141,8 @@ const initDisplayFeatures = (win: DisplayFeaturesWindow): void => { } const devicePosture = new DevicePosture(); - const getSegments = (): DOMRect[] => state.segments.map((s) => new DOMRect(s.left, s.top, s.width, s.height)); + const getSegments = (): DOMRect[] => + (isTopFrame ? state.segments : [viewportSegment()]).map((s) => new DOMRect(s.left, s.top, s.width, s.height)); try { Object.defineProperty(win.navigator, 'devicePosture', { @@ -210,16 +224,26 @@ const initDisplayFeatures = (win: DisplayFeaturesWindow): void => { } }); + const forwardToFrames = (posture: DevicePostureType) => { + win.document.querySelectorAll('iframe, frame').forEach((element) => { + const frame = (element as HTMLIFrameElement).contentDocument?.defaultView as + DisplayFeaturesWindow | null | undefined; + frame?.__osDisplayFeatures?.update({ posture }); + }); + }; + win.__osDisplayFeatures = { update: (update: DisplayFeaturesUpdate) => { if (update === null || typeof update !== 'object') { return; } const base = pending ?? state; - apply({ + const next: DisplayFeaturesState = { posture: isPosture(update.posture) ? update.posture : base.posture, - segments: parseSegments(update.segments) ?? base.segments, - }); + segments: (isTopFrame ? parseSegments(update.segments) : null) ?? base.segments, + }; + apply(next); + forwardToFrames(next.posture); }, }; diff --git a/core/src/tests/display-features.spec.ts b/core/src/tests/display-features.spec.ts index 1498b7184..611143bf5 100644 --- a/core/src/tests/display-features.spec.ts +++ b/core/src/tests/display-features.spec.ts @@ -180,6 +180,54 @@ describe('display features polyfill', () => { expect(existing.segments).toHaveLength(1); }); + describe('in a child frame', () => { + let iframe: HTMLIFrameElement; + let child: DisplayFeaturesWindow; + + beforeEach(() => { + iframe = document.createElement('iframe'); + document.body.appendChild(iframe); + child = iframe.contentWindow as DisplayFeaturesWindow; + }); + + afterEach(() => iframe.remove()); + + it('takes the posture from its parent and reports its own viewport as one segment', () => { + win.__osDisplayFeatures?.update({ posture: 'folded', segments: vertical }); + initDisplayFeatures(child); + expect((child.navigator as any).devicePosture.type).toBe('folded'); + const segments = (child.viewport as any).segments; + expect(segments).toHaveLength(1); + expect(segments[0]).toMatchObject({ x: 0, y: 0, width: child.innerWidth, height: child.innerHeight }); + const childStyle = child.document.documentElement.style; + expect(childStyle.getPropertyValue('--horizontal-viewport-segments')).toBe('1'); + expect(childStyle.getPropertyValue('--viewport-segment-width-0-0')).toBe(''); + }); + + it('receives posture changes from its parent but not segment changes', async () => { + initDisplayFeatures(child); + const change = jest.fn(); + const resize = jest.fn(); + (child.navigator as any).devicePosture.addEventListener('change', change); + child.addEventListener('resize', resize); + win.__osDisplayFeatures?.update({ posture: 'folded', segments: vertical }); + expect((child.navigator as any).devicePosture.type).toBe('folded'); + await flush(); + expect(change).toHaveBeenCalledTimes(1); + expect(resize).not.toHaveBeenCalled(); + expect((child.viewport as any).segments).toHaveLength(1); + }); + + it('does not install when the parent has no polyfill', () => { + const parentFeatures = win.__osDisplayFeatures; + delete win.__osDisplayFeatures; + initDisplayFeatures(child); + win.__osDisplayFeatures = parentFeatures; + expect(child.__osDisplayFeatures).toBeUndefined(); + expect((child.navigator as any).devicePosture).toBeUndefined(); + }); + }); + it('replaces a built-in navigator.devicePosture', () => { const builtIn = { type: 'folded' }; Object.defineProperty(navigator, 'devicePosture', { configurable: true, value: builtIn }); diff --git a/ios/Sources/Capacitor/DisplayFeatures.swift b/ios/Sources/Capacitor/DisplayFeatures.swift index 2aa99c090..86ee572f9 100644 --- a/ios/Sources/Capacitor/DisplayFeatures.swift +++ b/ios/Sources/Capacitor/DisplayFeatures.swift @@ -64,7 +64,9 @@ internal class DisplayFeatures { guard let userContentController else { return } - let next = WKUserScript(source: state.documentStartScript(polyfill: polyfill), injectionTime: .atDocumentStart, forMainFrameOnly: true) + let next = WKUserScript(source: state.documentStartScript(polyfill: polyfill), + injectionTime: .atDocumentStart, + forMainFrameOnly: false) if let script { // userScripts is bridged lazily from a live array that removeAllUserScripts() empties, so copy it first. let scripts = userContentController.userScripts.map { $0 } diff --git a/ios/Sources/Capacitor/assets/display-features.js b/ios/Sources/Capacitor/assets/display-features.js index ca98d7ead..c943d97b2 100644 --- a/ios/Sources/Capacitor/assets/display-features.js +++ b/ios/Sources/Capacitor/assets/display-features.js @@ -68,15 +68,28 @@ var __osDisplayFeaturesPolyfill = (function (exports) { return {}; } }; - const initDisplayFeatures = (win) => { + const sameOriginParent = (win) => { var _a; - if (win.__osDisplayFeatures || win.top !== win) { + const parent = (_a = win.frameElement) === null || _a === void 0 ? void 0 : _a.ownerDocument.defaultView; + return (parent === null || parent === void 0 ? void 0 : parent.__osDisplayFeatures) ? parent : null; + }; + const initDisplayFeatures = (win) => { + var _a, _b; + if (win.__osDisplayFeatures) { return; } - const initial = readNativeState(win); + const isTopFrame = win.parent === win; + const parent = isTopFrame ? null : sameOriginParent(win); + if (!isTopFrame && !parent) { + return; + } + const viewportSegment = () => ({ left: 0, top: 0, width: win.innerWidth, height: win.innerHeight }); + const initial = parent + ? { posture: (_a = parent.navigator.devicePosture) === null || _a === void 0 ? void 0 : _a.type } + : readNativeState(win); const state = { posture: isPosture(initial.posture) ? initial.posture : 'continuous', - segments: (_a = parseSegments(initial.segments)) !== null && _a !== void 0 ? _a : [{ left: 0, top: 0, width: win.innerWidth, height: win.innerHeight }], + segments: (_b = (parent ? null : parseSegments(initial.segments))) !== null && _b !== void 0 ? _b : [viewportSegment()], }; class DevicePosture extends EventTarget { constructor() { @@ -99,7 +112,7 @@ var __osDisplayFeaturesPolyfill = (function (exports) { } } const devicePosture = new DevicePosture(); - const getSegments = () => state.segments.map((s) => new DOMRect(s.left, s.top, s.width, s.height)); + const getSegments = () => (isTopFrame ? state.segments : [viewportSegment()]).map((s) => new DOMRect(s.left, s.top, s.width, s.height)); try { Object.defineProperty(win.navigator, 'devicePosture', { configurable: true, @@ -177,6 +190,13 @@ var __osDisplayFeaturesPolyfill = (function (exports) { apply(pending); } }); + const forwardToFrames = (posture) => { + win.document.querySelectorAll('iframe, frame').forEach((element) => { + var _a, _b; + const frame = (_a = element.contentDocument) === null || _a === void 0 ? void 0 : _a.defaultView; + (_b = frame === null || frame === void 0 ? void 0 : frame.__osDisplayFeatures) === null || _b === void 0 ? void 0 : _b.update({ posture }); + }); + }; win.__osDisplayFeatures = { update: (update) => { var _a; @@ -184,10 +204,12 @@ var __osDisplayFeaturesPolyfill = (function (exports) { return; } const base = pending !== null && pending !== void 0 ? pending : state; - apply({ + const next = { posture: isPosture(update.posture) ? update.posture : base.posture, - segments: (_a = parseSegments(update.segments)) !== null && _a !== void 0 ? _a : base.segments, - }); + segments: (_a = (isTopFrame ? parseSegments(update.segments) : null)) !== null && _a !== void 0 ? _a : base.segments, + }; + apply(next); + forwardToFrames(next.posture); }, }; if (win.document.documentElement) { From ad766c8aa812c17bb3510b9d8d1221e93dce2c8d Mon Sep 17 00:00:00 2001 From: Joseph Pender Date: Fri, 4 Dec 2026 16:15:36 -0600 Subject: [PATCH 6/6] only swap display features script when seeded state changes --- ios/Sources/Capacitor/DisplayFeatures.swift | 17 +++++-- .../Capacitor/DisplayFeaturesState.swift | 24 +++++++--- .../CapacitorTests/DisplayFeaturesTests.swift | 47 +++++++++++++------ 3 files changed, 63 insertions(+), 25 deletions(-) diff --git a/ios/Sources/Capacitor/DisplayFeatures.swift b/ios/Sources/Capacitor/DisplayFeatures.swift index 86ee572f9..c90028a08 100644 --- a/ios/Sources/Capacitor/DisplayFeatures.swift +++ b/ios/Sources/Capacitor/DisplayFeatures.swift @@ -35,8 +35,7 @@ internal class DisplayFeatures { let tracker = ReservedRegionTracker(frame: webView.bounds) tracker.onChange = { [weak self] division in DispatchQueue.main.async { - self?.division = division - self?.refresh() + self?.update(division: division) } } webView.addSubview(tracker) @@ -45,6 +44,11 @@ internal class DisplayFeatures { #endif } + func update(division: CGRect?) { + self.division = division + refresh() + } + private func refresh() { guard let webView else { return @@ -59,12 +63,17 @@ internal class DisplayFeatures { } // WKWebView has no synchronous bridge, so getState() is baked into the document-start script, which is - // swapped on every change. WKUserContentController cannot remove a single script, so the rest are re-added in order. + // swapped when it changes. WKUserContentController cannot remove a single script, + // so the rest are re-added in order. private func installScript() { guard let userContentController else { return } - let next = WKUserScript(source: state.documentStartScript(polyfill: polyfill), + let source = state.documentStartScript(polyfill: polyfill) + guard source != script?.source else { + return + } + let next = WKUserScript(source: source, injectionTime: .atDocumentStart, forMainFrameOnly: false) if let script { diff --git a/ios/Sources/Capacitor/DisplayFeaturesState.swift b/ios/Sources/Capacitor/DisplayFeaturesState.swift index 1aa3324f3..69dcdf00a 100644 --- a/ios/Sources/Capacitor/DisplayFeaturesState.swift +++ b/ios/Sources/Capacitor/DisplayFeaturesState.swift @@ -25,16 +25,25 @@ internal struct DisplayFeaturesState: Equatable { CGRect(x: 0, y: division.maxY, width: bounds.width, height: bounds.height - division.maxY) ]) } - return DisplayFeaturesState(posture: folded, segments: [whole]) + return DisplayFeaturesState(posture: continuous, segments: [whole]) } var json: String { - let object: [String: Any] = [ - "posture": posture, - "segments": segments.map { segment in - ["left": Double(segment.minX), "top": Double(segment.minY), "width": Double(segment.width), "height": Double(segment.height)] + json(segments: segments) + } + + private var seedJSON: String { + json(segments: segments.count > 1 ? segments : nil) + } + + private func json(segments: [CGRect]?) -> String { + var object: [String: Any] = ["posture": posture] + if let segments { + object["segments"] = segments.map { segment in + ["left": Double(segment.minX), "top": Double(segment.minY), + "width": Double(segment.width), "height": Double(segment.height)] } - ] + } guard let data = try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]), let json = String(data: data, encoding: .utf8) else { return "null" @@ -47,6 +56,7 @@ internal struct DisplayFeaturesState: Equatable { } func documentStartScript(polyfill: String) -> String { - "window.__osDisplayFeaturesNative = { getState: function () { return JSON.stringify(\(json)); } };\n\(polyfill)" + "window.__osDisplayFeaturesNative = { getState: function () { return JSON.stringify(\(seedJSON)); } };\n" + + polyfill } } diff --git a/ios/Tests/CapacitorTests/DisplayFeaturesTests.swift b/ios/Tests/CapacitorTests/DisplayFeaturesTests.swift index 841bca790..663bdf40a 100644 --- a/ios/Tests/CapacitorTests/DisplayFeaturesTests.swift +++ b/ios/Tests/CapacitorTests/DisplayFeaturesTests.swift @@ -44,9 +44,9 @@ struct DisplayFeaturesStateTests { CGRect(x: 790, y: 0, width: 20, height: 1000), CGRect(x: 0, y: 990, width: 800, height: 20) ]) - func divisionAtAnEdgeIsFoldedWithOneSegment(division: CGRect) { + func divisionNotCrossingTheWebViewIsContinuous(division: CGRect) { let state = DisplayFeaturesState.compute(bounds: bounds, division: division) - #expect(state.posture == "folded") + #expect(state.posture == "continuous") #expect(state.segments == [CGRect(x: 0, y: 0, width: 800, height: 1000)]) } @@ -58,11 +58,18 @@ struct DisplayFeaturesStateTests { } @Test func documentStartScriptSeedsGetStateBeforeThePolyfill() { - let state = DisplayFeaturesState.compute(bounds: bounds, division: nil) + let state = DisplayFeaturesState.compute(bounds: bounds, division: CGRect(x: 390, y: 0, width: 20, height: 1000)) let script = state.documentStartScript(polyfill: "polyfill();") #expect(script == "window.__osDisplayFeaturesNative = { getState: function () { return JSON.stringify(\(state.json)); } };" + "\npolyfill();") } + + @Test func documentStartScriptLeavesOutASingleSegment() { + let state = DisplayFeaturesState.compute(bounds: bounds, division: nil) + let script = state.documentStartScript(polyfill: "polyfill();") + #expect(script == #"window.__osDisplayFeaturesNative = { getState: function () { return JSON.stringify({"posture":"continuous"}); } };"# + + "\npolyfill();") + } } @MainActor @@ -80,36 +87,48 @@ struct DisplayFeaturesTests { #expect(JSExport.displayFeaturesJS()?.contains("__osDisplayFeatures") == true) } - @Test func installsSeededPolyfillInTheTopFrameAtDocumentStart() throws { + @Test func installsSeededPolyfillInEveryFrameAtDocumentStart() throws { let features = DisplayFeatures(webView: webView, userContentController: contentController, polyfill: "polyfill();") let script = try #require(contentController.userScripts.first) #expect(contentController.userScripts.count == 1) #expect(script.injectionTime == .atDocumentStart) - #expect(script.isForMainFrameOnly) - #expect(script.source.contains(#""width":400"#)) + #expect(!script.isForMainFrameOnly) + #expect(script.source.contains(#"{"posture":"continuous"}"#)) #expect(script.source.hasSuffix("polyfill();")) withExtendedLifetime(features) {} } - @Test func resizeSwapsTheScriptInPlace() async throws { - let before = WKUserScript(source: "before();", injectionTime: .atDocumentStart, forMainFrameOnly: true) - let after = WKUserScript(source: "after();", injectionTime: .atDocumentEnd, forMainFrameOnly: true) - contentController.addUserScript(before) + @Test func resizeKeepsTheInstalledScripts() async throws { let features = DisplayFeatures(webView: webView, userContentController: contentController, polyfill: "polyfill();") - contentController.addUserScript(after) + let installed = contentController.userScripts.map { $0 } webView.frame = CGRect(x: 0, y: 0, width: 600, height: 800) await withCheckedContinuation { continuation in DispatchQueue.main.async { continuation.resume() } } + let scripts = contentController.userScripts + #expect(scripts.count == installed.count) + #expect(zip(scripts, installed).allSatisfy { $0 === $1 }) + withExtendedLifetime(features) {} + } + + @Test func divisionChangeSwapsTheScriptInPlace() throws { + let before = WKUserScript(source: "before();", injectionTime: .atDocumentStart, forMainFrameOnly: true) + let after = WKUserScript(source: "after();", injectionTime: .atDocumentEnd, forMainFrameOnly: true) + contentController.addUserScript(before) + let features = DisplayFeatures(webView: webView, userContentController: contentController, polyfill: "polyfill();") + contentController.addUserScript(after) + + features.update(division: CGRect(x: 190, y: 0, width: 20, height: 800)) + let scripts = contentController.userScripts #expect(scripts.count == 3) #expect(scripts.first === before) #expect(scripts.last === after) let seeded = try #require(scripts.dropFirst().first) - #expect(seeded.source.contains(#""width":600"#)) - #expect(seeded.isForMainFrameOnly) - withExtendedLifetime(features) {} + #expect(seeded.source.contains(#""posture":"folded""#)) + #expect(seeded.source.contains(#""width":190"#)) + #expect(!seeded.isForMainFrameOnly) } }