File size: 13,536 Bytes
7540aea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33e6f65
7540aea
 
 
 
 
 
 
 
 
 
 
 
 
33e6f65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7540aea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33e6f65
7540aea
 
 
 
 
 
 
 
 
 
 
 
 
33e6f65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7540aea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33e6f65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7540aea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33e6f65
 
7540aea
 
 
 
 
 
 
 
 
 
33e6f65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7540aea
33e6f65
 
 
 
 
 
 
 
7540aea
33e6f65
 
 
 
7540aea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useState, useEffect, useMemo } from "react";
import { cn } from "@/lib/utils";
import { trpc } from "@/lib/trpc";
import {
  Plus,
  MessageSquare,
  Settings,
  Trash2,
  Edit3,
  Check,
  X,
  ChevronLeft,
  ChevronRight,
  DollarSign,
  Zap,
  LogOut,
  Search,
  ChevronDown,
} from "lucide-react";
import { useAuth } from "@/_core/hooks/useAuth";
import { getLoginUrl } from "@/const";

interface SidebarProps {
  currentSessionId: number | null;
  onSelectSession: (id: number) => void;
  onNewSession: () => void;
  onOpenSettings: () => void;
  collapsed: boolean;
  onToggleCollapse: () => void;
}

type DateGroup = "Today" | "Yesterday" | "This Week" | "This Month" | "Older";

function getDateGroup(dateStr: string): DateGroup {
  const date = new Date(dateStr);
  const now = new Date();
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  const yesterday = new Date(today);
  yesterday.setDate(yesterday.getDate() - 1);
  const weekAgo = new Date(today);
  weekAgo.setDate(weekAgo.getDate() - 7);
  const monthAgo = new Date(today);
  monthAgo.setMonth(monthAgo.getMonth() - 1);

  if (date >= today) return "Today";
  if (date >= yesterday) return "Yesterday";
  if (date >= weekAgo) return "This Week";
  if (date >= monthAgo) return "This Month";
  return "Older";
}

const GROUP_ORDER: DateGroup[] = ["Today", "Yesterday", "This Week", "This Month", "Older"];

