summaryrefslogtreecommitdiffhomepage
path: root/src/features/workspaces/ui/WorkspacesHome.svelte
blob: b330e1daad0cdfd93e20e950678beac93d2e6769 (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
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
<script lang="ts">
  import { onMount, untrack } from "svelte";
  import type { ComputerEntry } from "@dispatch/wire";
  import {
    PluginManager,
    WorkspacePluginModal,
    type PluginsStore,
    type WorkspaceLayoutPort,
  } from "../../plugins";
  import type { WorkspaceStore } from "../store.svelte";
  import { workspacePath } from "../logic/route";
  import {
    DEFAULT_VIEWPORT,
    geometryFor,
    pack,
    type GridGeometry,
    type Span,
  } from "../logic/tile-layout";
  import { type TileLayoutStore } from "../tile-layout-store.svelte";
  import HomeHeader from "./HomeHeader.svelte";
  import HomeTileGrid from "./HomeTileGrid.svelte";
  import TileActionBar from "./TileActionBar.svelte";
  import ResizePicker from "./ResizePicker.svelte";
  import WorkspaceDetails from "./WorkspaceDetails.svelte";
  import ArchivedWorkspaces from "./ArchivedWorkspaces.svelte";

  let {
    store,
    onNavigate,
    computers,
    hasActive,
    plugins,
    layout,
    tiles: tilesOverride,
  }: {
    store: WorkspaceStore;
    onNavigate: (path: string) => void;
    computers: readonly ComputerEntry[];
    /**
     * Optional port: whether the workspace has at least one active
     * (generating / queued) conversation — the tile's live indicator.
     * Wired by the composition root to the app store. Absent → no indicator.
     */
    hasActive?: (workspaceId: string) => boolean;
    /**
     * The plugin manager store (plan 07): drives the header's global
     * "Plugins" button + the action bar's per-workspace Plugins action.
     * Optional (absent in tests that don't exercise plugins).
     */
    plugins?: PluginsStore;
    /**
     * The layout port (plan 04 §4.4): forwarded to the per-workspace plugins
     * modal's "Reset layout to default" affordance. Absent → the modal's
     * layout section doesn't render.
     */
    layout?: WorkspaceLayoutPort;
    /**
     * The synced tile layout store (ONE shared document per device
     * orientation, persisted by the backend's home-tile-layout plugin).
     * Created by the page entry (App.svelte — the composition root that owns
     * the httpBase); tests inject one.
     */
    tiles: TileLayoutStore;
  } = $props();

  onMount(() => {
    void store.refresh();
  });

  // The store arrives fully wired (the page entry created it over the real
  // HTTP edge). The `untrack` capture (the repo's initial-value pattern, cf.
  // App.svelte) dealiases the prop once — the component instance is the
  // store's single owner from here on.
  const tiles: TileLayoutStore = untrack(() => tilesOverride);

  // Keep the layout merged with the live workspace list: unknown workspaces
  // (deep-link auto-creates) append at the end; deleted ones drop. The
  // no-op guards inside sync keep this effect from looping. Skipped until
  // the first non-empty list arrives — `sync([])` before the initial
  // `refresh()` resolves would WIPE the persisted order (the backend always
  // serves "default", so an empty list only ever means "not loaded yet").
  $effect(() => {
    const ids = store.list.map((ws) => ws.id);
    if (ids.length === 0) return;
    tiles.sync(ids);
  });

  // ── The tile canvas' size decides the geometry (ONE pure function — no
  // breakpoint classes). Unmeasured (tests) → the default landscape viewport.
  let regionEl = $state<HTMLDivElement | undefined>();
  let size = $state<{ width: number; height: number } | undefined>();
  const geometry: GridGeometry = $derived(
    geometryFor(size?.width ?? DEFAULT_VIEWPORT.width, size?.height ?? DEFAULT_VIEWPORT.height),
  );

  $effect(() => {
    const el = regionEl;
    if (!el || typeof ResizeObserver === "undefined") return;
    const observer = new ResizeObserver((entries) => {
      const rect = entries[0]?.contentRect;
      if (rect) size = { width: rect.width, height: rect.height };
    });
    observer.observe(el);
    return () => observer.disconnect();
  });

  // Lock the store's active orientation to the resolved grid geometry: the
  // landscape/portrait split IS the device-type split — every landscape
  // device shares the `wide` document, every portrait device the `tall` one.
  // Same-mode calls are a no-op inside the store; an orientation change
  // resets + re-probes (never flashing the other orientation's arrangement).
  $effect(() => {
    tiles.setMode(geometry.mode);
  });

  // The grid view: the SAME persisted data packs into either geometry —
  // positions re-derive here, spans clamp for the RENDER only.
  const placements = $derived(pack(tiles.entries, geometry));
  const workspacesById = $derived(new Map(store.list.map((ws) => [ws.id, ws])));

  // ── Selection + action bar ─────────────────────────────────────────────────
  let selectedId = $state<string | null>(null);
  const selected = $derived(selectedId !== null ? (workspacesById.get(selectedId) ?? null) : null);

  function select(id: string): void {
    selectedId = id;
  }

  function deselect(): void {
    selectedId = null;
  }

  // ── Rename mode (the create flow + the action bar's Rename action) ────────
  let renamingId = $state<string | null>(null);

  // ── Resize picker (transient ghost preview; commit persists) ──────────────
  let resizing = $state<{ id: string; span: Span | null } | null>(null);
  const resizingEntry = $derived(
    resizing ? (tiles.entries.find((tile) => tile.id === resizing?.id) ?? null) : null,
  );

  function startResize(): void {
    if (!selected) return;
    const entry = tiles.entries.find((tile) => tile.id === selected.id);
    resizing = {
      id: selected.id,
      span: entry
        ? { colSpan: entry.colSpan, rowSpan: entry.rowSpan }
        : { colSpan: 1, rowSpan: 1 },
    };
  }

  function commitResize(colSpan: number, rowSpan: number): void {
    if (!resizing) return;
    tiles.resize(resizing.id, colSpan, rowSpan);
    resizing = null;
  }

  function cancelResize(): void {
    resizing = null;
  }

  // ── Details flyout (the dense per-card settings). Id-based + gated on the
  // selection, so deselecting (Escape) also dismisses it. ─────────────────────
  let detailsForId = $state<string | null>(null);
  const detailsFor = $derived(
    selectedId !== null && detailsForId === selectedId
      ? (workspacesById.get(selectedId) ?? null)
      : null,
  );

  // ── Per-workspace plugin modal ─────────────────────────────────────────────
  let pluginsModalId = $state<string | null>(null);
  const pluginsModalFor = $derived(
    pluginsModalId !== null ? (workspacesById.get(pluginsModalId) ?? null) : null,
  );

  // Global plugin manager modal (plan 07 §7.2): the ONLY surface that
  // loads/unloads code (strict layering).
  let managerOpen = $state(false);

  // ── Archived workspaces modal ──────────────────────────────────────────────
  let archivedOpen = $state(false);

  // ── Actions (the action bar) ───────────────────────────────────────────────
  function openWorkspace(id: string): void {
    deselect();
    onNavigate(workspacePath(id));
  }

  async function deleteSelected(): Promise<void> {
    if (!selected) return;
    const ws = selected;
    if (
      !window.confirm(
        `Delete workspace "${ws.title}"? Its conversations will be closed and moved to "default".`,
      )
    ) {
      return;
    }
    const result = await store.remove(ws.id);
    if (result.ok) deselect();
  }

  async function toggleStar(): Promise<void> {
    if (!selected) return;
    await store.setStarred(selected.id, !selected.starred);
  }

  async function archiveSelected(): Promise<void> {
    if (!selected) return;
    const ws = selected;
    // Reversible without a confirm dialog — the workspace is hidden, not deleted.
    const result = await store.setArchived(ws.id, true);
    if (result.ok) deselect();
  }

  // ── Create (header popover): create on the backend — do NOT navigate —
  // place the new tile in the first empty slot, and go straight into rename.
  async function createWorkspace(
    slug: string,
  ): Promise<{ ok: true } | { ok: false; error: string }> {
    const result = await store.ensure(slug);
    if (!result.ok) return { ok: false, error: result.error };
    await store.refresh();
    // Idempotent: if the list refresh's sync already appended the id, this
    // MOVES it into the first empty slot instead of duplicating.
    tiles.placeFirstEmpty(slug, geometry);
    renamingId = slug;
    return { ok: true };
  }

  // ── Sort overflow: re-apply the recent-activity order ──────────────────────
  function sortByRecent(): void {
    const activity = new Map(store.list.map((ws) => [ws.id, ws.lastActivityAt]));
    tiles.sortByRecentActivity(activity);
  }

  // Escape unwinds the overlays: resize → selection.
  function handleKeydown(e: KeyboardEvent): void {
    if (e.key !== "Escape") return;
    if (resizing) {
      cancelResize();
    } else if (selectedId !== null) {
      deselect();
    }
  }
</script>

<svelte:window onkeydown={handleKeydown} />

<div class="flex h-screen w-full flex-col">
  <HomeHeader
    compact={geometry.mode === "tall"}
    withPlugins={plugins !== undefined}
    withSort={store.list.length > 1}
    onCreate={createWorkspace}
    onOpenPlugins={() => (managerOpen = true)}
    onSort={() => void sortByRecent()}
    onOpenArchived={() => (archivedOpen = true)}
  />

  <div bind:this={regionEl} class="min-h-0 w-full flex-1">
    {#if store.loading && store.list.length === 0}
      <div class="flex h-full items-center justify-center">
        <span class="loading loading-spinner loading-lg opacity-60"></span>
      </div>
    {:else if store.list.length === 0}
      <div class="flex h-full flex-col items-center justify-center gap-3 px-6 text-center">
        <p class="text-2xl font-black tracking-tight opacity-80">No workspaces yet</p>
        <p class="max-w-md text-sm opacity-60">
          Create one with <strong>New workspace</strong> above, or visit
          <code class="rounded bg-base-200 px-1.5 py-0.5">/your-name</code> in the URL — the first
          tile drops onto the canvas ready to rename.
        </p>
      </div>
    {:else}
      <HomeTileGrid
        {geometry}
        {placements}
        {workspacesById}
        {store}
        {selectedId}
        {renamingId}
        preview={
          resizing?.id !== undefined && resizing.span !== null
            ? { id: resizing.id, ...resizing.span }
            : null
        }
        {...(hasActive ? { hasActive } : {})}
        onOpen={openWorkspace}
        onSelect={select}
        onPlace={(id, cell) => cell !== null && tiles.placeAtCell(id, cell, geometry)}
        onRenameEnd={() => (renamingId = null)}
      />
    {/if}
  </div>
</div>

{#if selected && !renamingId}
  <TileActionBar
    ws={selected}
    withPlugins={plugins !== undefined}
    onOpen={() => openWorkspace(selected.id)}
    onRename={() => (renamingId = selected.id)}
    onResize={startResize}
    onToggleStar={() => void toggleStar()}
    onDetails={() => (detailsForId = selected.id)}
    onPlugins={() => (pluginsModalId = selected.id)}
    onArchive={() => void archiveSelected()}
    onDelete={() => void deleteSelected()}
    onClose={deselect}
  />
{/if}

{#if resizing && resizingEntry}
  <ResizePicker
    {geometry}
    initial={{ colSpan: resizingEntry.colSpan, rowSpan: resizingEntry.rowSpan }}
    onPreview={(span) => {
      if (resizing) resizing = { id: resizing.id, span };
    }}
    onCommit={commitResize}
    onCancel={cancelResize}
  />
{/if}

{#if detailsFor}
  <WorkspaceDetails ws={detailsFor} {store} {computers} onClose={() => (detailsForId = null)} />
{/if}

{#if pluginsModalFor && plugins}
  <WorkspacePluginModal
    workspaceId={pluginsModalFor.id}
    workspaceTitle={pluginsModalFor.title}
    {plugins}
    {...(layout ? { layout } : {})}
    onClose={() => (pluginsModalId = null)}
  />
{/if}

{#if managerOpen && plugins}
  <PluginManager {plugins} onClose={() => (managerOpen = false)} />
{/if}

{#if archivedOpen}
  <ArchivedWorkspaces
    {store}
    onOpen={(id) => openWorkspace(id)}
    onClose={() => (archivedOpen = false)}
  />
{/if}