capacitor-device-profile 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.1.2](https://github.com/jbcom/capacitor-device-profile/compare/v0.1.1...v0.1.2) (2026-10-07)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * ship the TypeScript sources that the declaration maps point at ([35e596c](https://github.com/jbcom/capacitor-device-profile/commit/35e596c0879fbeb4b42e47cdccb9bd4ba0b68555))
9
+ * ship the TypeScript sources that the declaration maps point at ([d20ba08](https://github.com/jbcom/capacitor-device-profile/commit/d20ba08522d4573c1a86ef6c7ced769257312367))
10
+
3
11
  ## 0.1.1 (2026-10-07)
4
12
 
5
13
  First release on npmjs, as `capacitor-device-profile`, MIT licensed, from `github.com/jbcom/capacitor-device-profile`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "capacitor-device-profile",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Mobile and foldable runtime over Capacitor: device profile (phone, foldable-open, tablet, desktop) that re-classifies live on fold and unfold, orientation policy, live safe-area insets, app lifecycle with a back-button stack, and a haptics facade.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -52,7 +52,8 @@
52
52
  "SECURITY.md",
53
53
  "dist",
54
54
  "docs/API.md",
55
- "docs/ARCHITECTURE.md"
55
+ "docs/ARCHITECTURE.md",
56
+ "src"
56
57
  ],
57
58
  "scripts": {
58
59
  "build": "node scripts/build.mjs",
package/src/haptics.ts ADDED
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Haptics facade. Native shells pass Capacitor's `Haptics` plugin; everywhere else every call is a
3
+ * no-op, so game code calls `haptics.impact()` unconditionally. A player setting can switch it off at
4
+ * runtime through `setEnabled`, and plugin failures are swallowed: a missing buzz must never throw
5
+ * into a frame loop.
6
+ */
7
+
8
+ export type ImpactStrength = 'light' | 'medium' | 'heavy'
9
+ export type NotificationKind = 'success' | 'warning' | 'error'
10
+
11
+ /**
12
+ * The subset of Capacitor's `Haptics` plugin this module uses. The values sent are the string values
13
+ * of Capacitor's `ImpactStyle` and `NotificationType` enums; the fields are typed `string` so the real
14
+ * plugin (whose parameters are those enums) is assignable without this package importing Capacitor.
15
+ */
16
+ export interface HapticsPluginLike {
17
+ impact(options?: { style?: string }): Promise<void>
18
+ notification(options?: { type?: string }): Promise<void>
19
+ selectionChanged(): Promise<void>
20
+ }
21
+
22
+ export interface Haptics {
23
+ readonly enabled: boolean
24
+ setEnabled(enabled: boolean): void
25
+ impact(strength?: ImpactStrength): void
26
+ notify(kind: NotificationKind): void
27
+ selection(): void
28
+ }
29
+
30
+ export interface HapticsOptions {
31
+ plugin?: HapticsPluginLike
32
+ native: boolean
33
+ enabled?: boolean
34
+ }
35
+
36
+ const IMPACT_STYLE = { light: 'LIGHT', medium: 'MEDIUM', heavy: 'HEAVY' } as const
37
+ const NOTIFICATION_TYPE = { success: 'SUCCESS', warning: 'WARNING', error: 'ERROR' } as const
38
+
39
+ export function createHaptics(options: HapticsOptions): Haptics {
40
+ let enabled = options.enabled ?? true
41
+ const plugin = options.native ? options.plugin : undefined
42
+ const fire = (call: (target: HapticsPluginLike) => Promise<void>) => {
43
+ if (!enabled || !plugin) return
44
+ void call(plugin).catch(() => undefined)
45
+ }
46
+ return {
47
+ get enabled() {
48
+ return enabled
49
+ },
50
+ setEnabled(next) {
51
+ enabled = next
52
+ },
53
+ impact(strength = 'light') {
54
+ fire((target) => target.impact({ style: IMPACT_STYLE[strength] }))
55
+ },
56
+ notify(kind) {
57
+ fire((target) => target.notification({ type: NOTIFICATION_TYPE[kind] }))
58
+ },
59
+ selection() {
60
+ fire((target) => target.selectionChanged())
61
+ },
62
+ }
63
+ }
package/src/index.ts ADDED
@@ -0,0 +1,47 @@
1
+ export {
2
+ createHaptics,
3
+ type Haptics,
4
+ type HapticsOptions,
5
+ type HapticsPluginLike,
6
+ type ImpactStrength,
7
+ type NotificationKind,
8
+ } from './haptics.js'
9
+ export {
10
+ type AppLifecycle,
11
+ type AppLifecycleOptions,
12
+ type AppPluginLike,
13
+ type BackHandler,
14
+ createAppLifecycle,
15
+ type LifecycleState,
16
+ type PluginListenerHandleLike,
17
+ } from './lifecycle.js'
18
+ export {
19
+ decideOrientation,
20
+ type OrientationDecision,
21
+ type PreferredOrientation,
22
+ } from './orientation.js'
23
+ export {
24
+ classifyDevice,
25
+ classifyFormFactor,
26
+ classifyFrame,
27
+ classifyOrientation,
28
+ type DevicePlatform,
29
+ type DeviceProfile,
30
+ EXPANDED_MIN_SHORT_EDGE,
31
+ type FormFactor,
32
+ type FrameClass,
33
+ isFoldableOpen,
34
+ NEAR_SQUARE_MAX_ASPECT,
35
+ readViewportFacts,
36
+ TABLET_MIN_SHORT_EDGE,
37
+ type ViewOrientation,
38
+ type ViewportFacts,
39
+ } from './profile.js'
40
+ export {
41
+ applySafeAreaVariables,
42
+ readSafeAreaInsets,
43
+ type SafeAreaInsets,
44
+ type SafeAreaWatchOptions,
45
+ watchSafeArea,
46
+ ZERO_INSETS,
47
+ } from './safeArea.js'
@@ -0,0 +1,130 @@
1
+ /**
2
+ * App lifecycle: pause/resume and the Android back button, on native shells and in the browser.
3
+ *
4
+ * The Capacitor `App` plugin is passed in rather than imported, so this package carries no runtime
5
+ * dependency on Capacitor and the logic unit-tests with a fake. On the web, pause/resume comes from
6
+ * `visibilitychange`, `pagehide` and `pageshow`.
7
+ *
8
+ * Back handling is a stack: the most recently pushed handler (an open modal, then the pause menu)
9
+ * runs first, and returning `true` consumes the press. An unconsumed press minimises the app instead
10
+ * of exiting it, so a stray back never discards unsaved progress.
11
+ */
12
+
13
+ export type LifecycleState = 'active' | 'background'
14
+
15
+ export interface PluginListenerHandleLike {
16
+ remove(): Promise<void>
17
+ }
18
+
19
+ /** The subset of Capacitor's `App` plugin this module uses. */
20
+ export interface AppPluginLike {
21
+ addListener(
22
+ event: 'appStateChange',
23
+ listener: (state: { isActive: boolean }) => void,
24
+ ): Promise<PluginListenerHandleLike>
25
+ addListener(
26
+ event: 'backButton',
27
+ listener: (event: { canGoBack: boolean }) => void,
28
+ ): Promise<PluginListenerHandleLike>
29
+ minimizeApp(): Promise<void>
30
+ }
31
+
32
+ /** Returns true when it handled the press. */
33
+ export type BackHandler = () => boolean
34
+
35
+ export interface AppLifecycleOptions {
36
+ /** Capacitor's `App` plugin; required for native back-button and state events. */
37
+ app?: AppPluginLike
38
+ /** True inside a native shell (`Capacitor.isNativePlatform()`). */
39
+ native: boolean
40
+ onPause?: () => void
41
+ onResume?: () => void
42
+ /** Window and document for the web path; default to the globals. */
43
+ window?: Window
44
+ document?: Document
45
+ }
46
+
47
+ export interface AppLifecycle {
48
+ readonly state: LifecycleState
49
+ /** Pushes a back handler; the returned function removes it. */
50
+ pushBackHandler(handler: BackHandler): () => void
51
+ /** Runs the back stack as a hardware back press would. Returns true when a handler consumed it. */
52
+ handleBack(): boolean
53
+ dispose(): Promise<void>
54
+ }
55
+
56
+ export function createAppLifecycle(options: AppLifecycleOptions): AppLifecycle {
57
+ const handlers: BackHandler[] = []
58
+ const handles: Promise<PluginListenerHandleLike>[] = []
59
+ const removers: Array<() => void> = []
60
+ let state: LifecycleState = 'active'
61
+ let disposed = false
62
+
63
+ const transition = (next: LifecycleState) => {
64
+ if (disposed || next === state) return
65
+ state = next
66
+ if (next === 'active') options.onResume?.()
67
+ else options.onPause?.()
68
+ }
69
+
70
+ const handleBack = (): boolean => {
71
+ for (let index = handlers.length - 1; index >= 0; index -= 1) {
72
+ const handler = handlers[index]
73
+ if (handler?.()) return true
74
+ }
75
+ return false
76
+ }
77
+
78
+ if (options.native && options.app) {
79
+ const app = options.app
80
+ handles.push(
81
+ app.addListener('appStateChange', ({ isActive }) =>
82
+ transition(isActive ? 'active' : 'background'),
83
+ ),
84
+ )
85
+ handles.push(
86
+ app.addListener('backButton', () => {
87
+ if (!handleBack()) void app.minimizeApp().catch(() => undefined)
88
+ }),
89
+ )
90
+ } else {
91
+ const win = options.window ?? (typeof window === 'undefined' ? undefined : window)
92
+ const doc = options.document ?? (typeof document === 'undefined' ? undefined : document)
93
+ if (win && doc) {
94
+ const onVisibility = () => transition(doc.hidden ? 'background' : 'active')
95
+ const onHide = () => transition('background')
96
+ const onShow = () => transition('active')
97
+ doc.addEventListener('visibilitychange', onVisibility)
98
+ win.addEventListener('pagehide', onHide)
99
+ win.addEventListener('pageshow', onShow)
100
+ removers.push(() => {
101
+ doc.removeEventListener('visibilitychange', onVisibility)
102
+ win.removeEventListener('pagehide', onHide)
103
+ win.removeEventListener('pageshow', onShow)
104
+ })
105
+ }
106
+ }
107
+
108
+ return {
109
+ get state() {
110
+ return state
111
+ },
112
+ pushBackHandler(handler) {
113
+ handlers.push(handler)
114
+ return () => {
115
+ const index = handlers.lastIndexOf(handler)
116
+ if (index >= 0) handlers.splice(index, 1)
117
+ }
118
+ },
119
+ handleBack,
120
+ async dispose() {
121
+ disposed = true
122
+ handlers.length = 0
123
+ for (const remove of removers.splice(0)) remove()
124
+ const settled = await Promise.allSettled(handles.splice(0))
125
+ await Promise.allSettled(
126
+ settled.flatMap((result) => (result.status === 'fulfilled' ? [result.value.remove()] : [])),
127
+ )
128
+ },
129
+ }
130
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Orientation policy. A game declares the orientation it is designed around; the policy decides, per
3
+ * device, which orientations are acceptable and whether to ask a phone player to rotate. Tablets and
4
+ * unfolded foldables are usable either way, so they are never nagged.
5
+ *
6
+ * Never force-rotate. The decision drives a per-screen "turn the device" hint only; the
7
+ * native shell leaves the screen orientation unlocked.
8
+ */
9
+ import type { DeviceProfile, ViewOrientation } from './profile.js'
10
+
11
+ /** `any` means the game lays out in both orientations on every device. */
12
+ export type PreferredOrientation = ViewOrientation | 'any'
13
+
14
+ export interface OrientationDecision {
15
+ /** Orientations the game should accept on this device. */
16
+ allowed: readonly ViewOrientation[]
17
+ /** True when the player should be asked to rotate the device. */
18
+ promptRotate: boolean
19
+ /** The orientation to ask for when `promptRotate` is true. */
20
+ target: ViewOrientation | null
21
+ }
22
+
23
+ const BOTH: readonly ViewOrientation[] = ['portrait', 'landscape']
24
+
25
+ export function decideOrientation(
26
+ profile: Pick<DeviceProfile, 'formFactor' | 'orientation' | 'touch'>,
27
+ preferred: PreferredOrientation,
28
+ ): OrientationDecision {
29
+ const flexible =
30
+ preferred === 'any' ||
31
+ !profile.touch ||
32
+ profile.formFactor === 'desktop' ||
33
+ profile.formFactor === 'tablet' ||
34
+ profile.formFactor === 'foldable-open'
35
+ if (flexible) return { allowed: BOTH, promptRotate: false, target: null }
36
+ const allowed: readonly ViewOrientation[] = [preferred]
37
+ const promptRotate = profile.orientation !== preferred
38
+ return { allowed, promptRotate, target: promptRotate ? preferred : null }
39
+ }
package/src/profile.ts ADDED
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Device profile: a pure classification of the current viewport into the categories a game's layout
3
+ * actually branches on. Every input is injectable so the classification unit-tests without a browser
4
+ * and so a native shell can feed it platform facts (Capacitor `Device.getInfo()`).
5
+ */
6
+
7
+ /** `compact` lays a HUD out for a phone; `expanded` has room for side panels. */
8
+ export type FrameClass = 'compact' | 'expanded'
9
+ export type ViewOrientation = 'portrait' | 'landscape'
10
+ /**
11
+ * The form factor a layout targets. `foldable-open` is an unfolded book-style foldable (OnePlus Open,
12
+ * Galaxy Z Fold, Pixel Fold): touch-primary, tablet-sized and near-square, so it plays in either
13
+ * orientation and needs a layout of its own rather than a stretched phone or a squashed tablet one.
14
+ */
15
+ export type FormFactor = 'phone' | 'foldable-open' | 'tablet' | 'desktop'
16
+ /** Platform names as Capacitor's `Device.getInfo().platform` reports them. */
17
+ export type DevicePlatform = 'web' | 'android' | 'ios' | 'electron'
18
+
19
+ export interface ViewportFacts {
20
+ /** CSS pixels (`window.innerWidth`). */
21
+ width: number
22
+ /** CSS pixels (`window.innerHeight`). */
23
+ height: number
24
+ devicePixelRatio: number
25
+ /** True when the primary input is touch (`maxTouchPoints > 0`). */
26
+ touch: boolean
27
+ platform: DevicePlatform
28
+ /** Native model string; used only to recognise iPads, which report a phone-like platform. */
29
+ model: string
30
+ }
31
+
32
+ export type DeviceProfile = Readonly<{
33
+ frame: FrameClass
34
+ formFactor: FormFactor
35
+ orientation: ViewOrientation
36
+ platform: DevicePlatform
37
+ native: boolean
38
+ touch: boolean
39
+ shortEdge: number
40
+ longEdge: number
41
+ /** Long edge divided by short edge; 1 is square. */
42
+ aspect: number
43
+ devicePixelRatio: number
44
+ }>
45
+
46
+ /** Short edge (CSS px) at which a frame counts as expanded. Phones stay below ~480. */
47
+ export const EXPANDED_MIN_SHORT_EDGE = 700
48
+ /** Short edge (CSS px) from which a touch screen is tablet-sized rather than a phone. */
49
+ export const TABLET_MIN_SHORT_EDGE = 600
50
+ /**
51
+ * Long/short aspect at or below which a screen is near-square. A phone in portrait is ~2.1, a 4:3
52
+ * tablet 1.33, an unfolded OnePlus Open ~1.08.
53
+ */
54
+ export const NEAR_SQUARE_MAX_ASPECT = 1.3
55
+
56
+ export function classifyOrientation(width: number, height: number): ViewOrientation {
57
+ return height > width ? 'portrait' : 'landscape'
58
+ }
59
+
60
+ /** True for an unfolded book-style foldable: near-square and tablet-sized, on a touch screen. */
61
+ export function isFoldableOpen(facts: Pick<ViewportFacts, 'width' | 'height' | 'touch'>): boolean {
62
+ if (!facts.touch) return false
63
+ const shortEdge = Math.min(facts.width, facts.height)
64
+ const longEdge = Math.max(facts.width, facts.height)
65
+ if (shortEdge <= 0) return false
66
+ return longEdge / shortEdge <= NEAR_SQUARE_MAX_ASPECT && shortEdge >= TABLET_MIN_SHORT_EDGE
67
+ }
68
+
69
+ export function classifyFormFactor(facts: ViewportFacts): FormFactor {
70
+ const shortEdge = Math.min(facts.width, facts.height)
71
+ if (facts.platform === 'ios' && /ipad/i.test(facts.model)) return 'tablet'
72
+ if (isFoldableOpen(facts)) return 'foldable-open'
73
+ if (!facts.touch && facts.platform === 'web') return 'desktop'
74
+ if (facts.platform === 'electron') return 'desktop'
75
+ return shortEdge >= TABLET_MIN_SHORT_EDGE ? 'tablet' : 'phone'
76
+ }
77
+
78
+ export function classifyFrame(facts: ViewportFacts): FrameClass {
79
+ if (facts.platform === 'ios') return /ipad/i.test(facts.model) ? 'expanded' : 'compact'
80
+ return Math.min(facts.width, facts.height) >= EXPANDED_MIN_SHORT_EDGE ? 'expanded' : 'compact'
81
+ }
82
+
83
+ export function classifyDevice(facts: ViewportFacts): DeviceProfile {
84
+ const shortEdge = Math.min(facts.width, facts.height)
85
+ const longEdge = Math.max(facts.width, facts.height)
86
+ const native = facts.platform === 'android' || facts.platform === 'ios'
87
+ return {
88
+ frame: classifyFrame(facts),
89
+ formFactor: classifyFormFactor(facts),
90
+ orientation: classifyOrientation(facts.width, facts.height),
91
+ platform: facts.platform,
92
+ native,
93
+ touch: facts.touch || native,
94
+ shortEdge,
95
+ longEdge,
96
+ aspect: shortEdge > 0 ? longEdge / shortEdge : 1,
97
+ devicePixelRatio: facts.devicePixelRatio,
98
+ }
99
+ }
100
+
101
+ interface BrowserLike {
102
+ innerWidth: number
103
+ innerHeight: number
104
+ devicePixelRatio?: number
105
+ navigator?: { maxTouchPoints?: number }
106
+ }
107
+
108
+ /**
109
+ * Reads viewport facts from a window (`null` outside a browser gives a 1280x720 desktop default).
110
+ * Platform facts default to `web` until a native shell says otherwise.
111
+ */
112
+ export function readViewportFacts(
113
+ win: BrowserLike | null = typeof window === 'undefined' ? null : window,
114
+ platform: Pick<ViewportFacts, 'platform' | 'model'> = { platform: 'web', model: '' },
115
+ ): ViewportFacts {
116
+ if (!win) {
117
+ return { width: 1280, height: 720, devicePixelRatio: 1, touch: false, ...platform }
118
+ }
119
+ return {
120
+ width: win.innerWidth,
121
+ height: win.innerHeight,
122
+ devicePixelRatio: win.devicePixelRatio ?? 1,
123
+ touch: (win.navigator?.maxTouchPoints ?? 0) > 0 || 'ontouchstart' in win,
124
+ ...platform,
125
+ }
126
+ }
package/src/react.tsx ADDED
@@ -0,0 +1,80 @@
1
+ /**
2
+ * React bindings: a live device profile and live safe-area insets. Both re-read on resize,
3
+ * orientation change, visual-viewport resize and fold posture change, so a foldable switches layout
4
+ * when it is folded or unfolded without a reload.
5
+ */
6
+ import { useEffect, useState } from 'react'
7
+ import {
8
+ classifyDevice,
9
+ type DeviceProfile,
10
+ readViewportFacts,
11
+ type ViewportFacts,
12
+ } from './profile.js'
13
+ import { readSafeAreaInsets, type SafeAreaInsets, watchSafeArea, ZERO_INSETS } from './safeArea.js'
14
+
15
+ type PlatformFacts = Pick<ViewportFacts, 'platform' | 'model'>
16
+
17
+ export interface UseDeviceProfileOptions {
18
+ /** Platform facts known synchronously, e.g. `{ platform: Capacitor.getPlatform(), model: '' }`. */
19
+ platform?: PlatformFacts
20
+ /** Async platform lookup, e.g. `() => Device.getInfo()` from `@capacitor/device`. */
21
+ loadPlatform?: () => Promise<PlatformFacts>
22
+ }
23
+
24
+ const WEB: PlatformFacts = { platform: 'web', model: '' }
25
+
26
+ /** Subscribes to every event that changes viewport geometry, including fold posture changes. */
27
+ export function subscribeViewportGeometry(callback: () => void): () => void {
28
+ const fold =
29
+ typeof window.matchMedia === 'function'
30
+ ? window.matchMedia('(horizontal-viewport-segments: 2), (vertical-viewport-segments: 2)')
31
+ : null
32
+ window.addEventListener('resize', callback)
33
+ window.addEventListener('orientationchange', callback)
34
+ window.visualViewport?.addEventListener('resize', callback)
35
+ fold?.addEventListener('change', callback)
36
+ return () => {
37
+ window.removeEventListener('resize', callback)
38
+ window.removeEventListener('orientationchange', callback)
39
+ window.visualViewport?.removeEventListener('resize', callback)
40
+ fold?.removeEventListener('change', callback)
41
+ }
42
+ }
43
+
44
+ export function useDeviceProfile(options: UseDeviceProfileOptions = {}): DeviceProfile {
45
+ const [platform, setPlatform] = useState<PlatformFacts>(options.platform ?? WEB)
46
+ const [profile, setProfile] = useState(() =>
47
+ classifyDevice(readViewportFacts(typeof window === 'undefined' ? null : window, platform)),
48
+ )
49
+ const loadPlatform = options.loadPlatform
50
+
51
+ useEffect(() => {
52
+ if (!loadPlatform) return
53
+ let cancelled = false
54
+ loadPlatform()
55
+ .then((info) => {
56
+ if (!cancelled) setPlatform({ platform: info.platform, model: info.model })
57
+ })
58
+ .catch(() => undefined)
59
+ return () => {
60
+ cancelled = true
61
+ }
62
+ }, [loadPlatform])
63
+
64
+ useEffect(() => {
65
+ const update = () => setProfile(classifyDevice(readViewportFacts(window, platform)))
66
+ update()
67
+ return subscribeViewportGeometry(update)
68
+ }, [platform])
69
+
70
+ return profile
71
+ }
72
+
73
+ /** Live safe-area insets; also publishes `--safe-*` CSS variables on the root element. */
74
+ export function useSafeAreaInsets(): SafeAreaInsets {
75
+ const [insets, setInsets] = useState<SafeAreaInsets>(() =>
76
+ typeof document === 'undefined' ? { ...ZERO_INSETS } : readSafeAreaInsets(document),
77
+ )
78
+ useEffect(() => watchSafeArea({ onChange: setInsets }), [])
79
+ return insets
80
+ }
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Safe-area insets as numbers and as CSS variables.
3
+ *
4
+ * `env(safe-area-inset-*)` already works inside CSS, but JavaScript layout (canvas HUDs, joystick
5
+ * placement) needs the numbers, and some Android WebViews do not refresh `env()` consumers after a
6
+ * fold, an orientation change or a cut-out change. `watchSafeArea` measures the insets through a
7
+ * hidden probe element and republishes them as `--safe-top/right/bottom/left` px variables on every
8
+ * resize, orientation change, visual-viewport resize and fold posture change.
9
+ */
10
+
11
+ export interface SafeAreaInsets {
12
+ top: number
13
+ right: number
14
+ bottom: number
15
+ left: number
16
+ }
17
+
18
+ export const ZERO_INSETS: Readonly<SafeAreaInsets> = Object.freeze({
19
+ top: 0,
20
+ right: 0,
21
+ bottom: 0,
22
+ left: 0,
23
+ })
24
+
25
+ const SIDES = ['top', 'right', 'bottom', 'left'] as const
26
+
27
+ export interface SafeAreaWatchOptions {
28
+ /** Element that receives the CSS variables. Defaults to `document.documentElement`. */
29
+ target?: HTMLElement
30
+ /** CSS variable prefix. Defaults to `--safe-` (so `--safe-top` ...). */
31
+ prefix?: string
32
+ /** Called with fresh insets after every measurement. */
33
+ onChange?: (insets: SafeAreaInsets) => void
34
+ }
35
+
36
+ function parsePx(value: string): number {
37
+ const parsed = Number.parseFloat(value)
38
+ return Number.isFinite(parsed) ? parsed : 0
39
+ }
40
+
41
+ /** Measures the current safe-area insets through a temporary probe element. */
42
+ export function readSafeAreaInsets(doc: Document = document): SafeAreaInsets {
43
+ const view = doc.defaultView
44
+ if (!view || !doc.body) return { ...ZERO_INSETS }
45
+ const probe = doc.createElement('div')
46
+ probe.setAttribute('aria-hidden', 'true')
47
+ probe.style.cssText = [
48
+ 'position:fixed',
49
+ 'visibility:hidden',
50
+ 'pointer-events:none',
51
+ 'padding-top:env(safe-area-inset-top,0px)',
52
+ 'padding-right:env(safe-area-inset-right,0px)',
53
+ 'padding-bottom:env(safe-area-inset-bottom,0px)',
54
+ 'padding-left:env(safe-area-inset-left,0px)',
55
+ ].join(';')
56
+ doc.body.appendChild(probe)
57
+ const style = view.getComputedStyle(probe)
58
+ const insets = {
59
+ top: parsePx(style.paddingTop),
60
+ right: parsePx(style.paddingRight),
61
+ bottom: parsePx(style.paddingBottom),
62
+ left: parsePx(style.paddingLeft),
63
+ }
64
+ probe.remove()
65
+ return insets
66
+ }
67
+
68
+ export function applySafeAreaVariables(
69
+ insets: SafeAreaInsets,
70
+ target: HTMLElement,
71
+ prefix = '--safe-',
72
+ ): void {
73
+ for (const side of SIDES) target.style.setProperty(`${prefix}${side}`, `${insets[side]}px`)
74
+ }
75
+
76
+ /**
77
+ * Measures the insets now and again after every geometry change. Returns a disposer that removes all
78
+ * listeners. Measurement runs on the next animation frame so a fold reports post-layout values.
79
+ */
80
+ export function watchSafeArea(options: SafeAreaWatchOptions = {}): () => void {
81
+ if (typeof window === 'undefined' || typeof document === 'undefined') return () => undefined
82
+ const target = options.target ?? document.documentElement
83
+ const prefix = options.prefix ?? '--safe-'
84
+ let frame = 0
85
+ const measure = () => {
86
+ frame = 0
87
+ const insets = readSafeAreaInsets(document)
88
+ applySafeAreaVariables(insets, target, prefix)
89
+ options.onChange?.(insets)
90
+ }
91
+ const schedule = () => {
92
+ if (frame !== 0) return
93
+ frame = window.requestAnimationFrame(measure)
94
+ }
95
+ measure()
96
+ window.addEventListener('resize', schedule)
97
+ window.addEventListener('orientationchange', schedule)
98
+ window.visualViewport?.addEventListener('resize', schedule)
99
+ const fold = foldPostureMedia(window)
100
+ fold?.addEventListener('change', schedule)
101
+ return () => {
102
+ if (frame !== 0) window.cancelAnimationFrame(frame)
103
+ window.removeEventListener('resize', schedule)
104
+ window.removeEventListener('orientationchange', schedule)
105
+ window.visualViewport?.removeEventListener('resize', schedule)
106
+ fold?.removeEventListener('change', schedule)
107
+ }
108
+ }
109
+
110
+ /** Media query that flips when a foldable changes posture; `null` where unsupported. */
111
+ function foldPostureMedia(win: Window): MediaQueryList | null {
112
+ if (typeof win.matchMedia !== 'function') return null
113
+ return win.matchMedia('(horizontal-viewport-segments: 2), (vertical-viewport-segments: 2)')
114
+ }