summaryrefslogtreecommitdiffhomepage
path: root/src/App.svelte
blob: 402c88dd591888e0684fa602f40cebae00eafd96 (plain)
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
<script lang="ts">
	import { App, createAppStore } from "./app";
	import { createHistoryAdapter } from "./adapters/history";
	import {
		createWorkspaceHttp,
		createWorkspaceStore,
		pageTitle,
		parsePath,
		WorkspacesHome,
		type Route,
	} from "./features/workspaces";
	import { resolveHttpUrl } from "./app/resolve-http-url";

	// Parse the route BEFORE creating the store so the boot draft + active
	// workspace are correct from the first render (no flash of the "default"
	// workspace when deep-linking to /<id>).
	const history = createHistoryAdapter();
	const initialRoute = parsePath(history.path);
	const store = createAppStore(
		initialRoute.kind === "workspace" ? { workspaceId: initialRoute.id } : {},
	);

	// The workspace HTTP edge shares the same httpBase resolution as the store.
	const httpBase = resolveHttpUrl(
		{
			VITE_HTTP_URL: import.meta.env.VITE_HTTP_URL,
			VITE_HTTP_PORT: import.meta.env.VITE_HTTP_PORT,
		},
		typeof location !== "undefined" ? location : undefined,
	);
	const workspaceStore = createWorkspaceStore(
		createWorkspaceHttp(httpBase, globalThis.fetch.bind(globalThis)),
	);

	let route = $state<Route>(initialRoute);

	// React to back/forward + programmatic navigation.
	$effect(() => {
		return history.subscribe((path) => {
			route = parsePath(path);
		});
	});

	// On entering a workspace: scope the store to it (idempotent — skip if already
	// scoped) + ensure the workspace exists (create-on-miss, so it appears in the
	// home list immediately). The backend also auto-creates on `chat.send`.
	$effect(() => {
		if (route.kind !== "workspace") return;
		const id = route.id;
		if (store.activeWorkspaceId !== id) {
			store.setActiveWorkspace(id);
		}
		void workspaceStore.ensure(id);
	});

	// Keep the browser tab title in sync with the route: "Dispatch" on the home
	// page, "Dispatch: {title}" on a workspace page (falling back to the URL slug
	// until the list loads it). Reads `route` + the workspace list, so it re-runs
	// on navigation and again once `ensure` refreshes the list.
	$effect(() => {
		if (typeof document === "undefined") return;
		document.title = pageTitle(route, workspaceStore.list);
	});

	function navigate(path: string): void {
		history.navigate(path);
	}
</script>

{#if route.kind === "home"}
	<WorkspacesHome store={workspaceStore} onNavigate={navigate} computers={store.computers} />
{:else}
	<App {store} />
{/if}