@djangocfg/ui-core 2.1.653 → 2.1.656

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@djangocfg/ui-core",
3
- "version": "2.1.653",
3
+ "version": "2.1.656",
4
4
  "description": "Pure React UI component library without Next.js dependencies - for Electron, Vite, CRA apps",
5
5
  "keywords": [
6
6
  "ui-components",
@@ -144,8 +144,8 @@
144
144
  "check:docs": "node scripts/check-docs.mjs"
145
145
  },
146
146
  "peerDependencies": {
147
- "@djangocfg/api": "^2.1.653",
148
- "@djangocfg/i18n": "^2.1.653",
147
+ "@djangocfg/api": "^2.1.656",
148
+ "@djangocfg/i18n": "^2.1.656",
149
149
  "consola": "^3.4.2",
150
150
  "lucide-react": "^1.68.0",
151
151
  "moment": "^2.30.1",
@@ -220,10 +220,10 @@
220
220
  "vaul": "1.1.2"
221
221
  },
222
222
  "devDependencies": {
223
- "@djangocfg/api": "^2.1.653",
224
- "@djangocfg/eslint-config": "^2.1.653",
225
- "@djangocfg/i18n": "^2.1.653",
226
- "@djangocfg/typescript-config": "^2.1.653",
223
+ "@djangocfg/api": "^2.1.656",
224
+ "@djangocfg/eslint-config": "^2.1.656",
225
+ "@djangocfg/i18n": "^2.1.656",
226
+ "@djangocfg/typescript-config": "^2.1.656",
227
227
  "@storybook/react-vite": "^10.6.5",
228
228
  "@types/node": "^24.13.3",
229
229
  "@types/react": "19.3.0",
@@ -8,8 +8,8 @@ export { useCanHover } from './useCanHover';
8
8
  export { useDisplayMode, useIsPwa } from './useDisplayMode';
9
9
  export { detectDisplayMode, syncDisplayModeAttribute } from './displayMode';
10
10
  export type { DisplayMode } from './displayMode';
11
- export { syncAppHeight, measureAppHeight } from './appHeight';
12
- export { syncScrollReset, resetShellScroll, settleShellScroll, clearStaleBodyLock, getResetLog } from './scrollReset';
13
- export type { ResetTrigger, ResetRecord } from './scrollReset';
14
- export { syncViewportDebug, viewportSnapshot, getViewportDebug, setViewportDebug, subscribeViewportDebug } from './viewportDebug';
11
+ export { syncViewport, remeasureViewport, getViewportLog } from './viewportSync';
12
+ export type { ViewportChange } from './viewportSync';
13
+ export type { HudState } from './viewportDebug';
14
+ export { syncViewportDebug, viewportSnapshot, getViewportHud, setViewportHud, subscribeViewportHud, nextViewportHud } from './viewportDebug';
15
15
  export { useBlockGestureZoom } from './useBlockGestureZoom';
@@ -1,39 +1,45 @@
1
1
  /**
2
- * Viewport HUD for chasing a displaced installed app. One way on: the Debug section of the Settings dialog
3
- * (`@djangocfg/layouts`, `builtins.debug`) flips `setViewportDebug`. The flag lives in `localStorage` (a failed read or
4
- * write degrades to "off" / "this page view only"); `syncViewportDebug` (mounted by `UiProviders`) draws the overlay
5
- * over the app while it is on, so the bug can be photographed outside the dialog. Off: nothing is drawn.
2
+ * Viewport HUD for chasing a displaced installed app. The state is one of `off`, `dot`, `small`, `medium`, `full`:
3
+ * - the Debug section of the Settings dialog (`@djangocfg/layouts`, `builtins.debug`) switches `off` <-> `small`;
4
+ * - tapping the HUD cycles small -> medium -> full -> dot; tapping the dot (24px, semi-transparent, in a corner) goes
5
+ * back to small. Only the HUD box and the dot take pointer events; the rest of the screen is untouched.
6
+ * - a host with no Settings dialog (a call page) passes `debug` to `UiProviders`: with nothing stored the state is `dot`.
7
+ * The state lives in `localStorage`, which is per origin (a failed read or write degrades to the default / this page view).
8
+ * `syncViewportDebug` (mounted by `UiProviders`) draws it over the app, so the bug can be photographed outside the dialog.
6
9
  */
7
10
 
8
11
  import { detectDisplayMode } from './displayMode';
9
- import { getResetLog, keyboardUp, locked, type ResetRecord } from './scrollReset';
12
+ import { getViewportLog, keyboardUp, locked, probeHeight } from './viewportSync';
10
13
 
11
14
  const KEY = 'viewportdebug';
12
15
 
13
- let memory = false;
16
+ export type HudState = 'off' | 'dot' | 'small' | 'medium' | 'full';
17
+ const STATES: readonly HudState[] = ['off', 'dot', 'small', 'medium', 'full'];
18
+
19
+ let memory: HudState | null = null;
14
20
  const listeners = new Set<() => void>();
15
21
 
16
- export function getViewportDebug(): boolean {
22
+ /** The stored state, else `fallback` (`dot` for a host that passed `debug`, otherwise `off`). */
23
+ export function getViewportHud(fallback: HudState = 'off'): HudState {
17
24
  try {
18
- const v = window.localStorage.getItem(KEY);
19
- if (v === '1' || v === '0') return v === '1';
25
+ const v = window.localStorage.getItem(KEY) as HudState | null;
26
+ return v && STATES.includes(v) ? v : fallback;
20
27
  } catch {
21
- /* storage blocked */
28
+ return memory ?? fallback; // storage blocked: this page view only
22
29
  }
23
- return memory;
24
30
  }
25
31
 
26
- export function setViewportDebug(on: boolean): void {
27
- memory = on;
32
+ export function setViewportHud(state: HudState): void {
33
+ memory = state;
28
34
  try {
29
- window.localStorage.setItem(KEY, on ? '1' : '0');
35
+ window.localStorage.setItem(KEY, state);
30
36
  } catch {
31
37
  /* private mode: kept for this page view */
32
38
  }
33
39
  listeners.forEach((l) => l());
34
40
  }
35
41
 
36
- export function subscribeViewportDebug(onChange: () => void): () => void {
42
+ export function subscribeViewportHud(onChange: () => void): () => void {
37
43
  listeners.add(onChange);
38
44
  window.addEventListener('storage', onChange);
39
45
  return () => {
@@ -42,35 +48,88 @@ export function subscribeViewportDebug(onChange: () => void): () => void {
42
48
  };
43
49
  }
44
50
 
51
+ /** One tap on the HUD: small -> medium -> full -> dot; one tap on the dot: small. */
52
+ export function nextViewportHud(state: HudState): HudState {
53
+ return ({ off: 'off', dot: 'small', small: 'medium', medium: 'full', full: 'dot' } as const)[state];
54
+ }
55
+
56
+ /** `env(safe-area-inset-*)` as the browser resolves it right now, read off a probe element. */
57
+ function safeInsets(): string {
58
+ const el = document.createElement('div');
59
+ el.style.cssText =
60
+ 'position:fixed;top:0;left:0;visibility:hidden;pointer-events:none;padding:env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left)';
61
+ document.body.appendChild(el);
62
+ const cs = getComputedStyle(el);
63
+ const out = [cs.paddingTop, cs.paddingRight, cs.paddingBottom, cs.paddingLeft].map((v) => parseFloat(v) || 0).join('/');
64
+ el.remove();
65
+ return out;
66
+ }
67
+
45
68
  const n = (v: number | undefined) => (v === undefined ? '-' : String(Math.round(v * 100) / 100));
46
69
 
47
- /** The text the HUD prints; pure over the live DOM so a test can read it. */
48
- export function viewportSnapshot(now: number = Date.now()): string {
70
+ function rectOf(el: Element | null): string {
71
+ if (!el) return 'none';
72
+ const r = el.getBoundingClientRect();
73
+ return `top ${n(r.top)} h ${n(r.height)}`;
74
+ }
75
+
76
+ function scrollOf(el: Element | null): string {
77
+ return el ? `top ${n(el.scrollTop)} sh ${n(el.scrollHeight)} ch ${n(el.clientHeight)}` : 'none';
78
+ }
79
+
80
+ export type HudLevel = 'small' | 'medium' | 'full';
81
+
82
+ /** The text the HUD prints at a level; pure over the live DOM so a test can read it. `full` is everything. */
83
+ export function viewportSnapshot(now: number = Date.now(), level: HudLevel = 'full'): string {
49
84
  const vv = window.visualViewport;
50
85
  const root = document.documentElement;
51
86
  const shell = document.querySelector<HTMLElement>('[data-app-shell]');
52
- const resets = getResetLog().map((r: ResetRecord) => `${((now - r.at) / 1000).toFixed(1)}s ago ${r.trigger}: ${r.what.join(', ')}`);
53
- return [
54
- `mode ${detectDisplayMode()} locked ${locked()} kbd ${keyboardUp()}`,
87
+ const bar = document.querySelector('[data-sidebar="topbar"]');
88
+ const appHeight = getComputedStyle(root).getPropertyValue('--app-height').trim() || '(unset)';
89
+ const ago = (at: number) => `${((now - at) / 1000).toFixed(1)}s ago`;
90
+ const changes = getViewportLog().map((c) => `${ago(c.at)} ${c.trigger}: ${c.what.join(', ')}`);
91
+ const mode = `mode ${detectDisplayMode()} locked ${locked()} kbd ${keyboardUp()}`;
92
+
93
+ if (level === 'small') {
94
+ return `${detectDisplayMode()} ih ${n(window.innerHeight)} app ${appHeight} sy ${n(window.scrollY)} shell ${shell ? n(shell.getBoundingClientRect().top) : '-'}`;
95
+ }
96
+ const core = [
97
+ mode,
55
98
  `scrollY ${n(window.scrollY)} shell.scrollTop ${shell ? n(shell.scrollTop) : 'no shell'}`,
56
- `innerHeight ${n(window.innerHeight)} --app-height ${getComputedStyle(root).getPropertyValue('--app-height').trim() || '(unset)'}`,
99
+ `innerHeight ${n(window.innerHeight)} --app-height ${appHeight}`,
57
100
  `vv h ${n(vv?.height)} top ${n(vv?.offsetTop)} scale ${n(vv?.scale)}`,
101
+ `shell ${rectOf(shell)}`,
102
+ `top bar ${rectOf(bar)}`,
103
+ ];
104
+ if (level === 'medium') {
105
+ return [...core, `last change: ${changes.at(-1) ?? '(none)'}`].join('\n');
106
+ }
107
+ return [
108
+ ...core,
109
+ `lvh ${n(probeHeight('lvh'))} dvh ${n(probeHeight('dvh'))} svh ${n(probeHeight('svh'))}`,
110
+ `screen.height ${n(window.screen?.height)} outerHeight ${n(window.outerHeight)}`,
111
+ `safe t/r/b/l ${safeInsets()}`,
112
+ `scrollingElement ${scrollOf(document.scrollingElement)}`,
113
+ `html ${scrollOf(root)} ${rectOf(root)}`,
114
+ `body ${scrollOf(document.body)} ${rectOf(document.body)}`,
58
115
  `body style: ${document.body.style.cssText || '(none)'}`,
59
116
  `body attr: ${document.body.hasAttribute('data-scroll-locked') ? 'data-scroll-locked' : '(none)'}`,
60
117
  `html style: ${root.style.cssText || '(none)'}`,
61
- `resets (last ${resets.length || 0}):`,
62
- ...(resets.length ? resets.map((r) => ` ${r}`) : [' (none)']),
118
+ `changes (last ${changes.length}):`,
119
+ ...(changes.length ? changes.map((c) => ` ${c}`) : [' (none)']),
63
120
  ].join('\n');
64
121
  }
65
122
 
66
- function mountHud(): () => void {
123
+ const BOX =
124
+ 'position:fixed;z-index:2147483647;margin:0;font:10px/1.35 ui-monospace,Menlo,monospace;white-space:pre-wrap;word-break:break-all;';
125
+
126
+ function mountHud(state: 'small' | 'medium' | 'full'): () => void {
67
127
  const hud = document.createElement('pre');
68
- hud.setAttribute('data-viewport-debug', '');
69
- hud.style.cssText =
70
- 'position:fixed;left:0;right:0;bottom:0;z-index:2147483647;margin:0;padding:6px 8px;pointer-events:none;' +
71
- 'font:10px/1.35 ui-monospace,Menlo,monospace;white-space:pre-wrap;word-break:break-all;color:#0f0;background:rgba(0,0,0,.82)';
128
+ hud.setAttribute('data-viewport-debug', state);
129
+ hud.style.cssText = `${BOX}left:0;right:0;bottom:0;padding:6px 8px;color:#0f0;background:rgba(0,0,0,.82);cursor:pointer`;
130
+ hud.addEventListener('click', () => setViewportHud(nextViewportHud(state)));
72
131
  const draw = () => {
73
- hud.textContent = viewportSnapshot();
132
+ hud.textContent = viewportSnapshot(Date.now(), state);
74
133
  };
75
134
  document.body.appendChild(hud);
76
135
  draw();
@@ -89,20 +148,29 @@ function mountHud(): () => void {
89
148
  };
90
149
  }
91
150
 
92
- /** Draws the HUD while the flag is on. Returns a cleanup. */
93
- export function syncViewportDebug(): () => void {
151
+ function mountDot(): () => void {
152
+ const dot = document.createElement('div');
153
+ dot.setAttribute('data-viewport-debug', 'dot');
154
+ dot.style.cssText = `${BOX}left:8px;bottom:calc(env(safe-area-inset-bottom,0px) + 8px);width:24px;height:24px;border-radius:50%;background:rgba(0,255,0,.35);cursor:pointer`;
155
+ dot.addEventListener('click', () => setViewportHud(nextViewportHud('dot')));
156
+ document.body.appendChild(dot);
157
+ return () => dot.remove();
158
+ }
159
+
160
+ /** Draws whatever the stored state says, and follows it. `debug` makes `dot` the default instead of `off`. Returns a cleanup. */
161
+ export function syncViewportDebug({ debug = false }: { debug?: boolean } = {}): () => void {
94
162
  if (typeof window === 'undefined' || typeof document === 'undefined') return () => {};
163
+ let shown: HudState = 'off';
95
164
  let unmount: (() => void) | null = null;
96
165
  const apply = () => {
97
- const on = getViewportDebug();
98
- if (on && !unmount) unmount = mountHud();
99
- else if (!on && unmount) {
100
- unmount();
101
- unmount = null;
102
- }
166
+ const state = getViewportHud(debug ? 'dot' : 'off');
167
+ if (state === shown) return;
168
+ unmount?.();
169
+ unmount = state === 'off' ? null : state === 'dot' ? mountDot() : mountHud(state);
170
+ shown = state;
103
171
  };
104
172
  apply();
105
- const stop = subscribeViewportDebug(apply);
173
+ const stop = subscribeViewportHud(apply);
106
174
  return () => {
107
175
  stop();
108
176
  unmount?.();
@@ -0,0 +1,194 @@
1
+ /**
2
+ * One hook for the installed app's viewport: `--app-height` and a shell that sits at scroll 0.
3
+ *
4
+ * Why it exists (all three are iOS standalone behaviours, see `@docs/PWA_AND_MOBILE.md`):
5
+ * 1. At launch `innerHeight`/`dvh` can be short by the top inset while `lvh` is right, so the shell height
6
+ * (`--app-height`) is the largest of `lvh`, `dvh`, `innerHeight`, capped at the screen.
7
+ * 2. The viewport can shrink for real with no keyboard (seen after an in-app browser sheet is closed: `innerHeight`
8
+ * 812 -> 771, `lvh` stayed 812). A larger `innerHeight` WAS seen earlier this session and it dropped, so `lvh` is not
9
+ * trusted any more and the height follows `max(innerHeight, dvh)` until `innerHeight` grows back.
10
+ * 3. A locked shell (`data-private-shell`, `overflow: hidden`) is still scrolled by the browser (a field lifted over the
11
+ * keyboard, a restored scroll position) and the reader cannot drag it back: window, html, body and the
12
+ * `[data-app-shell]` element are put back at 0.
13
+ *
14
+ * It does nothing outside an installed app, while the keyboard is up (it resizes the visual viewport, not the app) or on a
15
+ * pinch-zoomed page. Every trigger runs the same `settle`: now, and again after 300 ms, because iOS reports the final size
16
+ * late. A page-wide scroll is put back on the next frame.
17
+ */
18
+
19
+ import { detectDisplayMode, isInstalledMode, subscribeDisplayMode } from './displayMode';
20
+
21
+ const PROP = '--app-height';
22
+ const SHELL = '[data-app-shell]';
23
+ /** A drop of this many px below the largest `innerHeight` seen is a real shrink, not rounding or a bar animating. */
24
+ const SHRINK_PX = 8;
25
+ const SETTLE_MS = 300;
26
+ const LOG_SIZE = 5;
27
+
28
+ export interface ViewportChange {
29
+ at: number;
30
+ trigger: string;
31
+ /** What was changed, e.g. `--app-height 812 -> 771`, `shell 0,59`. */
32
+ what: string[];
33
+ }
34
+
35
+ const log: ViewportChange[] = [];
36
+
37
+ /** The last changes made (heights and scroll resets), oldest first, for the Debug HUD. */
38
+ export function getViewportLog(): readonly ViewportChange[] {
39
+ return log;
40
+ }
41
+
42
+ export function locked(): boolean {
43
+ return document.documentElement.hasAttribute('data-private-shell') && isInstalledMode(detectDisplayMode());
44
+ }
45
+
46
+ /** True while the keyboard (or any other inset) covers part of the layout viewport. */
47
+ export function keyboardUp(): boolean {
48
+ const vv = window.visualViewport;
49
+ return Boolean(vv) && window.innerHeight - vv!.height > 80;
50
+ }
51
+
52
+ function zoomed(): boolean {
53
+ return Boolean(window.visualViewport) && window.visualViewport!.scale > 1.01;
54
+ }
55
+
56
+ export function probeHeight(unit: 'lvh' | 'dvh' | 'svh'): number {
57
+ if (typeof CSS !== 'undefined' && CSS.supports && !CSS.supports('height', `100${unit}`)) return 0;
58
+ const el = document.createElement('div');
59
+ el.style.cssText = `position:fixed;top:0;left:0;width:0;height:100${unit};visibility:hidden;pointer-events:none`;
60
+ document.body.appendChild(el);
61
+ const h = el.getBoundingClientRect().height;
62
+ el.remove();
63
+ return h;
64
+ }
65
+
66
+ function capped(h: number): number {
67
+ const screenMax = Math.max(window.screen?.height || 0, window.screen?.width || 0);
68
+ return screenMax > 0 ? Math.min(h, screenMax) : h;
69
+ }
70
+
71
+ /** Puts window, html, body and the shell back at 0; returns what had to move. */
72
+ function zeroScroll(): string[] {
73
+ const what: string[] = [];
74
+ if (window.scrollX || window.scrollY) what.push(`window ${Math.round(window.scrollX)},${Math.round(window.scrollY)}`);
75
+ window.scrollTo(0, 0);
76
+ for (const [name, el] of [['html', document.documentElement], ['body', document.body]] as const) {
77
+ if (el.scrollTop) {
78
+ what.push(`${name} ${Math.round(el.scrollTop)}`);
79
+ el.scrollTop = 0;
80
+ }
81
+ }
82
+ for (const el of document.querySelectorAll<HTMLElement>(SHELL)) {
83
+ if (el.scrollTop || el.scrollLeft) {
84
+ what.push(`shell ${Math.round(el.scrollLeft)},${Math.round(el.scrollTop)}`);
85
+ el.scrollTop = 0;
86
+ el.scrollLeft = 0;
87
+ }
88
+ }
89
+ return what;
90
+ }
91
+
92
+ let remeasure: (() => string[]) | null = null;
93
+
94
+ /** The Debug section's "Re-measure now": runs the whole thing at once and returns what it changed. */
95
+ export function remeasureViewport(): string[] {
96
+ return remeasure?.() ?? [];
97
+ }
98
+
99
+ /** Installs every trigger. Returns a cleanup. */
100
+ export function syncViewport(): () => void {
101
+ if (typeof window === 'undefined' || typeof document === 'undefined') return () => {};
102
+ const root = document.documentElement;
103
+ let peakInner = 0;
104
+ let frame = 0;
105
+ const timers: number[] = [];
106
+
107
+ const run = (trigger: string): string[] => {
108
+ if (!isInstalledMode(detectDisplayMode())) {
109
+ root.style.removeProperty(PROP);
110
+ return [];
111
+ }
112
+ if (keyboardUp() || zoomed()) return [];
113
+ const what: string[] = [];
114
+ const inner = window.innerHeight;
115
+ peakInner = Math.max(peakInner, inner);
116
+ const h = peakInner - inner >= SHRINK_PX ? Math.max(inner, probeHeight('dvh')) : Math.max(probeHeight('lvh'), probeHeight('dvh'), inner);
117
+ const next = Math.round(capped(h));
118
+ const prev = parseFloat(root.style.getPropertyValue(PROP)) || null;
119
+ if (next > 0 && prev !== next) {
120
+ root.style.setProperty(PROP, `${next}px`);
121
+ what.push(`${PROP} ${prev ?? '-'} -> ${next}`);
122
+ }
123
+ if (locked()) what.push(...zeroScroll());
124
+ if (what.length) {
125
+ log.push({ at: Date.now(), trigger, what });
126
+ if (log.length > LOG_SIZE) log.shift();
127
+ }
128
+ return what;
129
+ };
130
+
131
+ const settle = (trigger: string) => {
132
+ run(trigger);
133
+ timers.push(window.setTimeout(() => run(trigger), SETTLE_MS));
134
+ };
135
+ remeasure = () => {
136
+ peakInner = 0; // a manual look trusts the viewport as it is now
137
+ return run('manual');
138
+ };
139
+
140
+ const onResize = () => settle('resize');
141
+ const onVisualViewport = () => settle('viewport-resize');
142
+ const onPageShow = () => settle('pageshow');
143
+ const onFocus = () => settle('focus');
144
+ const onFocusOut = () => settle('focusout');
145
+ const onOrientation = () => {
146
+ peakInner = 0; // landscape is not a shrink of portrait
147
+ settle('orientation');
148
+ };
149
+ const onVisible = () => {
150
+ if (document.visibilityState === 'visible') settle('visible');
151
+ };
152
+ // `scroll` does not bubble: the capture phase is how a scroll of the shell element is seen.
153
+ const onScroll = (event: Event) => {
154
+ const t = event.target;
155
+ if (frame || !(t === document || (t instanceof Element && t.matches(SHELL)))) return;
156
+ frame = window.requestAnimationFrame(() => {
157
+ frame = 0;
158
+ if (locked() && !keyboardUp() && !zoomed()) {
159
+ const what = zeroScroll();
160
+ if (what.length) {
161
+ log.push({ at: Date.now(), trigger: 'scroll', what });
162
+ if (log.length > LOG_SIZE) log.shift();
163
+ }
164
+ }
165
+ });
166
+ };
167
+
168
+ const vv = window.visualViewport;
169
+ const stopDisplay = subscribeDisplayMode(() => settle('display-mode'));
170
+ run('init');
171
+ window.addEventListener('resize', onResize);
172
+ vv?.addEventListener('resize', onVisualViewport);
173
+ window.addEventListener('pageshow', onPageShow);
174
+ window.addEventListener('focus', onFocus);
175
+ window.addEventListener('orientationchange', onOrientation);
176
+ document.addEventListener('focusout', onFocusOut);
177
+ document.addEventListener('visibilitychange', onVisible);
178
+ document.addEventListener('scroll', onScroll, { capture: true, passive: true });
179
+ return () => {
180
+ window.removeEventListener('resize', onResize);
181
+ vv?.removeEventListener('resize', onVisualViewport);
182
+ window.removeEventListener('pageshow', onPageShow);
183
+ window.removeEventListener('focus', onFocus);
184
+ window.removeEventListener('orientationchange', onOrientation);
185
+ document.removeEventListener('focusout', onFocusOut);
186
+ document.removeEventListener('visibilitychange', onVisible);
187
+ document.removeEventListener('scroll', onScroll, { capture: true });
188
+ stopDisplay();
189
+ if (frame) window.cancelAnimationFrame(frame);
190
+ timers.forEach((t) => window.clearTimeout(t));
191
+ remeasure = null;
192
+ root.style.removeProperty(PROP);
193
+ };
194
+ }
@@ -7,14 +7,18 @@ import { TooltipProvider } from '../components/overlay/tooltip';
7
7
  import { Toaster } from '../components/feedback/sonner';
8
8
  import { Boundary, type BoundaryProps } from '../components/boundary';
9
9
  import { syncDisplayModeAttribute } from '../hooks/media/displayMode';
10
- import { syncAppHeight } from '../hooks/media/appHeight';
11
- import { syncScrollReset } from '../hooks/media/scrollReset';
10
+ import { syncViewport } from '../hooks/media/viewportSync';
12
11
  import { syncViewportDebug } from '../hooks/media/viewportDebug';
13
12
  import { installChunkReloadListeners } from '../lib/chunk-reload';
14
13
  import { DialogProvider } from '../lib/dialog-service/DialogProvider';
15
14
 
16
15
  export interface UiProvidersProps {
17
16
  children: React.ReactNode;
17
+ /**
18
+ * Show the viewport diagnostic dot even when nobody turned the HUD on (a host with no Settings dialog: a call page).
19
+ * Tapping the dot opens the HUD; a state stored in `localStorage` still wins. @default false
20
+ */
21
+ debug?: boolean;
18
22
  /** Tooltip open delay in ms. @default 100 (snappy for desktop apps) */
19
23
  tooltipDelay?: number;
20
24
  /** Disable the Sonner toaster (e.g. when the host renders its own). */
@@ -80,6 +84,7 @@ export interface UiProvidersProps {
80
84
  */
81
85
  export function UiProviders({
82
86
  children,
87
+ debug = false,
83
88
  tooltipDelay = 100,
84
89
  noToaster,
85
90
  noDialogService,
@@ -91,12 +96,10 @@ export function UiProviders({
91
96
  React.useEffect(() => installChunkReloadListeners(), []);
92
97
  // `<html data-display-mode="browser|standalone|...">` for CSS (see styles/css/base.css tokens).
93
98
  React.useEffect(() => syncDisplayModeAttribute(), []);
94
- // `--app-height` measured in an installed app (iOS standalone reports dvh/100% short; see hooks/media/appHeight).
95
- React.useEffect(() => syncAppHeight(), []);
96
- // A locked app shell is scrolled by iOS to clear the keyboard and not scrolled back; put it back once the keyboard is down.
97
- React.useEffect(() => syncScrollReset(), []);
99
+ // Installed app viewport: `--app-height` and a shell at scroll 0 (see hooks/media/viewportSync).
100
+ React.useEffect(() => syncViewport(), []);
98
101
  // The Settings > Debug switch prints scroll, body/html style and viewport numbers on screen; off otherwise.
99
- React.useEffect(() => syncViewportDebug(), []);
102
+ React.useEffect(() => syncViewportDebug({ debug }), [debug]);
100
103
  // No SSR-skip on purpose: any nested library component that renders
101
104
  // `<Tooltip>` on its first paint expects to find `<TooltipProvider>`
102
105
  // already in the tree. Skipping the provider during SSR caused
@@ -204,7 +204,7 @@ html {
204
204
  }
205
205
 
206
206
  /* Installed app, first paint: iOS reports 100dvh short by the top inset with viewport-fit=cover, 100lvh is the full
207
- * screen. `syncAppHeight()` (UiProviders) then replaces this with the measured px value on <html>. */
207
+ * screen. `syncViewport()` (UiProviders) then replaces this with the measured px value on <html>. */
208
208
  @supports (height: 100lvh) {
209
209
  @media (display-mode: standalone), (display-mode: fullscreen) {
210
210
  :root { --app-height: 100lvh; }
@@ -1,69 +0,0 @@
1
- /**
2
- * `--app-height`: the real height of the app viewport, kept on `<html>`.
3
- *
4
- * Why it is measured: in an installed iOS app with `viewport-fit=cover` + a translucent status bar, WebKit reports
5
- * `100%`, `100svh` and `100dvh` as the screen height MINUS the top inset, so a shell sized from them stops short and
6
- * leaves a dead band at the bottom (and `overflow: hidden` clips the rest). `100lvh` and `window.innerHeight` are not
7
- * always right either, across iOS versions. So in an installed mode we take the largest of the candidates, capped at
8
- * the physical screen, and publish it as `--app-height`. In a browser tab the property is removed and the CSS default
9
- * (`100dvh`, see base.css) applies. The shell paints under the status bar and pads by `--safe-top` itself.
10
- */
11
-
12
- import { detectDisplayMode, isInstalledMode, subscribeDisplayMode } from './displayMode';
13
-
14
- const PROP = '--app-height';
15
-
16
- function probeHeight(unit: 'lvh' | 'dvh'): number {
17
- if (typeof CSS !== 'undefined' && CSS.supports && !CSS.supports('height', `100${unit}`)) return 0;
18
- const el = document.createElement('div');
19
- el.style.cssText = `position:fixed;top:0;left:0;width:0;height:100${unit};visibility:hidden;pointer-events:none`;
20
- document.body.appendChild(el);
21
- const h = el.getBoundingClientRect().height;
22
- el.remove();
23
- return h;
24
- }
25
-
26
- /** Largest plausible app height in px, or 0 when nothing could be measured. */
27
- export function measureAppHeight(): number {
28
- if (typeof document === 'undefined' || !document.body) return 0;
29
- const screenMax = Math.max(window.screen?.height || 0, window.screen?.width || 0);
30
- const candidates = [probeHeight('lvh'), probeHeight('dvh'), window.innerHeight].filter((n) => n > 0);
31
- if (!candidates.length) return 0;
32
- const best = Math.max(...candidates);
33
- return screenMax > 0 ? Math.min(best, screenMax) : best;
34
- }
35
-
36
- /** Keeps `--app-height` in step with the installed viewport. Returns a cleanup. */
37
- export function syncAppHeight(): () => void {
38
- if (typeof window === 'undefined' || typeof document === 'undefined') return () => {};
39
- const root = document.documentElement;
40
- const timers: number[] = [];
41
-
42
- const apply = () => {
43
- if (!isInstalledMode(detectDisplayMode())) {
44
- root.style.removeProperty(PROP);
45
- return;
46
- }
47
- const h = measureAppHeight();
48
- if (h > 0) root.style.setProperty(PROP, `${Math.round(h)}px`);
49
- };
50
- // iOS reports the new size a beat after `orientationchange`; re-measure once it settled.
51
- const applyLater = () => {
52
- apply();
53
- timers.push(window.setTimeout(apply, 120), window.setTimeout(apply, 400));
54
- };
55
-
56
- apply();
57
- window.addEventListener('resize', apply);
58
- window.addEventListener('orientationchange', applyLater);
59
- window.addEventListener('pageshow', apply);
60
- const unsubscribe = subscribeDisplayMode(apply);
61
- return () => {
62
- window.removeEventListener('resize', apply);
63
- window.removeEventListener('orientationchange', applyLater);
64
- window.removeEventListener('pageshow', apply);
65
- unsubscribe();
66
- timers.forEach((t) => window.clearTimeout(t));
67
- root.style.removeProperty(PROP);
68
- };
69
- }
@@ -1,206 +0,0 @@
1
- /**
2
- * Keeps a locked app shell at scroll 0, whatever moved it.
3
- *
4
- * Why: `PrivateLayout` locks the document (`overflow: hidden`, `data-private-shell`) and sizes itself from `--app-height`,
5
- * which in an installed iOS app is deliberately taller than `window.innerHeight` (see `appHeight.ts`). `overflow: hidden`
6
- * stops the finger, not the browser: iOS scrolls the layout viewport (and any clipped ancestor) to lift a focused field
7
- * over the keyboard, vaul's iOS scroll lock restores the `scrollY` it saw when the drawer opened, and WebKit can restore
8
- * scroll on a bfcache return. Nothing scrolls the shell back, and with the document locked the reader has nothing to drag:
9
- * the top bar is left above the screen.
10
- *
11
- * The reset is therefore independent of its trigger. While the shell is locked (installed mode + `data-private-shell`),
12
- * the keyboard is down and the page is not pinch-zoomed, ANY scroll of `window` or `[data-app-shell]` is put back to 0 on
13
- * the next frame (a capture-phase listener: `scroll` does not bubble). The other triggers (focus-out, visual viewport
14
- * resize, orientation, pageshow, tab visible, popstate, route change, an overlay closing) only make sure that a scroll
15
- * which fired no event, or fired while the keyboard was still up, is looked at again once things settled.
16
- *
17
- * Also removes a body scroll-lock left behind with no overlay open (see `clearStaleBodyLock`).
18
- * A pinch-zoomed page (`visualViewport.scale > 1`) is the reader's own offset and is never touched.
19
- */
20
-
21
- import { detectDisplayMode, isInstalledMode } from './displayMode';
22
-
23
- /** Elements that clip the shell and can be scrolled by focus although the reader cannot: `[data-app-shell]`. */
24
- const SHELL = '[data-app-shell]';
25
-
26
- /** Anything that legitimately holds a body scroll-lock: while one is mounted the lock is not stale. */
27
- const OVERLAY = '[role=dialog],[role=alertdialog],[role=menu],[role=listbox],[data-vaul-drawer],[data-radix-dialog-content]';
28
-
29
- /** Inline body properties vaul writes in `usePositionFixed` (`setPositionFixed`). */
30
- const VAUL_BODY_PROPS = ['position', 'top', 'left', 'right', 'height'] as const;
31
-
32
- /** react-remove-scroll marks the body with this attribute; its CSS (`overflow: hidden !important`) is keyed on it. */
33
- const SCROLL_LOCK_ATTR = 'data-scroll-locked';
34
-
35
- export type ResetTrigger =
36
- | 'scroll'
37
- | 'focusout'
38
- | 'viewport-resize'
39
- | 'orientation'
40
- | 'pageshow'
41
- | 'visible'
42
- | 'popstate'
43
- | 'route'
44
- | 'overlay-close'
45
- | 'manual';
46
-
47
- export interface ResetRecord {
48
- /** `Date.now()` of the reset. */
49
- at: number;
50
- trigger: ResetTrigger;
51
- /** What was put back, e.g. `window.scrollY 59`, `shell.scrollTop 59`, `body position:fixed`. */
52
- what: string[];
53
- }
54
-
55
- const LOG_SIZE = 5;
56
- const log: ResetRecord[] = [];
57
-
58
- /** The last resets that actually changed something, oldest first (for the `?viewportdebug=1` HUD). */
59
- export function getResetLog(): readonly ResetRecord[] {
60
- return log;
61
- }
62
-
63
- export function locked(): boolean {
64
- return document.documentElement.hasAttribute('data-private-shell') && isInstalledMode(detectDisplayMode());
65
- }
66
-
67
- function editable(el: Element | null): boolean {
68
- if (!el) return false;
69
- if (el instanceof HTMLElement && el.isContentEditable) return true;
70
- return el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement || (el instanceof HTMLInputElement && !/^(checkbox|radio|button|submit|reset|range|file|color|image)$/.test(el.type));
71
- }
72
-
73
- /** True while the keyboard (or any other inset) is covering part of the layout viewport. */
74
- export function keyboardUp(): boolean {
75
- const vv = window.visualViewport;
76
- return Boolean(vv) && window.innerHeight - vv!.height > 80;
77
- }
78
-
79
- function overlayOpen(): boolean {
80
- return document.querySelector(OVERLAY) !== null;
81
- }
82
-
83
- /**
84
- * Removes the body scroll-lock leftovers when no overlay is mounted. In the locked shell the lock is redundant (the
85
- * document is already `overflow: hidden`), so removing a stale one costs nothing and an inline `position: fixed` that
86
- * outlives its drawer is what displaces the whole page.
87
- * - vaul: inline `position: fixed !important; top: -Npx; left; right: 0; height: auto`, only in a Safari tab that is
88
- * not standalone (`setPositionFixed` bails out in `display-mode: standalone`), undone by its own cleanup.
89
- * - react-remove-scroll (Radix Dialog, modal menus): the `data-scroll-locked` attribute on `<body>`; the rest is a
90
- * stylesheet keyed on it, not inline style.
91
- */
92
- export function clearStaleBodyLock(): string[] {
93
- if (overlayOpen()) return [];
94
- const body = document.body;
95
- const what: string[] = [];
96
- if (body.style.position === 'fixed') {
97
- for (const prop of VAUL_BODY_PROPS) body.style.removeProperty(prop);
98
- what.push('body position:fixed');
99
- }
100
- if (body.hasAttribute(SCROLL_LOCK_ATTR)) {
101
- body.removeAttribute(SCROLL_LOCK_ATTR);
102
- what.push(`body ${SCROLL_LOCK_ATTR}`);
103
- }
104
- return what;
105
- }
106
-
107
- /** Puts a displaced shell back. Returns true when something had to be put back. */
108
- export function resetShellScroll(trigger: ResetTrigger = 'manual'): boolean {
109
- if (typeof window === 'undefined' || !locked() || keyboardUp()) return false;
110
- if (window.visualViewport && window.visualViewport.scale > 1.01) return false;
111
- const what = clearStaleBodyLock();
112
- if (window.scrollX || window.scrollY) {
113
- what.push(`window ${Math.round(window.scrollX)},${Math.round(window.scrollY)}`);
114
- window.scrollTo(0, 0);
115
- }
116
- for (const el of document.querySelectorAll<HTMLElement>(SHELL)) {
117
- if (el.scrollTop || el.scrollLeft) {
118
- what.push(`shell ${Math.round(el.scrollLeft)},${Math.round(el.scrollTop)}`);
119
- el.scrollTop = 0;
120
- el.scrollLeft = 0;
121
- }
122
- }
123
- if (!what.length) return false;
124
- log.push({ at: Date.now(), trigger, what });
125
- if (log.length > LOG_SIZE) log.shift();
126
- return true;
127
- }
128
-
129
- let timers: number[] = [];
130
-
131
- function clearTimers() {
132
- timers.forEach((t) => window.clearTimeout(t));
133
- timers = [];
134
- }
135
-
136
- /**
137
- * Resets now and again as things settle: the keyboard takes ~250-400ms to go down and iOS reports the final size late;
138
- * vaul's exit animation lasts 500ms and its cleanup scrolls to the position it saw at open.
139
- * Safe to call from a route change (`PrivateContent`) whether or not `syncScrollReset` is installed.
140
- */
141
- export function settleShellScroll(trigger: ResetTrigger, delays: readonly number[] = [150, 450]): void {
142
- if (typeof window === 'undefined') return;
143
- resetShellScroll(trigger);
144
- for (const ms of delays) timers.push(window.setTimeout(() => resetShellScroll(trigger), ms));
145
- }
146
-
147
- /** Installs every trigger. Returns a cleanup. */
148
- export function syncScrollReset(): () => void {
149
- if (typeof window === 'undefined' || typeof document === 'undefined') return () => {};
150
- const vv = window.visualViewport;
151
-
152
- let frame = 0;
153
- const onScroll = (event: Event) => {
154
- const t = event.target;
155
- // `scroll` fires on `document` for the window and does not bubble: the capture phase is how an element's is seen.
156
- const mine = t === document || (t instanceof Element && t.matches(SHELL));
157
- if (!mine || frame) return;
158
- frame = window.requestAnimationFrame(() => {
159
- frame = 0;
160
- resetShellScroll('scroll');
161
- });
162
- };
163
- const onFocusOut = (event: FocusEvent) => {
164
- if (editable(event.target as Element | null) && !editable(event.relatedTarget as Element | null)) settleShellScroll('focusout');
165
- };
166
- const onViewport = () => settleShellScroll('viewport-resize');
167
- const onOrientation = () => settleShellScroll('orientation');
168
- const onPageShow = () => settleShellScroll('pageshow');
169
- const onVisible = () => {
170
- if (document.visibilityState === 'visible') settleShellScroll('visible');
171
- };
172
- const onPopState = () => settleShellScroll('popstate');
173
-
174
- // A Radix Dialog / vaul Drawer portals into `<body>` and locks it through `<body>`'s own attributes: watching the body
175
- // (children + the two lock markers, not the subtree) sees every one close, including one unmounted by a navigation.
176
- let hadOverlay = overlayOpen();
177
- const observer = typeof MutationObserver === 'undefined' ? null : new MutationObserver(() => {
178
- const open = overlayOpen();
179
- const closed = hadOverlay && !open;
180
- hadOverlay = open;
181
- if (closed || (!open && (document.body.style.position === 'fixed' || document.body.hasAttribute(SCROLL_LOCK_ATTR)))) {
182
- settleShellScroll('overlay-close', [150, 450, 800]);
183
- }
184
- });
185
- observer?.observe(document.body, { childList: true, attributes: true, attributeFilter: ['style', SCROLL_LOCK_ATTR] });
186
-
187
- document.addEventListener('scroll', onScroll, { capture: true, passive: true });
188
- document.addEventListener('focusout', onFocusOut);
189
- document.addEventListener('visibilitychange', onVisible);
190
- vv?.addEventListener('resize', onViewport);
191
- window.addEventListener('orientationchange', onOrientation);
192
- window.addEventListener('pageshow', onPageShow);
193
- window.addEventListener('popstate', onPopState);
194
- return () => {
195
- document.removeEventListener('scroll', onScroll, { capture: true });
196
- document.removeEventListener('focusout', onFocusOut);
197
- document.removeEventListener('visibilitychange', onVisible);
198
- vv?.removeEventListener('resize', onViewport);
199
- window.removeEventListener('orientationchange', onOrientation);
200
- window.removeEventListener('pageshow', onPageShow);
201
- window.removeEventListener('popstate', onPopState);
202
- observer?.disconnect();
203
- if (frame) window.cancelAnimationFrame(frame);
204
- clearTimers();
205
- };
206
- }