@djangocfg/ui-core 2.1.651 → 2.1.653

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.651",
3
+ "version": "2.1.653",
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.651",
148
- "@djangocfg/i18n": "^2.1.651",
147
+ "@djangocfg/api": "^2.1.653",
148
+ "@djangocfg/i18n": "^2.1.653",
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.651",
224
- "@djangocfg/eslint-config": "^2.1.651",
225
- "@djangocfg/i18n": "^2.1.651",
226
- "@djangocfg/typescript-config": "^2.1.651",
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",
227
227
  "@storybook/react-vite": "^10.6.5",
228
228
  "@types/node": "^24.13.3",
229
229
  "@types/react": "19.3.0",
@@ -9,5 +9,7 @@ export { useDisplayMode, useIsPwa } from './useDisplayMode';
9
9
  export { detectDisplayMode, syncDisplayModeAttribute } from './displayMode';
10
10
  export type { DisplayMode } from './displayMode';
11
11
  export { syncAppHeight, measureAppHeight } from './appHeight';
12
- export { syncScrollReset, resetShellScroll } from './scrollReset';
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';
13
15
  export { useBlockGestureZoom } from './useBlockGestureZoom';
@@ -1,12 +1,20 @@
1
1
  /**
2
- * Brings a locked app shell back to scroll 0 once the on-screen keyboard is gone.
2
+ * Keeps a locked app shell at scroll 0, whatever moved it.
3
3
  *
4
4
  * Why: `PrivateLayout` locks the document (`overflow: hidden`, `data-private-shell`) and sizes itself from `--app-height`,
5
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: focusing a field makes iOS scroll the layout viewport (and any clipped ancestor) so
7
- * the field clears the keyboard, and after the keyboard closes it does not scroll back. The top bar is then left above
8
- * the screen with nothing the reader can drag to reach it. While the keyboard is up the offset is how iOS shows the
9
- * field, so it is left alone; once it is down (focus left a field, or the visual viewport is whole again) it is reset.
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`).
10
18
  * A pinch-zoomed page (`visualViewport.scale > 1`) is the reader's own offset and is never touched.
11
19
  */
12
20
 
@@ -15,7 +23,44 @@ import { detectDisplayMode, isInstalledMode } from './displayMode';
15
23
  /** Elements that clip the shell and can be scrolled by focus although the reader cannot: `[data-app-shell]`. */
16
24
  const SHELL = '[data-app-shell]';
17
25
 
18
- function locked(): boolean {
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 {
19
64
  return document.documentElement.hasAttribute('data-private-shell') && isInstalledMode(detectDisplayMode());
20
65
  }
21
66
 
@@ -26,41 +71,136 @@ function editable(el: Element | null): boolean {
26
71
  }
27
72
 
28
73
  /** True while the keyboard (or any other inset) is covering part of the layout viewport. */
29
- function keyboardUp(): boolean {
74
+ export function keyboardUp(): boolean {
30
75
  const vv = window.visualViewport;
31
76
  return Boolean(vv) && window.innerHeight - vv!.height > 80;
32
77
  }
33
78
 
34
- export function resetShellScroll(): void {
35
- if (!locked() || keyboardUp()) return;
36
- if (window.visualViewport && window.visualViewport.scale > 1.01) return;
37
- if (window.scrollX || window.scrollY) window.scrollTo(0, 0);
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
+ }
38
116
  for (const el of document.querySelectorAll<HTMLElement>(SHELL)) {
39
- if (el.scrollTop) el.scrollTop = 0;
40
- if (el.scrollLeft) el.scrollLeft = 0;
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
+ }
41
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));
42
145
  }
43
146
 
44
- /** Installs the reset on focus-out and on visual-viewport changes. Returns a cleanup. */
147
+ /** Installs every trigger. Returns a cleanup. */
45
148
  export function syncScrollReset(): () => void {
46
149
  if (typeof window === 'undefined' || typeof document === 'undefined') return () => {};
47
- const timers: number[] = [];
48
- // The keyboard takes ~250-400ms to go down and iOS reports the final size late: look again as it settles.
49
- const settle = () => {
50
- resetShellScroll();
51
- timers.push(window.setTimeout(resetShellScroll, 150), window.setTimeout(resetShellScroll, 450));
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
+ });
52
162
  };
53
163
  const onFocusOut = (event: FocusEvent) => {
54
- if (editable(event.target as Element | null) && !editable(event.relatedTarget as Element | null)) settle();
164
+ if (editable(event.target as Element | null) && !editable(event.relatedTarget as Element | null)) settleShellScroll('focusout');
55
165
  };
56
- const vv = window.visualViewport;
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 });
57
188
  document.addEventListener('focusout', onFocusOut);
58
- vv?.addEventListener('resize', settle);
59
- window.addEventListener('orientationchange', settle);
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);
60
194
  return () => {
195
+ document.removeEventListener('scroll', onScroll, { capture: true });
61
196
  document.removeEventListener('focusout', onFocusOut);
62
- vv?.removeEventListener('resize', settle);
63
- window.removeEventListener('orientationchange', settle);
64
- timers.forEach((t) => window.clearTimeout(t));
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();
65
205
  };
