Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

asset-url-state.ts

47 lines1.8 KB

1import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
2import type { AssetUrlState as SharedAssetUrlState } from "@t3tools/client-runtime/state/assets";
3​
4export type AssetUrlFailureReason = "disconnected" | "failed";
5​
6/** The shared state plus a reason on failure, so previews can offer the right retry. */
7export type AssetUrlState =
8 | { readonly _tag: "Loading" }
9 | { readonly _tag: "Failure"; readonly reason: AssetUrlFailureReason }
10 | Extract<SharedAssetUrlState, { readonly _tag: "Success" }>;
11​
12/**
13 * Folds the shared asset URL state with the environment connection phase. A
14 * dead environment wins over everything else: even a resolved URL is
15 * unreachable there, and a failed query is caused by the outage, not the file.
16 */
17export function deriveAssetUrlState(input: {
18 readonly connectionPhase: EnvironmentConnectionPhase;
19 readonly shared: SharedAssetUrlState;
20}): AssetUrlState {
21 if (
22 input.connectionPhase === "offline" ||
23 input.connectionPhase === "reconnecting" ||
24 input.connectionPhase === "error"
25 ) {
26 return { _tag: "Failure", reason: "disconnected" };
27 }
28 if (input.shared._tag === "Success") {
29 return input.shared;
30 }
31 switch (input.connectionPhase) {
32 // "available" is the idle, not yet dialled state. A pending query there is
33 // still on its way, but the query atom fails at once while idle, so a
34 // failure means the environment is not connected rather than the file is
35 // missing.
36 case "available":
37 return input.shared._tag === "Failure"
38 ? { _tag: "Failure", reason: "disconnected" }
39 : { _tag: "Loading" };
40 case "connecting":
41 return { _tag: "Loading" };
42 case "connected":
43 return input.shared._tag === "Failure"
44 ? { _tag: "Failure", reason: "failed" }
45 : { _tag: "Loading" };
46 }