@justai/core 0.43.1 → 0.45.0

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.
@@ -0,0 +1,28 @@
1
+ /**
2
+ * @justai/core/account — who is signed in, as the global shell asks it. One small contract with two
3
+ * implementations: the fleet's auth SDK (the default) and an app's own adapter.
4
+ *
5
+ * Part of the framework-free heart of the persona shell. See `./index.js` for what this package is.
6
+ */
7
+ /** What the shell shows of an account. */
8
+ export interface ShellAccount {
9
+ name: string | null;
10
+ email: string | null;
11
+ picture: string | null;
12
+ }
13
+ /** The contract between the global shell and wherever an app's account lives. */
14
+ export interface AccountAdapter {
15
+ read(): ShellAccount | null;
16
+ subscribe(onChange: () => void): () => void;
17
+ signIn(): void;
18
+ signOut?(): void;
19
+ open?(anchor: HTMLElement): void;
20
+ }
21
+ /** The default adapter: the fleet's auth SDK. */
22
+ export declare const sdkAccount: AccountAdapter;
23
+ /** Register the app's own account adapter (the header's `account="adapter"` mode reads it). */
24
+ export declare function setAccountAdapter(adapter: AccountAdapter | null): void;
25
+ /** The registered app adapter, or null. */
26
+ export declare function accountAdapter(): AccountAdapter | null;
27
+ /** Hear when an app adapter is registered or replaced. Returns the unsubscribe. */
28
+ export declare function onAccountAdapter(fn: () => void): () => void;
@@ -0,0 +1,84 @@
1
+ /**
2
+ * @justai/core/account — who is signed in, as the global shell asks it. One small contract with two
3
+ * implementations: the fleet's auth SDK (the default) and an app's own adapter.
4
+ *
5
+ * Part of the framework-free heart of the persona shell. See `./index.js` for what this package is.
6
+ */
7
+ const AUTH = "https://auth.justai.pro";
8
+ const here = () => location.origin + location.pathname + location.search;
9
+ const sdk = () => (typeof window !== "undefined" ? (window.justaiAuth ?? null) : null);
10
+ const SESSION_KEY = "justai_token";
11
+ const fromSession = () => {
12
+ try {
13
+ const tok = localStorage.getItem(SESSION_KEY);
14
+ if (!tok)
15
+ return null;
16
+ const b64 = tok.split(".")[1].replace(/-/g, "+").replace(/_/g, "/");
17
+ const p = JSON.parse(decodeURIComponent(escape(atob(b64))));
18
+ if (p.exp && p.exp * 1000 < Date.now())
19
+ return null;
20
+ return { name: p.name || null, email: p.email || null, picture: p.picture || null };
21
+ }
22
+ catch {
23
+ return null;
24
+ }
25
+ };
26
+ /** The default adapter: the fleet's auth SDK. */
27
+ export const sdkAccount = {
28
+ read() {
29
+ const s = sdk();
30
+ if (s && "user" in s) {
31
+ const u = s.user;
32
+ return u ? { name: u.name || null, email: u.email || null, picture: u.picture || null } : null;
33
+ }
34
+ return fromSession();
35
+ },
36
+ subscribe(onChange) {
37
+ const onStorage = (e) => { if (e.key === SESSION_KEY)
38
+ onChange(); };
39
+ addEventListener("storage", onStorage);
40
+ document.addEventListener("justai-auth", onChange);
41
+ return () => { removeEventListener("storage", onStorage); document.removeEventListener("justai-auth", onChange); };
42
+ },
43
+ signIn() {
44
+ const s = sdk();
45
+ if (s && typeof s.signIn === "function")
46
+ return s.signIn();
47
+ location.href = AUTH + "/?action=signin&return_url=" + encodeURIComponent(here());
48
+ },
49
+ signOut() {
50
+ const s = sdk();
51
+ if (s && typeof s.signOut === "function")
52
+ return s.signOut();
53
+ location.href = AUTH + "/?action=signout&return_url=" + encodeURIComponent(here());
54
+ },
55
+ };
56
+ // ── THE APP'S ADAPTER ─────────────────────────────────────────────────────────────────────────────
57
+ // Registered on globalThis for the same reason the surfaces registry is: an app chunk and the header's
58
+ // chunk may each bundle their own copy of this module.
59
+ const REGISTRY = "__justaiAccount";
60
+ const registry = () => {
61
+ const g = globalThis;
62
+ return g[REGISTRY] || (g[REGISTRY] = { adapter: null, waiting: new Set() });
63
+ };
64
+ /** Register the app's own account adapter (the header's `account="adapter"` mode reads it). */
65
+ export function setAccountAdapter(adapter) {
66
+ const r = registry();
67
+ r.adapter = adapter;
68
+ for (const fn of [...r.waiting]) {
69
+ try {
70
+ fn();
71
+ }
72
+ catch { /* one listener is not the registry */ }
73
+ }
74
+ }
75
+ /** The registered app adapter, or null. */
76
+ export function accountAdapter() {
77
+ return registry().adapter;
78
+ }
79
+ /** Hear when an app adapter is registered or replaced. Returns the unsubscribe. */
80
+ export function onAccountAdapter(fn) {
81
+ const r = registry();
82
+ r.waiting.add(fn);
83
+ return () => { r.waiting.delete(fn); };
84
+ }
package/dist/index.d.ts CHANGED
@@ -31,6 +31,8 @@
31
31
  * ./chrome Cancel and Done, in thirteen languages
32
32
  * ./presentation standalone, or inside somebody else's sheet
33
33
  * ./scroll landing on the kernel, and the spy
