Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 28 additions & 8 deletions mobile/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import { PortalHost } from "@rn-primitives/portal";
import { StatusBar } from "expo-status-bar";
import { CircleDot, FileText, PlusCircle, ScanLine, Settings as Gear, X } from "lucide-react-native";
import React, { useCallback, useEffect, useRef, useState } from "react";
import { Animated, Pressable, View } from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { Animated, BackHandler, Pressable, View } from "react-native";
import { SafeAreaProvider, SafeAreaView } from "react-native-safe-area-context";
import { Health, Overview, Report as ReportData, Zone, getJson, listen, loadSettings } from "./src/api";
import { Job, initQueue, setStep, subscribe } from "./src/queue";
Expand All @@ -19,6 +20,7 @@ import { Settings } from "./src/screens/Settings";
import { Today } from "./src/screens/Today";

type Tab = "today" | "capture" | "scan" | "report";
const ZONES_KEY = "tw.zones";
const TABS: [Tab, any, string][] = [["today", CircleDot, "Heute"], ["capture", PlusCircle, "Erfassen"], ["scan", ScanLine, "Scan"], ["report", FileText, "Bericht"]];

export default function App() {
Expand Down Expand Up @@ -46,10 +48,13 @@ export default function App() {
const load = useCallback(async () => {
setRefreshing(true);
try {
const [h, z, o, r] = await Promise.all([
getJson<Health>("/health"), getJson<Zone[]>("/zones"), getJson<Overview>("/api/overview"), getJson<ReportData>("/api/v2/report"),
]);
setHealth(h); setZones(z); setOverview(o); setReport(r); setError(null);
// health and zones decide "connected"; a failing report or overview must not take the rest down
const [h, z] = await Promise.all([getJson<Health>("/health"), getJson<Zone[]>("/zones")]);
setHealth(h); setZones(z); setError(null);
AsyncStorage.setItem(ZONES_KEY, JSON.stringify(z)); // so recording works offline later
const [o, r] = await Promise.allSettled([getJson<Overview>("/api/overview"), getJson<ReportData>("/api/v2/report")]);
if (o.status === "fulfilled") setOverview(o.value);
if (r.status === "fulfilled") setReport(r.value);
} catch (e: any) {
setError(e.message); setHealth(null);
} finally {
Expand All @@ -58,7 +63,12 @@ export default function App() {
}, []);

useEffect(() => {
(async () => { await loadSettings(); setReady(true); await initQueue(); load(); })();
(async () => {
await loadSettings();
const cached = await AsyncStorage.getItem(ZONES_KEY);
if (cached) setZones(JSON.parse(cached));
setReady(true); await initQueue(); load();
})();
return subscribe(setJobs);
}, [load]);

Expand All @@ -73,6 +83,16 @@ export default function App() {
return () => { stop(); if (t) clearTimeout(t); };
}, [ready, health?.project, load]);

// Android back: close settings, else go to the capture tab, else leave the app
useEffect(() => {
const sub = BackHandler.addEventListener("hardwareBackPress", () => {
if (showSettings) { setShowSettings(false); return true; }
if (tab !== "capture") { setTab("capture"); return true; }
return false;
});
return () => sub.remove();
}, [showSettings, tab]);

const names: Record<string, string> = {};
(overview?.zones ?? []).forEach((z) => z.elements.forEach((e) => (names[e.id] = e.name)));
const pending = jobs.filter((j) => j.status !== "done" && j.status !== "error").length;
Expand Down Expand Up @@ -100,12 +120,12 @@ export default function App() {
<View className="flex-1">
{!ready ? null : showSettings ? <Settings onClose={() => setShowSettings(false)} onSaved={load} />
: tab === "today" ? <Today data={overview} error={error} reload={load} refreshing={refreshing} toast={toast} />
: tab === "capture" ? <Capture zones={zones} jobs={jobs} names={names} toast={toast} />
: tab === "capture" ? <Capture zones={zones} jobs={jobs} names={names} toast={toast} online={!!health} openSettings={() => setShowSettings(true)} />
: tab === "scan" ? <Scan toast={toast} />
: <Report data={report} reload={load} refreshing={refreshing} toast={toast} />}
</View>

<Animated.View pointerEvents="none" style={{ position: "absolute", left: 16, right: 16, bottom: 96, opacity: fade, alignItems: "center" }}>
<Animated.View pointerEvents="none" accessibilityLiveRegion="polite" style={{ position: "absolute", left: 16, right: 16, bottom: 96, opacity: fade, alignItems: "center" }}>
{msg && (
<View className={cn("rounded-lg px-4 py-3 shadow-lg", msg.err ? "bg-destructive" : "bg-primary")}>
<Text className="text-sm font-medium text-white">{msg.text}</Text>
Expand Down
4 changes: 2 additions & 2 deletions mobile/components/ui/badge.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,9 @@ const badgeTextVariants = cva('text-xs font-medium', {
secondary: 'text-secondary-foreground',
destructive: 'text-white',
outline: 'text-foreground',
success: 'text-success',
success: 'text-green-800',
warning: 'text-warning-foreground',
info: 'text-info',
info: 'text-blue-800',
},
},
defaultVariants: {
Expand Down
4 changes: 2 additions & 2 deletions mobile/components/ui/button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,10 @@ const buttonVariants = cva(
link: '',
},
size: {
default: cn('h-10 px-4 py-2 sm:h-9', Platform.select({ web: 'has-[>svg]:px-3' })),
default: cn('h-11 px-4 py-2', Platform.select({ web: 'has-[>svg]:px-3' })), // Tagwerk: 44 pt minimum
sm: cn('h-9 gap-1.5 rounded-md px-3 sm:h-8', Platform.select({ web: 'has-[>svg]:px-2.5' })),
lg: cn('h-11 rounded-md px-6 sm:h-10', Platform.select({ web: 'has-[>svg]:px-4' })),
icon: 'h-10 w-10 sm:h-9 sm:w-9',
icon: 'h-11 w-11',
// Tagwerk: glove-friendly targets on site
xl: 'h-14 rounded-lg px-6',
hero: 'h-20 rounded-xl px-6',
Expand Down
26 changes: 16 additions & 10 deletions mobile/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,24 +31,24 @@ export function parseConnect(text: string): Settings | null {
return /^https?:\/\//.test(t) ? { server: t, token: "" } : null;
}

const headers = (): Record<string, string> => (current.token ? { Authorization: `Bearer ${current.token}` } : {});
const headers = (token = current.token): Record<string, string> => (token ? { Authorization: `Bearer ${token}` } : {});

/** A page URL to open in the browser (pages read the token from `?token=`). */
export function pageUrl(path: string): string {
const u = `${current.server}${path}`;
return current.token ? `${u}${u.includes("?") ? "&" : "?"}token=${encodeURIComponent(current.token)}` : u;
}

export async function getJson<T>(path: string, timeoutMs = 10000, server = current.server): Promise<T> {
export async function getJson<T>(path: string, timeoutMs = 10000, server = current.server, token = current.token): Promise<T> {
const ctl = new AbortController();
const timer = setTimeout(() => ctl.abort(), timeoutMs);
try {
const r = await fetch(`${server}${path}`, { headers: headers(), signal: ctl.signal });
const r = await fetch(`${server}${path}`, { headers: headers(token), signal: ctl.signal });
const body = await r.json().catch(() => ({}));
if (!r.ok) throw new Error(body.detail || `HTTP ${r.status}`);
if (!r.ok) throw Object.assign(new Error(body.detail || `HTTP ${r.status}`), { status: r.status });
return body as T;
} catch (e: any) {
if (e?.name === "AbortError") throw new Error("Server antwortet nicht (Tailscale an?)");
if (e?.name === "AbortError") throw new Error("Keine Verbindung: Server antwortet nicht (Tailscale an?)");
throw e;
} finally {
clearTimeout(timer);
Expand All @@ -70,7 +70,8 @@ export type MediaFile = { uri: string; name: string; type: string };
* server starts processing; the promise resolves with the server's answer. */
export async function postForm<T>(
path: string, fields: Record<string, string | undefined>, files: MediaFile[],
onProgress?: (fraction: number) => void, onUploaded?: () => void, server = current.server,
onProgress?: (fraction: number) => void, onUploaded?: () => void, server = current.server, token = current.token,
timeoutMs = 15 * 60 * 1000, // upload + GPU processing of a long video; a dead connection must not hang the queue
): Promise<T> {
const form = new FormData();
for (const [k, v] of Object.entries(fields)) if (v !== undefined && v !== "") form.append(k, v);
Expand All @@ -81,7 +82,8 @@ export async function postForm<T>(
return new Promise<T>((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("POST", `${server}${path}`);
for (const [k, v] of Object.entries(headers())) xhr.setRequestHeader(k, v);
for (const [k, v] of Object.entries(headers(token))) xhr.setRequestHeader(k, v);
xhr.timeout = timeoutMs;
xhr.upload.onprogress = (e) => e.lengthComputable && onProgress?.(e.loaded / e.total);
xhr.upload.onload = () => { onProgress?.(1); onUploaded?.(); };
xhr.onload = () => {
Expand All @@ -91,22 +93,26 @@ export async function postForm<T>(
else reject(new Error(body.detail || `HTTP ${xhr.status}`));
};
xhr.onerror = () => reject(new Error("Keine Verbindung zum Server"));
xhr.ontimeout = () => reject(new Error("Keine Verbindung: Zeitüberschreitung"));
xhr.onabort = () => reject(new Error("Keine Verbindung: abgebrochen"));
xhr.send(form);
});
}

/** Live pipeline steps from the API's websocket (`/events`). Returns a function that closes it. */
export function listen(onMessage: (m: any) => void): () => void {
let ws: WebSocket | null = null, closed = false, backoff = 1000;
let timer: ReturnType<typeof setTimeout> | null = null;
const open = () => {
if (closed) return;
const base = current.server.replace(/^http/, "ws");
ws = new WebSocket(`${base}/events${current.token ? `?token=${encodeURIComponent(current.token)}` : ""}`);
ws.onmessage = (ev) => { try { onMessage(JSON.parse(String(ev.data))); } catch { /* ignore */ } };
ws.onopen = () => { backoff = 1000; };
ws.onclose = () => { if (!closed) setTimeout(open, backoff); backoff = Math.min(backoff * 2, 15000); };
ws.onclose = () => { if (!closed) timer = setTimeout(open, backoff); backoff = Math.min(backoff * 2, 15000); };
};
open();
return () => { closed = true; ws?.close(); };
return () => { closed = true; if (timer) clearTimeout(timer); ws?.close(); };
}

// ---------- response shapes (only the fields the app reads) ----------
Expand All @@ -120,7 +126,7 @@ export type Activity = {
export type Change = { element_id: string; action: string; state: string; pct?: number; quote?: string; evidence?: string; activity_id?: string };
export type Overview = {
date: string;
kpi: { pct_actual: number; pct_planned: number; spi: number; delay_d: number; forecast_finish: string; open_defects?: number };
kpi: { pct_actual: number; pct_planned: number; spi: number | null; delay_d: number; forecast_finish: string | null; open_defects?: number };
activities: Activity[];
zones: { zone_id: string; name: string; elements: Element[] }[];
proposals: { element_id: string; state: string; name?: string; quote?: string; capture_id?: string }[];
Expand Down
Loading
Loading