Files
adolf/ui/src/app/router-outlet.ts
alvis bedb527145
Some checks failed
ClawSweeper Dispatch / dispatch (push) Has been cancelled
CodeQL / Security High (actions) (push) Has been cancelled
CodeQL / Security High (channel-runtime-boundary) (push) Has been cancelled
CodeQL / Security High (core-auth-secrets) (push) Has been cancelled
CodeQL / Security High (mcp-process-tool-boundary) (push) Has been cancelled
CodeQL / Security High (network-ssrf-boundary) (push) Has been cancelled
CodeQL / Security High (plugin-trust-boundary) (push) Has been cancelled
CodeQL / Security High (process-exec-boundary) (push) Has been cancelled
Docs Sync Publish Repo / sync-publish-repo (push) Has been cancelled
Docs / docs (push) Has been cancelled
OpenClaw Stable Main Closeout / Resolve stable release closeout inputs (push) Has been cancelled
OpenClaw Stable Main Closeout / Verify stable main closeout (push) Has been cancelled
Workflow Sanity / no-tabs (push) Has been cancelled
Workflow Sanity / actionlint (push) Has been cancelled
Workflow Sanity / generated-doc-baselines (push) Has been cancelled
CI / runner-admission (push) Has been cancelled
CI / preflight (push) Has been cancelled
CI / security-fast (push) Has been cancelled
CI / pnpm-store-warmup (push) Has been cancelled
CI / build-artifacts (push) Has been cancelled
CI / native-i18n (push) Has been cancelled
CI / ${{ matrix.check_name }} (push) Has been cancelled
CI / ${{ matrix.checkName }} (push) Has been cancelled
CI / checks-node-compat-node22 (push) Has been cancelled
CI / check-bundled-channel-config-metadata (push) Has been cancelled
CI / check-dependencies (push) Has been cancelled
CI / check-guards (push) Has been cancelled
CI / check-lint (push) Has been cancelled
CI / check-prod-types (push) Has been cancelled
CI / check-shrinkwrap (push) Has been cancelled
CI / check-test-types (push) Has been cancelled
CI / check-additional-boundaries-a (push) Has been cancelled
CI / check-additional-boundaries-bcd (push) Has been cancelled
CI / check-additional-extension-bundled (push) Has been cancelled
CI / check-additional-extension-channels (push) Has been cancelled
CI / check-additional-extension-package-boundary (push) Has been cancelled
CI / check-additional-runtime-topology-architecture (push) Has been cancelled
CI / check-session-accessor-boundary (push) Has been cancelled
CI / check-session-transcript-reader-boundary (push) Has been cancelled
CI / check-docs (push) Has been cancelled
CI / skills-python (push) Has been cancelled
CI / macos-swift (push) Has been cancelled
CI / ios-build (push) Has been cancelled
CI / ci-timings-summary (push) Has been cancelled
Native App Locale Refresh / Refresh native fa (push) Has been cancelled
Native App Locale Refresh / Refresh native fr (push) Has been cancelled
Native App Locale Refresh / Refresh native hi (push) Has been cancelled
Native App Locale Refresh / Refresh native id (push) Has been cancelled
Native App Locale Refresh / Refresh native it (push) Has been cancelled
Native App Locale Refresh / Refresh native ja-JP (push) Has been cancelled
Control UI Locale Refresh / plan (push) Has been cancelled
Control UI Locale Refresh / Refresh ${{ matrix.locale }} (push) Has been cancelled
Control UI Locale Refresh / Commit control UI locale refresh (push) Has been cancelled
Live Media Runner Image / Build live media runner image (push) Has been cancelled
Native App Locale Refresh / Refresh native ar (push) Has been cancelled
Native App Locale Refresh / Refresh native de (push) Has been cancelled
Native App Locale Refresh / Refresh native es (push) Has been cancelled
Native App Locale Refresh / Refresh native ko (push) Has been cancelled
Native App Locale Refresh / Refresh native nl (push) Has been cancelled
Native App Locale Refresh / Refresh native pl (push) Has been cancelled
Native App Locale Refresh / Refresh native pt-BR (push) Has been cancelled
Native App Locale Refresh / Refresh native ru (push) Has been cancelled
Native App Locale Refresh / Refresh native sv (push) Has been cancelled
Native App Locale Refresh / Refresh native th (push) Has been cancelled
Native App Locale Refresh / Refresh native tr (push) Has been cancelled
Native App Locale Refresh / Refresh native uk (push) Has been cancelled
Native App Locale Refresh / Refresh native vi (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-CN (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-TW (push) Has been cancelled
Native App Locale Refresh / Commit native locale refresh (push) Has been cancelled
Plugin Init Scaffold Validation / Validate provider scaffold (push) Has been cancelled
Plugin NPM Release / preview_plugins_npm (push) Has been cancelled
Plugin NPM Release / Validate release publish approval (push) Has been cancelled
Plugin NPM Release / preview_plugin_pack (push) Has been cancelled
Plugin NPM Release / publish_plugins_npm (push) Has been cancelled
Sandbox Common Smoke / sandbox-common-smoke (push) Has been cancelled
Website Installer Sync / static (push) Has been cancelled
Website Installer Sync / linux-docker (push) Has been cancelled
Website Installer Sync / macos-installer (push) Has been cancelled
Website Installer Sync / windows-installer (push) Has been cancelled
Website Installer Sync / sync-website (push) Has been cancelled
Vendor OpenClaw source as Adolf fork baseline
Adolf is a fork/vendored clone of github.com/openclaw/openclaw (v2026.6.11),
free to diverge. Tree copied sans upstream .git; upstream remote added for
future syncs. Node pinned to 24 (.nvmrc); engines already require >=22.19.
Preserves docs/ARCHITECTURE.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LeqyaxJF2nbRXJtae2kNB2
2026-07-05 09:36:54 +00:00

325 lines
9.6 KiB
TypeScript

import type { RouteMatch, Router, RouterState } from "@openclaw/uirouter";
import { html, LitElement, nothing } from "lit";
import { AsyncDirective } from "lit/async-directive.js";
import { property } from "lit/decorators.js";
import { directive } from "lit/directive.js";
import { t } from "../i18n/index.ts";
const PENDING_UI_DELAY_MS = 1_000;
type RenderableModule<TData> = {
render: (data: TData | undefined) => unknown;
};
export type RouterOutletOptions<TLoadContext = unknown> = {
retryContext?: TLoadContext;
};
export type RouterOutletBoundaryOptions = {
onNotFound?: () => void;
};
export type RouterOutletSelection<
TRouteId extends string = string,
TModule = unknown,
TData = unknown,
> = {
status: RouterState<TRouteId, TModule, TData>["status"];
active: RouteMatch<TRouteId, TModule, TData> | undefined;
pending: RouteMatch<TRouteId, TModule, TData> | undefined;
showPending: boolean;
};
export function selectRenderedRouteMatch<TRouteId extends string, TModule, TData>(
active: RouteMatch<TRouteId, TModule, TData> | undefined,
pending: RouteMatch<TRouteId, TModule, TData> | undefined,
): RouteMatch<TRouteId, TModule, TData> | undefined {
const coldPending =
pending?.status === "pending" && pending.module === undefined && pending.error === undefined;
return coldPending && active ? active : (pending ?? active);
}
function selectRouterOutletState<TRouteId extends string, TModule, TData>(
state: RouterState<TRouteId, TModule, TData>,
): RouterOutletSelection<TRouteId, TModule, TData> {
return {
status: state.status,
active: state.matches[0],
pending: state.pendingMatches[0],
showPending: false,
};
}
function equalRouterOutletState(
previous: RouterOutletSelection,
next: RouterOutletSelection,
): boolean {
return (
previous.status === next.status &&
previous.active === next.active &&
previous.pending === next.pending
);
}
function isRenderableModule<TData>(module: unknown): module is RenderableModule<TData> {
return (
typeof module === "object" &&
module !== null &&
"render" in module &&
typeof module.render === "function"
);
}
function measureRoutedRender<T>(routeId: string, render: () => T): T {
const startedAt = globalThis.performance?.now() ?? 0;
const result = render();
const durationMs = Math.round((globalThis.performance?.now() ?? startedAt) - startedAt);
if (durationMs >= 16) {
console.debug("[openclaw] routed render", { routeId, durationMs });
}
return result;
}
function renderPending() {
return html`
<section class="card lazy-view-state lazy-view-state--loading" role="status">
<div class="card-title">${t("lazyView.loadingTitle")}</div>
<div class="card-sub">${t("common.loading")}</div>
</section>
`;
}
function renderError<TRouteId extends string, TLoadContext, TModule, TData>(
router: Router<TRouteId, TLoadContext, TModule, TData>,
retryContext: TLoadContext | undefined,
error: unknown,
routeId: TRouteId,
render?: () => unknown,
) {
const routeError = error instanceof Error ? error.message : String(error);
return html`
${render?.() ?? nothing}
<div class="callout danger" role="alert">
<strong>${t("lazyView.errorTitle")}</strong>
<div>${routeError}</div>
<button
class="btn btn--sm"
@click=${() =>
retryContext === undefined
? undefined
: void router.revalidate(retryContext, routeId).catch(() => undefined)}
>
${t("lazyView.retry")}
</button>
</div>
`;
}
export function renderRouterOutlet<TRouteId extends string, TLoadContext, TModule, TData = unknown>(
router: Router<TRouteId, TLoadContext, TModule, TData>,
selection: RouterOutletSelection<TRouteId, TModule, TData>,
options: RouterOutletOptions<TLoadContext> = {},
): unknown {
const pending = selection.pending;
const renderedMatch = selectRenderedRouteMatch(selection.active, pending);
if (renderedMatch?.status === "notFound") {
return nothing;
}
if (renderedMatch?.status === "redirected") {
return nothing;
}
if (!renderedMatch) {
return nothing;
}
const routeId = renderedMatch.routeId;
if (!renderedMatch?.module) {
return renderedMatch.error
? renderError<TRouteId, TLoadContext, TModule, TData>(
router,
options.retryContext,
renderedMatch.error,
routeId,
)
: selection.showPending
? renderPending()
: nothing;
}
const routeModule = renderedMatch.module;
if (!isRenderableModule<TData>(routeModule)) {
return renderedMatch.error
? renderError<TRouteId, TLoadContext, TModule, TData>(
router,
options.retryContext,
renderedMatch.error,
routeId,
)
: null;
}
const renderedPage = () =>
measureRoutedRender(routeId, () => routeModule.render(renderedMatch.data));
return renderedMatch.error
? renderError<TRouteId, TLoadContext, TModule, TData>(
router,
options.retryContext,
renderedMatch.error,
routeId,
renderedPage,
)
: renderedPage();
}
class RouterOutletDirective extends AsyncDirective {
private router?: Router<string, unknown, unknown, unknown>;
private retryContext: unknown;
private unsubscribe?: () => void;
private boundaryOptions?: RouterOutletBoundaryOptions;
private notFoundScheduled = false;
private pendingMatchId?: string;
private pendingTimer?: ReturnType<typeof globalThis.setTimeout>;
private pendingSelection?: RouterOutletSelection;
private showPending = false;
override render(
router: unknown,
retryContext: unknown,
boundaryOptions: RouterOutletBoundaryOptions,
) {
const nextRouter = router as Router<string, unknown, unknown, unknown>;
this.updateSubscription(nextRouter);
this.router = nextRouter;
this.retryContext = retryContext;
this.boundaryOptions = boundaryOptions;
return this.renderSelection(selectRouterOutletState(nextRouter.getState()));
}
override disconnected() {
this.unsubscribe?.();
this.unsubscribe = undefined;
this.clearPendingTimer();
this.pendingSelection = undefined;
this.boundaryOptions = undefined;
this.retryContext = undefined;
this.notFoundScheduled = false;
}
override reconnected() {
if (this.router) {
this.updateSubscription(this.router);
}
}
private updateSubscription(router: Router<string, unknown, unknown, unknown>) {
if (this.router === router && this.unsubscribe) {
return;
}
this.unsubscribe?.();
this.unsubscribe = router.subscribeSelector(
selectRouterOutletState,
(selection) => {
if (this.isConnected) {
this.setValue(this.renderSelection(selection));
}
},
equalRouterOutletState,
);
}
private renderSelection(selection: RouterOutletSelection) {
this.pendingSelection = selection;
const pending = selection.pending;
const coldPending =
pending?.status === "pending" && pending.module === undefined && pending.error === undefined;
const needsPendingFallback = coldPending && !selection.active;
if (!needsPendingFallback) {
this.clearPendingTimer();
this.pendingMatchId = undefined;
this.showPending = false;
} else if (this.pendingMatchId !== pending.id) {
this.clearPendingTimer();
this.pendingMatchId = pending.id;
this.showPending = false;
this.pendingTimer = globalThis.setTimeout(() => {
this.pendingTimer = undefined;
const pendingSelection = this.pendingSelection;
if (!pendingSelection || pendingSelection.pending?.id !== this.pendingMatchId) {
return;
}
this.showPending = true;
this.setValue(this.renderSelection(pendingSelection));
}, PENDING_UI_DELAY_MS);
}
if (selection.status === "notFound") {
if (!this.notFoundScheduled) {
this.notFoundScheduled = true;
queueMicrotask(() => {
this.notFoundScheduled = false;
this.boundaryOptions?.onNotFound?.();
});
}
} else {
this.notFoundScheduled = false;
}
const router = this.router;
if (!router) {
return nothing;
}
return renderRouterOutlet(
router,
{ ...selection, showPending: this.showPending },
{
retryContext: this.retryContext,
},
);
}
private clearPendingTimer() {
if (this.pendingTimer !== undefined) {
globalThis.clearTimeout(this.pendingTimer);
this.pendingTimer = undefined;
}
}
}
const routerOutletDirective = directive(RouterOutletDirective);
export function routerOutlet<TRouteId extends string, TModule, TData, TContext>(
router: Router<TRouteId, TContext, TModule, TData>,
boundaryOptions: RouterOutletBoundaryOptions,
options: RouterOutletOptions<TContext> = {},
): unknown {
return routerOutletDirective(router, options.retryContext, boundaryOptions);
}
export class OpenClawRouterOutlet<
TRouteId extends string = string,
TLoadContext = unknown,
TModule = unknown,
TData = unknown,
> extends LitElement {
@property({ attribute: false }) router?: Router<TRouteId, TLoadContext, TModule, TData>;
@property({ attribute: false }) retryContext?: TLoadContext;
@property({ attribute: false }) onNotFound?: () => void;
override createRenderRoot() {
return this;
}
override render() {
if (!this.router) {
return nothing;
}
return routerOutlet(
this.router,
{ onNotFound: this.onNotFound },
{
retryContext: this.retryContext,
},
);
}
}
if (!customElements.get("openclaw-router-outlet")) {
customElements.define("openclaw-router-outlet", OpenClawRouterOutlet);
}