Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 | 8x 17x 77x 17x 17x 8x 17x 8x 8x 8x 8x 8x 8x 8x 17x 17x 8x 8x 8x 8x 8x 8x 8x 77x 17x 8x 8x 8x 8x 8x 17x 17x 69x 17x 17x 12x 12x 4x 4x 4x 17x 17x 17x 8x 8x 17x 8x 8x 8x 17x 17x 17x 17x 17x 17x 17x 9x 9x 34x 8x | /**
* App — top-level blong-browser application component.
*
* Provides the single composition root for the portal UI. Wraps the Portal
* shell with BlongProvider so all child components have access to the handler
* proxy, the schema registry, and TanStack Query.
*
* This component is the canonical reuse point:
* - `portalReady` renders it into the DOM via ReactDOM.createRoot
* - Storybook decorators mount it with a mock handler proxy
* - Unit tests can render it with a spy handler proxy
*
* Props mirror IPortalProps so callers can customise the shell (logo, etc.)
* while the provider wiring is always handled here.
*/
import {ConfirmDialog, ConfirmPopup, PrimeReactProvider} from '../../primereact/shell.js';
import './App.css';
import type {IHandlerProxy, ILogger} from '@feasibleone/blong';
import React from 'react';
import {BlongProvider, useBlong, type IBlongPortalConfig} from '../../context/BlongContext.js';
import {collectStart} from '../../i18n/collect.js';
import {withTranslationReport} from '../../i18n/menu.js';
import {bgLocale} from '../../primereact/locales.js';
import {useAppStore} from '../../state/appStore.js';
import {type IPortalConfig} from '../../storybook.js';
import {AccountMenu} from '../AccountMenu/AccountMenu.js';
import {ErrorDialog} from '../Error/Error.js';
import {FeedbackLayer} from '../../feedback/FeedbackLayer.js';
import {FeedbackToggle} from '../../feedback/FeedbackToggle.js';
import {FeedbackActiveContext} from '../../feedback/useFeedbackTarget.js';
import {prefetchPageSystem} from '../../prefetch.js';
import {sessionKey} from '../../lib/sessionKey.js';
import {ActionHint} from '../Hint/Hint.js';
import {LanguageSwitcher} from '../LanguageSwitcher/LanguageSwitcher.js';
import {Login} from '../Login/Login.js';
import {LoginPopup} from '../LoginPopup/LoginPopup.js';
import {OAuthCallback} from '../OAuthCallback/OAuthCallback.js';
import {Portal, type IPortalProps} from '../Portal/Portal.js';
import {Theme, type IThemeConfig} from '../Theme/Theme.js';
import {ThemeSwitcher} from '../ThemeSwitcher/ThemeSwitcher.js';
import {LanguageDataRefresh} from './LanguageDataRefresh.js';
const DEFAULT_THEME: IThemeConfig = {
type: 'compact',
palette: 'dark',
// Bundled PrimeReact locales — registered up front so `setLanguage`
// (e.g. from a user's preferred language at login) never crashes the
// Theme with an unknown locale. Only activated when that language is set.
languages: {bg: bgLocale},
};
export interface IAppProps extends IPortalProps {
/**
* Handler proxy injected by the browser platform.
* config.portal may contain schemaUrl, baseUrl, debug, loginRoute.
*/
handlerProxy: IHandlerProxy<{portal?: IBlongPortalConfig} & Record<string, unknown>>;
/** Logger instance */
log?: ILogger;
/** PrimeReact theme configuration (defaults to compact / dark palette) */
theme?: IThemeConfig;
/**
* When provided, renders in place of the Portal shell.
* Useful for Storybook decorators and unit tests that need provider
* context (BlongProvider + Theme) without the full portal UI.
*/
children?: React.ReactNode;
/**
* Optional component rendered instead of the portal when the user is not
* authenticated (i.e. `auth.isAuthenticated` is false).
* The component may call useBlong() to access the handler proxy.
*/
loginComponent?: React.ComponentType;
}
function AppShell({
loginComponent: LoginComponent,
children,
portalProps,
}: {
loginComponent?: React.ComponentType;
children?: React.ReactNode;
portalProps: IPortalProps;
}) {
const {handler, config} = useBlong();
const isAuthenticated = useAppStore(s => s.auth.isAuthenticated);
// Boot-time session restore: exchange the restore cookie for fresh tokens
// so a reload with a live session skips the login screen. `restored`
// gates the first paint to avoid a login-screen flash while the request
// round-trips.
const [restored, setRestored] = React.useState(false);
React.useEffect(() => {
// The shell is on screen; everything a page needs can arrive while the reader
// logs in, so the first menu click opens a page instead of its code.
prefetchPageSystem();
}, []);
React.useEffect(() => {
let cancelled = false;
(async () => {
try {
await handler.authSessionGet({}, {});
} catch {
// Ignore — stays logged out.
} finally {
Eif (!cancelled) setRestored(true);
}
})();
return () => {
cancelled = true;
};
}, [handler]);
// OAuth callback handling runs once — after a successful exchange the
// callback URL is stripped and the App must drop this screen (the session
// token is already in the store by then).
const [oauthHandled, setOauthHandled] = React.useState(false);
React.useEffect(() => {
Eif (isAuthenticated) {
// The composing entry point, not `portalConfigGet`: that name resolves
// to a single provider, so two realms that own pages would replace each
// other's menu (see src/portalConfig.ts).
const merged = handler.portalConfigMerge({}, {}) as Promise<IPortalConfig> | undefined;
Promise.resolve(merged)
.then(config => {
// The untranslated-strings page is only reachable from a portal
// that collects, so a normal menu never grows it (`D-634`).
Eif (config)
useAppStore.getState().setPortalConfig(withTranslationReport(config));
})
// The composed answer arrives after the suite's own config has
// already painted, so the menu (and a realm's brand) changes under
// the reader's feet. Say when that has happened, one frame later:
// the Playwright fixture waits for it, so a capture never catches
// the portal half-composed. Set even when the merge failed, because
// the failure is what the fixture reports.
.finally(() => {
requestAnimationFrame(() => {
document.documentElement.setAttribute('data-portal-config', 'merged');
});
});
}
}, [handler, isAuthenticated]);
// The database half of the dictionary. The method names come from the merged
// portal configuration, so blong-browser needs no dependency on blong-core and
// a suite can point them elsewhere (D-630). Registering the loader does not
// call it: login and the language switcher do. Only the label dictionary is
// read — a record's own name is translated by the query that reads it, in the
// active language, and never in the browser (`D-635`).
const mergedPortalConfig = useAppStore(s => s.portal.portalConfig);
React.useEffect(() => {
const load = mergedPortalConfig?.translation?.load;
const store = useAppStore.getState();
Eif (!load?.label) {
store.setTranslationLoader(undefined);
return;
}
const methods = handler as unknown as Record<
string,
((params: object, $meta: object) => Promise<unknown>) | undefined
>;
store.setTranslationLoader(async language => {
const label = await methods[load.label!]?.({languageCode: language}, {});
return {label: label as Record<string, string> | undefined};
});
// A session that is already up (a restore, or a config that changed under
// the reader) gets the newly available dictionary without a reload.
if (store.auth.isAuthenticated) void store.languageActivate(store.language);
}, [mergedPortalConfig?.translation?.load, handler]);
// A stored file is read by the browser from a plain `<img>` or `<a>` — a route, not a call — so the
// session cannot vouch for the read itself: `/a/<namespace>/<key>` reads a cookie, and the realm that
// mints it is named in the merged portal configuration, exactly as the dictionary readers are
// (`@@D-836`). Issue it once per session and again when the reader's authority changes; a cookie
// older than the session it was minted from shows a picture that is not there to show. Best effort:
// a suite with no blob realm names no method, and a failed issue leaves the pictures broken rather
// than the page (`@@D-836`). This effect is where the cadence is proved, because a realm's browser
// test group cannot reach a sibling port (`@@D-851`).
const scopeIssue = mergedPortalConfig?.blob?.issue;
const sessionIdentity = useAppStore(s =>
sessionKey(s.auth.profile?.actorId, s.auth.permissions),
);
const issuedRef = React.useRef<string | null>(null);
React.useEffect(() => {
Iif (!isAuthenticated) {
issuedRef.current = null;
return;
}
if (!scopeIssue || issuedRef.current === sessionIdentity) return;
issuedRef.current = sessionIdentity;
const methods = handler as unknown as Record<
string,
((params: object, $meta: object) => Promise<unknown>) | undefined
>;
Promise.resolve(methods[scopeIssue]?.({}, {})).catch(() => {
// The cookie never arrived: the pictures are the loss, not the page.
});
}, [handler, isAuthenticated, scopeIssue, sessionIdentity]);
const loginHandler = React.useCallback(
async ({username, password}: {username: string; password: string}) => {
await handler.authLogin({username, password}, {});
},
[handler],
);
const appConfig = config as {
portal?: IBlongPortalConfig;
login?: {
registerPage?: string;
username?: string;
tokenHint?: {text?: string; command?: string};
};
google?: {baseUrl?: string; clientId?: string; redirectUri?: string; scope?: string};
};
// Register the app's per-language translation dictionaries so the UI can
// apply the user's preferred language (returned at login) to the locale.
// An empty map is registered too: composition then answers with the bundled
// dictionary, which is all the login screen has before a session exists.
React.useEffect(() => {
useAppStore.getState().setTranslationsByLanguage(appConfig.portal?.translations ?? {});
// Collection is a dev/test facility: the report page and the Playwright
// seed writer both read it, and a normal portal never turns it on.
Iif (appConfig.portal?.translation?.collect) collectStart();
}, [appConfig.portal?.translations, appConfig.portal?.translation?.collect]);
// The collector global doubles as the test hook for a language switch: a
// Playwright fixture cannot reach the store (it is exposed only behind
// `testHook`), and activating a language has to await the database
// dictionary rather than only set the locale.
React.useEffect(() => {
const api = (globalThis as unknown as {__blongI18n?: Record<string, unknown>}).__blongI18n;
Eif (api) {
api.activate = (language: string) => useAppStore.getState().languageActivate(language);
}
}, []);
const registerPage = appConfig.login?.registerPage;
// The suite's brand, when it named one (`ui.portal.portal.brand`). Read from
// the static config and not from the merged portal config: the login screen
// paints before a session exists, and composing the merged config needs one.
const brand = appConfig.portal?.brand;
const googleEnabled = Boolean(appConfig.google?.baseUrl && appConfig.google?.clientId);
const onGoogle = React.useCallback(() => {
void handler.authGoogleRedirect({}, {});
}, [handler]);
const onExchange = React.useCallback(
async ({
code,
state,
redirectUri,
}: {
code: string;
state?: string;
redirectUri?: string;
}) => {
await handler.authGoogleLogin({code, state, redirectUri}, {});
},
[handler],
);
// OAuth callback route — the Google (or mock) redirect target. The app may
// be served under a base path (e.g. `/s/`), so match the suffix.
Iif (
typeof window !== 'undefined' &&
!oauthHandled &&
window.location.pathname.endsWith('/oauth/callback')
) {
return (
<OAuthCallback
onExchange={onExchange}
onSuccess={() => setOauthHandled(true)}
/>
);
}
// Wait for the boot-time session restore before painting — avoids flashing
// the login screen when a live session is restored from the cookie.
if (!restored) return null;
Iif (!isAuthenticated) {
return LoginComponent ? (
<LoginComponent />
) : (
<Login
onLogin={loginHandler}
logoIcon={brand?.logoIcon ?? 'pi pi-globe'}
logoUrl={brand?.logoUrl}
title={appConfig.portal?.title ?? 'Blong Portal'}
orgTitle={brand?.orgTitle}
orgIcon={brand?.orgIcon}
orgLogoUrl={brand?.orgLogoUrl}
registerPage={registerPage}
defaultUsername={appConfig.login?.username}
passwordHint={appConfig.login?.tokenHint}
googleLogin={googleEnabled ? {onGoogle} : undefined}
// titleComponent={}
// orgComponent={}
/>
);
}
return (
children ?? (
<Portal
{...portalProps}
menubarEnd={
<>
<FeedbackToggle />
<ThemeSwitcher />
<LanguageSwitcher />
<AccountMenu />
</>
}
/>
)
);
}
export function App({
handlerProxy,
theme = DEFAULT_THEME,
children,
loginComponent,
log,
...portalProps
}: IAppProps) {
// One subscription for the whole tree: the annotated components read this
// through context instead of each subscribing to the store (`@@D-667`).
const feedbackActive = useAppStore(state => state.feedback.active);
return (
<BlongProvider
handlerProxy={handlerProxy}
log={log}
>
<PrimeReactProvider>
<Theme theme={theme}>
<FeedbackActiveContext value={feedbackActive}>
<LanguageDataRefresh />
<AppShell
loginComponent={loginComponent}
portalProps={portalProps}
>
{children}
</AppShell>
<LoginPopup />
<ErrorDialog />
<ConfirmDialog />
<ConfirmPopup />
<ActionHint />
<FeedbackLayer />
</FeedbackActiveContext>
</Theme>
</PrimeReactProvider>
</BlongProvider>
);
}
|