-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
412 lines (398 loc) · 14 KB
/
Copy pathApp.tsx
File metadata and controls
412 lines (398 loc) · 14 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
import { useCallback, useEffect, useRef, useState } from "react";
import { createBrowserStorage } from "./browser-storage";
import { useHudController } from "./fast-hud-controller";
import { resolveG2DisplayHideStrategy } from "./g2-display-hide";
import { resolveG2TileImageFormat } from "./g2-tile-format";
import { resolveG2TilePaletteMode } from "./g2-tile-palette";
import { resolveHudModeResolution } from "./hud-mode-resolution";
import { resolveImageSendConcurrency } from "./image-send-concurrency";
import type { FastCanvasBattery } from "./glasses";
import { createLiveDashboardSession } from "./live-dashboard";
import type { EvenStorage } from "./live-cache";
import {
createInitialLiveDashboardState,
type LiveDashboardState,
} from "./live-state";
import { resolveOrsKey } from "./ors-key";
import { resolvePhoneLocale } from "./phone-i18n";
import {
DEFAULT_PHONE_PREFERENCES,
resolvePhonePreferences,
} from "./phone-preferences";
import type { PhonePreferences } from "./phone-types";
import { PhoneCompanion } from "./phone/PhoneCompanion";
import {
defaultRssSources,
resolveRssSources,
type RssSource,
} from "./rss-sources";
import { localizeBuiltInTodos } from "./todos";
import { RouteControls } from "./RouteControls";
import type {
Destination,
RouteProfile,
RoutingStatus,
} from "./routing";
import {
createAiHudSnapshot,
type AiHudSnapshot,
} from "./ai-hud-state";
import {
costSummaryForCurrentPeriod,
resolveAiUsageLedger,
} from "./ai-cost";
import { resolveAiConversationHistory } from "./ai-history";
import { resolveOpenAiKey } from "./openai-key";
import { TRANSPORT_STATUS } from "./transport-status";
import { useConversateCompanion } from "./use-conversate-companion";
import { HudSurface } from "./HudSurface";
type AppProps = { autoStart?: boolean };
export function App({ autoStart = true }: AppProps) {
const displayHideStrategy = resolveG2DisplayHideStrategy(
window.location.search,
);
const imageSendConcurrency = resolveImageSendConcurrency(
window.location.search,
);
const tileImageFormat = resolveG2TileImageFormat(window.location.search);
const tilePaletteMode = resolveG2TilePaletteMode(window.location.search);
const {
calibrationMode,
canvasHudMode,
diagnosticMode,
fastCanvasHudMode,
hardwareBmpMode,
hybridHudMode,
layeredHybridHudMode,
modes,
} = resolveHudModeResolution(
window.location.pathname,
window.location.search,
);
const canvasRef = useRef<HTMLCanvasElement>(null);
const liveSessionRef = useRef<
ReturnType<typeof createLiveDashboardSession> | undefined
>(undefined);
const displayRefreshRef = useRef<(() => void) | undefined>(undefined);
const [status, setStatus] = useState<string>(
autoStart ? TRANSPORT_STATUS.preparing : TRANSPORT_STATUS.disabled,
);
const [routingStatus, setRoutingStatus] = useState<RoutingStatus>({
enabled: false,
});
const [companionRoute, setCompanionRoute] = useState<
LiveDashboardState["route"]
>({ status: "disabled" });
const [companionLive, setCompanionLive] = useState<LiveDashboardState>(() => {
const initial = createInitialLiveDashboardState();
const initialLocale = resolvePhoneLocale(
DEFAULT_PHONE_PREFERENCES.locale,
typeof navigator === "undefined" ? "en" : navigator.language,
);
return {
...initial,
todos: {
...initial.todos,
value: localizeBuiltInTodos(
initial.todos.value ?? [],
initialLocale,
),
},
};
});
const [companionBattery, setCompanionBattery] = useState<
FastCanvasBattery | undefined
>();
const [companionStorage, setCompanionStorage] = useState<EvenStorage>(
createBrowserStorage,
);
const [phonePreferences, setPhonePreferencesState] = useState<
PhonePreferences
>(DEFAULT_PHONE_PREFERENCES);
const phonePreferencesRef = useRef<PhonePreferences>(
DEFAULT_PHONE_PREFERENCES,
);
const phonePreferencesRevisionRef = useRef(0);
const [companionOrsKey, setCompanionOrsKeyState] = useState<string>();
const companionOrsKeyRef = useRef<string | undefined>(undefined);
const [companionOpenAiKey, setCompanionOpenAiKeyState] = useState<string>();
const companionOpenAiKeyRef = useRef<string | undefined>(undefined);
const [companionAiSnapshot, setCompanionAiSnapshotState] = useState(
() => createAiHudSnapshot(false),
);
const aiSnapshotRef = useRef<AiHudSnapshot>(createAiHudSnapshot(false));
const [companionRssSources, setCompanionRssSources] = useState<
readonly RssSource[]
>(defaultRssSources("ko"));
const conversate = useConversateCompanion(companionStorage, fastCanvasHudMode);
const phoneNavigationAvailable = routingStatus.enabled
|| companionOrsKey !== undefined;
const setPhonePreferences = useCallback((value: PhonePreferences) => {
const browserLanguage = typeof navigator === "undefined"
? "en"
: navigator.language;
const previousLocale = resolvePhoneLocale(
phonePreferencesRef.current.locale,
browserLanguage,
);
const nextLocale = resolvePhoneLocale(value.locale, browserLanguage);
phonePreferencesRef.current = value;
phonePreferencesRevisionRef.current += 1;
setPhonePreferencesState(value);
if (nextLocale !== previousLocale) {
setCompanionLive((current) => {
if (!current.todos.value) return current;
return {
...current,
todos: {
...current.todos,
value: localizeBuiltInTodos(current.todos.value, nextLocale),
},
};
});
liveSessionRef.current?.refreshLocale?.();
displayRefreshRef.current?.();
}
}, []);
const setCompanionOrsKey = (value: string | undefined) => {
companionOrsKeyRef.current = value;
setCompanionOrsKeyState(value);
liveSessionRef.current?.setRoutingKey?.(value);
};
const setCompanionOpenAiKey = (value: string | undefined) => {
companionOpenAiKeyRef.current = value;
setCompanionOpenAiKeyState(value);
};
const setCompanionAiSnapshot = useCallback((value: AiHudSnapshot) => {
aiSnapshotRef.current = value;
setCompanionAiSnapshotState(value);
}, []);
const phoneLocale = resolvePhoneLocale(
phonePreferences.locale,
typeof navigator === "undefined" ? "en" : navigator.language,
);
useEffect(() => {
if (!fastCanvasHudMode) return;
let active = true;
const revision = phonePreferencesRevisionRef.current;
void resolvePhonePreferences(
companionStorage,
phoneNavigationAvailable,
).then((value) => {
if (
active
&& phonePreferencesRevisionRef.current === revision
) {
setPhonePreferences(value);
}
});
return () => {
active = false;
};
}, [companionStorage, fastCanvasHudMode, phoneNavigationAvailable]);
useEffect(() => {
if (!fastCanvasHudMode) return;
let active = true;
void resolveOrsKey(companionStorage).then((value) => {
if (active) setCompanionOrsKey(value);
});
return () => {
active = false;
};
}, [companionStorage, fastCanvasHudMode]);
useEffect(() => {
if (!fastCanvasHudMode) return;
let active = true;
void resolveRssSources(companionStorage, phoneLocale).then((value) => {
if (!active) return;
setCompanionRssSources(value);
void liveSessionRef.current?.refreshNewsSources?.();
});
return () => {
active = false;
};
}, [companionStorage, fastCanvasHudMode, phoneLocale]);
useEffect(() => {
if (!fastCanvasHudMode) return;
let active = true;
void Promise.all([
resolveOpenAiKey(companionStorage),
resolveAiConversationHistory(companionStorage),
resolveAiUsageLedger(companionStorage),
]).then(([key, history, ledger]) => {
if (!active) return;
const costs = costSummaryForCurrentPeriod(ledger);
setCompanionOpenAiKey(key);
setCompanionAiSnapshot(createAiHudSnapshot(
Boolean(key),
history,
costs.weekUsd,
costs.monthUsd,
costs.hasUnpricedUsage,
));
});
return () => {
active = false;
};
}, [companionStorage, fastCanvasHudMode]);
useHudController({
autoStart,
canvasRef,
liveSessionRef,
phonePreferencesRef,
displayRefreshRef,
companionOrsKeyRef,
companionOpenAiKeyRef,
aiSnapshotRef,
conversateSettingsRef: conversate.settingsRef,
conversateSnapshotRef: conversate.snapshotRef,
displayHideStrategy,
imageSendConcurrency,
tileImageFormat,
tilePaletteMode,
modes,
setStatus,
setRoutingStatus,
setCompanionRoute,
setCompanionLive,
setCompanionBattery,
setCompanionStorage,
setPhonePreferences,
setCompanionAiSnapshot,
setConversateSnapshot: conversate.setSnapshot,
});
const startCompanionRoute = async (
destination: Destination,
profile: RouteProfile,
) => {
const session = liveSessionRef.current;
if (!session) throw new Error("길찾기 세션이 아직 준비되지 않았습니다.");
await session.startRoute(destination, profile);
};
const endCompanionRoute = async () => {
const session = liveSessionRef.current;
if (!session) throw new Error("길찾기 세션이 아직 준비되지 않았습니다.");
await session.endRoute();
};
const resumeCompanionRoute = async () => {
const session = liveSessionRef.current;
if (!session) throw new Error("길찾기 세션이 아직 준비되지 않았습니다.");
await session.resumeRoute();
};
const activeCompanionRoute = companionRoute.status === "fresh"
|| companionRoute.status === "stale"
|| companionRoute.status === "loading"
? companionRoute.value
: undefined;
const effectiveRoutingStatus: RoutingStatus = {
enabled: phoneNavigationAvailable,
};
const hudSurface = <HudSurface canvasRef={canvasRef} modes={modes} locale={phoneLocale} />;
if (fastCanvasHudMode) {
return (
<PhoneCompanion
canvas={hudSurface}
status={status}
battery={companionBattery}
live={companionLive}
routingStatus={effectiveRoutingStatus}
preferences={phonePreferences}
storage={companionStorage}
onPreferencesChange={setPhonePreferences}
onTodosChange={(items) => {
liveSessionRef.current?.replaceTodos?.(items);
setCompanionLive((current) => ({
...current,
todos: { status: "fresh", value: items },
}));
}}
onWeatherRefresh={() => (
liveSessionRef.current?.refreshWeather?.()
?? Promise.resolve("dropped")
)}
rssSources={companionRssSources}
onRssSourcesChange={(sources) => {
setCompanionRssSources(sources);
void liveSessionRef.current?.refreshNewsSources?.();
}}
onOrsKeyChange={setCompanionOrsKey}
openAiKey={companionOpenAiKey}
aiSnapshot={companionAiSnapshot}
onOpenAiKeyChange={(key) => {
setCompanionOpenAiKey(key);
const next = {
...aiSnapshotRef.current,
configured: Boolean(key),
phase: key ? "idle" as const : "unconfigured" as const,
error: undefined,
};
setCompanionAiSnapshot(next);
displayRefreshRef.current?.();
}}
onAiSnapshotChange={(snapshot) => {
setCompanionAiSnapshot(snapshot);
displayRefreshRef.current?.();
}}
conversateSettings={conversate.settings}
conversateSnapshot={conversate.snapshot}
onConversateSettingsChange={conversate.setSettings}
onConversateSnapshotChange={conversate.setSnapshot}
onDeleteRoute={endCompanionRoute}
routeControls={(
<RouteControls
locale={phoneLocale}
status={effectiveRoutingStatus}
orsKey={companionOrsKey}
activeRoute={activeCompanionRoute}
routeStatus={companionRoute.status}
onStart={startCompanionRoute}
onResume={resumeCompanionRoute}
onEnd={endCompanionRoute}
/>
)}
/>
);
}
return (
<main className="preview-stage">
<header className="preview-header">
<div>
<strong>SANDEVISTAN / G2 RASTER TEST</strong>
<span>
{hardwareBmpMode
? "1-BIT BMP · CLICK TO SEND"
: diagnosticMode
? "OFFICIAL SAMPLE.PNG · RAW BYTES"
: calibrationMode
? "576×288 MAX BOUNDARY"
: layeredHybridHudMode
? "STATIC CANVAS + NATIVE TEXT + Z-ORDER · SCROLL · 4 PAGES"
: hybridHudMode
? "STATIC CANVAS + NATIVE TEXT · SCROLL · 4 PAGES"
: canvasHudMode
? "576×288 · CANVAS HUD · SCROLL · 4 PAGES"
: "576×288 · 4 IMAGE TILES"}
{" · STATIC MOCK"}
</span>
</div>
<output aria-live="polite">{status}</output>
</header>
{hudSurface}
<p className="preview-note">
{hardwareBmpMode
? "안경에 준비 문구를 표시한 뒤 링/터치바를 클릭하면 200×100 1-bit BMP를 전송합니다."
: diagnosticMode
? "진단 모드에서는 Even Realities 공식 sample.png 원본 바이트를 그대로 전송합니다."
: calibrationMode
? "외곽 띠, 보조 테두리, 중앙 십자와 32px 눈금을 네 타일로 전송합니다."
: layeredHybridHudMode
? "Canvas 배경 위에 명시적 최상위 레이어의 네이티브 Text를 표시합니다."
: hybridHudMode
? "Canvas에는 정적 배경만 보이며, 실제 안경 문구는 네이티브 Text로 한 번에 전환됩니다."
: canvasHudMode
? "기본 뉴스 화면에서 아래 스크롤은 다음, 위 스크롤은 이전 페이지를 네 타일로 전송합니다."
: "이 Canvas가 네 장의 PNG로 나뉘어 안경에 순차 전송됩니다."}
</p>
</main>
);
}