Open History to see the last commit
1import type { DeviceHubAccess } from "@t3tools/client-runtime/state/deviceHubAccess";
2import { withDeviceHubQuery } from "@t3tools/client-runtime/state/deviceHubAccess";
3import * as Schema from "effect/Schema";
4import { msg } from "gt-react";
5
6import { m } from "~/i18n/messages";
7
8export type AndroidFoldPosture = "closed" | "opened";
9
10export interface AndroidFoldState {
11 readonly supported: boolean;
12 readonly posture: "closed" | "half_opened" | "opened" | "flipped" | "tent" | null;
13 readonly hingeAngle: number | null;
14}
15
16export class AndroidFoldError extends Schema.TaggedError<AndroidFoldError>()("AndroidFoldError", {
17 message: Schema.String,
18 status: Schema.Number,
19}) {}
20
21const isRecord = (value: unknown): value is Record<string, unknown> =>
22 typeof value === "object" && value !== null && !Array.isArray(value);
23
24const parseFold = (payload: unknown): AndroidFoldState => {
25 if (!isRecord(payload) || payload.ok !== true || !isRecord(payload.fold)) {
26 throw new Error(m(msg("Unexpected Android fold response.")));
27 }
28 const { supported, posture, hingeAngle } = payload.fold;
29 if (
30 typeof supported !== "boolean" ||
31 (posture !== null &&
32 posture !== "closed" &&
33 posture !== "half_opened" &&
34 posture !== "opened" &&
35 posture !== "flipped" &&
36 posture !== "tent") ||
37 (hingeAngle !== null && (typeof hingeAngle !== "number" || !Number.isFinite(hingeAngle)))
38 ) {
39 throw new Error(m(msg("Unexpected Android fold response.")));
40 }
41 return { supported, posture, hingeAngle };
42};
43
44const foldRequest = async (
45 access: DeviceHubAccess,
46 deviceId: string,
47 posture?: AndroidFoldPosture,
48 signal?: AbortSignal,
49): Promise<AndroidFoldState> => {
50 const url = withDeviceHubQuery(
51 `${access.httpBase}/vendor/serve-emu/api/fold?${new URLSearchParams({ device: deviceId })}`,
52 access,
53 );
54 const response = await fetch(url, {
55 method: posture ? "POST" : "GET",
56 cache: "no-store",
57 credentials: access.credentials ? "include" : "same-origin",
58 ...(posture
59 ? { headers: { "content-type": "application/json" }, body: JSON.stringify({ posture }) }
60 : {}),
61 ...(signal ? { signal } : {}),
62 });
63 if (!response.ok) {
64 const payload: unknown = await response.json().catch(() => null);
65 const error = isRecord(payload) ? payload.error : null;
66 throw new AndroidFoldError({
67 message:
68 typeof error === "string"
69 ? error
70 : m(msg("Fold command failed ({status}).", { status: response.status })),
71 status: response.status,
72 });
73 }
74 return parseFold(await response.json());
75};
76
77export const readAndroidFold = (access: DeviceHubAccess, deviceId: string, signal?: AbortSignal) =>
78 foldRequest(access, deviceId, undefined, signal);
79
80export const setAndroidFold = (
81 access: DeviceHubAccess,
82 deviceId: string,
83 posture: AndroidFoldPosture,
84 signal?: AbortSignal,
85) => foldRequest(access, deviceId, posture, signal);