66
206
  }
@@ -0,0 +1,110 @@
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.
6
+ */
7
+
8
+ import { detectDisplayMode } from './displayMode';
9
+ import { getResetLog, keyboardUp, locked, type ResetRecord } from './scrollReset';
10
+
11
+ const KEY = 'viewportdebug';
12
+
13
+ let memory = false;
14
+ const listeners = new Set<() => void>();
15
+
16
+ export function getViewportDebug(): boolean {
17
+ try {
18
+ const v = window.localStorage.getItem(KEY);
19
+ if (v === '1' || v === '0') return v === '1';
20
+ } catch {
21
+ /* storage blocked */
22
+ }
23
+ return memory;
24
+ }
25
+
26
+ export function setViewportDebug(on: boolean): void {
27
+ memory = on;
28
+ try {
29
+ window.localStorage.setItem(KEY, on ? '1' : '0');
30
+ } catch {
31
+ /* private mode: kept for this page view */
32
+ }
33
+ listeners.forEach((l) => l());
34
+ }
35
+
36
+ export function subscribeViewportDebug(onChange: () => void): () => void {
37
+ listeners.add(onChange);
38
+ window.addEventListener('storage', onChange);
39
+ return () => {
40
+ listeners.delete(onChange);
41
+ window.removeEventListener('storage', onChange);
42
+ };
43
+ }
44
+
45
+ const n = (v: number | undefined) => (v === undefined ? '-' : String(Math.round(v * 100) / 100));
46
+
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 {
49
+ const vv = window.visualViewport;
50
+ const root = document.documentElement;
51
+ 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()}`,
55
+ `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)'}`,
57
+ `vv h ${n(vv?.height)} top ${n(vv?.offsetTop)} scale ${n(vv?.scale)}`,
58
+ `body style: ${document.body.style.cssText || '(none)'}`,
59
+ `body attr: ${document.body.hasAttribute('data-scroll-locked') ? 'data-scroll-locked' : '(none)'}`,
60
+ `html style: ${root.style.cssText || '(none)'}`,
61
+ `resets (last ${resets.length || 0}):`,
62
+ ...(resets.length ? resets.map((r) => ` ${r}`) : [' (none)']),
63
+ ].join('\n');
64
+ }
65
+
66
+ function mountHud(): () => void {
67
+ 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)';
72
+ const draw = () => {
73
+ hud.textContent = viewportSnapshot();
74
+ };
75
+ document.body.appendChild(hud);
76
+ draw();
77
+ const id = window.setInterval(draw, 400);
78
+ window.addEventListener('scroll', draw, true);
79
+ window.addEventListener('resize', draw);
80
+ window.visualViewport?.addEventListener('resize', draw);
81
+ window.visualViewport?.addEventListener('scroll', draw);
82
+ return () => {
83
+ window.clearInterval(id);
84
+ window.removeEventListener('scroll', draw, true);
85
+ window.removeEventListener('resize', draw);
86
+ window.visualViewport?.removeEventListener('resize', draw);
87
+ window.visualViewport?.removeEventListener('scroll', draw);
88
+ hud.remove();
89
+ };
90
+ }
91
+
92
+ /** Draws the HUD while the flag is on. Returns a cleanup. */
93
+ export function syncViewportDebug(): () => void {
94
+ if (typeof window === 'undefined' || typeof document === 'undefined') return () => {};
95
+ let unmount: (() => void) | null = null;
96
+ const apply = () => {
97
+ const on = getViewportDebug();
98
+ if (on && !unmount) unmount = mountHud();
99
+ else if (!on && unmount) {
100
+ unmount();
101
+ unmount = null;
102
+ }
103
+ };
104
+ apply();
105
+ const stop = subscribeViewportDebug(apply);
106
+ return () => {
107
+ stop();
108
+ unmount?.();
109
+ };
110
+ }
@@ -9,6 +9,7 @@ import { Boundary, type BoundaryProps } from '../components/boundary';
9
9
  import { syncDisplayModeAttribute } from '../hooks/media/displayMode';
10
10
  import { syncAppHeight } from '../hooks/media/appHeight';
11
11
  import { syncScrollReset } from '../hooks/media/scrollReset';
12
+ import { syncViewportDebug } from '../hooks/media/viewportDebug';
12
13
  import { installChunkReloadListeners } from '../lib/chunk-reload';
13
14
  import { DialogProvider } from '../lib/dialog-service/DialogProvider';
14
15
 
@@ -94,6 +95,8 @@ export function UiProviders({
94
95
  React.useEffect(() => syncAppHeight(), []);
95
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.
96
97
  React.useEffect(() => syncScrollReset(), []);
98
+ // The Settings > Debug switch prints scroll, body/html style and viewport numbers on screen; off otherwise.
99
+ React.useEffect(() => syncViewportDebug(), []);
97
100
  // No SSR-skip on purpose: any nested library component that renders
98
101
  // `<Tooltip>` on its first paint expects to find `<TooltipProvider>`
99
102
  // already in the tree. Skipping the provider during SSR caused