34
+ * ./surfaces the kernel as the document, the profile and the posts as layers (opt-in)
35
+ * ./account who is signed in, as the global shell asks it (the SDK, or an app's adapter)
34
36
  * ./mark the persona's mark, and adopting a host's
35
37
  * ./face a host persona's face, for a child mounted on it
36
38
  * ./random a fair random integer, pick, sample and shuffle — crypto.getRandomValues only
@@ -57,5 +59,7 @@ export * from "./consent.js";
57
59
  export * from "./chrome.js";
58
60
  export * from "./presentation.js";
59
61
  export * from "./scroll.js";
62
+ export * from "./surfaces.js";
63
+ export * from "./account.js";
60
64
  export * from "./mark.js";
61
65
  export * from "./face.js";
package/dist/index.js CHANGED
@@ -31,6 +31,8 @@
31
31
  * ./chrome Cancel and Done, in thirteen languages
32
32
  * ./presentation standalone, or inside somebody else's sheet
33
33
  * ./scroll landing on the kernel, and the spy
34
+ * ./surfaces the kernel as the document, the profile and the posts as layers (opt-in)
35
+ * ./account who is signed in, as the global shell asks it (the SDK, or an app's adapter)
34
36
  * ./mark the persona's mark, and adopting a host's
35
37
  * ./face a host persona's face, for a child mounted on it
36
38
  * ./random a fair random integer, pick, sample and shuffle — crypto.getRandomValues only
@@ -57,5 +59,7 @@ export * from "./consent.js";
57
59
  export * from "./chrome.js";
58
60
  export * from "./presentation.js";
59
61
  export * from "./scroll.js";
62
+ export * from "./surfaces.js";
63
+ export * from "./account.js";
60
64
  export * from "./mark.js";
61
65
  export * from "./face.js";
package/dist/mark.d.ts CHANGED
@@ -11,6 +11,13 @@ export declare function toolbarMark(iconSvg: string, options?: {
11
11
  fills?: number;
12
12
  /** How many pixels of INK the surface wants, default 20 — the toolbar row's rule. */
13
13
  ink?: number;
14
+ /**
15
+ * `"ink"` (default): the figure's paint becomes `currentColor` — the golden rule below.
16
+ * `"own"`: the figure keeps its own paint (its gradients, re-pointed to this copy's ids). For the
17
+ * LIT copy a shell shows while its cut is current, when the persona's mark is lit in its own colours
18
+ * (Shell R1, 2026-11-19) — the same picture a persona used to rebuild by re-pointing from its CSS.
19
+ */
20
+ paint?: "ink" | "own";
14
21
  }): string;
15
22
  export declare function adoptMark(options?: {
16
23
  /** The element holding the host's `<img>`. Defaults to `#navParent`. */
package/dist/mark.js CHANGED
@@ -100,7 +100,7 @@ export function toolbarMark(iconSvg, options) {
100
100
  // Only the PAINT is neutralised, and only outside `<defs>`: the gradients stay defined, so a
101
101
  // persona that wants its own colours *while current* can re-point to them from its own CSS. qr
102
102
  // does. That is a decision about what the accent looks like, never about when it appears.
103
- {
103
+ if (o.paint !== "own") {
104
104
  const cut = s.lastIndexOf("</defs>");
105
105
  const head = cut >= 0 ? s.slice(0, cut + 7) : "";
106
106
  const body = (cut >= 0 ? s.slice(cut + 7) : s)
@@ -0,0 +1,64 @@
1
+ /**
2
+ * @justai/core/surfaces — the persona page's three SURFACES, entered only on purpose. The kernel is
3
+ * the workspace; the profile and the posts are revealed by an explicit act and leave the flow again
4
+ * once the visitor is back in the kernel. It knows the three cut ids, the toolbar and the history, and
5
+ * nothing about which framework drew them.
6
+ *
7
+ * Part of the framework-free heart of the persona shell. See `./index.js` for what this package is
8
+ * and why its behaviour lives one level below @justai/cuts.
9
+ */
10
+ /** The three surfaces. The kernel is the default workspace; the other two are revealed on purpose. */
11
+ export type Surface = "kernel" | "profile" | "posts";
12
+ /**
13
+ * The history-state keys this behaviour writes. NAMESPACED and MERGED rather than owned: an app may
14
+ * keep its own state on the same entry, and replacing the whole object would be the shell clobbering
15
+ * the app — the very thing the hash rule below exists to prevent.
16
+ */
17
+ export declare const SURFACE_STATE = "justaiSurface";
18
+ /**
19
+ * Which surface a location asks for. Pure — the one decision the boot script, the behaviour and the
20
+ * tests all make, so it is written once and reachable on its own.
21
+ *
22
+ * A shell fragment wins (it is an explicit address); then the surface remembered on this history
23
+ * entry (a reload, or a layer opened over an app's own fragment); then the kernel. `has` says which
24
+ * layers the page actually carries — a `#posts` on a persona with no stream is the kernel.
25
+ */
26
+ export declare function surfaceFor(hash: string, state: unknown, has?: (s: Surface) => boolean): Surface;
27
+ /** True for the fragments this behaviour owns — the only ones it ever reads as an address or rewrites. */
28
+ export declare function isShellFragment(hash: string): boolean;
29
+ export declare function surfaceBoot(): void;
30
+ /** The boot as an injectable IIFE — derived from {@link surfaceBoot}, never written twice. */
31
+ export declare const SURFACE_BOOT_JS: string;
32
+ /** The global shell's two modes: the Golden row over the kernel, or a document's own workspace. */
33
+ export type ShellMode = "app" | "document";
34
+ /** Called after a surface change, once the new surface is current and reachable. */
35
+ export type SurfaceListener = (now: Surface, from: Surface) => void;
36
+ /** The event the same change is announced as, on `document` (`detail: { surface, from }`). */
37
+ export declare const SURFACE_EVENT = "justai-surface";
38
+ /** The current surface, or `null` on a page that has not opted into the surfaces contract. */
39
+ export declare function currentSurface(): Surface | null;
40
+ /** True while the kernel is current — and on a page without surfaces, where there is nothing else. */
41
+ export declare function inKernel(): boolean;
42
+ /** Subscribe to surface changes. Returns the unsubscribe. */
43
+ export declare function onSurfaceChange(listener: SurfaceListener): () => void;
44
+ /**
45
+ * Bring the kernel back — the row's own trip home — and resolve once it is current and reachable
46
+ * (not inert, not covered). Resolves at once when it already is, or when the page has no surfaces.
47
+ */
48
+ export declare function toKernel(): Promise<void>;
49
+ /** The global shell's current mode. */
50
+ export declare function shellMode(): ShellMode;
51
+ /**
52
+ * Enter or leave Shell R1's document mode. Entering brings the kernel back first; the returned promise
53
+ * resolves once the mode is in force. On a page without surfaces it only sets the mode.
54
+ */
55
+ export declare function setShellMode(mode: ShellMode): Promise<void>;
56
+ export interface PersonaSurfacesOptions {
57
+ /** The bar that sticks over the kernel. Default `.toolbar`; pdf-edit's face passes `.fbar`. */
58
+ toolbar?: string | HTMLElement | null;
59
+ /** Maps a surface to its nav's id. Default `profile` → `navProfile`. */
60
+ navFor?: (s: Surface) => string;
61
+ /** Whether this owns `body.ready`. Pass `false` on a page that reveals itself. */
62
+ reveal?: boolean;
63
+ }
64
+ export declare function personaSurfaces(options?: PersonaSurfacesOptions): void;
@@ -0,0 +1,689 @@
1
+ /**
2
+ * @justai/core/surfaces — the persona page's three SURFACES, entered only on purpose. The kernel is
3
+ * the workspace; the profile and the posts are revealed by an explicit act and leave the flow again
4
+ * once the visitor is back in the kernel. It knows the three cut ids, the toolbar and the history, and
5
+ * nothing about which framework drew them.
6
+ *
7
+ * Part of the framework-free heart of the persona shell. See `./index.js` for what this package is
8
+ * and why its behaviour lives one level below @justai/cuts.
9
+ */
10
+ /**
11
+ * The history-state keys this behaviour writes. NAMESPACED and MERGED rather than owned: an app may
12
+ * keep its own state on the same entry, and replacing the whole object would be the shell clobbering
13
+ * the app — the very thing the hash rule below exists to prevent.
14
+ */
15
+ export const SURFACE_STATE = "justaiSurface";
16
+ const FROM_STATE = "justaiSurfaceFrom";
17
+ // queries: hash ownership · #device · #file= · #handoff= · the shell rewrote my hash · app-owned
18
+ // fragment · connect deep link lost
19
+ //
20
+ // ── THE SHELL OWNS THREE FRAGMENTS AND NO OTHERS ────────────────────────────────────────────────
21
+ //
22
+ // `#profile`, `#posts`, and `#kernel` (legacy — the spy wrote it for a year, and old links and the
23
+ // children's way back still carry it). Every other fragment belongs to the app: Connect routes its
24
+ // views on `#device/<id>/<feature>`, `/files` hands a file over as `#file=`, name-picker receives
25
+ // `#handoff=`. The spy rewrote all of them to `#kernel` on its first frame, which is why three of
26
+ // those apps capture their fragment in the head before the shell can see it. This never writes over
27
+ // a fragment it does not own.
28
+ /**
29
+ * Which surface a location asks for. Pure — the one decision the boot script, the behaviour and the
30
+ * tests all make, so it is written once and reachable on its own.
31
+ *
32
+ * A shell fragment wins (it is an explicit address); then the surface remembered on this history
33
+ * entry (a reload, or a layer opened over an app's own fragment); then the kernel. `has` says which
34
+ * layers the page actually carries — a `#posts` on a persona with no stream is the kernel.
35
+ */
36
+ export function surfaceFor(hash, state, has = () => true) {
37
+ if (hash === "#profile" && has("profile"))
38
+ return "profile";
39
+ if (hash === "#posts" && has("posts"))
40
+ return "posts";
41
+ if (hash === "#profile" || hash === "#posts" || hash === "#kernel")
42
+ return "kernel";
43
+ const kept = state && typeof state === "object" ? state[SURFACE_STATE] : null;
44
+ if ((kept === "profile" || kept === "posts") && has(kept))
45
+ return kept;
46
+ return "kernel";
47
+ }
48
+ /** True for the fragments this behaviour owns — the only ones it ever reads as an address or rewrites. */
49
+ export function isShellFragment(hash) {
50
+ return hash === "#profile" || hash === "#posts" || hash === "#kernel";
51
+ }
52
+ // queries: the profile flashes before the kernel · data-surface is set late · surface boot ·
53
+ // SURFACE_BOOT_JS · head script
54
+ //
55
+ // ── THE SURFACE IS DECIDED IN THE HEAD, BEFORE THE FIRST PAINT ──────────────────────────────────
56
+ //
57
+ // The CSS that takes the profile and the posts out of the flow keys on `html[data-reveal]`. Written
58
+ // by the module script it would arrive after the first paint, and a reload at `#posts` would show
59
+ // the kernel for a frame and then swap. So the attribute is written by an inline script in the head,
60
+ // synchronously — it is also the opt-in itself: a persona that does not render this has no
61
+ // `data-surface`, and every rule and behaviour of this module stays out of its way.
62
+ //
63
+ // It cannot import `surfaceFor` (an inline script closes over nothing), so the same decision is
64
+ // spelled out here in its smallest form; the behaviour then re-asks with the page in hand, and a
65
+ // layer the page turns out not to carry falls back to the kernel there. The unit specs hold the two
66
+ // to the same answers.
67
+ export function surfaceBoot() {
68
+ try {
69
+ const h = location.hash;
70
+ let s = "kernel";
71
+ if (h === "#profile" || h === "#posts")
72
+ s = h.slice(1);
73
+ else if (h !== "#kernel") {
74
+ const st = history.state;
75
+ const kept = st && typeof st === "object" ? st.justaiSurface : null;
76
+ if (kept === "profile" || kept === "posts")
77
+ s = kept;
78
+ }
79
+ document.documentElement.setAttribute("data-surface", s);
80
+ document.documentElement.setAttribute("data-reveal", s === "kernel" ? "" : s);
81
+ document.documentElement.setAttribute("data-cover", s === "posts" ? "posts" : "");
82
+ }
83
+ catch (e) {
84
+ document.documentElement.setAttribute("data-surface", "kernel");
85
+ document.documentElement.setAttribute("data-reveal", "");
86
+ }
87
+ }
88
+ /** The boot as an injectable IIFE — derived from {@link surfaceBoot}, never written twice. */
89
+ export const SURFACE_BOOT_JS = "(" + surfaceBoot.toString() + ")();";
90
+ /** The event the same change is announced as, on `document` (`detail: { surface, from }`). */
91
+ export const SURFACE_EVENT = "justai-surface";
92
+ const REGISTRY = "__justaiSurfaces";
93
+ const registry = () => {
94
+ const g = globalThis;
95
+ return g[REGISTRY] || (g[REGISTRY] = { ctl: null, listeners: new Set(), mode: "app" });
96
+ };
97
+ const tell = (now, from) => {
98
+ for (const fn of [...registry().listeners]) {
99
+ try {
100
+ fn(now, from);
101
+ }
102
+ catch { /* one listener's error is not the shell's */ }
103
+ }
104
+ try {
105
+ document.dispatchEvent(new CustomEvent(SURFACE_EVENT, { detail: { surface: now, from } }));
106
+ }
107
+ catch { /* no DOM, no event */ }
108
+ };
109
+ /** The current surface, or `null` on a page that has not opted into the surfaces contract. */
110
+ export function currentSurface() {
111
+ const c = registry().ctl;
112
+ if (c)
113
+ return c.current();
114
+ if (typeof document === "undefined")
115
+ return null;
116
+ const a = document.documentElement.getAttribute("data-surface");
117
+ return a === "kernel" || a === "profile" || a === "posts" ? a : null;
118
+ }
119
+ /** True while the kernel is current — and on a page without surfaces, where there is nothing else. */
120
+ export function inKernel() {
121
+ const s = currentSurface();
122
+ return s === null || s === "kernel";
123
+ }
124
+ /** Subscribe to surface changes. Returns the unsubscribe. */
125
+ export function onSurfaceChange(listener) {
126
+ const r = registry();
127
+ r.listeners.add(listener);
128
+ return () => { r.listeners.delete(listener); };
129
+ }
130
+ /**
131
+ * Bring the kernel back — the row's own trip home — and resolve once it is current and reachable
132
+ * (not inert, not covered). Resolves at once when it already is, or when the page has no surfaces.
133
+ */
134
+ export function toKernel() {
135
+ const c = registry().ctl;
136
+ if (!c || c.current() === "kernel")
137
+ return Promise.resolve();
138
+ return new Promise((done) => {
139
+ let finished = false;
140
+ const finish = () => { if (finished)
141
+ return; finished = true; off(); clearTimeout(guard); done(); };
142
+ const off = onSurfaceChange((now) => { if (now === "kernel")
143
+ finish(); });
144
+ // The trip home goes Back over the shell's own entry; a Back the browser never delivers (a page
145
+ // opened at #posts has no entry under it to go back to) must not leave the caller waiting.
146
+ const guard = setTimeout(() => { if (c.current() !== "kernel")
147
+ c.land(); finish(); }, 900);
148
+ c.go("kernel");
149
+ });
150
+ }
151
+ /** The global shell's current mode. */
152
+ export function shellMode() {
153
+ return registry().mode;
154
+ }
155
+ /**
156
+ * Enter or leave Shell R1's document mode. Entering brings the kernel back first; the returned promise
157
+ * resolves once the mode is in force. On a page without surfaces it only sets the mode.
158
+ */
159
+ export async function setShellMode(mode) {
160
+ if (mode === "document")
161
+ await toKernel();
162
+ const r = registry();
163
+ r.mode = mode;
164
+ if (typeof document === "undefined")
165
+ return;
166
+ const root = document.documentElement;
167
+ if (mode === "document")
168
+ root.setAttribute("data-shell-mode", "document");
169
+ else
170
+ root.removeAttribute("data-shell-mode");
171
+ // the bar comes back at its own height; anything measuring it (the kernel's floor) hears a resize
172
+ if (mode === "app")
173
+ requestAnimationFrame(() => dispatchEvent(new Event("resize")));
174
+ }
175
+ /** The history-state key a teardown leaves on the entry it replaced in place (see R2.1 above). */
176
+ const DUP_STATE = "justaiSurfaceDup";
177
+ export function personaSurfaces(options) {
178
+ const o = options || {};
179
+ const root = document.documentElement;
180
+ const kernel = document.getElementById("kernel");
181
+ if (!kernel)
182
+ return;
183
+ const below = document.getElementById("below");
184
+ const profile = document.getElementById("profile");
185
+ const posts = document.getElementById("posts");
186
+ const sectionOf = (s) => (s === "kernel" ? kernel : s === "profile" ? profile : posts);
187
+ const has = (s) => Boolean(sectionOf(s));
188
+ const navOf = (s) => document.getElementById(o.navFor ? o.navFor(s) : "nav" + s.charAt(0).toUpperCase() + s.slice(1));
189
+ const toolbar = typeof o.toolbar === "string" ? document.querySelector(o.toolbar) : o.toolbar || document.querySelector(".toolbar");
190
+ // THE BAR IS MEASURED, as in ./scroll: the posts open under it and an app kernel's floor reads it.
191
+ const measureShell = () => {
192
+ if (!toolbar)
193
+ return;
194
+ const h = Math.ceil(toolbar.getBoundingClientRect().height);
195
+ if (h > 0)
196
+ root.style.setProperty("--shell-top", h + "px");
197
+ };
198
+ measureShell();
199
+ addEventListener("resize", measureShell, { passive: true });
200
+ if (document.fonts && document.fonts.ready)
201
+ document.fonts.ready.then(measureShell);
202
+ const shellTop = () => (toolbar ? toolbar.getBoundingClientRect().height : 0);
203
+ // The page decides where it is; the browser must not "restore" a scroll position into it.
204
+ if ("scrollRestoration" in history)
205
+ history.scrollRestoration = "manual";
206
+ const reduced = () => typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
207
+ // ── GEOMETRY, IN THE ONE VOCABULARY EVERY MOVE USES ────────────────────────────────────────────
208
+ // The kernel RESTS at the top of `#below`, where the bar sticks. With the profile out of the flow that
209
+ // is 0; with it revealed, the profile's height. `kernelY` is how far into the kernel the visitor had
210
+ // scrolled, kept relative to that rest, so it survives the profile coming and going above it.
211
+ // Read off the KERNEL itself (its top less the bar), not off `#below`: a revealed profile now sits
212
+ // inside `#below`, between the bar and the kernel (see THE PROFILE SITS UNDER THE BAR below).
213
+ // The kernel rests one shell GAP under the bar, not against it (@justai/ui `--shell-gap`, 2026-11-03):
214
+ // read from the kernel's own top margin, so a kernel that takes none (a game, an art piece) rests flush.
215
+ const shellGap = () => parseFloat(getComputedStyle(kernel).marginTop) || 0;
216
+ const restY = () => kernel.getBoundingClientRect().top - shellTop() - shellGap() + window.scrollY;
217
+ // Whole pixels: WebKit keeps scroll positions as integers and truncates (700 → 699 per round trip).
218
+ const jump = (top) => window.scrollTo({ top: Math.round(top), behavior: "instant" });
219
+ let kernelY = 0;
220
+ // ── PRESENTATION ───────────────────────────────────────────────────────────────────────────────
221
+ // One write per attribute per change, and none when nothing changed: an attribute on <html> restyles
222
+ // the whole document, and the teardown used to write the same value three times.
223
+ const setAttr = (name, value) => { if (root.getAttribute(name) !== value)
224
+ root.setAttribute(name, value); };
225
+ const shown = new Set();
226
+ const writeReveal = () => setAttr("data-reveal", [...shown].join(" "));
227
+ // The profile sits ABOVE the kernel, so bringing it in or out moves everything under it by its height.
228
+ // The target is ABSOLUTE — the position read before the change plus the difference — so Chromium's
229
+ // scroll anchoring and WebKit's lack of it land on the same pixel.
230
+ // queries: the toolbar jumps when the posts open from the profile · toolbar under the profile ·
231
+ // sticky toolbar loses the top · profile above the bar
232
+ //
233
+ // ── THE PROFILE SITS UNDER THE BAR (R2.1, owner's physical finding) ─────────────────────────────
234
+ //
235
+ // In every persona's markup the profile comes BEFORE `#below`, the box the bar sticks within, so a
236
+ // profile revealed in place put the bar under it: measured at 390×844, the bar at y=376 while the
237
+ // profile showed. The push to the posts then moved the profile and the kernel around a bar hanging
238
+ // mid-screen, and when the profile left the flow `#below` rose to the top and the bar jumped 376 → 0.
239
+ // The bar must be the one fixed reference on screen. So while it is revealed the profile is MOVED into
240
+ // `#below`, right after the bar's slot — the bar is then the topmost thing in the box it sticks within,
241
+ // flush at the top from the first frame to the last, and everything moves under it — and goes back to
242
+ // its own place in the markup when it leaves (out of the flow by then, so the move costs no layout).
243
+ const profileHome = profile ? { parent: profile.parentElement, next: profile.nextSibling } : null;
244
+ const barSlot = below && toolbar ? Array.from(below.children).find((el) => el.contains(toolbar)) ?? null : null;
245
+ const seatProfile = (underBar) => {
246
+ if (!profile || !below || !barSlot || !profileHome?.parent)
247
+ return;
248
+ if (underBar) {
249
+ if (profile.parentElement !== below)
250
+ below.insertBefore(profile, barSlot.nextSibling);
251
+ }
252
+ else if (profile.parentElement !== profileHome.parent)
253
+ profileHome.parent.insertBefore(profile, profileHome.next);
254
+ };
255
+ const showProfile = () => {
256
+ if (shown.has("profile") || !profile)
257
+ return;
258
+ seatProfile(true);
259
+ const y0 = window.scrollY, r0 = restY();
260
+ shown.add("profile");
261
+ writeReveal();
262
+ jump(y0 + (restY() - r0));
263
+ };
264
+ const hideProfile = () => {
265
+ if (!shown.has("profile"))
266
+ return;
267
+ const y0 = window.scrollY, r0 = restY();
268
+ shown.delete("profile");
269
+ writeReveal();
270
+ jump(Math.max(0, y0 - (r0 - restY())));
271
+ seatProfile(false);
272
+ };
273
+ // Out of sight = wholly under the bar.
274
+ const profileOutOfSight = () => !!profile && profile.getBoundingClientRect().bottom <= shellTop() + 1;
275
+ // POSTS: a layer over the kernel (surfaces.css) — but it must not FEEL like one (owner, R2.1 option A).
276
+ // queries: posts transition · the posts slide over the app like a drawer · push transition · page
277
+ // moves up with the posts · posts motion curve
278
+ //
279
+ // The trip is a PUSH, the way a page scrolls: as the stream rises from the bottom of the screen, the
280
+ // page above it — the kernel, and the profile if it is showing; never the bar — rises with it by the
281
+ // same distance on the same curve, so the visitor reads one long page moving down. The way back is the
282
+ // exact reverse. Nothing fades, scales, springs or overshoots.
283
+ //
284
+ // THE CURVE IS THE GLIDE'S, MEASURED. The profile's trip is the browser's own smooth scroll; sampled
285
+ // frame by frame (Chromium and WebKit, 350–1400px) it starts slow, is 36% there at a quarter, 81% at
286
+ // half and 96% at three quarters — cubic-bezier(0.35, 0, 0.10, 1) to within 1%. The duration follows
287
+ // the distance as the browser's does (≈350ms for a phone's screen); a page that turned it into a
288
+ // panel's motion would be the drawer the owner rejected.
289
+ const PUSH_EASING = "cubic-bezier(0.35, 0, 0.10, 1)";
290
+ const pushDuration = (d) => Math.round(Math.min(520, Math.max(240, 180 + 0.22 * d)));
291
+ // What moves with the page: every block beside the kernel under the bar (the kernel itself, and a
292
+ // persona's own section between it and the stream), plus the profile when it is in the flow — never
293
+ // the bar's slot, never the stream.
294
+ const movers = () => {
295
+ const list = [];
296
+ if (profile && shown.has("profile"))
297
+ list.push(profile);
298
+ const parent = kernel.parentElement;
299
+ const kids = parent ? Array.from(parent.children) : [kernel];
300
+ for (const el of kids) {
301
+ if (el === posts || el === profile || (toolbar && el.contains(toolbar)))
302
+ continue;
303
+ list.push(el);
304
+ }
305
+ return list;
306
+ };
307
+ let motion = [];
308
+ // THE SEAM IS CLOSED BY CONSTRUCTION. The stream and the page are separate animations; WebKit can run
309
+ // them a frame-fraction apart (measured: up to 6px, one frame in three runs), and a strip of ground
310
+ // between them would read as two things. For the length of the trip the stream carries 16px of its own
311
+ // ground above its top edge — over the page's edge, which it covers anyway, and under the bar.
312
+ const SEAM = 16;
313
+ const stopMotion = () => {
314
+ for (const a of motion)
315
+ a.cancel();
316
+ motion = [];
317
+ if (posts)
318
+ posts.style.removeProperty("box-shadow");
319
+ };
320
+ const pushMotion = (dir, atEnd, beforeFirstFrame) => {
321
+ stopMotion();
322
+ if (!posts || reduced() || typeof posts.animate !== "function") {
323
+ beforeFirstFrame?.();
324
+ atEnd();
325
+ return;
326
+ }
327
+ const d = Math.round(posts.getBoundingClientRect().height || innerHeight - shellTop());
328
+ const opts = { duration: pushDuration(d), easing: PUSH_EASING, fill: "both" };
329
+ const down = `translateY(${d}px)`, up = `translateY(${-d}px)`, home = "translateY(0)";
330
+ const into = dir === "in";
331
+ const ground = getComputedStyle(posts).backgroundColor;
332
+ if (ground && ground !== "rgba(0, 0, 0, 0)" && ground !== "transparent")
333
+ posts.style.setProperty("box-shadow", `0 -${SEAM}px 0 ${ground}`);
334
+ const all = [posts.animate(into ? [{ transform: down }, { transform: home }] : [{ transform: home }, { transform: down }], opts)];
335
+ for (const el of movers())
336
+ all.push(el.animate(into ? [{ transform: home }, { transform: up }] : [{ transform: up }, { transform: home }], opts));
337
+ motion = all;
338
+ // The animations hold their first frame from now (fill: both), so whatever the caller changes here —
339
+ // uncovering the kernel on the way back — is painted already in place, never for a frame at rest.
340
+ beforeFirstFrame?.();
341
+ const mine = all;
342
+ all[0].onfinish = () => {
343
+ if (motion !== mine)
344
+ return;
345
+ atEnd(); // the caller covers or removes FIRST, while every frame still holds its end
346
+ stopMotion(); // and only then do the transforms go — nothing is ever seen jumping back
347
+ };
348
+ };
349
+ const showPosts = (covered) => {
350
+ if (!posts || shown.has("posts"))
351
+ return;
352
+ shown.add("posts");
353
+ writeReveal();
354
+ posts.scrollTop = 0;
355
+ pushMotion("in", () => { if (current === "posts") {
356
+ setAttr("data-cover", "posts");
357
+ covered?.();
358
+ } });
359
+ };
360
+ const hidePosts = (then) => {
361
+ if (!shown.has("posts")) {
362
+ then?.();
363
+ return;
364
+ }
365
+ pushMotion("out", () => { if (current !== "posts") {
366
+ shown.delete("posts");
367
+ writeReveal();
368
+ } then?.(); }, () => setAttr("data-cover", ""));
369
+ };
370
+ // ── STATE: WHAT THE ROW SAYS ───────────────────────────────────────────────────────────────────
371
+ let current = "kernel";
372
+ const paint = (s) => {
373
+ setAttr("data-surface", s);
374
+ for (const id of ["kernel", "profile", "posts"]) {
375
+ const nav = navOf(id);
376
+ if (!nav)
377
+ continue;
378
+ nav.classList.toggle("active", id === s);
379
+ if (id === s)
380
+ nav.setAttribute("aria-current", "page");
381
+ else
382
+ nav.removeAttribute("aria-current");
383
+ }
384
+ // Under the posts the kernel is behind a layer: alive and laid out, but not reachable.
385
+ kernel.inert = s === "posts";
386
+ };
387
+ toolbar?.classList.add("stuck");
388
+ // ── THE GLIDE: THE PROFILE'S EXPLICIT TRIP, ANIMATED BY SCROLLING ──────────────────────────────
389
+ let moving = 0;
390
+ const glide = (top) => new Promise((done) => {
391
+ const me = ++moving;
392
+ window.scrollTo({ top: Math.max(0, Math.round(top)), behavior: reduced() ? "instant" : "smooth" });
393
+ let last = NaN, still = 0;
394
+ const t0 = performance.now();
395
+ const tick = () => {
396
+ if (me !== moving)
397
+ return done();
398
+ const y = window.scrollY;
399
+ still = Math.abs(y - last) < 0.5 ? still + 1 : 0;
400
+ last = y;
401
+ if (still >= 3 || performance.now() - t0 > 2000) {
402
+ moving = 0;
403
+ done();
404
+ settle();
405
+ }
406
+ else
407
+ requestAnimationFrame(tick);
408
+ };
409
+ requestAnimationFrame(tick);
410
+ });
411
+ // ── SETTLE: WHAT THE PAGE IS, NOW THAT IT HAS STOPPED ─────────────────────────────────────────
412
+ // 1. A current profile the visitor has scrolled wholly out of sight has been LEFT (R2.1: in place —
413
+ // the entry is replaced, never gone back over).
414
+ // 2. While the kernel is current the profile is not in the flow, whatever the trip back managed.
415
+ // The posts are never decided here: no scroll ever leaves them.
416
+ const settle = () => {
417
+ if (moving)
418
+ return;
419
+ if (current === "profile" && profileOutOfSight())
420
+ leaveProfile();
421
+ if (current !== "profile" && shown.has("profile") && (current === "kernel" || profileOutOfSight()))
422
+ hideProfile();
423
+ if (current === "kernel")
424
+ kernelY = Math.max(0, window.scrollY - restY());
425
+ };
426
+ let idle = 0;
427
+ window.addEventListener("scroll", () => {
428
+ if (moving)
429
+ return;
430
+ clearTimeout(idle);
431
+ idle = window.setTimeout(settle, 180);
432
+ }, { passive: true });
433
+ // ── HISTORY ────────────────────────────────────────────────────────────────────────────────────
434
+ // The toolbar's trips carry the surface on the history entry and leave the address alone — the URL a
435
+ // visitor sees (and an app's own fragment) never changes for a trip. `#profile`/`#posts` are still
436
+ // honoured as addresses when a page is OPENED at one, and then tidied into the entry the same way.
437
+ const stateObj = () => {
438
+ const s = history.state;
439
+ return s && typeof s === "object" ? { ...s } : {};
440
+ };
441
+ const here = () => location.pathname + location.search + (isShellFragment(location.hash) ? "" : location.hash);
442
+ let lastState = history.state;
443
+ let lastHref = location.href;
444
+ const push = (st) => { history.pushState(st, "", here()); lastState = history.state; lastHref = location.href; };
445
+ const replace = (st) => { history.replaceState(st, "", here()); lastState = history.state; lastHref = location.href; };
446
+ const kernelState = (dup) => {
447
+ const st = stateObj();
448
+ delete st[SURFACE_STATE];
449
+ delete st[FROM_STATE];
450
+ if (dup)
451
+ st[DUP_STATE] = 1;
452
+ else
453
+ delete st[DUP_STATE];
454
+ return st;
455
+ };
456
+ let opener = null;
457
+ let keyboard = false;
458
+ const focusInto = (l) => {
459
+ if (!keyboard)
460
+ return;
461
+ const el = sectionOf(l);
462
+ if (!el.hasAttribute("tabindex"))
463
+ el.setAttribute("tabindex", "-1");
464
+ el.focus({ preventScroll: true });
465
+ };
466
+ // ── THE TRANSITIONS ────────────────────────────────────────────────────────────────────────────
467
+ const apply = (next) => {
468
+ if (!has(next))
469
+ next = "kernel";
470
+ if (next === current) {
471
+ paint(next);
472
+ return;
473
+ }
474
+ const from = current;
475
+ if (from === "kernel")
476
+ kernelY = Math.max(0, window.scrollY - restY());
477
+ current = next;
478
+ paint(next);
479
+ if (next === "profile") {
480
+ if (shown.has("posts")) {
481
+ // queries: posts → profile stops at the kernel · two motions · pauses half way
482
+ // ONE TRIP, THE EXACT REVERSE OF profile → posts. It used to be two: the stream pushed down to
483
+ // the kernel, came to rest, and only then did the profile glide in from above — the owner saw it
484
+ // stop at the kernel and carry on. Now, while the stream still covers the screen (so nothing of
485
+ // this is seen), the profile is seated under the bar and the page put at its top; then one push
486
+ // brings the profile and the kernel down together as the stream leaves below.
487
+ if (profile) {
488
+ seatProfile(true);
489
+ if (!shown.has("profile")) {
490
+ shown.add("profile");
491
+ writeReveal();
492
+ }
493
+ jump(0);
494
+ }
495
+ hidePosts(() => focusInto("profile"));
496
+ }
497
+ else {
498
+ showProfile();
499
+ void glide(0);
500
+ focusInto("profile");
501
+ }
502
+ }
503
+ else if (next === "posts") {
504
+ // A profile left above the kernel goes the moment the stream covers it — out of sight, in the
505
+ // push's own last frame, so nothing is seen to move.
506
+ showPosts(() => { if (shown.has("profile")) {
507
+ hideProfile();
508
+ jump(restY() + kernelY);
509
+ } });
510
+ focusInto("posts");
511
+ }
512
+ else {
513
+ const back = keyboard && opener && opener.isConnected ? opener : null;
514
+ opener = null;
515
+ if (shown.has("posts"))
516
+ hidePosts(() => { if (current === "kernel")
517
+ jump(restY() + kernelY); });
518
+ if (shown.has("profile"))
519
+ void glide(restY() + kernelY);
520
+ back?.focus({ preventScroll: true });
521
+ }
522
+ keyboard = false;
523
+ // the new surface is current and reachable now (inert and cover are already written): say so
524
+ tell(next, from);
525
+ };
526
+ // Leaving the profile by scrolling out of it: in place. The entry the trip pushed becomes a kernel
527
+ // entry marked as a duplicate; nothing navigates, the address does not move.
528
+ const leaveProfile = () => {
529
+ const st = stateObj();
530
+ const ours = st[SURFACE_STATE] === "profile" && st[FROM_STATE] === "kernel";
531
+ current = "kernel";
532
+ paint("kernel");
533
+ replace(kernelState(ours));
534
+ tell("kernel", "profile");
535
+ };
536
+ // ── THE FIRST SURFACE ─────────────────────────────────────────────────────────────────────────
537
+ {
538
+ const first = surfaceFor(location.hash, history.state, has);
539
+ // An address the page was opened at (`#profile`, `#posts`, legacy `#kernel`) is honoured and then
540
+ // tidied into the entry, so a later teardown has no address to change.
541
+ if (isShellFragment(location.hash)) {
542
+ const st = stateObj();
543
+ if (first === "kernel") {
544
+ delete st[SURFACE_STATE];
545
+ }
546
+ else
547
+ st[SURFACE_STATE] = first;
548
+ replace(st);
549
+ }
550
+ current = first;
551
+ if (first !== "kernel")
552
+ shown.add(first);
553
+ if (first === "profile")
554
+ seatProfile(true);
555
+ writeReveal();
556
+ setAttr("data-cover", first === "posts" ? "posts" : "");
557
+ paint(first);
558
+ if (first === "profile") {
559
+ jump(0);
560
+ requestAnimationFrame(() => { if (current === "profile")
561
+ jump(0); });
562
+ }
563
+ }
564
+ // ── EXPLICIT NAVIGATION ───────────────────────────────────────────────────────────────────────
565
+ // kernel → a layer PUSHES one entry, so Back returns to the kernel; layer ↔ layer REPLACES it; a
566
+ // layer → kernel from the row goes BACK over that entry when it was this page's own push — an explicit
567
+ // trip home, the same as the visitor's own Back — and replaces otherwise. Only the profile's teardown
568
+ // by scrolling replaces in place (R2.1): that one is not a navigation, so it must not look like one.
569
+ const go = (to) => {
570
+ if (!has(to))
571
+ to = "kernel";
572
+ if (to === current) {
573
+ if (to === "profile")
574
+ void glide(0);
575
+ else if (to === "posts" && posts)
576
+ posts.scrollTo({ top: 0, behavior: reduced() ? "instant" : "smooth" });
577
+ keyboard = false;
578
+ return;
579
+ }
580
+ const st = stateObj();
581
+ delete st[DUP_STATE];
582
+ if (current === "kernel") {
583
+ push({ ...st, [SURFACE_STATE]: to, [FROM_STATE]: "kernel" });
584
+ apply(to);
585
+ }
586
+ else if (to !== "kernel") {
587
+ replace({ ...st, [SURFACE_STATE]: to });
588
+ apply(to);
589
+ }
590
+ else if (st[FROM_STATE] === "kernel")
591
+ history.back(); // popstate takes it home
592
+ else {
593
+ replace(kernelState(false));
594
+ apply("kernel");
595
+ }
596
+ };
597
+ // the lifecycle API's handle on this page (see THE LIFECYCLE above). `land` is the trip home without a
598
+ // traversal — for a Back the browser could not deliver.
599
+ registry().ctl = {
600
+ current: () => current,
601
+ go: (to) => go(to),
602
+ land: () => { if (current !== "kernel") {
603
+ replace(kernelState(false));
604
+ apply("kernel");
605
+ } },
606
+ };
607
+ const documentMode = () => registry().mode === "document";
608
+ document.addEventListener("click", (e) => {
609
+ if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey)
610
+ return;
611
+ const target = e.target instanceof Element ? e.target : null;
612
+ const a = target ? target.closest('a[href^="#"]') : null;
613
+ if (!a)
614
+ return;
615
+ const href = a.getAttribute("href") || "";
616
+ if (!isShellFragment(href))
617
+ return;
618
+ e.preventDefault();
619
+ // a document's workspace has the screen: the shell's fragments open nothing until it closes
620
+ if (documentMode())
621
+ return;
622
+ // `detail` is the click count: 0 for an activation that came from the keyboard (Enter on a link) or
623
+ // assistive technology, never for a pointer or a finger.
624
+ keyboard = e.detail === 0;
625
+ const to = href.slice(1);
626
+ if (to !== "kernel" && current === "kernel")
627
+ opener = a;
628
+ go(to);
629
+ });
630
+ // Back and Forward. A Back that arrives on a kernel entry FROM a teardown's duplicate steps once more,
631
+ // so the visitor's Back always does something they can see.
632
+ // queries: back from the profile did nothing · a dead back press · connect route undone by back
633
+ //
634
+ // The step-over applies to a TRAVERSAL from the duplicate onto the entry it shadows — same address,
635
+ // since a trip never changes the address. An app's own new fragment (Connect's `#device/…`) arrives
636
+ // with a different address and is never stepped over.
637
+ const sync = () => {
638
+ const was = lastState;
639
+ const sameAddress = location.href === lastHref;
640
+ lastState = history.state;
641
+ lastHref = location.href;
642
+ let s = surfaceFor(location.hash, history.state, has);
643
+ // In document mode no surface can be shown (the shell is hidden): a Back or Forward onto a surface's
644
+ // entry lands on the kernel instead, and the entry is told so — nothing opens out of sight.
645
+ if (documentMode() && s !== "kernel") {
646
+ replace(kernelState(false));
647
+ s = "kernel";
648
+ }
649
+ if (isShellFragment(location.hash)) {
650
+ const st = stateObj();
651
+ if (s === "kernel")
652
+ delete st[SURFACE_STATE];
653
+ else
654
+ st[SURFACE_STATE] = s;
655
+ replace(st);
656
+ }
657
+ const now = stateObj();
658
+ // Several teardowns can leave several duplicates in a row; each Back steps over every one of them.
659
+ if (s === "kernel" && current === "kernel" && sameAddress && was && typeof was === "object" && was[DUP_STATE] && !now[SURFACE_STATE]) {
660
+ history.back();
661
+ return;
662
+ }
663
+ apply(s); // `keyboard` stays as the row/Escape set it: their trip home arrives here via history.back()
664
+ };
665
+ window.addEventListener("popstate", sync);
666
+ window.addEventListener("hashchange", () => { if (isShellFragment(location.hash))
667
+ sync(); });
668
+ const somethingOpen = () => {
669
+ if (document.querySelector("dialog[open]"))
670
+ return true;
671
+ try {
672
+ return Boolean(document.querySelector(":popover-open"));
673
+ }
674
+ catch {
675
+ return false;
676
+ }
677
+ };
678
+ document.addEventListener("keydown", (e) => {
679
+ if (e.key !== "Escape" || current === "kernel" || e.defaultPrevented || somethingOpen() || documentMode())
680
+ return;
681
+ keyboard = true;
682
+ go("kernel");
683
+ });
684
+ if (o.reveal !== false) {
685
+ const reveal = () => document.body.classList.add("ready");
686
+ requestAnimationFrame(reveal);
687
+ setTimeout(reveal, 500);
688
+ }
689
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@justai/core",
3
- "version": "0.43.1",
3
+ "version": "0.45.0",
4
4
  "description": "The framework-free heart of the persona shell — the load-bearing behaviour (auth capture, reveal, ready) as plain strings, so Astro and Next inject the SAME logic instead of each re-writing it.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -45,6 +45,14 @@
45
45
  "types": "./dist/scroll.d.ts",
46
46
  "default": "./dist/scroll.js"
47
47
  },
48
+ "./surfaces": {
49
+ "types": "./dist/surfaces.d.ts",
50
+ "default": "./dist/surfaces.js"
51
+ },
52
+ "./account": {
53
+ "types": "./dist/account.d.ts",
54
+ "default": "./dist/account.js"
55
+ },
48
56
  "./mark": {
49
57
  "types": "./dist/mark.d.ts",
50
58
  "default": "./dist/mark.js"