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

DeviceDuoViewport.tsx

204 lines8.3 KB

1import { useEffect, useRef, type RefObject } from "react";
2import type { DuoViewer } from "@t3tools/client-runtime/device/duo-viewer";
3import type { DeviceModelSource } from "@t3tools/client-runtime/device/model";
4import { createPhoneInteraction } from "@t3tools/client-runtime/device/phone-interaction";
5import { createCanvasFrameSink } from "@t3tools/client-runtime/device/frame";
6import type { DeviceScreenSize, DeviceStreamClient } from "@t3tools/client-runtime/device/stream";
7import { createDuoPinch } from "@t3tools/client-runtime/device/duo-control";
8import { bindPhoneTrackpad } from "./phoneTrackpad";
9import { observeResize } from "../../lib/observeResize";
10​
11const loadDuoViewer = () => import("@t3tools/client-runtime/device/duo-viewer");
12​
13export function DeviceDuoViewport(props: {
14 readonly model: DeviceModelSource;
15 readonly source: RefObject<HTMLCanvasElement | null>;
16 readonly onFrameListener: (listener: (() => void) | null) => void;
17 readonly onResetReady: (reset: (() => void) | null) => void;
18 readonly onInputCancel: (cancel: (() => void) | null) => void;
19 readonly client: RefObject<DeviceStreamClient | null>;
20 readonly screen: DeviceScreenSize | null;
21 readonly hingePreview: number | null;
22 readonly controlError: string | null;
23 readonly onUnavailable: () => void;
24}) {
25 const hostRef = useRef<HTMLDivElement | null>(null);
26 const canvasRef = useRef<HTMLCanvasElement | null>(null);
27 const viewerRef = useRef<DuoViewer | null>(null);
28 const interactionRef = useRef<ReturnType<typeof createPhoneInteraction> | null>(null);
29 const pinchRef = useRef<ReturnType<typeof createDuoPinch> | null>(null);
30 const trackpadRef = useRef<ReturnType<typeof bindPhoneTrackpad> | null>(null);
31 const screenRef = useRef(props.screen);
32 const modelRef = useRef(props.model);
33 const previewRef = useRef(props.hingePreview);
34 const { source, client, onInputCancel, onResetReady, onUnavailable, onFrameListener } = props;
35​
36 useEffect(() => {
37 screenRef.current = props.screen;
38 modelRef.current = props.model;
39 interactionRef.current?.end();
40 viewerRef.current?.setScreen(props.screen);
41 }, [props.screen, props.model]);
42​
43 useEffect(() => {
44 if (props.controlError || !props.screen) {
45 trackpadRef.current?.cancel();
46 viewerRef.current?.rejectOrientation();
47 }
48 }, [props.controlError, props.screen]);
49​
50 useEffect(() => {
51 previewRef.current = props.hingePreview;
52 if (!pinchRef.current?.active) viewerRef.current?.setHingePreview(props.hingePreview);
53 }, [props.hingePreview]);
54​
55 useEffect(() => {
56 const host = hostRef.current;
57 const canvas = canvasRef.current;
58 const decoded = source.current;
59 if (!host || !canvas || !decoded) return;
60 let disposed = false;
61 let trackpad: ReturnType<typeof bindPhoneTrackpad> | null = null;
62 let stopTrackpadEnd: (() => void) | undefined;
63 const resize = () => {
64 const { width, height } = host.getBoundingClientRect();
65 viewerRef.current?.resize(width, height, window.devicePixelRatio);
66 };
67 const stopObserving = observeResize(host, resize);
68 const blur = () => {
69 interactionRef.current?.end();
70 trackpad?.cancel();
71 viewerRef.current?.cancelInput();
72 };
73 onInputCancel(blur);
74 window.addEventListener("blur", blur);
75 void loadDuoViewer()
76 .then(({ createDuoViewer }) => {
77 if (disposed) return;
78 const sources = {
79 1: document.createElement("canvas"),
80 3: document.createElement("canvas"),
81 };
82 const viewer = createDuoViewer({
83 canvas,
84 sources,
85 onUnavailable,
86 onPanelRequested: (panel) =>
87 client.current?.controlDuo({
88 control: "physical",
89 value: panel === 1 ? "facedown" : "faceup",
90 }),
91 onOrientationRequested: (value) =>
92 client.current?.controlDuo({ control: "orientation", value }),
93 onModelError: (cause) => console.warn("Device 3D asset could not load", cause),
94 model: modelRef.current,
95 });
96 viewerRef.current = viewer;
97 onResetReady(viewer.resetPose);
98 viewer.setScreen(screenRef.current);
99 const primaryFrame = () => {
100 const panel = screenRef.current?.screenId;
101 if (panel === 1 || panel === 3) viewer.frameUpdated(panel, decoded);
102 };
103 onFrameListener(primaryFrame);
104 primaryFrame();
105 viewer.setHingePreview(previewRef.current);
106 client.current?.setDuoPanels({
107 onScreen(next) {
108 screenRef.current = next;
109 interactionRef.current?.end();
110 viewer.setScreen(next);
111 },
112 cover: createCanvasFrameSink(sources[1], () => viewer.frameUpdated(1)),
113 inner: createCanvasFrameSink(sources[3], () => viewer.frameUpdated(3)),
114 });
115 interactionRef.current = createPhoneInteraction({
116 screenPoint: (point, captured) => viewer.screenPoint(point.x, point.y, captured),
117 touch: (phase, point) => client.current?.sendRawTouch(phase, point.x, point.y),
118 orbit: viewer.orbit,
119 zoomBy: () => {},
120 onInteractionActive: viewer.setInteractionActive,
121 });
122 const pinch = createDuoPinch({
123 angle: () =>
124 previewRef.current ??
125 screenRef.current?.hingeAngle ??
126 (screenRef.current?.screenId === 1 ? 0 : 180),
127 contains: (x, y) => !!screenRef.current && viewer.beginHinge(x, y),
128 change: (angle) => {
129 viewer.setHingePreview(angle ?? previewRef.current, true);
130 if (angle !== null) client.current?.controlDuo({ control: "angle", value: angle });
131 },
132 });
133 pinchRef.current = pinch;
134 trackpad = bindPhoneTrackpad(canvas, interactionRef.current, {
135 begin(x, y) {
136 interactionRef.current?.end();
137 return pinch.begin(x, y);
138 },
139 move: pinch.move,
140 end: pinch.end,
141 });
142 trackpadRef.current = trackpad;
143 stopTrackpadEnd = window.desktopBridge?.onTrackpadScrollEnd?.(() => trackpad?.endOrbit());
144 resize();
145 })
146 .catch(() => {
147 if (!disposed) onUnavailable();
148 });
149 return () => {
150 disposed = true;
151 stopTrackpadEnd?.();
152 trackpad?.dispose();
153 trackpadRef.current = null;
154 pinchRef.current = null;
155 interactionRef.current?.end();
156 interactionRef.current = null;
157 onInputCancel(null);
158 onResetReady(null);
159 onFrameListener(null);
160 client.current?.setDuoPanels(null);
161 stopObserving();
162 window.removeEventListener("blur", blur);
163 viewerRef.current?.dispose();
164 viewerRef.current = null;
165 };
166 }, [onInputCancel, onResetReady, client, onUnavailable, source, onFrameListener]);
167​
168 const point = (event: React.PointerEvent<HTMLCanvasElement>) => {
169 const rect = event.currentTarget.getBoundingClientRect();
170 return {
171 x: (event.clientX - rect.left) / rect.width,
172 y: (event.clientY - rect.top) / rect.height,
173 };
174 };
175 return (
176 <div className="absolute inset-0">
177 <div ref={hostRef} className="absolute inset-0">
178 <div
179 aria-hidden
180 className="pointer-events-none absolute bottom-[6%] left-1/2 h-5 w-2/5 -translate-x-1/2 rounded-full bg-foreground/10 blur-xl"
181 />
182 <canvas
183 ref={canvasRef}
184 aria-label="Interactive 3D iPhone Duo. Drag the screen to interact. Drag outside it or swipe with two fingers to turn. Pinch over the device to open or close its hinge."
185 className="size-full touch-none"
186 onPointerDown={(event) => {
187 if (event.button !== 0) return;
188 if (!interactionRef.current?.begin(event.pointerId, point(event), event.altKey)) return;
189 event.preventDefault();
190 event.currentTarget.setPointerCapture(event.pointerId);
191 (event.currentTarget.closest('[role="application"]') as HTMLElement | null)?.focus();
192 }}
193 onPointerMove={(event) => interactionRef.current?.move(event.pointerId, point(event))}
194 onPointerUp={(event) => {
195 interactionRef.current?.move(event.pointerId, point(event));
196 interactionRef.current?.end(event.pointerId);
197 }}
198 onPointerCancel={(event) => interactionRef.current?.end(event.pointerId)}
199 onLostPointerCapture={(event) => interactionRef.current?.end(event.pointerId)}
200 />
201 </div>
202 </div>
203 );