export function Sidebar({
  currentSessionId,
  onSelectSession,
  onNewSession,
  onOpenSettings,
  collapsed,
  onToggleCollapse,
}: SidebarProps) {
  const { user } = useAuth();
  const utils = trpc.useUtils();
  const { data: sessions, isLoading } = trpc.sessions.list.useQuery();
  const { data: costSummary } = trpc.costs.summary.useQuery(undefined, {
    enabled: !!user,
  });
  const deleteMutation = trpc.sessions.delete.useMutation({
    onSuccess: () => utils.sessions.list.invalidate(),
  });
  const updateMutation = trpc.sessions.update.useMutation({
    onSuccess: () => utils.sessions.list.invalidate(),
  });
  const logoutMutation = trpc.auth.logout.useMutation({
    onSuccess: () => window.location.reload(),
  });

  const [editingId, setEditingId] = useState<number | null>(null);
  const [editTitle, setEditTitle] = useState("");
  const [searchQuery, setSearchQuery] = useState("");
  const [collapsedGroups, setCollapsedGroups] = useState<Set<DateGroup>>(new Set());

  // Filter sessions by search
  const filteredSessions = useMemo(() => {
    if (!sessions) return [];
    if (!searchQuery.trim()) return sessions;
    const q = searchQuery.toLowerCase();
    return sessions.filter(
      (s) =>
        s.title.toLowerCase().includes(q) ||
        (s.model && s.model.toLowerCase().includes(q))
    );
  }, [sessions, searchQuery]);

  // Group sessions by date
  const groupedSessions = useMemo(() => {
    const groups = new Map<DateGroup, typeof filteredSessions>();
    for (const session of filteredSessions) {
      const group = getDateGroup(session.updatedAt || session.createdAt);
      if (!groups.has(group)) groups.set(group, []);
      groups.get(group)!.push(session);
    }
    return groups;
  }, [filteredSessions]);

  const toggleGroup = (group: DateGroup) => {
    setCollapsedGroups((prev) => {
      const next = new Set(prev);
      if (next.has(group)) next.delete(group);
      else next.add(group);
      return next;
    });
  };

  // Listen for title updates from SSE
  useEffect(() => {
    const handler = () => {
      utils.sessions.list.invalidate();
    };
    window.addEventListener("session-title-update", handler);
    return () => window.removeEventListener("session-title-update", handler);
  }, [utils]);

  const startEdit = (id: number, title: string) => {
    setEditingId(id);
    setEditTitle(title);
  };

  const saveEdit = () => {
    if (editingId && editTitle.trim()) {
      updateMutation.mutate({ id: editingId, title: editTitle.trim() });
    }
    setEditingId(null);
  };

  if (collapsed) {
    return (
      <div className="w-12 bg-sidebar border-r border-sidebar-border flex flex-col items-center py-3 gap-2">
        <button
          onClick={onToggleCollapse}
          className="size-8 rounded-lg hover:bg-sidebar-accent flex items-center justify-center text-sidebar-foreground/60 hover:text-sidebar-foreground transition-colors"
        >
          <ChevronRight className="size-4" />
        </button>
        <button
          onClick={onNewSession}
          className="size-8 rounded-lg bg-primary/20 hover:bg-primary/30 flex items-center justify-center text-primary transition-colors"
          title="New session"
        >
          <Plus className="size-4" />
        </button>
        <div className="flex-1" />
        <button
          onClick={onOpenSettings}
          className="size-8 rounded-lg hover:bg-sidebar-accent flex items-center justify-center text-sidebar-foreground/60 hover:text-sidebar-foreground transition-colors"
          title="Settings"
        >
          <Settings className="size-4" />
        </button>
      </div>
    );
  }

  const renderSession = (session: (typeof filteredSessions)[0]) => (
    <div
      key={session.id}
      className={cn(
        "group flex items-center gap-2 rounded-lg px-2.5 py-2 cursor-pointer transition-colors",
        session.id === currentSessionId
          ? "bg-sidebar-accent text-sidebar-accent-foreground"
          : "text-sidebar-foreground/70 hover:bg-sidebar-accent/50 hover:text-sidebar-foreground"
      )}
      onClick={() => onSelectSession(session.id)}
    >
      <MessageSquare className="size-3.5 shrink-0 opacity-60" />

      {editingId === session.id ? (
        <div className="flex-1 flex items-center gap-1">
          <input
            value={editTitle}
            onChange={(e) => setEditTitle(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === "Enter") saveEdit();
              if (e.key === "Escape") setEditingId(null);
            }}
            className="flex-1 bg-background text-xs rounded px-1.5 py-0.5 outline-none border border-border"
            autoFocus
            onClick={(e) => e.stopPropagation()}
          />
          <button
            onClick={(e) => {
              e.stopPropagation();
              saveEdit();
            }}
            className="text-green-400 hover:text-green-300"
          >
            <Check className="size-3" />
          </button>
          <button
            onClick={(e) => {
              e.stopPropagation();
              setEditingId(null);
            }}
            className="text-muted-foreground hover:text-foreground"
          >
            <X className="size-3" />
          </button>
        </div>
      ) : (
        <>
          <span className="flex-1 text-xs truncate">{session.title}</span>
          <div className="hidden group-hover:flex items-center gap-0.5">
            <button
              onClick={(e) => {
                e.stopPropagation();
                startEdit(session.id, session.title);
              }}
              className="size-5 rounded hover:bg-background/50 flex items-center justify-center"
            >
              <Edit3 className="size-3" />
            </button>
            <button
              onClick={(e) => {
                e.stopPropagation();
                if (confirm("Delete this session?")) {
                  deleteMutation.mutate({ id: session.id });
                }
              }}
              className="size-5 rounded hover:bg-destructive/20 text-destructive flex items-center justify-center"
            >
              <Trash2 className="size-3" />
            </button>
          </div>
        </>
      )}
    </div>
  );

  return (
    <div className="w-64 bg-sidebar border-r border-sidebar-border flex flex-col h-full">
      {/* Header */}
      <div className="p-3 flex items-center justify-between border-b border-sidebar-border">
        <div className="flex items-center gap-2">
          <Zap className="size-5 text-primary" />
          <span className="font-semibold text-sm text-sidebar-foreground">
            Claw
          </span>
        </div>
        <div className="flex items-center gap-1">
          <button
            onClick={onNewSession}
            className="size-7 rounded-md hover:bg-sidebar-accent flex items-center justify-center text-sidebar-foreground/60 hover:text-sidebar-foreground transition-colors"
            title="New session"
          >
            <Plus className="size-4" />
          </button>
          <button
            onClick={onToggleCollapse}
            className="size-7 rounded-md hover:bg-sidebar-accent flex items-center justify-center text-sidebar-foreground/60 hover:text-sidebar-foreground transition-colors"
          >
            <ChevronLeft className="size-4" />
          </button>
        </div>
      </div>

      {/* Search */}
      <div className="px-2 pt-2">
        <div className="relative">
          <Search className="absolute left-2 top-1/2 -translate-y-1/2 size-3.5 text-muted-foreground" />
          <input
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="Search sessions..."
            className="w-full bg-sidebar-accent/50 border border-sidebar-border rounded-md pl-7 pr-2 py-1.5 text-xs outline-none focus:border-primary placeholder:text-muted-foreground/50"
          />
        </div>
      </div>

      {/* Sessions list — grouped by date */}
      <div className="flex-1 overflow-y-auto py-2 px-2">
        {isLoading && (
          <div className="text-xs text-muted-foreground text-center py-4">
            Loading sessions...
          </div>
        )}
        {filteredSessions.length === 0 && !isLoading && (
          <div className="text-xs text-muted-foreground text-center py-4">
            {searchQuery ? "No matching sessions" : "No sessions yet"}
          </div>
        )}
        {GROUP_ORDER.map((group) => {
          const groupSessions = groupedSessions.get(group);
          if (!groupSessions || groupSessions.length === 0) return null;
          const isCollapsed = collapsedGroups.has(group);
          return (
            <div key={group} className="mb-2">
              <button
                onClick={() => toggleGroup(group)}
                className="w-full flex items-center gap-1.5 px-1 py-1 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground/60 hover:text-muted-foreground transition-colors"
              >
                <ChevronDown
                  className={cn(
                    "size-3 transition-transform",
                    isCollapsed && "-rotate-90"
                  )}
                />
                <span>{group}</span>
                <span className="ml-auto text-[9px] font-normal opacity-50">
                  {groupSessions.length}
                </span>
              </button>
              {!isCollapsed && (
                <div className="space-y-0.5">
                  {groupSessions.map(renderSession)}
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* Cost widget */}
      {costSummary && (
        <div className="mx-2 mb-2 px-2.5 py-2 rounded-lg bg-sidebar-accent/30 border border-sidebar-border">
          <div className="flex items-center gap-1.5 text-[10px] text-muted-foreground mb-0.5">
            <DollarSign className="size-3" />
            <span>Total Cost</span>
          </div>
          <div className="text-sm font-mono font-semibold text-primary">
            ${Number(costSummary.totalCost || 0).toFixed(4)}
          </div>
          <div className="text-[10px] text-muted-foreground">
            {Number(costSummary.totalPromptTokens || 0).toLocaleString()} +{" "}
            {Number(costSummary.totalCompletionTokens || 0).toLocaleString()}{" "}
            tokens
          </div>
        </div>
      )}

      {/* Bottom section */}
      <div className="border-t border-sidebar-border p-2 space-y-0.5">
        <button
          onClick={onOpenSettings}
          className="w-full flex items-center gap-2.5 rounded-lg px-2.5 py-2 text-sidebar-foreground/70 hover:bg-sidebar-accent/50 hover:text-sidebar-foreground transition-colors"
        >
          <Settings className="size-3.5" />
          <span className="text-xs">Settings</span>
        </button>

        {user ? (
          <div className="flex items-center gap-2 px-2.5 py-2">
            <div className="size-6 rounded-full bg-primary/20 flex items-center justify-center text-primary text-[10px] font-bold">
              {user.name?.[0]?.toUpperCase() || "U"}
            </div>
            <span className="flex-1 text-xs text-sidebar-foreground/70 truncate">
              {user.name || "User"}
            </span>
            <button
              onClick={() => logoutMutation.mutate()}
              className="size-6 rounded hover:bg-sidebar-accent flex items-center justify-center text-sidebar-foreground/40 hover:text-sidebar-foreground transition-colors"
              title="Logout"
            >
              <LogOut className="size-3" />
            </button>
          </div>
        ) : (
          <a
            href={getLoginUrl()}
            className="w-full flex items-center gap-2.5 rounded-lg px-2.5 py-2 text-primary hover:bg-sidebar-accent/50 transition-colors"
          >
            <span className="text-xs font-medium">Sign in</span>
          </a>
        )}
      </div>
    </div>
  );
}