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

deviceFold.ts

82 lines2.7 KB

1import type { DeviceHubAccess } from "@t3tools/client-runtime/state/deviceHubAccess";
2import { withDeviceHubQuery } from "@t3tools/client-runtime/state/deviceHubAccess";
3​
4export type AndroidFoldPosture = "closed" | "opened";
5​
6export interface AndroidFoldState {
7 readonly supported: boolean;
8 readonly posture: "closed" | "half_opened" | "opened" | "flipped" | "tent" | null;
9 readonly hingeAngle: number | null;
11​
12export class AndroidFoldError extends Error {
13 readonly status: number;
14​
15 constructor(message: string, status: number) {
16 super(message);
17 this.status = status;
18 }
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("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("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 typeof error === "string" ? error : `Fold command failed (${response.status}).`,
68 response.status,
69 );
70 }
71 return parseFold(await response.json());
72};
73​
74export const readAndroidFold = (access: DeviceHubAccess, deviceId: string, signal?: AbortSignal) =>
75 foldRequest(access, deviceId, undefined, signal);
76​
77export const setAndroidFold = (
78 access: DeviceHubAccess,
79 deviceId: string,
80 posture: AndroidFoldPosture,
81 signal?: AbortSignal,
82) => foldRequest(access, deviceId, posture, signal);