File size: 4,780 Bytes
7f72224 9e15897 7f72224 b2aa446 7f72224 9e15897 7f72224 9e15897 7f72224 b2aa446 7f72224 | 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 | import { Component, useEffect, useState } from "react";
import type { ReactNode } from "react";
import { LogoLoader } from "../ui/LogoLoader";
import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, checkTenant, signal } from "../apiContract";
export const APP_OPEN_TIMEOUT_MS = 12_000;
const MESSAGES = {
loading: "Loading this App.",
router_unavailable: "This App cannot open because its routes are unavailable.",
no_grant: "Your access limit prevents this App from reading its source.",
not_connected: "Connect the App's connector in Connectors to open this App.",
refreshing: "This App's source is refreshing and opens when the refresh ends",
no_rows: "This App has no source rows yet.",
source_unavailable: "This App cannot read its source right now.",
held: "This App is not available yet.",
chunk_unavailable: "This App could not load its screen.",
unavailable: "This App is unavailable or is not shared with you.",
};
export type AppReasonState = keyof typeof MESSAGES;
export interface AppAvailability {
state: AppReasonState | "ready";
message?: string | null;
lock?: string | null;
}
/** A shared logo while opening, then one sentence for a named reason. */
export function AppReason({ state, connector }: { state: AppReasonState; connector?: string }) {
if (state === "loading") return <div className="shell-loading">
<LogoLoader data-app-reason={state} />
</div>;
const label = ({ amazon: "Amazon", amazon_ads: "Amazon Ads", odoo: "Odoo" } as Record<string, string>)[connector || ""];
const message = state === "not_connected"
? <>Connect {label || "the App's connector"} in <a href="#/connectors">Connectors</a> to open this App.</>
: MESSAGES[state];
return <p className="cg-app-frame-missing" role="status" data-app-reason={state}
title={state === "no_grant" ? "Access limit" : undefined}>{message}</p>;
}
/** The browser accepts reason codes, never arbitrary server exception text. */
export function availabilityState(value: unknown): AppAvailability["state"] {
const state = value && typeof value === "object" ? (value as { state?: unknown }).state : null;
return state === "ready" || (typeof state === "string" && state !== "loading"
&& Object.prototype.hasOwnProperty.call(MESSAGES, state)) ? state as AppAvailability["state"] : "unavailable";
}
export function useAppOpening(id: string, initial?: AppAvailability): { state: AppAvailability["state"]; application?: unknown } {
const [result, setResult] = useState<{ id: string; state: AppAvailability["state"]; application?: unknown } | null>(null);
useEffect(() => {
const controller = new AbortController();
let active = true;
const settle = (state: AppAvailability["state"], application?: unknown) => {
if (active) setResult({ id, state, application });
};
const timeout = setTimeout(() => {
settle("source_unavailable");
active = false;
controller.abort();
}, APP_OPEN_TIMEOUT_MS);
void fetch(`${API_V1}/applications/${encodeURIComponent(id)}/availability`, {
credentials: CREDENTIALS, signal: controller.signal,
}).then(async (response) => {
if (checkTenant(response)) return;
if (response.status === 401) signal(UNAUTHORIZED_EVENT);
if (!response.ok) {
settle(response.status >= 500 ? "source_unavailable" : "unavailable");
return;
}
const body = await response.json() as { availability?: unknown; application?: unknown };
settle(availabilityState(body.availability), body.application);
}).catch(() => settle("source_unavailable")).finally(() => clearTimeout(timeout));
return () => {
active = false;
clearTimeout(timeout);
controller.abort();
};
}, [id]);
return result?.id === id ? result : { state: initial ? availabilityState(initial) : "loading" };
}
export function useAppAvailability(id: string, initial?: AppAvailability): AppAvailability["state"] {
return useAppOpening(id, initial).state;
}
/** A lost chunk reaches an error boundary even when its request never settles. */
export async function boundedAppChunk<T>(load: () => Promise<T>, timeoutMs = APP_OPEN_TIMEOUT_MS): Promise<T> {
let timer: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([load(), new Promise<never>((_resolve, reject) => {
timer = setTimeout(() => reject(new Error("App screen unavailable")), timeoutMs);
})]);
} finally {
clearTimeout(timer);
}
}
export class AppViewErrorBoundary extends Component<{ children: ReactNode; fallback: ReactNode }, { failed: boolean }> {
state = { failed: false };
static getDerivedStateFromError() { return { failed: true }; }
render() { return this.state.failed ? this.props.fallback : this.props.children; }
}
|