@hadoku/task-ui-components 4.22.0 → 4.22.1

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.
@@ -183,6 +183,11 @@
183
183
  * has something to grow into now that its basis is 0. */
184
184
  flex: 1 1 auto;
185
185
  min-width: 0;
186
+ flex-wrap: wrap;
187
+ }
188
+ /* A refused rename's reason, on its own line under the input. */
189
+ .settings-popout__inline > .settings-popout__error {
190
+ flex-basis: 100%;
186
191
  }
187
192
 
188
193
  .settings-popout__tier {
@@ -1 +1 @@
1
- {"version":3,"file":"ConnectedSettings.d.ts","sourceRoot":"","sources":["../../src/components/ConnectedSettings.tsx"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,OAAO,KAAmD,MAAM,OAAO,CAAA;AAEvE,OAAO,EAWL,KAAK,IAAI,EACV,MAAM,uBAAuB,CAAA;AAC9B,OAAO,mBAAmB,CAAA;AAE1B,MAAM,WAAW,sBAAsB;IACrC;;;;;;+EAM2E;IAC3E,QAAQ,CAAC,EAAE,IAAI,CAAA;IACf,uEAAuE;IACvE,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACpB,mEAAmE;IACnE,YAAY,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,KAAK,IAAI,CAAA;IAC5C;;;;;;8BAM0B;IAC1B,QAAQ,CAAC,EAAE,KAAK,CAAC,SAAS,CAAA;CAC3B;AA0ED,wBAAgB,iBAAiB,CAAC,EAChC,QAAQ,EAAE,YAAY,EACtB,IAAI,EAAE,QAAQ,EACd,YAAY,EACZ,QAAQ,EACT,EAAE,sBAAsB,qBAqnBxB"}
1
+ {"version":3,"file":"ConnectedSettings.d.ts","sourceRoot":"","sources":["../../src/components/ConnectedSettings.tsx"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,OAAO,KAAmD,MAAM,OAAO,CAAA;AAEvE,OAAO,EAWL,KAAK,IAAI,EACV,MAAM,uBAAuB,CAAA;AAC9B,OAAO,mBAAmB,CAAA;AAE1B,MAAM,WAAW,sBAAsB;IACrC;;;;;;+EAM2E;IAC3E,QAAQ,CAAC,EAAE,IAAI,CAAA;IACf,uEAAuE;IACvE,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACpB,mEAAmE;IACnE,YAAY,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,KAAK,IAAI,CAAA;IAC5C;;;;;;8BAM0B;IAC1B,QAAQ,CAAC,EAAE,KAAK,CAAC,SAAS,CAAA;CAC3B;AA0ED,wBAAgB,iBAAiB,CAAC,EAChC,QAAQ,EAAE,YAAY,EACtB,IAAI,EAAE,QAAQ,EACd,YAAY,EACZ,QAAQ,EACT,EAAE,sBAAsB,qBAyoBxB"}
@@ -68,6 +68,7 @@ function ConnectedSettings({
68
68
  const [nameDraft, setNameDraft] = useState(resolvedName ?? "");
69
69
  const [editingName, setEditingName] = useState(false);
70
70
  const [nameSaving, setNameSaving] = useState(false);
71
+ const [nameError, setNameError] = useState(null);
71
72
  const [displayName, setLocalName] = useState(resolvedName);
72
73
  const [keyFormOpen, setKeyFormOpen] = useState(false);
73
74
  const [keyDraft, setKeyDraft] = useState("");
@@ -131,13 +132,16 @@ function ConnectedSettings({
131
132
  return;
132
133
  }
133
134
  setNameSaving(true);
134
- const stored = await setDisplayName(trimmed);
135
+ const result = await setDisplayName(trimmed);
135
136
  setNameSaving(false);
136
- if (stored !== null) {
137
- setLocalName(stored);
138
- setNameDraft(stored);
139
- onNameChange?.(stored);
137
+ if (!result.ok) {
138
+ setNameError(result.error);
139
+ return;
140
140
  }
141
+ setNameError(null);
142
+ setLocalName(result.name);
143
+ setNameDraft(result.name ?? "");
144
+ if (result.name !== null) onNameChange?.(result.name);
141
145
  setEditingName(false);
142
146
  }, [nameDraft, displayName, onNameChange]);
143
147
  const openKeyForm = useCallback(() => {
@@ -272,7 +276,12 @@ function ConnectedSettings({
272
276
  maxLength: 64,
273
277
  autoFocus: true,
274
278
  disabled: nameSaving,
275
- onChange: (e) => setNameDraft(e.target.value),
279
+ "aria-invalid": nameError !== null,
280
+ "aria-describedby": nameError ? "settings-popout-name-error" : void 0,
281
+ onChange: (e) => {
282
+ setNameDraft(e.target.value);
283
+ setNameError(null);
284
+ },
276
285
  onKeyDown: (e) => {
277
286
  if (e.key === "Enter") {
278
287
  saveName().catch(reportErr);
@@ -280,6 +289,7 @@ function ConnectedSettings({
280
289
  if (e.key === "Escape") {
281
290
  e.stopPropagation();
282
291
  setEditingName(false);
292
+ setNameError(null);
283
293
  setNameDraft(displayName ?? "");
284
294
  }
285
295
  }
@@ -296,6 +306,15 @@ function ConnectedSettings({
296
306
  },
297
307
  children: nameSaving ? "…" : "Save"
298
308
  }
309
+ ),
310
+ nameError && /* @__PURE__ */ jsx(
311
+ "span",
312
+ {
313
+ id: "settings-popout-name-error",
314
+ className: "settings-popout__error",
315
+ role: "alert",
316
+ children: nameError
317
+ }
299
318
  )
300
319
  ] }) : /* @__PURE__ */ jsx(
301
320
  "button",
@@ -1 +1 @@
1
- {"version":3,"file":"ConnectedSettings.js","sources":["../../src/components/ConnectedSettings.tsx"],"sourcesContent":["/**\n * ConnectedSettings — the unified per-user settings control for the hadoku\n * ecosystem: a gear button that opens a popout housing everything that is a\n * property of the PERSON (not the app):\n * - current access tier (read-only, friendly label)\n * - display name (inline edit → POST /session/name)\n * - avatar (a link to hadoku.me/account, where it is managed)\n * - global content-visibility level (tiered pill → PUT /prefs/api/v1/content-level)\n * - switch key (an inline sign-in form, on the site's own sign-in client)\n *\n * \"Connected\" (parallel to ConnectedThemePicker): it self-wires to the\n * hadoku.me edge-router via same-origin fetches (see lib/settingsClient), so\n * dropping `<ConnectedSettings />` into any app under hadoku.me needs zero\n * props. Identity is resolved via whoami() unless the host passes `userType` /\n * `name` (avoids a redundant fetch when the app already knows).\n *\n * All of that is resolved AT MOUNT via `prefetchSettings()`, never on\n * gear-click — opening the popout must cost zero requests. See the effect\n * below, and `e2e/settings-prefetch.spec.ts` in hadoku-task, which fails if the\n * fetch moves back behind the click.\n *\n * Mirrors ThemePicker's controlled-popout pattern: owns its own `open` state +\n * a full-viewport overlay for click-outside dismiss. The content pill renders\n * `maxLevel` segments (friend ⇒ 3, admin ⇒ 4) and is hidden for public callers.\n * maxLevel comes from the server so the tier ceiling is never trusted from the\n * client.\n */\nimport React, { useCallback, useEffect, useRef, useState } from 'react'\nimport { SettingsIcon } from './ThemeIcons'\nimport {\n deleteOwnAccount,\n prefetchSettings,\n setContentLevel,\n setDisplayName,\n loadSignIn,\n loadSignInClient,\n passkeyHref,\n passkeysSupported,\n switchKeyHref,\n type ContentLevelState,\n type Tier\n} from '../lib/settingsClient'\nimport '../app-header.css'\n\nexport interface ConnectedSettingsProps {\n /** Caller's tier. Omit to self-resolve via whoami().\n *\n * This exists for apps that CANNOT reach `/session/whoami` — conjure sits\n * behind a path-prefixed shim that serves nothing outside `/conjure`, so\n * whoami 404s and the tier would fall back to guest. It is an identity\n * hint, not a way to present a different tier than the edge assigns: every\n * gate that matters is enforced server-side off the edge-stamped tier. */\n userType?: Tier\n /** Display name. Omit to self-resolve via whoami(). Same rationale. */\n name?: string | null\n /** Notify the host (e.g. a \"Signed in as …\" label) of a rename. */\n onNameChange?: (name: string | null) => void\n /** App-specific settings rendered as a final section in the same popout, so\n * an app with its own preferences keeps ONE unified gear instead of a second\n * control. Shown under an \"App preferences\" divider.\n *\n * This slot is deliberately unconstrained — put whatever the app needs in\n * it. The constraint is only that it lands AFTER the four canonical rows and\n * cannot change them. */\n children?: React.ReactNode\n}\n\n/** Rejects once `signal` aborts, so a call that ignores the signal (an older\n * site client, a prompt that never settles) still lets the UI go. */\nfunction untilAborted(signal: AbortSignal): Promise<never> {\n return new Promise((_, reject) => {\n const fail = () => reject(new Error('cancelled'))\n if (signal.aborted) fail()\n else signal.addEventListener('abort', fail, { once: true })\n })\n}\n\n/** Abort reason when the popout closes: a dismissal, not an error to show. */\nconst CLOSED = 'closed'\n\n/** Rejection sink for fire-and-forget settings actions. The client helpers\n * already resolve to null on failure (state reflects it), so this only trips\n * on truly unexpected throws — log rather than swallow silently. */\nfunction reportErr(err: unknown) {\n // task-ui-components v2 dropped its logger; keep the package dependency-free.\n console.error('[ConnectedSettings] action failed', (err as Error)?.message ?? err)\n}\n\n/** Inline, not in app-header.css: every app runs this component from the\n * site's shared vendor module, but compiles app-header.css into its own\n * stylesheet at ITS build, so a new rule reaches an app only when it rebuilds. */\nconst PASSKEY_DOT: React.CSSProperties = {\n position: 'absolute',\n top: 2,\n right: 2,\n width: 8,\n height: 8,\n borderRadius: '50%',\n background: 'var(--color-primary)',\n pointerEvents: 'none'\n}\n\n/** Save passkey pulses while the dot is asking for it. Keyframes cannot be\n * inline, so the rule is injected once into the document instead, for the\n * same reason PASSKEY_DOT is inline. */\nconst PASSKEY_PULSE_CLASS = 'settings-popout__btn--pulse'\nconst PASSKEY_PULSE_STYLE_ID = 'settings-passkey-pulse'\nconst PASSKEY_PULSE_CSS = `\n@keyframes settings-passkey-pulse {\n 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--color-primary) 70%, transparent); }\n 70% { box-shadow: 0 0 0 8px color-mix(in srgb, var(--color-primary) 0%, transparent); }\n 100% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--color-primary) 0%, transparent); }\n}\n@media (prefers-reduced-motion: no-preference) {\n .${PASSKEY_PULSE_CLASS}:not(:disabled) {\n animation: settings-passkey-pulse 1.6s ease-out infinite;\n }\n}\n`\n\nfunction usePasskeyPulseStyle(active: boolean) {\n useEffect(() => {\n if (!active || document.getElementById(PASSKEY_PULSE_STYLE_ID)) return\n const el = document.createElement('style')\n el.id = PASSKEY_PULSE_STYLE_ID\n el.textContent = PASSKEY_PULSE_CSS\n document.head.appendChild(el)\n }, [active])\n}\n\nconst TIER_LABEL: Record<Tier, string> = {\n admin: 'Administrator',\n wife: 'Wife',\n service: 'Service',\n friend: 'Friend',\n member: 'Member',\n public: 'Guest'\n}\n\nexport function ConnectedSettings({\n userType: userTypeProp,\n name: nameProp,\n onNameChange,\n children\n}: ConnectedSettingsProps) {\n const [open, setOpen] = useState(false)\n const rootRef = useRef<HTMLDivElement>(null)\n\n // Identity — from props if supplied, else resolved lazily via whoami().\n const [userType, setUserType] = useState<Tier>(userTypeProp ?? 'public')\n const [resolvedName, setResolvedName] = useState<string | null>(nameProp ?? null)\n\n // Name editing\n const [nameDraft, setNameDraft] = useState(resolvedName ?? '')\n const [editingName, setEditingName] = useState(false)\n const [nameSaving, setNameSaving] = useState(false)\n const [displayName, setLocalName] = useState<string | null>(resolvedName)\n\n // Key swap. The draft lives only in this state and the input: it is never\n // logged, stored or sent anywhere but the site's sign-in client.\n const [keyFormOpen, setKeyFormOpen] = useState(false)\n const [keyDraft, setKeyDraft] = useState('')\n const [keyBusy, setKeyBusy] = useState(false)\n const [keyError, setKeyError] = useState<string | null>(null)\n\n // Passkeys, through the same site client: save one while signed in, or\n // sign in with one from the key form. One prompt at a time, and always\n // cancellable: a password manager can dismiss the browser's prompt without\n // ever answering it, so Cancel, closing the popout and the site client's own\n // time limit each end the wait.\n const [passkeyMode, setPasskeyMode] = useState<'save' | 'signin' | null>(null)\n const [passkeySaved, setPasskeySaved] = useState(false)\n // How many passkeys sign this person in, from whoami; null = unknown.\n const [passkeyCount, setPasskeyCount] = useState<number | null>(null)\n const [passkeyError, setPasskeyError] = useState<string | null>(null)\n // Delete account: one click arms it, a second, separate button confirms.\n const [deleteStage, setDeleteStage] = useState<'idle' | 'confirm' | 'busy'>('idle')\n const [deleteError, setDeleteError] = useState<string | null>(null)\n const passkeyCtl = useRef<AbortController | null>(null)\n const cancelPasskey = useCallback((reason?: string) => passkeyCtl.current?.abort(reason), [])\n\n // Content level\n const [content, setContent] = useState<ContentLevelState | null>(null)\n const [levelSaving, setLevelSaving] = useState(false)\n\n // One flag for the whole prefetch, not one per request — the panel body\n // reveals when everything has settled, so nothing pops in a beat late. In\n // practice the user never sees it: the prefetch starts at mount and is long\n // done by the time the gear is clicked. It only shows if they click within\n // the first moments of the page.\n const [resolving, setResolving] = useState(true)\n\n // Everyone who is SIGNED IN, expressed as \"not public\" rather than as a list\n // of tiers. The list form (`=== 'admin' || === 'friend' || === 'service'`)\n // is an exact-match allowlist: it silently excluded `wife` the moment that\n // tier existed, which is the failure the rank model is meant to prevent.\n // There is no rank helper in this bundle, but \"above public\" needs none.\n const showContentPill = userType !== 'public'\n\n // Signed in on a key with no passkey: the gear carries a dot and Save passkey\n // is the primary action until one is saved. Unknown counts never prompt.\n const needsPasskey =\n !resolving &&\n userType !== 'public' &&\n passkeyCount === 0 &&\n !passkeySaved &&\n passkeysSupported()\n usePasskeyPulseStyle(needsPasskey)\n\n // Keep local identity in sync when the host controls it via props.\n useEffect(() => {\n if (userTypeProp !== undefined) setUserType(userTypeProp)\n }, [userTypeProp])\n useEffect(() => {\n if (nameProp !== undefined) {\n setResolvedName(nameProp)\n setLocalName(nameProp)\n setNameDraft(nameProp ?? '')\n }\n }, [nameProp])\n\n // Resolve everything the panel shows AT MOUNT — not on open.\n //\n // This used to be gated on `open`, which made the gear the trigger for\n // whoami + content-level (167ms / 186ms on prod, concurrent) — a round trip\n // the user waited out with the panel already on screen and blank. Nothing\n // about that data depends on the click:\n // it's the signed-in user's own identity, settled at boot and unchanged for\n // the life of the page. So it rides along with the app's boot traffic, and\n // clicking the gear costs zero requests. `e2e/settings-prefetch.spec.ts` in\n // hadoku-task pins that.\n //\n // The client memoises across callers, so mounting this in several places (or\n // remounting it) does not multiply requests, and on hadoku.me the identity\n // half is free — it awaits the whoami the shell already had in flight.\n useEffect(() => {\n let live = true\n prefetchSettings({ userType: userTypeProp, name: nameProp })\n .then(({ identity, content: state, passkeys }) => {\n if (!live) return\n setPasskeyCount(passkeys)\n // Props stay authoritative: the host passed them because it can see an\n // identity this component can't resolve for itself.\n if (userTypeProp === undefined) {\n setUserType(identity.userType)\n setResolvedName(identity.name)\n setLocalName(identity.name)\n setNameDraft(identity.name ?? '')\n }\n if (state) setContent(state)\n })\n .catch(reportErr)\n .finally(() => {\n if (live) setResolving(false)\n })\n return () => {\n live = false\n }\n // Hints are read once, on the first mount that gets there — the prefetch is\n // page-scoped and a later prop change cannot un-issue it. Identity changes\n // arrive through the sync effects above, and a key swap reloads the page.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n\n // Escape closes.\n useEffect(() => {\n if (!open) return\n const onKey = (e: KeyboardEvent) => {\n if (e.key === 'Escape') setOpen(false)\n }\n window.addEventListener('keydown', onKey)\n return () => window.removeEventListener('keydown', onKey)\n }, [open])\n\n const saveName = useCallback(async () => {\n const trimmed = nameDraft.trim()\n if (!trimmed || trimmed === displayName) {\n setEditingName(false)\n return\n }\n setNameSaving(true)\n const stored = await setDisplayName(trimmed)\n setNameSaving(false)\n if (stored !== null) {\n setLocalName(stored)\n setNameDraft(stored)\n onNameChange?.(stored)\n }\n setEditingName(false)\n }, [nameDraft, displayName, onNameChange])\n\n // Open the form AND start loading the site's sign-in client, which begins its\n // fingerprint collection as it evaluates — so it is ready by submit. Where the\n // client cannot load at all (not on hadoku.me), the page-level /auth flow is\n // the only way to sign in, so go there.\n const openKeyForm = useCallback(() => {\n setKeyFormOpen(true)\n setKeyError(null)\n loadSignIn()\n .then(signIn => {\n if (!signIn) window.location.assign(switchKeyHref())\n })\n .catch(reportErr)\n }, [])\n\n const submitKey = useCallback(async () => {\n setKeyBusy(true)\n setKeyError(null)\n const signIn = await loadSignIn()\n if (!signIn) {\n window.location.assign(switchKeyHref())\n return\n }\n try {\n await signIn(keyDraft)\n } catch (err) {\n // A refused key is an inline error, never a redirect.\n setKeyError((err as Error)?.message || 'Invalid key')\n setKeyBusy(false)\n return\n }\n // The page now acts for a different identity: everything must re-mount.\n // Busy stays on through the reload so the form can't be resubmitted.\n window.location.reload()\n }, [keyDraft])\n\n const savePasskey = useCallback(async () => {\n const ctl = new AbortController()\n passkeyCtl.current = ctl\n setPasskeyMode('save')\n setPasskeyError(null)\n try {\n const client = await Promise.race([loadSignInClient(), untilAborted(ctl.signal)])\n if (!client?.addPasskey) {\n window.location.assign(passkeyHref('add'))\n return\n }\n await Promise.race([client.addPasskey({ signal: ctl.signal }), untilAborted(ctl.signal)])\n setPasskeySaved(true)\n } catch (err) {\n if (ctl.signal.reason !== CLOSED) {\n setPasskeyError(\n ctl.signal.aborted ? 'Passkey not saved' : (err as Error)?.message || 'Passkey not saved'\n )\n }\n } finally {\n if (passkeyCtl.current === ctl) passkeyCtl.current = null\n setPasskeyMode(null)\n }\n }, [])\n\n const signInWithPasskey = useCallback(async () => {\n const ctl = new AbortController()\n passkeyCtl.current = ctl\n setPasskeyMode('signin')\n setKeyBusy(true)\n setKeyError(null)\n let leaving = false\n try {\n const client = await Promise.race([loadSignInClient(), untilAborted(ctl.signal)])\n if (!client?.signInWithPasskey) {\n leaving = true\n window.location.assign(passkeyHref('signin'))\n return\n }\n await Promise.race([\n client.signInWithPasskey({ signal: ctl.signal }),\n untilAborted(ctl.signal)\n ])\n // The page now acts for a different identity: everything must re-mount.\n // Busy stays on through the reload so nothing can be resubmitted.\n leaving = true\n window.location.reload()\n } catch (err) {\n if (ctl.signal.reason !== CLOSED) {\n setKeyError(\n ctl.signal.aborted\n ? 'Passkey sign-in cancelled'\n : (err as Error)?.message || 'Passkey sign-in cancelled'\n )\n }\n } finally {\n if (passkeyCtl.current === ctl) passkeyCtl.current = null\n if (!leaving) {\n setPasskeyMode(null)\n setKeyBusy(false)\n }\n }\n }, [])\n\n // Closing the popout (or leaving the page) abandons an open prompt.\n useEffect(() => {\n if (!open) cancelPasskey(CLOSED)\n }, [open, cancelPasskey])\n useEffect(() => () => cancelPasskey(CLOSED), [cancelPasskey])\n\n const pickLevel = useCallback(\n async (level: number) => {\n if (!content || level === content.level || levelSaving) return\n const prev = content\n setContent({ ...content, level }) // optimistic\n setLevelSaving(true)\n const result = await setContentLevel(level)\n setLevelSaving(false)\n setContent(result ?? prev) // adopt server truth, or revert\n },\n [content, levelSaving]\n )\n\n // No caller-supplied class on the root. The four rows below are the\n // platform's, not the app's, and a className here is enough to restyle or\n // hide any of them — which is the drift this component exists to prevent.\n // Apps extend via `children`, never by reaching into this markup.\n return (\n <div className=\"settings-popout\" ref={rootRef}>\n <button\n type=\"button\"\n className=\"app-header__icon-btn settings-toggle-btn\"\n aria-label={needsPasskey ? 'User settings, no passkey saved' : 'User settings'}\n style={needsPasskey ? { position: 'relative' } : undefined}\n aria-expanded={open}\n onClick={() => setOpen(v => !v)}\n >\n <SettingsIcon />\n {needsPasskey && (\n <span className=\"settings-toggle-btn__dot\" style={PASSKEY_DOT} aria-hidden=\"true\" />\n )}\n </button>\n\n {open && <div className=\"settings-popout__overlay\" onClick={() => setOpen(false)} />}\n\n {open && (\n <div className=\"settings-popout__panel\" role=\"dialog\" aria-label=\"User settings\">\n <div className=\"settings-popout__header\">Settings</div>\n\n {/* Access tier. While resolving, the state still says 'public' —\n rendering \"Guest\" there would be a wrong answer that corrects\n itself a moment later, which reads exactly like the lag this\n placeholder exists to remove. */}\n <section className=\"settings-popout__row\">\n <span className=\"settings-popout__label\">Access tier</span>\n {resolving ? (\n <span className=\"settings-popout__value\">…</span>\n ) : (\n <span className={`settings-popout__tier settings-popout__tier--${userType}`}>\n {TIER_LABEL[userType]}\n </span>\n )}\n </section>\n\n {/* Display name */}\n <section className=\"settings-popout__row\">\n <span className=\"settings-popout__label\">Display name</span>\n {resolving ? (\n <span className=\"settings-popout__value\">…</span>\n ) : editingName ? (\n <span className=\"settings-popout__inline\">\n <input\n className=\"settings-popout__input\"\n value={nameDraft}\n maxLength={64}\n autoFocus\n disabled={nameSaving}\n onChange={e => setNameDraft(e.target.value)}\n onKeyDown={e => {\n if (e.key === 'Enter') {\n saveName().catch(reportErr)\n }\n if (e.key === 'Escape') {\n // The edit's Escape, not the popout's (window listener).\n e.stopPropagation()\n setEditingName(false)\n setNameDraft(displayName ?? '')\n }\n }}\n />\n <button\n type=\"button\"\n className=\"settings-popout__btn settings-popout__btn--primary\"\n disabled={nameSaving}\n onClick={() => {\n saveName().catch(reportErr)\n }}\n >\n {nameSaving ? '…' : 'Save'}\n </button>\n </span>\n ) : (\n <button\n type=\"button\"\n className=\"settings-popout__value settings-popout__value--editable\"\n aria-label=\"Edit display name\"\n onClick={() => {\n setNameDraft(displayName ?? '')\n setEditingName(true)\n }}\n >\n {displayName || 'Unnamed'}\n </button>\n )}\n </section>\n\n {/* Avatar. Managed on /account (character, Discord, Steam, upload),\n so this is only the way there: no thumbnail, because drawing one\n would cost every app a request at mount. A new tab, so following\n it never takes anyone out of a game mid-match. Hidden for public\n callers, like the content pill: /account needs a session. */}\n {!resolving && userType !== 'public' && (\n <section className=\"settings-popout__row\">\n <span className=\"settings-popout__label\">Avatar</span>\n <a className=\"settings-popout__btn\" href=\"/account\" target=\"_blank\" rel=\"noopener\">\n Change\n </a>\n </section>\n )}\n\n {/* Content visibility level. Held back until the first-open fetch\n settles, so it lands in the same paint as the tier and name\n rather than a round trip behind them. `content` is fetched\n concurrently with whoami(), so by then it is already here. */}\n {!resolving && showContentPill && (\n <section className=\"settings-popout__row settings-popout__row--stack\">\n <span className=\"settings-popout__label\">Content visibility</span>\n {content ? (\n <>\n <div\n className=\"settings-popout__pill\"\n role=\"radiogroup\"\n aria-label=\"Content visibility level\"\n >\n {Array.from({ length: content.maxLevel }, (_, i) => i + 1).map(lvl => (\n <button\n key={lvl}\n type=\"button\"\n role=\"radio\"\n aria-checked={lvl === content.level}\n aria-label={`Level ${lvl}`}\n className={`settings-popout__seg${\n lvl <= content.level ? ' settings-popout__seg--filled' : ''\n }`}\n disabled={levelSaving}\n onClick={() => {\n pickLevel(lvl).catch(reportErr)\n }}\n >\n {lvl}\n </button>\n ))}\n </div>\n <span className=\"settings-popout__hint\">\n Higher levels reveal more mature content across apps. Level 1 is\n safe-for-everyone.\n </span>\n </>\n ) : (\n // Not \"Loading…\" — the fetch has already settled by the time\n // this section renders at all, so a null here means it failed.\n <span className=\"settings-popout__hint\">Currently unavailable.</span>\n )}\n </section>\n )}\n\n {/* Switch key. Signs in inline through the SITE's sign-in client\n (the /auth page's own code path), never a post of ours. A real\n <form> with a username + current-password pair, so password\n managers offer and save the key. */}\n {keyFormOpen ? (\n <section className=\"settings-popout__row settings-popout__row--stack\">\n <form\n className=\"settings-popout__key-form\"\n onSubmit={e => {\n e.preventDefault()\n submitKey().catch(reportErr)\n }}\n >\n <input\n type=\"text\"\n name=\"username\"\n autoComplete=\"username\"\n value=\"hadoku\"\n readOnly\n hidden\n />\n <label className=\"settings-popout__label\" htmlFor=\"settings-popout-key\">\n Access key\n </label>\n <span className=\"settings-popout__inline\">\n <input\n id=\"settings-popout-key\"\n className=\"settings-popout__input\"\n type=\"password\"\n name=\"password\"\n autoComplete=\"current-password\"\n autoCapitalize=\"none\"\n spellCheck={false}\n autoFocus\n value={keyDraft}\n disabled={keyBusy}\n aria-invalid={keyError !== null}\n aria-describedby={keyError ? 'settings-popout-key-error' : undefined}\n onChange={e => setKeyDraft(e.target.value)}\n />\n <button\n type=\"submit\"\n className=\"settings-popout__btn settings-popout__btn--primary\"\n disabled={keyBusy}\n >\n {keyBusy ? 'Signing in…' : 'Sign in'}\n </button>\n </span>\n {passkeysSupported() && (\n <span className=\"settings-popout__inline\">\n <button\n type=\"button\"\n className=\"settings-popout__btn\"\n disabled={keyBusy}\n onClick={() => {\n signInWithPasskey().catch(reportErr)\n }}\n >\n {passkeyMode === 'signin' ? 'Waiting for passkey…' : 'Use a passkey'}\n </button>\n </span>\n )}\n {/* Cancel on a line of its own: in the row it would slide under\n the pointer, and a double click would cancel what it started. */}\n {passkeyMode === 'signin' && (\n <span className=\"settings-popout__inline\">\n <button\n type=\"button\"\n className=\"settings-popout__btn\"\n onClick={() => cancelPasskey()}\n >\n Cancel\n </button>\n </span>\n )}\n {keyError && (\n <span\n id=\"settings-popout-key-error\"\n className=\"settings-popout__error\"\n role=\"alert\"\n >\n {keyError}\n </span>\n )}\n </form>\n </section>\n ) : (\n <section className=\"settings-popout__row settings-popout__row--stack\">\n <span className=\"settings-popout__inline\">\n <span className=\"settings-popout__label settings-popout__label--grow\">\n Access key\n </span>\n {/* Signed-in people only: the site refuses to save one for anyone else. */}\n {!resolving && userType !== 'public' && passkeysSupported() && (\n <button\n type=\"button\"\n className={`settings-popout__btn${needsPasskey ? ` settings-popout__btn--primary ${PASSKEY_PULSE_CLASS}` : ''}`}\n disabled={passkeyMode !== null || passkeySaved}\n onClick={() => {\n savePasskey().catch(reportErr)\n }}\n >\n {passkeySaved\n ? 'Passkey saved'\n : passkeyMode === 'save'\n ? 'Saving…'\n : 'Save passkey'}\n </button>\n )}\n <button\n type=\"button\"\n className=\"settings-popout__btn\"\n disabled={passkeyMode === 'save'}\n onClick={openKeyForm}\n >\n Switch key\n </button>\n </span>\n {/* Its own line, so nothing moves under a double click. */}\n {passkeyMode === 'save' && (\n <span className=\"settings-popout__inline\">\n <button\n type=\"button\"\n className=\"settings-popout__btn\"\n onClick={() => cancelPasskey()}\n >\n Cancel\n </button>\n </span>\n )}\n {passkeyError && (\n <span className=\"settings-popout__error\" role=\"alert\">\n {passkeyError}\n </span>\n )}\n </section>\n )}\n\n {/* A self-made account (member) can delete itself. The confirm is a\n separate button on its own line, so a double click on Delete\n never confirms. */}\n {!resolving && userType === 'member' && (\n <section className=\"settings-popout__row settings-popout__row--stack\">\n <span className=\"settings-popout__inline\">\n <span className=\"settings-popout__label settings-popout__label--grow\">Account</span>\n {deleteStage === 'idle' ? (\n <button\n type=\"button\"\n className=\"settings-popout__btn\"\n onClick={() => {\n setDeleteError(null)\n setDeleteStage('confirm')\n }}\n >\n Delete account\n </button>\n ) : (\n <button\n type=\"button\"\n className=\"settings-popout__btn\"\n disabled={deleteStage === 'busy'}\n onClick={() => setDeleteStage('idle')}\n >\n Keep\n </button>\n )}\n </span>\n {deleteStage !== 'idle' && (\n <span className=\"settings-popout__inline\">\n <button\n type=\"button\"\n className=\"settings-popout__btn settings-popout__btn--primary\"\n disabled={deleteStage === 'busy'}\n onClick={() => {\n setDeleteStage('busy')\n deleteOwnAccount()\n .then(deleted => {\n if (!deleted) {\n setDeleteError('Account not deleted')\n setDeleteStage('confirm')\n return\n }\n localStorage.removeItem('hadoku_session_id')\n localStorage.removeItem('hadoku_user_type')\n window.location.assign('/')\n })\n .catch(reportErr)\n }}\n >\n {deleteStage === 'busy' ? 'Deleting…' : 'Delete for good'}\n </button>\n </span>\n )}\n {deleteError && (\n <span className=\"settings-popout__error\" role=\"alert\">\n {deleteError}\n </span>\n )}\n </section>\n )}\n\n {/* App-specific settings (optional) — same popout, one gear. */}\n {children && (\n <section className=\"settings-popout__row settings-popout__row--stack settings-popout__app\">\n {children}\n </section>\n )}\n </div>\n )}\n </div>\n )\n}\n"],"names":[],"mappings":";;;;;AAqEA,SAAS,aAAa,QAAqC;AACzD,SAAO,IAAI,QAAQ,CAAC,GAAG,WAAW;AAChC,UAAM,OAAO,MAAM,OAAO,IAAI,MAAM,WAAW,CAAC;AAChD,QAAI,OAAO,QAAS,MAAA;AAAA,gBACR,iBAAiB,SAAS,MAAM,EAAE,MAAM,MAAM;AAAA,EAC5D,CAAC;AACH;AAGA,MAAM,SAAS;AAKf,SAAS,UAAU,KAAc;AAE/B,UAAQ,MAAM,qCAAsC,KAAe,WAAW,GAAG;AACnF;AAKA,MAAM,cAAmC;AAAA,EACvC,UAAU;AAAA,EACV,KAAK;AAAA,EACL,OAAO;AAAA,EACP,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,cAAc;AAAA,EACd,YAAY;AAAA,EACZ,eAAe;AACjB;AAKA,MAAM,sBAAsB;AAC5B,MAAM,yBAAyB;AAC/B,MAAM,oBAAoB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KAOrB,mBAAmB;AAAA;AAAA;AAAA;AAAA;AAMxB,SAAS,qBAAqB,QAAiB;AAC7C,YAAU,MAAM;AACd,QAAI,CAAC,UAAU,SAAS,eAAe,sBAAs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,gBACF;AACA,6BAAa,WAAW,mBAAmB;AAC3C,6BAAa,WAAW,kBAAkB;AAC1C,uBAAO,SAAS,OAAO,GAAG;AAAA,cAC5B,CAAC,EACA,MAAM,SAAS;AAAA,YACpB;AAAA,YAEC,UAAA,gBAAgB,SAAS,cAAc;AAAA,UAAA;AAAA,QAAA,GAE5C;AAAA,QAED,eACC,oBAAC,QAAA,EAAK,WAAU,0BAAyB,MAAK,SAC3C,UAAA,YAAA,CACH;AAAA,MAAA,GAEJ;AAAA,MAID,YACC,oBAAC,WAAA,EAAQ,WAAU,yEAChB,SAAA,CACH;AAAA,IAAA,EAAA,CAEJ;AAAA,EAAA,GAEJ;AAEJ;"}
1
+ {"version":3,"file":"ConnectedSettings.js","sources":["../../src/components/ConnectedSettings.tsx"],"sourcesContent":["/**\n * ConnectedSettings — the unified per-user settings control for the hadoku\n * ecosystem: a gear button that opens a popout housing everything that is a\n * property of the PERSON (not the app):\n * - current access tier (read-only, friendly label)\n * - display name (inline edit → POST /session/name)\n * - avatar (a link to hadoku.me/account, where it is managed)\n * - global content-visibility level (tiered pill → PUT /prefs/api/v1/content-level)\n * - switch key (an inline sign-in form, on the site's own sign-in client)\n *\n * \"Connected\" (parallel to ConnectedThemePicker): it self-wires to the\n * hadoku.me edge-router via same-origin fetches (see lib/settingsClient), so\n * dropping `<ConnectedSettings />` into any app under hadoku.me needs zero\n * props. Identity is resolved via whoami() unless the host passes `userType` /\n * `name` (avoids a redundant fetch when the app already knows).\n *\n * All of that is resolved AT MOUNT via `prefetchSettings()`, never on\n * gear-click — opening the popout must cost zero requests. See the effect\n * below, and `e2e/settings-prefetch.spec.ts` in hadoku-task, which fails if the\n * fetch moves back behind the click.\n *\n * Mirrors ThemePicker's controlled-popout pattern: owns its own `open` state +\n * a full-viewport overlay for click-outside dismiss. The content pill renders\n * `maxLevel` segments (friend ⇒ 3, admin ⇒ 4) and is hidden for public callers.\n * maxLevel comes from the server so the tier ceiling is never trusted from the\n * client.\n */\nimport React, { useCallback, useEffect, useRef, useState } from 'react'\nimport { SettingsIcon } from './ThemeIcons'\nimport {\n deleteOwnAccount,\n prefetchSettings,\n setContentLevel,\n setDisplayName,\n loadSignIn,\n loadSignInClient,\n passkeyHref,\n passkeysSupported,\n switchKeyHref,\n type ContentLevelState,\n type Tier\n} from '../lib/settingsClient'\nimport '../app-header.css'\n\nexport interface ConnectedSettingsProps {\n /** Caller's tier. Omit to self-resolve via whoami().\n *\n * This exists for apps that CANNOT reach `/session/whoami` — conjure sits\n * behind a path-prefixed shim that serves nothing outside `/conjure`, so\n * whoami 404s and the tier would fall back to guest. It is an identity\n * hint, not a way to present a different tier than the edge assigns: every\n * gate that matters is enforced server-side off the edge-stamped tier. */\n userType?: Tier\n /** Display name. Omit to self-resolve via whoami(). Same rationale. */\n name?: string | null\n /** Notify the host (e.g. a \"Signed in as …\" label) of a rename. */\n onNameChange?: (name: string | null) => void\n /** App-specific settings rendered as a final section in the same popout, so\n * an app with its own preferences keeps ONE unified gear instead of a second\n * control. Shown under an \"App preferences\" divider.\n *\n * This slot is deliberately unconstrained — put whatever the app needs in\n * it. The constraint is only that it lands AFTER the four canonical rows and\n * cannot change them. */\n children?: React.ReactNode\n}\n\n/** Rejects once `signal` aborts, so a call that ignores the signal (an older\n * site client, a prompt that never settles) still lets the UI go. */\nfunction untilAborted(signal: AbortSignal): Promise<never> {\n return new Promise((_, reject) => {\n const fail = () => reject(new Error('cancelled'))\n if (signal.aborted) fail()\n else signal.addEventListener('abort', fail, { once: true })\n })\n}\n\n/** Abort reason when the popout closes: a dismissal, not an error to show. */\nconst CLOSED = 'closed'\n\n/** Rejection sink for fire-and-forget settings actions. The client helpers\n * already resolve to null on failure (state reflects it), so this only trips\n * on truly unexpected throws — log rather than swallow silently. */\nfunction reportErr(err: unknown) {\n // task-ui-components v2 dropped its logger; keep the package dependency-free.\n console.error('[ConnectedSettings] action failed', (err as Error)?.message ?? err)\n}\n\n/** Inline, not in app-header.css: every app runs this component from the\n * site's shared vendor module, but compiles app-header.css into its own\n * stylesheet at ITS build, so a new rule reaches an app only when it rebuilds. */\nconst PASSKEY_DOT: React.CSSProperties = {\n position: 'absolute',\n top: 2,\n right: 2,\n width: 8,\n height: 8,\n borderRadius: '50%',\n background: 'var(--color-primary)',\n pointerEvents: 'none'\n}\n\n/** Save passkey pulses while the dot is asking for it. Keyframes cannot be\n * inline, so the rule is injected once into the document instead, for the\n * same reason PASSKEY_DOT is inline. */\nconst PASSKEY_PULSE_CLASS = 'settings-popout__btn--pulse'\nconst PASSKEY_PULSE_STYLE_ID = 'settings-passkey-pulse'\nconst PASSKEY_PULSE_CSS = `\n@keyframes settings-passkey-pulse {\n 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--color-primary) 70%, transparent); }\n 70% { box-shadow: 0 0 0 8px color-mix(in srgb, var(--color-primary) 0%, transparent); }\n 100% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--color-primary) 0%, transparent); }\n}\n@media (prefers-reduced-motion: no-preference) {\n .${PASSKEY_PULSE_CLASS}:not(:disabled) {\n animation: settings-passkey-pulse 1.6s ease-out infinite;\n }\n}\n`\n\nfunction usePasskeyPulseStyle(active: boolean) {\n useEffect(() => {\n if (!active || document.getElementById(PASSKEY_PULSE_STYLE_ID)) return\n const el = document.createElement('style')\n el.id = PASSKEY_PULSE_STYLE_ID\n el.textContent = PASSKEY_PULSE_CSS\n document.head.appendChild(el)\n }, [active])\n}\n\nconst TIER_LABEL: Record<Tier, string> = {\n admin: 'Administrator',\n wife: 'Wife',\n service: 'Service',\n friend: 'Friend',\n member: 'Member',\n public: 'Guest'\n}\n\nexport function ConnectedSettings({\n userType: userTypeProp,\n name: nameProp,\n onNameChange,\n children\n}: ConnectedSettingsProps) {\n const [open, setOpen] = useState(false)\n const rootRef = useRef<HTMLDivElement>(null)\n\n // Identity — from props if supplied, else resolved lazily via whoami().\n const [userType, setUserType] = useState<Tier>(userTypeProp ?? 'public')\n const [resolvedName, setResolvedName] = useState<string | null>(nameProp ?? null)\n\n // Name editing\n const [nameDraft, setNameDraft] = useState(resolvedName ?? '')\n const [editingName, setEditingName] = useState(false)\n const [nameSaving, setNameSaving] = useState(false)\n const [nameError, setNameError] = useState<string | null>(null)\n const [displayName, setLocalName] = useState<string | null>(resolvedName)\n\n // Key swap. The draft lives only in this state and the input: it is never\n // logged, stored or sent anywhere but the site's sign-in client.\n const [keyFormOpen, setKeyFormOpen] = useState(false)\n const [keyDraft, setKeyDraft] = useState('')\n const [keyBusy, setKeyBusy] = useState(false)\n const [keyError, setKeyError] = useState<string | null>(null)\n\n // Passkeys, through the same site client: save one while signed in, or\n // sign in with one from the key form. One prompt at a time, and always\n // cancellable: a password manager can dismiss the browser's prompt without\n // ever answering it, so Cancel, closing the popout and the site client's own\n // time limit each end the wait.\n const [passkeyMode, setPasskeyMode] = useState<'save' | 'signin' | null>(null)\n const [passkeySaved, setPasskeySaved] = useState(false)\n // How many passkeys sign this person in, from whoami; null = unknown.\n const [passkeyCount, setPasskeyCount] = useState<number | null>(null)\n const [passkeyError, setPasskeyError] = useState<string | null>(null)\n // Delete account: one click arms it, a second, separate button confirms.\n const [deleteStage, setDeleteStage] = useState<'idle' | 'confirm' | 'busy'>('idle')\n const [deleteError, setDeleteError] = useState<string | null>(null)\n const passkeyCtl = useRef<AbortController | null>(null)\n const cancelPasskey = useCallback((reason?: string) => passkeyCtl.current?.abort(reason), [])\n\n // Content level\n const [content, setContent] = useState<ContentLevelState | null>(null)\n const [levelSaving, setLevelSaving] = useState(false)\n\n // One flag for the whole prefetch, not one per request — the panel body\n // reveals when everything has settled, so nothing pops in a beat late. In\n // practice the user never sees it: the prefetch starts at mount and is long\n // done by the time the gear is clicked. It only shows if they click within\n // the first moments of the page.\n const [resolving, setResolving] = useState(true)\n\n // Everyone who is SIGNED IN, expressed as \"not public\" rather than as a list\n // of tiers. The list form (`=== 'admin' || === 'friend' || === 'service'`)\n // is an exact-match allowlist: it silently excluded `wife` the moment that\n // tier existed, which is the failure the rank model is meant to prevent.\n // There is no rank helper in this bundle, but \"above public\" needs none.\n const showContentPill = userType !== 'public'\n\n // Signed in on a key with no passkey: the gear carries a dot and Save passkey\n // is the primary action until one is saved. Unknown counts never prompt.\n const needsPasskey =\n !resolving &&\n userType !== 'public' &&\n passkeyCount === 0 &&\n !passkeySaved &&\n passkeysSupported()\n usePasskeyPulseStyle(needsPasskey)\n\n // Keep local identity in sync when the host controls it via props.\n useEffect(() => {\n if (userTypeProp !== undefined) setUserType(userTypeProp)\n }, [userTypeProp])\n useEffect(() => {\n if (nameProp !== undefined) {\n setResolvedName(nameProp)\n setLocalName(nameProp)\n setNameDraft(nameProp ?? '')\n }\n }, [nameProp])\n\n // Resolve everything the panel shows AT MOUNT — not on open.\n //\n // This used to be gated on `open`, which made the gear the trigger for\n // whoami + content-level (167ms / 186ms on prod, concurrent) — a round trip\n // the user waited out with the panel already on screen and blank. Nothing\n // about that data depends on the click:\n // it's the signed-in user's own identity, settled at boot and unchanged for\n // the life of the page. So it rides along with the app's boot traffic, and\n // clicking the gear costs zero requests. `e2e/settings-prefetch.spec.ts` in\n // hadoku-task pins that.\n //\n // The client memoises across callers, so mounting this in several places (or\n // remounting it) does not multiply requests, and on hadoku.me the identity\n // half is free — it awaits the whoami the shell already had in flight.\n useEffect(() => {\n let live = true\n prefetchSettings({ userType: userTypeProp, name: nameProp })\n .then(({ identity, content: state, passkeys }) => {\n if (!live) return\n setPasskeyCount(passkeys)\n // Props stay authoritative: the host passed them because it can see an\n // identity this component can't resolve for itself.\n if (userTypeProp === undefined) {\n setUserType(identity.userType)\n setResolvedName(identity.name)\n setLocalName(identity.name)\n setNameDraft(identity.name ?? '')\n }\n if (state) setContent(state)\n })\n .catch(reportErr)\n .finally(() => {\n if (live) setResolving(false)\n })\n return () => {\n live = false\n }\n // Hints are read once, on the first mount that gets there — the prefetch is\n // page-scoped and a later prop change cannot un-issue it. Identity changes\n // arrive through the sync effects above, and a key swap reloads the page.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n\n // Escape closes.\n useEffect(() => {\n if (!open) return\n const onKey = (e: KeyboardEvent) => {\n if (e.key === 'Escape') setOpen(false)\n }\n window.addEventListener('keydown', onKey)\n return () => window.removeEventListener('keydown', onKey)\n }, [open])\n\n const saveName = useCallback(async () => {\n const trimmed = nameDraft.trim()\n if (!trimmed || trimmed === displayName) {\n setEditingName(false)\n return\n }\n setNameSaving(true)\n const result = await setDisplayName(trimmed)\n setNameSaving(false)\n // A refusal keeps the editor open on the draft, saying why.\n if (!result.ok) {\n setNameError(result.error)\n return\n }\n setNameError(null)\n setLocalName(result.name)\n setNameDraft(result.name ?? '')\n if (result.name !== null) onNameChange?.(result.name)\n setEditingName(false)\n }, [nameDraft, displayName, onNameChange])\n\n // Open the form AND start loading the site's sign-in client, which begins its\n // fingerprint collection as it evaluates — so it is ready by submit. Where the\n // client cannot load at all (not on hadoku.me), the page-level /auth flow is\n // the only way to sign in, so go there.\n const openKeyForm = useCallback(() => {\n setKeyFormOpen(true)\n setKeyError(null)\n loadSignIn()\n .then(signIn => {\n if (!signIn) window.location.assign(switchKeyHref())\n })\n .catch(reportErr)\n }, [])\n\n const submitKey = useCallback(async () => {\n setKeyBusy(true)\n setKeyError(null)\n const signIn = await loadSignIn()\n if (!signIn) {\n window.location.assign(switchKeyHref())\n return\n }\n try {\n await signIn(keyDraft)\n } catch (err) {\n // A refused key is an inline error, never a redirect.\n setKeyError((err as Error)?.message || 'Invalid key')\n setKeyBusy(false)\n return\n }\n // The page now acts for a different identity: everything must re-mount.\n // Busy stays on through the reload so the form can't be resubmitted.\n window.location.reload()\n }, [keyDraft])\n\n const savePasskey = useCallback(async () => {\n const ctl = new AbortController()\n passkeyCtl.current = ctl\n setPasskeyMode('save')\n setPasskeyError(null)\n try {\n const client = await Promise.race([loadSignInClient(), untilAborted(ctl.signal)])\n if (!client?.addPasskey) {\n window.location.assign(passkeyHref('add'))\n return\n }\n await Promise.race([client.addPasskey({ signal: ctl.signal }), untilAborted(ctl.signal)])\n setPasskeySaved(true)\n } catch (err) {\n if (ctl.signal.reason !== CLOSED) {\n setPasskeyError(\n ctl.signal.aborted ? 'Passkey not saved' : (err as Error)?.message || 'Passkey not saved'\n )\n }\n } finally {\n if (passkeyCtl.current === ctl) passkeyCtl.current = null\n setPasskeyMode(null)\n }\n }, [])\n\n const signInWithPasskey = useCallback(async () => {\n const ctl = new AbortController()\n passkeyCtl.current = ctl\n setPasskeyMode('signin')\n setKeyBusy(true)\n setKeyError(null)\n let leaving = false\n try {\n const client = await Promise.race([loadSignInClient(), untilAborted(ctl.signal)])\n if (!client?.signInWithPasskey) {\n leaving = true\n window.location.assign(passkeyHref('signin'))\n return\n }\n await Promise.race([\n client.signInWithPasskey({ signal: ctl.signal }),\n untilAborted(ctl.signal)\n ])\n // The page now acts for a different identity: everything must re-mount.\n // Busy stays on through the reload so nothing can be resubmitted.\n leaving = true\n window.location.reload()\n } catch (err) {\n if (ctl.signal.reason !== CLOSED) {\n setKeyError(\n ctl.signal.aborted\n ? 'Passkey sign-in cancelled'\n : (err as Error)?.message || 'Passkey sign-in cancelled'\n )\n }\n } finally {\n if (passkeyCtl.current === ctl) passkeyCtl.current = null\n if (!leaving) {\n setPasskeyMode(null)\n setKeyBusy(false)\n }\n }\n }, [])\n\n // Closing the popout (or leaving the page) abandons an open prompt.\n useEffect(() => {\n if (!open) cancelPasskey(CLOSED)\n }, [open, cancelPasskey])\n useEffect(() => () => cancelPasskey(CLOSED), [cancelPasskey])\n\n const pickLevel = useCallback(\n async (level: number) => {\n if (!content || level === content.level || levelSaving) return\n const prev = content\n setContent({ ...content, level }) // optimistic\n setLevelSaving(true)\n const result = await setContentLevel(level)\n setLevelSaving(false)\n setContent(result ?? prev) // adopt server truth, or revert\n },\n [content, levelSaving]\n )\n\n // No caller-supplied class on the root. The four rows below are the\n // platform's, not the app's, and a className here is enough to restyle or\n // hide any of them — which is the drift this component exists to prevent.\n // Apps extend via `children`, never by reaching into this markup.\n return (\n <div className=\"settings-popout\" ref={rootRef}>\n <button\n type=\"button\"\n className=\"app-header__icon-btn settings-toggle-btn\"\n aria-label={needsPasskey ? 'User settings, no passkey saved' : 'User settings'}\n style={needsPasskey ? { position: 'relative' } : undefined}\n aria-expanded={open}\n onClick={() => setOpen(v => !v)}\n >\n <SettingsIcon />\n {needsPasskey && (\n <span className=\"settings-toggle-btn__dot\" style={PASSKEY_DOT} aria-hidden=\"true\" />\n )}\n </button>\n\n {open && <div className=\"settings-popout__overlay\" onClick={() => setOpen(false)} />}\n\n {open && (\n <div className=\"settings-popout__panel\" role=\"dialog\" aria-label=\"User settings\">\n <div className=\"settings-popout__header\">Settings</div>\n\n {/* Access tier. While resolving, the state still says 'public' —\n rendering \"Guest\" there would be a wrong answer that corrects\n itself a moment later, which reads exactly like the lag this\n placeholder exists to remove. */}\n <section className=\"settings-popout__row\">\n <span className=\"settings-popout__label\">Access tier</span>\n {resolving ? (\n <span className=\"settings-popout__value\">…</span>\n ) : (\n <span className={`settings-popout__tier settings-popout__tier--${userType}`}>\n {TIER_LABEL[userType]}\n </span>\n )}\n </section>\n\n {/* Display name */}\n <section className=\"settings-popout__row\">\n <span className=\"settings-popout__label\">Display name</span>\n {resolving ? (\n <span className=\"settings-popout__value\">…</span>\n ) : editingName ? (\n <span className=\"settings-popout__inline\">\n <input\n className=\"settings-popout__input\"\n value={nameDraft}\n maxLength={64}\n autoFocus\n disabled={nameSaving}\n aria-invalid={nameError !== null}\n aria-describedby={nameError ? 'settings-popout-name-error' : undefined}\n onChange={e => {\n setNameDraft(e.target.value)\n setNameError(null)\n }}\n onKeyDown={e => {\n if (e.key === 'Enter') {\n saveName().catch(reportErr)\n }\n if (e.key === 'Escape') {\n // The edit's Escape, not the popout's (window listener).\n e.stopPropagation()\n setEditingName(false)\n setNameError(null)\n setNameDraft(displayName ?? '')\n }\n }}\n />\n <button\n type=\"button\"\n className=\"settings-popout__btn settings-popout__btn--primary\"\n disabled={nameSaving}\n onClick={() => {\n saveName().catch(reportErr)\n }}\n >\n {nameSaving ? '…' : 'Save'}\n </button>\n {nameError && (\n <span\n id=\"settings-popout-name-error\"\n className=\"settings-popout__error\"\n role=\"alert\"\n >\n {nameError}\n </span>\n )}\n </span>\n ) : (\n <button\n type=\"button\"\n className=\"settings-popout__value settings-popout__value--editable\"\n aria-label=\"Edit display name\"\n onClick={() => {\n setNameDraft(displayName ?? '')\n setEditingName(true)\n }}\n >\n {displayName || 'Unnamed'}\n </button>\n )}\n </section>\n\n {/* Avatar. Managed on /account (character, Discord, Steam, upload),\n so this is only the way there: no thumbnail, because drawing one\n would cost every app a request at mount. A new tab, so following\n it never takes anyone out of a game mid-match. Hidden for public\n callers, like the content pill: /account needs a session. */}\n {!resolving && userType !== 'public' && (\n <section className=\"settings-popout__row\">\n <span className=\"settings-popout__label\">Avatar</span>\n <a className=\"settings-popout__btn\" href=\"/account\" target=\"_blank\" rel=\"noopener\">\n Change\n </a>\n </section>\n )}\n\n {/* Content visibility level. Held back until the first-open fetch\n settles, so it lands in the same paint as the tier and name\n rather than a round trip behind them. `content` is fetched\n concurrently with whoami(), so by then it is already here. */}\n {!resolving && showContentPill && (\n <section className=\"settings-popout__row settings-popout__row--stack\">\n <span className=\"settings-popout__label\">Content visibility</span>\n {content ? (\n <>\n <div\n className=\"settings-popout__pill\"\n role=\"radiogroup\"\n aria-label=\"Content visibility level\"\n >\n {Array.from({ length: content.maxLevel }, (_, i) => i + 1).map(lvl => (\n <button\n key={lvl}\n type=\"button\"\n role=\"radio\"\n aria-checked={lvl === content.level}\n aria-label={`Level ${lvl}`}\n className={`settings-popout__seg${\n lvl <= content.level ? ' settings-popout__seg--filled' : ''\n }`}\n disabled={levelSaving}\n onClick={() => {\n pickLevel(lvl).catch(reportErr)\n }}\n >\n {lvl}\n </button>\n ))}\n </div>\n <span className=\"settings-popout__hint\">\n Higher levels reveal more mature content across apps. Level 1 is\n safe-for-everyone.\n </span>\n </>\n ) : (\n // Not \"Loading…\" — the fetch has already settled by the time\n // this section renders at all, so a null here means it failed.\n <span className=\"settings-popout__hint\">Currently unavailable.</span>\n )}\n </section>\n )}\n\n {/* Switch key. Signs in inline through the SITE's sign-in client\n (the /auth page's own code path), never a post of ours. A real\n <form> with a username + current-password pair, so password\n managers offer and save the key. */}\n {keyFormOpen ? (\n <section className=\"settings-popout__row settings-popout__row--stack\">\n <form\n className=\"settings-popout__key-form\"\n onSubmit={e => {\n e.preventDefault()\n submitKey().catch(reportErr)\n }}\n >\n <input\n type=\"text\"\n name=\"username\"\n autoComplete=\"username\"\n value=\"hadoku\"\n readOnly\n hidden\n />\n <label className=\"settings-popout__label\" htmlFor=\"settings-popout-key\">\n Access key\n </label>\n <span className=\"settings-popout__inline\">\n <input\n id=\"settings-popout-key\"\n className=\"settings-popout__input\"\n type=\"password\"\n name=\"password\"\n autoComplete=\"current-password\"\n autoCapitalize=\"none\"\n spellCheck={false}\n autoFocus\n value={keyDraft}\n disabled={keyBusy}\n aria-invalid={keyError !== null}\n aria-describedby={keyError ? 'settings-popout-key-error' : undefined}\n onChange={e => setKeyDraft(e.target.value)}\n />\n <button\n type=\"submit\"\n className=\"settings-popout__btn settings-popout__btn--primary\"\n disabled={keyBusy}\n >\n {keyBusy ? 'Signing in…' : 'Sign in'}\n </button>\n </span>\n {passkeysSupported() && (\n <span className=\"settings-popout__inline\">\n <button\n type=\"button\"\n className=\"settings-popout__btn\"\n disabled={keyBusy}\n onClick={() => {\n signInWithPasskey().catch(reportErr)\n }}\n >\n {passkeyMode === 'signin' ? 'Waiting for passkey…' : 'Use a passkey'}\n </button>\n </span>\n )}\n {/* Cancel on a line of its own: in the row it would slide under\n the pointer, and a double click would cancel what it started. */}\n {passkeyMode === 'signin' && (\n <span className=\"settings-popout__inline\">\n <button\n type=\"button\"\n className=\"settings-popout__btn\"\n onClick={() => cancelPasskey()}\n >\n Cancel\n </button>\n </span>\n )}\n {keyError && (\n <span\n id=\"settings-popout-key-error\"\n className=\"settings-popout__error\"\n role=\"alert\"\n >\n {keyError}\n </span>\n )}\n </form>\n </section>\n ) : (\n <section className=\"settings-popout__row settings-popout__row--stack\">\n <span className=\"settings-popout__inline\">\n <span className=\"settings-popout__label settings-popout__label--grow\">\n Access key\n </span>\n {/* Signed-in people only: the site refuses to save one for anyone else. */}\n {!resolving && userType !== 'public' && passkeysSupported() && (\n <button\n type=\"button\"\n className={`settings-popout__btn${needsPasskey ? ` settings-popout__btn--primary ${PASSKEY_PULSE_CLASS}` : ''}`}\n disabled={passkeyMode !== null || passkeySaved}\n onClick={() => {\n savePasskey().catch(reportErr)\n }}\n >\n {passkeySaved\n ? 'Passkey saved'\n : passkeyMode === 'save'\n ? 'Saving…'\n : 'Save passkey'}\n </button>\n )}\n <button\n type=\"button\"\n className=\"settings-popout__btn\"\n disabled={passkeyMode === 'save'}\n onClick={openKeyForm}\n >\n Switch key\n </button>\n </span>\n {/* Its own line, so nothing moves under a double click. */}\n {passkeyMode === 'save' && (\n <span className=\"settings-popout__inline\">\n <button\n type=\"button\"\n className=\"settings-popout__btn\"\n onClick={() => cancelPasskey()}\n >\n Cancel\n </button>\n </span>\n )}\n {passkeyError && (\n <span className=\"settings-popout__error\" role=\"alert\">\n {passkeyError}\n </span>\n )}\n </section>\n )}\n\n {/* A self-made account (member) can delete itself. The confirm is a\n separate button on its own line, so a double click on Delete\n never confirms. */}\n {!resolving && userType === 'member' && (\n <section className=\"settings-popout__row settings-popout__row--stack\">\n <span className=\"settings-popout__inline\">\n <span className=\"settings-popout__label settings-popout__label--grow\">Account</span>\n {deleteStage === 'idle' ? (\n <button\n type=\"button\"\n className=\"settings-popout__btn\"\n onClick={() => {\n setDeleteError(null)\n setDeleteStage('confirm')\n }}\n >\n Delete account\n </button>\n ) : (\n <button\n type=\"button\"\n className=\"settings-popout__btn\"\n disabled={deleteStage === 'busy'}\n onClick={() => setDeleteStage('idle')}\n >\n Keep\n </button>\n )}\n </span>\n {deleteStage !== 'idle' && (\n <span className=\"settings-popout__inline\">\n <button\n type=\"button\"\n className=\"settings-popout__btn settings-popout__btn--primary\"\n disabled={deleteStage === 'busy'}\n onClick={() => {\n setDeleteStage('busy')\n deleteOwnAccount()\n .then(deleted => {\n if (!deleted) {\n setDeleteError('Account not deleted')\n setDeleteStage('confirm')\n return\n }\n localStorage.removeItem('hadoku_session_id')\n localStorage.removeItem('hadoku_user_type')\n window.location.assign('/')\n })\n .catch(reportErr)\n }}\n >\n {deleteStage === 'busy' ? 'Deleting…' : 'Delete for good'}\n </button>\n </span>\n )}\n {deleteError && (\n <span className=\"settings-popout__error\" role=\"alert\">\n {deleteError}\n </span>\n )}\n </section>\n )}\n\n {/* App-specific settings (optional) — same popout, one gear. */}\n {children && (\n <section className=\"settings-popout__row settings-popout__row--stack settings-popout__app\">\n {children}\n </section>\n )}\n </div>\n )}\n </div>\n )\n}\n"],"names":[],"mappings":";;;;;AAqEA,SAAS,aAAa,QAAqC;AACzD,SAAO,IAAI,QAAQ,CAAC,GAAG,WAAW;AAChC,UAAM,OAAO,MAAM,OAAO,IAAI,MAAM,WAAW,CAAC;AAChD,QAAI,OAAO,QAAS,MAAA;AAAA,gBACR,iBAAiB,SAAS,MAAM,EAAE,MAAM,MAAM;AAAA,EAC5D,CAAC;AACH;AAGA,MAAM,SAAS;AAKf,SAAS,UAAU,KAAc;AAE/B,UAAQ,MAAM,qCAAsC,KAAe,WAAW,GAAG;AACnF;AAKA,MAAM,cAAmC;AAAA,EACvC,UAAU;AAAA,EACV,KAAK;AAAA,EACL,OAAO;AAAA,EACP,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,cAAc;AAAA,EACd,YAAY;AAAA,EACZ,eAAe;AACjB;AAKA,MAAM,sBAAsB;AAC5B,MAAM,yBAAyB;AAC/B,MAAM,oBAAoB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KAOrB,mBAAmB;AAAA;AAAA;AAAA;AAAA;AAMxB,SAAS,qBAAqB,QAAiB;AAC7C,YAAU,MAAM;AACd,QAAI,CAAC,UAAU,SAAS,eAAe,sBAAsB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AU,gBAAgB;AAAA,cAC1B,SAAS,MAAM,eAAe,MAAM;AAAA,cACrC,UAAA;AAAA,YAAA;AAAA,UAAA;AAAA,QAED,GAEJ;AAAA,QACC,gBAAgB,UACf,oBAAC,QAAA,EAAK,WAAU,2BACd,UAAA;AAAA,UAAC;AAAA,UAAA;AAAA,YACC,MAAK;AAAA,YACL,WAAU;AAAA,YACV,UAAU,gBAAgB;AAAA,YAC1B,SAAS,MAAM;AACb,6BAAe,MAAM;AACrB,+BAAA,EACG,KAAK,CAAA,YAAW;AACf,oBAAI,CAAC,SAAS;AACZ,iCAAe,qBAAqB;AACpC,iCAAe,SAAS;AACxB;AAAA,gBACF;AACA,6BAAa,WAAW,mBAAmB;AAC3C,6BAAa,WAAW,kBAAkB;AAC1C,uBAAO,SAAS,OAAO,GAAG;AAAA,cAC5B,CAAC,EACA,MAAM,SAAS;AAAA,YACpB;AAAA,YAEC,UAAA,gBAAgB,SAAS,cAAc;AAAA,UAAA;AAAA,QAAA,GAE5C;AAAA,QAED,eACC,oBAAC,QAAA,EAAK,WAAU,0BAAyB,MAAK,SAC3C,UAAA,YAAA,CACH;AAAA,MAAA,GAEJ;AAAA,MAID,YACC,oBAAC,WAAA,EAAQ,WAAU,yEAChB,SAAA,CACH;AAAA,IAAA,EAAA,CAEJ;AAAA,EAAA,GAEJ;AAEJ;"}
@@ -39,9 +39,20 @@ export declare function setContentLevel(level: number): Promise<ContentLevelStat
39
39
  /** Delete the signed-in member's own account (edge-router refuses any key
40
40
  * someone was handed). True when it is gone; the session cookie is cleared. */
41
41
  export declare function deleteOwnAccount(): Promise<boolean>;
42
- /** POST a new display name for the signed-in user. Returns the stored name
43
- * (may differ from the request for wp-* protected keys) or null on failure. */
44
- export declare function setDisplayName(name: string): Promise<string | null>;
42
+ /**
43
+ * POST a new display name for the signed-in user. Answers the stored name (may
44
+ * differ from the request for wp-* protected keys), or why it was refused: the
45
+ * server's own words where it gave any ("That display name is already taken"),
46
+ * so the editor can say them.
47
+ */
48
+ export type RenameResult = {
49
+ ok: true;
50
+ name: string | null;
51
+ } | {
52
+ ok: false;
53
+ error: string;
54
+ };
55
+ export declare function setDisplayName(name: string): Promise<RenameResult>;
45
56
  /**
46
57
  * The hadoku tier ladder, LOW to HIGH: `public < member < friend < service < wife < admin`.
47
58
  * `member` is a self-signed-up account (a passkey, no key), cardtable only.
@@ -1 +1 @@
1
- {"version":3,"file":"settingsClient.d.ts","sourceRoot":"","sources":["../../src/lib/settingsClient.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAwDH,MAAM,WAAW,iBAAiB;IAChC,oEAAoE;IACpE,KAAK,EAAE,MAAM,CAAA;IACb,uEAAuE;IACvE,QAAQ,EAAE,MAAM,CAAA;CACjB;AAED,4EAA4E;AAC5E,wBAAsB,eAAe,IAAI,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC,CAYzE;AAED;uEACuE;AACvE,wBAAsB,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC,CAgBtF;AAED;gFACgF;AAChF,wBAAsB,gBAAgB,IAAI,OAAO,CAAC,OAAO,CAAC,CAczD;AAED;gFACgF;AAChF,wBAAsB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAgBzE;AAED;;;;;;;GAOG;AACH,MAAM,MAAM,IAAI,GAAG,QAAQ,GAAG,QAAQ,GAAG,QAAQ,GAAG,SAAS,GAAG,MAAM,GAAG,OAAO,CAAA;AAEhF,MAAM,WAAW,QAAQ;IACvB,QAAQ,EAAE,IAAI,CAAA;IACd,IAAI,EAAE,MAAM,GAAG,IAAI,CAAA;CACpB;AAyBD;;;;GAIG;AACH,wBAAsB,MAAM,IAAI,OAAO,CAAC,QAAQ,CAAC,CAShD;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,aAAa,IAAI,MAAM,CAKtC;AAED,6DA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8FAA8F;IAC9F,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAA;CACxB;AAED,gFAAgF;AAChF,MAAM,WAAW,qBAAqB;IACpC,gEAAgE;IAChE,QAAQ,CAAC,EAAE,IAAI,CAAA;IACf,mEAAmE;IACnE,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CACrB;AAID;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,GAAE,qBAA0B,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAG7F"}
@@ -64,12 +64,16 @@ async function setDisplayName(name) {
64
64
  body: JSON.stringify({ name }),
65
65
  signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
66
66
  });
67
- if (!res.ok) return null;
67
+ if (!res.ok) {
68
+ const body2 = await res.json().catch(() => null);
69
+ const said = typeof body2?.error === "string" ? body2.error : null;
70
+ return { ok: false, error: said ?? `Not saved (${res.status})` };
71
+ }
68
72
  const body = await res.json();
69
73
  patchSnapshot((prev) => ({ ...prev, identity: { ...prev.identity, name: body.name } }));
70
- return body.name;
74
+ return { ok: true, name: body.name };
71
75
  } catch {
72
- return null;
76
+ return { ok: false, error: "Not saved: no connection" };
73
77
  }
74
78
  }
75
79
  function sharedWhoami() {
@@ -1 +1 @@
1
- {"version":3,"file":"settingsClient.js","sources":["../../src/lib/settingsClient.ts"],"sourcesContent":["/**\n * Client for the unified user-settings modal (ConnectedSettings).\n *\n * Two concerns, both cookie-authed against the hadoku.me edge-router, which\n * resolves the `hadoku_session` cookie / `X-Session-Id` header → X-User-Key +\n * X-User-Id for the backend:\n * - display name → POST /session/name (edge-router, self rename)\n * - content level → GET/PUT /prefs/api/v1/content-level (prefs-api)\n *\n * Switching keys goes through the SITE's sign-in client, never a call of ours:\n * see `loadSignIn()`, with `switchKeyHref()` as the fallback.\n *\n * These are same-origin relative paths, so ConnectedSettings is portable to any\n * app served under hadoku.me with zero wiring. Off-origin (e.g. a Storybook or\n * a non-hadoku host) every call resolves to null and the UI degrades to a\n * read-only shell — it never throws.\n *\n * The raw key is never held in the browser (the auth page deliberately drops\n * it), so name + content-level changes go through session identity, not a key\n * header, and no app ever asks for a key at all.\n *\n * WHEN THESE RUN\n * --------------\n * Everything the popout displays is resolved at PAGE LOAD, not on gear-click —\n * see `prefetchSettings()`. Opening settings must cost zero requests. Pinned by\n * `e2e/settings-prefetch.spec.ts` in hadoku-task.\n */\n\n/** Edge-router / prefs-api endpoints (same-origin relative). */\nconst CONTENT_LEVEL_PATH = '/prefs/api/v1/content-level'\nconst SESSION_NAME = '/session/name'\nconst ACCOUNT_DELETE = '/session/account/delete'\nconst SESSION_WHOAMI = '/session/whoami'\n\n/**\n * The ecosystem's shared boot-whoami promise. hadoku_site's `mf-loader.js`\n * kicks `GET /session/whoami` in parallel with the micro-frontend's module\n * import and parks the promise here precisely so the app it loads doesn't\n * resolve identity a second time; @wolffm/prefs-client already consumes it\n * under the same name. Reading it is what makes settings' identity free.\n *\n * Absent outside that shell (standalone vite, Capacitor, Storybook) — there we\n * fetch, and publish the result under the same key so the next reader is free\n * too.\n */\nconst WHOAMI_GLOBAL = '__hadokuWhoami'\n\n/**\n * Raw whoami body, as both mf-loader and this module see it off the wire.\n *\n * `contentLevel` / `maxContentLevel` are OPTIONAL because the shape is\n * versioned by whatever edge-router is deployed, not by this bundle. They\n * arrive from edge-router ≥ the 2026-08-07 change, which reports the level\n * `authGate` had already resolved to stamp X-Hadoku-Content-Level. When they\n * are absent we fall back to the standalone GET — see resolveSettings.\n *\n * `passkeys` (edge-router ≥ 2026-10-28) counts the passkeys that sign this\n * session in. Absent means unknown, never none.\n */\ninterface WhoamiBody {\n valid?: boolean\n userType?: Tier\n name?: string | null\n contentLevel?: number\n maxContentLevel?: number\n passkeys?: number\n}\n\n// Hard timeout on every settings request. Without it, a request throttled by\n// the browser (e.g. the tab going to the background) leaves the caller's\n// \"saving\" flag stuck true — which disabled the content-level pills until the\n// tab regained focus. AbortSignal.timeout guarantees the promise settles.\nconst REQUEST_TIMEOUT_MS = 8000\n\n/** Session-id header the same way whoami() sends it (cookie is the fallback). */\nfunction sessionHeaders(extra?: Record<string, string>): Record<string, string> {\n const headers: Record<string, string> = { 'Content-Type': 'application/json', ...extra }\n const sid = typeof window !== 'undefined' ? localStorage.getItem('hadoku_session_id') : null\n if (sid) headers['X-Session-Id'] = sid\n return headers\n}\n\nexport interface ContentLevelState {\n /** Current global content-visibility level (1 = safest default). */\n level: number\n /** Highest level this caller's tier may select (friend=3, admin=4). */\n maxLevel: number\n}\n\n/** GET the caller's current content level + tier ceiling. null on error. */\nexport async function getContentLevel(): Promise<ContentLevelState | null> {\n try {\n const res = await fetch(CONTENT_LEVEL_PATH, {\n credentials: 'same-origin',\n headers: sessionHeaders(),\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)\n })\n if (!res.ok) return null\n return (await res.json()) as ContentLevelState\n } catch {\n return null\n }\n}\n\n/** PUT a new content level. Server clamps to the tier ceiling → 400 if out of\n * range. Returns the stored state on success, null on any failure. */\nexport async function setContentLevel(level: number): Promise<ContentLevelState | null> {\n try {\n const res = await fetch(CONTENT_LEVEL_PATH, {\n method: 'PUT',\n credentials: 'same-origin',\n headers: sessionHeaders(),\n body: JSON.stringify({ level }),\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)\n })\n if (!res.ok) return null\n const stored = (await res.json()) as ContentLevelState\n patchSnapshot(prev => ({ ...prev, content: stored }))\n return stored\n } catch {\n return null\n }\n}\n\n/** Delete the signed-in member's own account (edge-router refuses any key\n * someone was handed). True when it is gone; the session cookie is cleared. */\nexport async function deleteOwnAccount(): Promise<boolean> {\n try {\n const res = await fetch(ACCOUNT_DELETE, {\n method: 'POST',\n credentials: 'same-origin',\n headers: sessionHeaders(),\n body: '{}',\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)\n })\n if (!res.ok) return false\n return ((await res.json()) as { deleted?: boolean }).deleted === true\n } catch {\n return false\n }\n}\n\n/** POST a new display name for the signed-in user. Returns the stored name\n * (may differ from the request for wp-* protected keys) or null on failure. */\nexport async function setDisplayName(name: string): Promise<string | null> {\n try {\n const res = await fetch(SESSION_NAME, {\n method: 'POST',\n credentials: 'same-origin',\n headers: sessionHeaders(),\n body: JSON.stringify({ name }),\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)\n })\n if (!res.ok) return null\n const body = (await res.json()) as { ok: boolean; name: string | null }\n patchSnapshot(prev => ({ ...prev, identity: { ...prev.identity, name: body.name } }))\n return body.name\n } catch {\n return null\n }\n}\n\n/**\n * The hadoku tier ladder, LOW to HIGH: `public < member < friend < service < wife < admin`.\n * `member` is a self-signed-up account (a passkey, no key), cardtable only.\n * Mirrors TIER_RANK in @wolffm/worker-utils, which this browser bundle cannot\n * import (it would pull hono into the client). A tier missing here does not\n * error — it fails the union and, worse, drops out of every `Record<Tier, …>`\n * lookup, so the caller renders as if unrecognised. Keep it complete.\n */\nexport type Tier = 'public' | 'member' | 'friend' | 'service' | 'wife' | 'admin'\n\nexport interface Identity {\n userType: Tier\n name: string | null\n}\n\n/**\n * The page's one whoami body, resolved at most once no matter how many callers.\n *\n * Under the hadoku.me shell this costs NO request: mf-loader kicks whoami in\n * parallel with the micro-frontend's module import and parks the promise on\n * WHOAMI_GLOBAL for exactly this reason (@wolffm/prefs-client reads the same\n * key). Elsewhere — standalone vite, Capacitor, Storybook — we fetch once and\n * publish under the same key so the next reader is free too.\n *\n * Resolves to null rather than throwing on any failure.\n */\nfunction sharedWhoami(): Promise<WhoamiBody | null> {\n const g = globalThis as { [WHOAMI_GLOBAL]?: Promise<WhoamiBody | null> }\n g[WHOAMI_GLOBAL] ??= fetch(SESSION_WHOAMI, {\n credentials: 'same-origin',\n headers: sessionHeaders(),\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)\n })\n .then(res => (res.ok ? (res.json() as Promise<WhoamiBody>) : null))\n .catch(() => null)\n return g[WHOAMI_GLOBAL]\n}\n\n/**\n * Resolve the signed-in caller's tier + display name from the edge-router.\n * Returns { userType: 'public', name: null } for anonymous / off-origin / any\n * failure — never throws, so ConnectedSettings can render unconditionally.\n */\nexport async function whoami(): Promise<Identity> {\n if (typeof window === 'undefined') return { userType: 'public', name: null }\n try {\n const body = await sharedWhoami()\n if (!body?.valid) return { userType: 'public', name: null }\n return { userType: body.userType ?? 'public', name: body.name ?? null }\n } catch {\n return { userType: 'public', name: null }\n }\n}\n\n/**\n * Where a \"Switch key\" control sends the user when the inline sign-in client\n * (`loadSignIn()`) can't be loaded: the site's sign-in page, which brings them\n * back here afterwards.\n *\n * A browser session is created ONLY by /auth (hadoku_site, 2026-10-25): every\n * render of that page carries an edge-signed funnel token and the device\n * fingerprint, and /session/create alerts on — and will refuse — a sign-in\n * without them. So an app never posts a key itself.\n *\n * `switch=1` stops /auth from sending an already signed-in visitor straight\n * back, which would make switching impossible. `return` is this page's path,\n * query and hash; /auth redirects there with the new session cookie, and the\n * shell's mf-loader resyncs the localStorage mirror (hadoku_session_id /\n * hadoku_user_type) from /session/whoami on that load, so nothing here writes it.\n */\nexport function switchKeyHref(): string {\n return (\n '/auth?switch=1&return=' +\n encodeURIComponent(window.location.pathname + window.location.search + window.location.hash)\n )\n}\n\n/** What the site's sign-in client resolves to on success. */\nexport interface SignInResult {\n valid: boolean\n userType?: string\n sessionId?: string\n}\n\n/** `signIn` from hadoku.me's `/auth/sign-in.js`. Resolves on success; throws an\n * `Error` carrying the server's message on a refused or empty key. */\nexport type SignIn = (key: string) => Promise<SignInResult>\n\n/**\n * The site serves its sign-in page's own client as a module, so an app can sign\n * in INLINE on the same code path as /auth: a fresh funnel token per call, the\n * device fingerprint, and the `/session/create` post that sets the cookie (and\n * writes the hadoku_session_id / hadoku_user_type mirror). This package never\n * posts /session/create itself — a direct post would skip the fingerprint and\n * read as off-funnel — and it does not vendor a copy.\n *\n * The specifier is a VARIABLE on purpose. A literal `import('/auth/sign-in.js')`\n * would have every bundler that re-bundles this package (hadoku_site's build\n * among them) try to resolve the path at build time; this one is only ever\n * resolved by the browser, against whatever origin the page is on. For the\n * same reason it is typed here (`SignIn`) rather than by an ambient module\n * declaration, which only a literal specifier would pick up.\n *\n * The module starts collecting the fingerprint as soon as it evaluates, so call\n * this when a sign-in form OPENS, not when it submits. Memoised; resolves to\n * null when the module can't be loaded (a dev server that isn't hadoku.me),\n * which is the caller's cue to fall back to `switchKeyHref()`.\n */\nconst SIGN_IN_MODULE = '/auth/sign-in.js'\nlet signInModule: Promise<SignInClient | null> | null = null\n\n/**\n * The whole sign-in client. The passkey half is optional: a site build from\n * before it exports only `signIn`, and the passkey controls then fall back to\n * the /auth page (`passkeyHref()`), as a missing module does.\n */\nexport interface SignInClient {\n signIn: SignIn\n /** Like `signIn`, with a passkey in place of the key. Throws Error(message).\n * `signal` cancels the open prompt. */\n signInWithPasskey?: (opts?: { signal?: AbortSignal }) => Promise<SignInResult>\n /** Saves a passkey for the signed-in person on this device. Throws Error(message). */\n addPasskey?: (opts?: { signal?: AbortSignal }) => Promise<{ saved: boolean; passkeys: number }>\n}\n\nexport function loadSignInClient(): Promise<SignInClient | null> {\n signInModule ??= import(/* @vite-ignore */ SIGN_IN_MODULE).then(\n (m: Partial<Record<keyof SignInClient, unknown>>) =>\n typeof m.signIn === 'function'\n ? {\n signIn: m.signIn as SignIn,\n signInWithPasskey:\n typeof m.signInWithPasskey === 'function'\n ? (m.signInWithPasskey as SignInClient['signInWithPasskey'])\n : undefined,\n addPasskey:\n typeof m.addPasskey === 'function'\n ? (m.addPasskey as SignInClient['addPasskey'])\n : undefined\n }\n : null,\n () => {\n // Let a later open retry: a failed fetch is not cached by the browser.\n signInModule = null\n return null\n }\n )\n return signInModule\n}\n\nexport function loadSignIn(): Promise<SignIn | null> {\n return loadSignInClient().then(c => c?.signIn ?? null)\n}\n\n/** Whether this browser can use a passkey at all (WebAuthn present). */\nexport function passkeysSupported(): boolean {\n return typeof window !== 'undefined' && 'PublicKeyCredential' in window\n}\n\n/**\n * The /auth page's passkey flows, for when the sign-in client can't be\n * loaded: `add` saves one for the signed-in visitor, `signin` is the page with\n * its passkey button. Both come back here afterwards.\n */\nexport function passkeyHref(mode: 'add' | 'signin'): string {\n if (mode === 'signin') return switchKeyHref()\n return (\n '/auth?passkey=add&return=' +\n encodeURIComponent(window.location.pathname + window.location.search + window.location.hash)\n )\n}\n\n/* ------------------------------------------------------------------ *\n * Prefetch\n * ------------------------------------------------------------------ */\n\n/** Everything the settings popout displays, resolved together. */\nexport interface SettingsSnapshot {\n identity: Identity\n /** null = public caller (no pill) or the request failed. */\n content: ContentLevelState | null\n /** Passkeys that sign this person in; null = unknown (older edge, host-supplied identity). */\n passkeys: number | null\n}\n\n/** Identity the host already knows, so we don't ask the server for it again. */\nexport interface SettingsPrefetchHints {\n /** Caller's tier. When supplied, whoami is skipped entirely. */\n userType?: Tier\n /** Caller's display name. Only meaningful alongside `userType`. */\n name?: string | null\n}\n\nlet snapshot: Promise<SettingsSnapshot> | null = null\n\n/**\n * Resolve — once per page load — everything the settings popout shows.\n *\n * This is THE entry point, and it is called from ConnectedSettings' MOUNT, not\n * from its open handler. Settings data is user identity: it is known at boot,\n * it doesn't change while the page is up, and making the gear the trigger left\n * the panel on screen but blank for a round trip (measured on prod: whoami\n * 167ms and content-level 186ms, issued concurrently). It now rides along with\n * the app's own boot traffic and the click costs nothing.\n *\n * Idempotent and shared: every caller after the first gets the same promise, so\n * N mounted consumers still produce at most one whoami for the whole page.\n * Mutations below write through to it rather than invalidating, so a remount\n * never shows a value the user just changed.\n *\n * Against a current edge-router this issues NO requests of its own at all — the\n * level rides on the whoami the shell already had in flight. See\n * resolveSettings for the fallback when it doesn't.\n */\nexport function prefetchSettings(hints: SettingsPrefetchHints = {}): Promise<SettingsSnapshot> {\n snapshot ??= resolveSettings(hints)\n return snapshot\n}\n\nasync function resolveSettings(hints: SettingsPrefetchHints): Promise<SettingsSnapshot> {\n // The whoami body, not just the adapted identity — edge-router carries the\n // content level on it (see below), and reading the raw body is how we get at\n // it without a second request.\n //\n // Skipped entirely when the host supplied identity: that prop exists for apps\n // that CANNOT reach /session/whoami (conjure sits behind a path-prefixed shim\n // where it 404s), so asking anyway would spend a request to learn nothing.\n const selfResolving = hints.userType === undefined && typeof window !== 'undefined'\n const bodyPromise = selfResolving ? sharedWhoami() : Promise.resolve(null)\n\n const identityPromise: Promise<Identity> =\n hints.userType !== undefined\n ? Promise.resolve({ userType: hints.userType, name: hints.name ?? null })\n : whoami()\n\n // PREFERRED PATH: take the level straight off whoami.\n //\n // edge-router's authGate has already resolved it (registry key → userId →\n // prefs D1) to stamp X-Hadoku-Content-Level, so reporting it on whoami costs\n // it nothing — and it saves us a proxied round trip to prefs-api that\n // measured 132-420ms against prod. Better still, whoami is in flight before\n // this bundle has even loaded, so the value is here the moment we ask.\n //\n // FALLBACK: the standalone GET, for any edge-router older than the\n // 2026-08-07 change, and for callers not behind it at all (Capacitor,\n // Storybook, a non-hadoku host). Gated on identity because the pill is\n // hidden for public callers — fetching an anonymous visitor's level is a\n // guaranteed-wasted request on every page view. `hadoku_user_type` is\n // written by the loader before anything mounts, so where it already says\n // \"signed in\" the fallback goes out concurrently rather than behind whoami.\n const contentPromise = bodyPromise.then(body => {\n const carried = contentFromWhoami(body)\n if (carried) return carried\n if (looksSignedIn(hints.userType)) return getContentLevel()\n return identityPromise.then(id => (id.userType === 'public' ? null : getContentLevel()))\n })\n\n const [identity, content, body] = await Promise.all([\n identityPromise,\n contentPromise,\n bodyPromise\n ])\n return { identity, content, passkeys: passkeysFromWhoami(body) }\n}\n\nfunction passkeysFromWhoami(body: WhoamiBody | null): number | null {\n return body?.valid && typeof body.passkeys === 'number' ? body.passkeys : null\n}\n\n/**\n * Adapt the content level off a whoami body, or null if that edge-router\n * doesn't report it.\n *\n * Both fields are required, and both must be numbers: a body carrying a level\n * without its ceiling would render a pill with zero segments — worse than the\n * fallback fetch, because it looks like a working control that offers nothing.\n */\nfunction contentFromWhoami(body: WhoamiBody | null): ContentLevelState | null {\n if (!body?.valid) return null\n const { contentLevel, maxContentLevel } = body\n if (typeof contentLevel !== 'number' || typeof maxContentLevel !== 'number') return null\n if (maxContentLevel < 1) return null\n return { level: contentLevel, maxLevel: maxContentLevel }\n}\n\n/** Best-effort \"is this caller signed in?\" from state available synchronously. */\nfunction looksSignedIn(hinted?: Tier): boolean {\n if (hinted !== undefined) return hinted !== 'public'\n if (typeof window === 'undefined') return false\n const cached = localStorage.getItem('hadoku_user_type')\n return cached !== null && cached !== 'public'\n}\n\n/** Keep the prefetched snapshot in step with a successful mutation. */\nfunction patchSnapshot(patch: (prev: SettingsSnapshot) => SettingsSnapshot) {\n if (!snapshot) return\n snapshot = snapshot.then(patch)\n}\n"],"names":["body"],"mappings":"AA6BA,MAAM,qBAAqB;AAC3B,MAAM,eAAe;AACrB,MAAM,iBAAiB;AACvB,MAAM,iBAAiB;AAavB,MAAM,gBAAgB;AA2BtB,MAAM,qBAAqB;AAG3B,SAAS,eAAe,OAAwD;AAC9E,QAAM,UAAkC,EAAE,gBAAgB,oBAAoB,GAAG,MAAA;AACjF,QAAM,MAAM,OAAO,WAAW,cAAc,aAAa,QAAQ,mBAAmB,IAAI;AACxF,MAAI,IAAK,SAAQ,cAAc,IAAI;AACnC,SAAO;AACT;AAUA,eAAsB,kBAAqD;AACzE,MAAI;AACF,UAAM,MAAM,MAAM,MAAM,oBAAoB;AAAA,MAC1C,aAAa;AAAA,MACb,SAAS,eAAA;AAAA,MACT,QAAQ,YAAY,QAAQ,kBAAkB;AAAA,IAAA,CAC/C;AACD,QAAI,CAAC,IAAI,GAAI,QAAO;AACpB,WAAQ,MAAM,IAAI,KAAA;AAAA,EACpB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAIA,eAAsB,gBAAgB,OAAkD;AACtF,MAAI;AACF,UAAM,MAAM,MAAM,MAAM,oBAAoB;AAAA,MAC1C,QAAQ;AAAA,MACR,aAAa;AAAA,MACb,SAAS,eAAA;AAAA,MACT,MAAM,KAAK,UAAU,EAAE,OAAO;AAAA,MAC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AQ,kBAAkB;AACtD,SAAO,WAAW,QAAQ,WAAW;AACvC;AAGA,SAAS,cAAc,OAAqD;AAC1E,MAAI,CAAC,SAAU;AACf,aAAW,SAAS,KAAK,KAAK;AAChC;"}
1
+ {"version":3,"file":"settingsClient.js","sources":["../../src/lib/settingsClient.ts"],"sourcesContent":["/**\n * Client for the unified user-settings modal (ConnectedSettings).\n *\n * Two concerns, both cookie-authed against the hadoku.me edge-router, which\n * resolves the `hadoku_session` cookie / `X-Session-Id` header → X-User-Key +\n * X-User-Id for the backend:\n * - display name → POST /session/name (edge-router, self rename)\n * - content level → GET/PUT /prefs/api/v1/content-level (prefs-api)\n *\n * Switching keys goes through the SITE's sign-in client, never a call of ours:\n * see `loadSignIn()`, with `switchKeyHref()` as the fallback.\n *\n * These are same-origin relative paths, so ConnectedSettings is portable to any\n * app served under hadoku.me with zero wiring. Off-origin (e.g. a Storybook or\n * a non-hadoku host) every call resolves to null and the UI degrades to a\n * read-only shell — it never throws.\n *\n * The raw key is never held in the browser (the auth page deliberately drops\n * it), so name + content-level changes go through session identity, not a key\n * header, and no app ever asks for a key at all.\n *\n * WHEN THESE RUN\n * --------------\n * Everything the popout displays is resolved at PAGE LOAD, not on gear-click —\n * see `prefetchSettings()`. Opening settings must cost zero requests. Pinned by\n * `e2e/settings-prefetch.spec.ts` in hadoku-task.\n */\n\n/** Edge-router / prefs-api endpoints (same-origin relative). */\nconst CONTENT_LEVEL_PATH = '/prefs/api/v1/content-level'\nconst SESSION_NAME = '/session/name'\nconst ACCOUNT_DELETE = '/session/account/delete'\nconst SESSION_WHOAMI = '/session/whoami'\n\n/**\n * The ecosystem's shared boot-whoami promise. hadoku_site's `mf-loader.js`\n * kicks `GET /session/whoami` in parallel with the micro-frontend's module\n * import and parks the promise here precisely so the app it loads doesn't\n * resolve identity a second time; @wolffm/prefs-client already consumes it\n * under the same name. Reading it is what makes settings' identity free.\n *\n * Absent outside that shell (standalone vite, Capacitor, Storybook) — there we\n * fetch, and publish the result under the same key so the next reader is free\n * too.\n */\nconst WHOAMI_GLOBAL = '__hadokuWhoami'\n\n/**\n * Raw whoami body, as both mf-loader and this module see it off the wire.\n *\n * `contentLevel` / `maxContentLevel` are OPTIONAL because the shape is\n * versioned by whatever edge-router is deployed, not by this bundle. They\n * arrive from edge-router ≥ the 2026-08-07 change, which reports the level\n * `authGate` had already resolved to stamp X-Hadoku-Content-Level. When they\n * are absent we fall back to the standalone GET — see resolveSettings.\n *\n * `passkeys` (edge-router ≥ 2026-10-28) counts the passkeys that sign this\n * session in. Absent means unknown, never none.\n */\ninterface WhoamiBody {\n valid?: boolean\n userType?: Tier\n name?: string | null\n contentLevel?: number\n maxContentLevel?: number\n passkeys?: number\n}\n\n// Hard timeout on every settings request. Without it, a request throttled by\n// the browser (e.g. the tab going to the background) leaves the caller's\n// \"saving\" flag stuck true — which disabled the content-level pills until the\n// tab regained focus. AbortSignal.timeout guarantees the promise settles.\nconst REQUEST_TIMEOUT_MS = 8000\n\n/** Session-id header the same way whoami() sends it (cookie is the fallback). */\nfunction sessionHeaders(extra?: Record<string, string>): Record<string, string> {\n const headers: Record<string, string> = { 'Content-Type': 'application/json', ...extra }\n const sid = typeof window !== 'undefined' ? localStorage.getItem('hadoku_session_id') : null\n if (sid) headers['X-Session-Id'] = sid\n return headers\n}\n\nexport interface ContentLevelState {\n /** Current global content-visibility level (1 = safest default). */\n level: number\n /** Highest level this caller's tier may select (friend=3, admin=4). */\n maxLevel: number\n}\n\n/** GET the caller's current content level + tier ceiling. null on error. */\nexport async function getContentLevel(): Promise<ContentLevelState | null> {\n try {\n const res = await fetch(CONTENT_LEVEL_PATH, {\n credentials: 'same-origin',\n headers: sessionHeaders(),\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)\n })\n if (!res.ok) return null\n return (await res.json()) as ContentLevelState\n } catch {\n return null\n }\n}\n\n/** PUT a new content level. Server clamps to the tier ceiling → 400 if out of\n * range. Returns the stored state on success, null on any failure. */\nexport async function setContentLevel(level: number): Promise<ContentLevelState | null> {\n try {\n const res = await fetch(CONTENT_LEVEL_PATH, {\n method: 'PUT',\n credentials: 'same-origin',\n headers: sessionHeaders(),\n body: JSON.stringify({ level }),\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)\n })\n if (!res.ok) return null\n const stored = (await res.json()) as ContentLevelState\n patchSnapshot(prev => ({ ...prev, content: stored }))\n return stored\n } catch {\n return null\n }\n}\n\n/** Delete the signed-in member's own account (edge-router refuses any key\n * someone was handed). True when it is gone; the session cookie is cleared. */\nexport async function deleteOwnAccount(): Promise<boolean> {\n try {\n const res = await fetch(ACCOUNT_DELETE, {\n method: 'POST',\n credentials: 'same-origin',\n headers: sessionHeaders(),\n body: '{}',\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)\n })\n if (!res.ok) return false\n return ((await res.json()) as { deleted?: boolean }).deleted === true\n } catch {\n return false\n }\n}\n\n/**\n * POST a new display name for the signed-in user. Answers the stored name (may\n * differ from the request for wp-* protected keys), or why it was refused: the\n * server's own words where it gave any (\"That display name is already taken\"),\n * so the editor can say them.\n */\nexport type RenameResult = { ok: true; name: string | null } | { ok: false; error: string }\n\nexport async function setDisplayName(name: string): Promise<RenameResult> {\n try {\n const res = await fetch(SESSION_NAME, {\n method: 'POST',\n credentials: 'same-origin',\n headers: sessionHeaders(),\n body: JSON.stringify({ name }),\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)\n })\n if (!res.ok) {\n const body = (await res.json().catch(() => null)) as { error?: unknown } | null\n const said = typeof body?.error === 'string' ? body.error : null\n return { ok: false, error: said ?? `Not saved (${res.status})` }\n }\n const body = (await res.json()) as { ok: boolean; name: string | null }\n patchSnapshot(prev => ({ ...prev, identity: { ...prev.identity, name: body.name } }))\n return { ok: true, name: body.name }\n } catch {\n return { ok: false, error: 'Not saved: no connection' }\n }\n}\n\n/**\n * The hadoku tier ladder, LOW to HIGH: `public < member < friend < service < wife < admin`.\n * `member` is a self-signed-up account (a passkey, no key), cardtable only.\n * Mirrors TIER_RANK in @wolffm/worker-utils, which this browser bundle cannot\n * import (it would pull hono into the client). A tier missing here does not\n * error — it fails the union and, worse, drops out of every `Record<Tier, …>`\n * lookup, so the caller renders as if unrecognised. Keep it complete.\n */\nexport type Tier = 'public' | 'member' | 'friend' | 'service' | 'wife' | 'admin'\n\nexport interface Identity {\n userType: Tier\n name: string | null\n}\n\n/**\n * The page's one whoami body, resolved at most once no matter how many callers.\n *\n * Under the hadoku.me shell this costs NO request: mf-loader kicks whoami in\n * parallel with the micro-frontend's module import and parks the promise on\n * WHOAMI_GLOBAL for exactly this reason (@wolffm/prefs-client reads the same\n * key). Elsewhere — standalone vite, Capacitor, Storybook — we fetch once and\n * publish under the same key so the next reader is free too.\n *\n * Resolves to null rather than throwing on any failure.\n */\nfunction sharedWhoami(): Promise<WhoamiBody | null> {\n const g = globalThis as { [WHOAMI_GLOBAL]?: Promise<WhoamiBody | null> }\n g[WHOAMI_GLOBAL] ??= fetch(SESSION_WHOAMI, {\n credentials: 'same-origin',\n headers: sessionHeaders(),\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)\n })\n .then(res => (res.ok ? (res.json() as Promise<WhoamiBody>) : null))\n .catch(() => null)\n return g[WHOAMI_GLOBAL]\n}\n\n/**\n * Resolve the signed-in caller's tier + display name from the edge-router.\n * Returns { userType: 'public', name: null } for anonymous / off-origin / any\n * failure — never throws, so ConnectedSettings can render unconditionally.\n */\nexport async function whoami(): Promise<Identity> {\n if (typeof window === 'undefined') return { userType: 'public', name: null }\n try {\n const body = await sharedWhoami()\n if (!body?.valid) return { userType: 'public', name: null }\n return { userType: body.userType ?? 'public', name: body.name ?? null }\n } catch {\n return { userType: 'public', name: null }\n }\n}\n\n/**\n * Where a \"Switch key\" control sends the user when the inline sign-in client\n * (`loadSignIn()`) can't be loaded: the site's sign-in page, which brings them\n * back here afterwards.\n *\n * A browser session is created ONLY by /auth (hadoku_site, 2026-10-25): every\n * render of that page carries an edge-signed funnel token and the device\n * fingerprint, and /session/create alerts on — and will refuse — a sign-in\n * without them. So an app never posts a key itself.\n *\n * `switch=1` stops /auth from sending an already signed-in visitor straight\n * back, which would make switching impossible. `return` is this page's path,\n * query and hash; /auth redirects there with the new session cookie, and the\n * shell's mf-loader resyncs the localStorage mirror (hadoku_session_id /\n * hadoku_user_type) from /session/whoami on that load, so nothing here writes it.\n */\nexport function switchKeyHref(): string {\n return (\n '/auth?switch=1&return=' +\n encodeURIComponent(window.location.pathname + window.location.search + window.location.hash)\n )\n}\n\n/** What the site's sign-in client resolves to on success. */\nexport interface SignInResult {\n valid: boolean\n userType?: string\n sessionId?: string\n}\n\n/** `signIn` from hadoku.me's `/auth/sign-in.js`. Resolves on success; throws an\n * `Error` carrying the server's message on a refused or empty key. */\nexport type SignIn = (key: string) => Promise<SignInResult>\n\n/**\n * The site serves its sign-in page's own client as a module, so an app can sign\n * in INLINE on the same code path as /auth: a fresh funnel token per call, the\n * device fingerprint, and the `/session/create` post that sets the cookie (and\n * writes the hadoku_session_id / hadoku_user_type mirror). This package never\n * posts /session/create itself — a direct post would skip the fingerprint and\n * read as off-funnel — and it does not vendor a copy.\n *\n * The specifier is a VARIABLE on purpose. A literal `import('/auth/sign-in.js')`\n * would have every bundler that re-bundles this package (hadoku_site's build\n * among them) try to resolve the path at build time; this one is only ever\n * resolved by the browser, against whatever origin the page is on. For the\n * same reason it is typed here (`SignIn`) rather than by an ambient module\n * declaration, which only a literal specifier would pick up.\n *\n * The module starts collecting the fingerprint as soon as it evaluates, so call\n * this when a sign-in form OPENS, not when it submits. Memoised; resolves to\n * null when the module can't be loaded (a dev server that isn't hadoku.me),\n * which is the caller's cue to fall back to `switchKeyHref()`.\n */\nconst SIGN_IN_MODULE = '/auth/sign-in.js'\nlet signInModule: Promise<SignInClient | null> | null = null\n\n/**\n * The whole sign-in client. The passkey half is optional: a site build from\n * before it exports only `signIn`, and the passkey controls then fall back to\n * the /auth page (`passkeyHref()`), as a missing module does.\n */\nexport interface SignInClient {\n signIn: SignIn\n /** Like `signIn`, with a passkey in place of the key. Throws Error(message).\n * `signal` cancels the open prompt. */\n signInWithPasskey?: (opts?: { signal?: AbortSignal }) => Promise<SignInResult>\n /** Saves a passkey for the signed-in person on this device. Throws Error(message). */\n addPasskey?: (opts?: { signal?: AbortSignal }) => Promise<{ saved: boolean; passkeys: number }>\n}\n\nexport function loadSignInClient(): Promise<SignInClient | null> {\n signInModule ??= import(/* @vite-ignore */ SIGN_IN_MODULE).then(\n (m: Partial<Record<keyof SignInClient, unknown>>) =>\n typeof m.signIn === 'function'\n ? {\n signIn: m.signIn as SignIn,\n signInWithPasskey:\n typeof m.signInWithPasskey === 'function'\n ? (m.signInWithPasskey as SignInClient['signInWithPasskey'])\n : undefined,\n addPasskey:\n typeof m.addPasskey === 'function'\n ? (m.addPasskey as SignInClient['addPasskey'])\n : undefined\n }\n : null,\n () => {\n // Let a later open retry: a failed fetch is not cached by the browser.\n signInModule = null\n return null\n }\n )\n return signInModule\n}\n\nexport function loadSignIn(): Promise<SignIn | null> {\n return loadSignInClient().then(c => c?.signIn ?? null)\n}\n\n/** Whether this browser can use a passkey at all (WebAuthn present). */\nexport function passkeysSupported(): boolean {\n return typeof window !== 'undefined' && 'PublicKeyCredential' in window\n}\n\n/**\n * The /auth page's passkey flows, for when the sign-in client can't be\n * loaded: `add` saves one for the signed-in visitor, `signin` is the page with\n * its passkey button. Both come back here afterwards.\n */\nexport function passkeyHref(mode: 'add' | 'signin'): string {\n if (mode === 'signin') return switchKeyHref()\n return (\n '/auth?passkey=add&return=' +\n encodeURIComponent(window.location.pathname + window.location.search + window.location.hash)\n )\n}\n\n/* ------------------------------------------------------------------ *\n * Prefetch\n * ------------------------------------------------------------------ */\n\n/** Everything the settings popout displays, resolved together. */\nexport interface SettingsSnapshot {\n identity: Identity\n /** null = public caller (no pill) or the request failed. */\n content: ContentLevelState | null\n /** Passkeys that sign this person in; null = unknown (older edge, host-supplied identity). */\n passkeys: number | null\n}\n\n/** Identity the host already knows, so we don't ask the server for it again. */\nexport interface SettingsPrefetchHints {\n /** Caller's tier. When supplied, whoami is skipped entirely. */\n userType?: Tier\n /** Caller's display name. Only meaningful alongside `userType`. */\n name?: string | null\n}\n\nlet snapshot: Promise<SettingsSnapshot> | null = null\n\n/**\n * Resolve — once per page load — everything the settings popout shows.\n *\n * This is THE entry point, and it is called from ConnectedSettings' MOUNT, not\n * from its open handler. Settings data is user identity: it is known at boot,\n * it doesn't change while the page is up, and making the gear the trigger left\n * the panel on screen but blank for a round trip (measured on prod: whoami\n * 167ms and content-level 186ms, issued concurrently). It now rides along with\n * the app's own boot traffic and the click costs nothing.\n *\n * Idempotent and shared: every caller after the first gets the same promise, so\n * N mounted consumers still produce at most one whoami for the whole page.\n * Mutations below write through to it rather than invalidating, so a remount\n * never shows a value the user just changed.\n *\n * Against a current edge-router this issues NO requests of its own at all — the\n * level rides on the whoami the shell already had in flight. See\n * resolveSettings for the fallback when it doesn't.\n */\nexport function prefetchSettings(hints: SettingsPrefetchHints = {}): Promise<SettingsSnapshot> {\n snapshot ??= resolveSettings(hints)\n return snapshot\n}\n\nasync function resolveSettings(hints: SettingsPrefetchHints): Promise<SettingsSnapshot> {\n // The whoami body, not just the adapted identity — edge-router carries the\n // content level on it (see below), and reading the raw body is how we get at\n // it without a second request.\n //\n // Skipped entirely when the host supplied identity: that prop exists for apps\n // that CANNOT reach /session/whoami (conjure sits behind a path-prefixed shim\n // where it 404s), so asking anyway would spend a request to learn nothing.\n const selfResolving = hints.userType === undefined && typeof window !== 'undefined'\n const bodyPromise = selfResolving ? sharedWhoami() : Promise.resolve(null)\n\n const identityPromise: Promise<Identity> =\n hints.userType !== undefined\n ? Promise.resolve({ userType: hints.userType, name: hints.name ?? null })\n : whoami()\n\n // PREFERRED PATH: take the level straight off whoami.\n //\n // edge-router's authGate has already resolved it (registry key → userId →\n // prefs D1) to stamp X-Hadoku-Content-Level, so reporting it on whoami costs\n // it nothing — and it saves us a proxied round trip to prefs-api that\n // measured 132-420ms against prod. Better still, whoami is in flight before\n // this bundle has even loaded, so the value is here the moment we ask.\n //\n // FALLBACK: the standalone GET, for any edge-router older than the\n // 2026-08-07 change, and for callers not behind it at all (Capacitor,\n // Storybook, a non-hadoku host). Gated on identity because the pill is\n // hidden for public callers — fetching an anonymous visitor's level is a\n // guaranteed-wasted request on every page view. `hadoku_user_type` is\n // written by the loader before anything mounts, so where it already says\n // \"signed in\" the fallback goes out concurrently rather than behind whoami.\n const contentPromise = bodyPromise.then(body => {\n const carried = contentFromWhoami(body)\n if (carried) return carried\n if (looksSignedIn(hints.userType)) return getContentLevel()\n return identityPromise.then(id => (id.userType === 'public' ? null : getContentLevel()))\n })\n\n const [identity, content, body] = await Promise.all([\n identityPromise,\n contentPromise,\n bodyPromise\n ])\n return { identity, content, passkeys: passkeysFromWhoami(body) }\n}\n\nfunction passkeysFromWhoami(body: WhoamiBody | null): number | null {\n return body?.valid && typeof body.passkeys === 'number' ? body.passkeys : null\n}\n\n/**\n * Adapt the content level off a whoami body, or null if that edge-router\n * doesn't report it.\n *\n * Both fields are required, and both must be numbers: a body carrying a level\n * without its ceiling would render a pill with zero segments — worse than the\n * fallback fetch, because it looks like a working control that offers nothing.\n */\nfunction contentFromWhoami(body: WhoamiBody | null): ContentLevelState | null {\n if (!body?.valid) return null\n const { contentLevel, maxContentLevel } = body\n if (typeof contentLevel !== 'number' || typeof maxContentLevel !== 'number') return null\n if (maxContentLevel < 1) return null\n return { level: contentLevel, maxLevel: maxContentLevel }\n}\n\n/** Best-effort \"is this caller signed in?\" from state available synchronously. */\nfunction looksSignedIn(hinted?: Tier): boolean {\n if (hinted !== undefined) return hinted !== 'public'\n if (typeof window === 'undefined') return false\n const cached = localStorage.getItem('hadoku_user_type')\n return cached !== null && cached !== 'public'\n}\n\n/** Keep the prefetched snapshot in step with a successful mutation. */\nfunction patchSnapshot(patch: (prev: SettingsSnapshot) => SettingsSnapshot) {\n if (!snapshot) return\n snapshot = snapshot.then(patch)\n}\n"],"names":["body"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 @@
823
823
  * has something to grow into now that its basis is 0. */
824
824
  flex: 1 1 auto;
825
825
  min-width: 0;
826
+ flex-wrap: wrap;
827
+ }
828
+ /* A refused rename's reason, on its own line under the input. */
829
+ .settings-popout__inline > .settings-popout__error {
830
+ flex-basis: 100%;
826
831
  }
827
832
  .settings-popout__tier {
828
833
  font-size: 0.78rem;
@@ -823,6 +823,11 @@
823
823
  * has something to grow into now that its basis is 0. */
824
824
  flex: 1 1 auto;
825
825
  min-width: 0;
826
+ flex-wrap: wrap;
827
+ }
828
+ /* A refused rename's reason, on its own line under the input. */
829
+ .settings-popout__inline > .settings-popout__error {
830
+ flex-basis: 100%;
826
831
  }
827
832
  .settings-popout__tier {
828
833
  font-size: 0.78rem;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hadoku/task-ui-components",
3
- "version": "4.22.0",
3
+ "version": "4.22.1",
4
4
  "description": "Reusable UI components with Bento grid and metallic gradient support",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -183,6 +183,11 @@
183
183
  * has something to grow into now that its basis is 0. */
184
184
  flex: 1 1 auto;
185
185
  min-width: 0;
186
+ flex-wrap: wrap;
187
+ }
188
+ /* A refused rename's reason, on its own line under the input. */
189
+ .settings-popout__inline > .settings-popout__error {
190
+ flex-basis: 100%;
186
191
  }
187
192
 
188
193
  .settings-popout__tier {
@@ -154,6 +154,7 @@ export function ConnectedSettings({
154
154
  const [nameDraft, setNameDraft] = useState(resolvedName ?? '')
155
155
  const [editingName, setEditingName] = useState(false)
156
156
  const [nameSaving, setNameSaving] = useState(false)
157
+ const [nameError, setNameError] = useState<string | null>(null)
157
158
  const [displayName, setLocalName] = useState<string | null>(resolvedName)
158
159
 
159
160
  // Key swap. The draft lives only in this state and the input: it is never
@@ -279,13 +280,17 @@ export function ConnectedSettings({
279
280
  return
280
281
  }
281
282
  setNameSaving(true)
282
- const stored = await setDisplayName(trimmed)
283
+ const result = await setDisplayName(trimmed)
283
284
  setNameSaving(false)
284
- if (stored !== null) {
285
- setLocalName(stored)
286
- setNameDraft(stored)
287
- onNameChange?.(stored)
285
+ // A refusal keeps the editor open on the draft, saying why.
286
+ if (!result.ok) {
287
+ setNameError(result.error)
288
+ return
288
289
  }
290
+ setNameError(null)
291
+ setLocalName(result.name)
292
+ setNameDraft(result.name ?? '')
293
+ if (result.name !== null) onNameChange?.(result.name)
289
294
  setEditingName(false)
290
295
  }, [nameDraft, displayName, onNameChange])
291
296
 
@@ -461,7 +466,12 @@ export function ConnectedSettings({
461
466
  maxLength={64}
462
467
  autoFocus
463
468
  disabled={nameSaving}
464
- onChange={e => setNameDraft(e.target.value)}
469
+ aria-invalid={nameError !== null}
470
+ aria-describedby={nameError ? 'settings-popout-name-error' : undefined}
471
+ onChange={e => {
472
+ setNameDraft(e.target.value)
473
+ setNameError(null)
474
+ }}
465
475
  onKeyDown={e => {
466
476
  if (e.key === 'Enter') {
467
477
  saveName().catch(reportErr)
@@ -470,6 +480,7 @@ export function ConnectedSettings({
470
480
  // The edit's Escape, not the popout's (window listener).
471
481
  e.stopPropagation()
472
482
  setEditingName(false)
483
+ setNameError(null)
473
484
  setNameDraft(displayName ?? '')
474
485
  }
475
486
  }}
@@ -484,6 +495,15 @@ export function ConnectedSettings({
484
495
  >
485
496
  {nameSaving ? '…' : 'Save'}
486
497
  </button>
498
+ {nameError && (
499
+ <span
500
+ id="settings-popout-name-error"
501
+ className="settings-popout__error"
502
+ role="alert"
503
+ >
504
+ {nameError}
505
+ </span>
506
+ )}
487
507
  </span>
488
508
  ) : (
489
509
  <button
@@ -140,9 +140,15 @@ export async function deleteOwnAccount(): Promise<boolean> {
140
140
  }
141
141
  }
142
142
 
143
- /** POST a new display name for the signed-in user. Returns the stored name
144
- * (may differ from the request for wp-* protected keys) or null on failure. */
145
- export async function setDisplayName(name: string): Promise<string | null> {
143
+ /**
144
+ * POST a new display name for the signed-in user. Answers the stored name (may
145
+ * differ from the request for wp-* protected keys), or why it was refused: the
146
+ * server's own words where it gave any ("That display name is already taken"),
147
+ * so the editor can say them.
148
+ */
149
+ export type RenameResult = { ok: true; name: string | null } | { ok: false; error: string }
150
+
151
+ export async function setDisplayName(name: string): Promise<RenameResult> {
146
152
  try {
147
153
  const res = await fetch(SESSION_NAME, {
148
154
  method: 'POST',
@@ -151,12 +157,16 @@ export async function setDisplayName(name: string): Promise<string | null> {
151
157
  body: JSON.stringify({ name }),
152
158
  signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
153
159
  })
154
- if (!res.ok) return null
160
+ if (!res.ok) {
161
+ const body = (await res.json().catch(() => null)) as { error?: unknown } | null
162
+ const said = typeof body?.error === 'string' ? body.error : null
163
+ return { ok: false, error: said ?? `Not saved (${res.status})` }
164
+ }
155
165
  const body = (await res.json()) as { ok: boolean; name: string | null }
156
166
  patchSnapshot(prev => ({ ...prev, identity: { ...prev.identity, name: body.name } }))
157
- return body.name
167
+ return { ok: true, name: body.name }
158
168
  } catch {
159
- return null
169
+ return { ok: false, error: 'Not saved: no connection' }
160
170
  }
161
171
  }
162
172