-
Notifications
You must be signed in to change notification settings - Fork 516
Expand file tree
/
Copy pathstack-companion.tsx
More file actions
564 lines (500 loc) · 20 KB
/
stack-companion.tsx
File metadata and controls
564 lines (500 loc) · 20 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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
'use client';
import { Button, Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui';
import { ChangelogEntry } from '@/lib/changelog';
import { cn } from '@/lib/utils';
import { checkVersion, VersionCheckResult } from '@/lib/version-check';
import { BookOpenIcon, CircleNotchIcon, ClockClockwiseIcon, LightbulbIcon, XIcon } from '@phosphor-icons/react';
import { runAsynchronously } from '@stackframe/stack-shared/dist/utils/promises';
import React, { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react';
import packageJson from '../../package.json';
import { FeedbackForm } from './feedback-form';
import { ChangelogWidget } from './stack-companion/changelog-widget';
import { FeatureRequestBoard } from './stack-companion/feature-request-board';
import { UnifiedDocsWidget } from './stack-companion/unified-docs-widget';
/**
* Compare two CalVer versions in YYYY.MM.DD format
* Returns true if version1 is newer than version2
*/
function isNewerCalVer(version1: string, version2: string): boolean {
const parseCalVer = (version: string): Date | null => {
const match = version.match(/^(\d{4})\.(\d{2})\.(\d{2})$/);
if (!match) return null;
const [, year, month, day] = match;
return new Date(parseInt(year), parseInt(month) - 1, parseInt(day));
};
const date1 = parseCalVer(version1);
const date2 = parseCalVer(version2);
if (!date1 || !date2) {
// Fallback to string comparison if parsing fails
return version1 > version2;
}
return date1.getTime() > date2.getTime();
}
/**
* Sanitize a string value for use in a cookie
* Removes or encodes characters that could break cookie parsing
*/
function sanitizeCookieValue(value: string): string {
// Remove or encode special characters that break cookie parsing
return encodeURIComponent(value);
}
type SidebarItem = {
id: string,
label: string,
icon: React.ElementType,
color: string,
hoverBg: string,
};
const sidebarItems: SidebarItem[] = [
{
id: 'docs',
label: 'Docs',
icon: BookOpenIcon,
color: 'text-blue-600 dark:text-blue-400',
hoverBg: 'hover:bg-blue-500/10',
},
{
id: 'feedback',
label: 'Feature Requests',
icon: LightbulbIcon,
color: 'text-purple-600 dark:text-purple-400',
hoverBg: 'hover:bg-purple-500/10',
},
{
id: 'changelog',
label: 'Changelog',
icon: ClockClockwiseIcon,
color: 'text-green-600 dark:text-green-400',
hoverBg: 'hover:bg-green-500/10',
},
{
id: 'support',
label: "Support",
icon: CircleNotchIcon,
color: 'text-orange-600 dark:text-orange-400',
hoverBg: 'hover:bg-orange-500/10',
}
];
const MIN_DRAWER_WIDTH = 400;
const MAX_DRAWER_WIDTH = 800;
const DEFAULT_DRAWER_WIDTH = 480;
const CLOSE_THRESHOLD = 100;
// Breakpoint for split-screen mode
const SPLIT_SCREEN_BREAKPOINT = 1000;
// Context for sharing companion state with layout
type StackCompanionContextType = {
drawerWidth: number,
isSplitScreenMode: boolean,
};
const StackCompanionContext = createContext<StackCompanionContextType>({
drawerWidth: 0,
isSplitScreenMode: false,
});
export function useStackCompanion() {
return useContext(StackCompanionContext);
}
export function StackCompanion({ className }: { className?: string }) {
const [activeItem, setActiveItem] = useState<string | null>(null);
const [mounted, setMounted] = useState(false);
const [versionCheckResult, setVersionCheckResult] = useState<VersionCheckResult>(null);
const [drawerWidth, setDrawerWidth] = useState(0);
const [isResizing, setIsResizing] = useState(false);
const [isAnimating, setIsAnimating] = useState(false);
const [isDragging, setIsDragging] = useState(false);
const [isSplitScreenMode, setIsSplitScreenMode] = useState(false);
const [changelogData, setChangelogData] = useState<ChangelogEntry[] | undefined>(undefined);
const [hasNewVersions, setHasNewVersions] = useState(false);
const [lastSeenVersion, setLastSeenVersion] = useState('');
const startXRef = useRef(0);
const startWidthRef = useRef(0);
const dragThresholdRef = useRef(false);
const animationTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const draggingTimeoutRef = useRef<NodeJS.Timeout | null>(null);
useEffect(() => {
setMounted(true);
}, []);
// Cleanup animation timeouts on unmount
useEffect(() => {
return () => {
if (animationTimeoutRef.current) {
clearTimeout(animationTimeoutRef.current);
}
if (draggingTimeoutRef.current) {
clearTimeout(draggingTimeoutRef.current);
}
};
}, []);
// Detect screen size for split-screen mode
useEffect(() => {
const checkScreenSize = () => {
setIsSplitScreenMode(window.innerWidth >= SPLIT_SCREEN_BREAKPOINT);
};
checkScreenSize();
window.addEventListener('resize', checkScreenSize);
return () => window.removeEventListener('resize', checkScreenSize);
}, []);
useEffect(() => {
const cleanup = checkVersion(setVersionCheckResult, {
delay: 2000,
silentFailure: true,
errorPrefix: "Version check failed in companion"
});
return cleanup;
}, []);
// Fetch changelog data on mount and check for new versions
useEffect(() => {
const fetchChangelogData = async () => {
try {
const response = await fetch('/api/changelog');
if (response.ok) {
const payload = await response.json();
const entries = payload.entries || [];
setChangelogData(entries);
// Check for new versions
const lastSeenRaw = document.cookie
.split('; ')
.find(row => row.startsWith('stack-last-seen-changelog-version='))
?.split('=')[1] || '';
const lastSeen = lastSeenRaw ? decodeURIComponent(lastSeenRaw) : '';
setLastSeenVersion(lastSeen);
if (entries.length > 0) {
// If no lastSeen cookie, user hasn't seen any changelog yet - show bell
if (!lastSeen) {
setHasNewVersions(true);
} else {
const hasNewer = entries.some((entry: ChangelogEntry) => {
if (entry.isUnreleased) return false;
return isNewerCalVer(entry.version, lastSeen);
});
setHasNewVersions(hasNewer);
}
}
} else {
// If fetch failed, leave changelogData as undefined so widget can try fetching itself
console.error('Failed to fetch changelog data: response not OK');
}
} catch (error) {
console.error('Failed to fetch changelog data:', error);
// Leave changelogData as undefined so widget can try fetching itself
}
};
runAsynchronously(fetchChangelogData());
}, []);
// Re-check for new versions when changelog is opened/closed
useEffect(() => {
if (activeItem === 'changelog') {
// When changelog is opened, mark the latest version as seen
if (changelogData && changelogData.length > 0) {
const latestVersion = changelogData[0].version;
document.cookie = `stack-last-seen-changelog-version=${sanitizeCookieValue(latestVersion)}; path=/; max-age=31536000`; // 1 year
setLastSeenVersion(latestVersion);
}
// Clear the notification badge immediately
setHasNewVersions(false);
} else if (activeItem === null) {
// When closed, re-check if there are new versions
const lastSeenRaw = document.cookie
.split('; ')
.find(row => row.startsWith('stack-last-seen-changelog-version='))
?.split('=')[1] || '';
const lastSeen = lastSeenRaw ? decodeURIComponent(lastSeenRaw) : '';
if (changelogData && changelogData.length > 0) {
// If no lastSeen cookie, user hasn't seen any changelog yet - show bell
if (!lastSeen) {
setHasNewVersions(true);
} else {
const hasNewer = changelogData.some((entry: ChangelogEntry) => {
if (entry.isUnreleased) return false;
return isNewerCalVer(entry.version, lastSeen);
});
setHasNewVersions(hasNewer);
}
} else {
setHasNewVersions(false);
}
}
}, [activeItem, changelogData]);
const openDrawer = useCallback((itemId: string) => {
setActiveItem(itemId);
setIsAnimating(true);
// Start animation
requestAnimationFrame(() => {
setDrawerWidth(DEFAULT_DRAWER_WIDTH);
if (animationTimeoutRef.current) {
clearTimeout(animationTimeoutRef.current);
}
animationTimeoutRef.current = setTimeout(() => setIsAnimating(false), 300);
});
}, []);
const closeDrawer = useCallback(() => {
setIsAnimating(true);
setDrawerWidth(0);
if (animationTimeoutRef.current) {
clearTimeout(animationTimeoutRef.current);
}
animationTimeoutRef.current = setTimeout(() => {
setActiveItem(null);
setIsAnimating(false);
}, 300);
}, []);
// Handle click vs drag
const handleItemClick = useCallback((itemId: string) => {
if (dragThresholdRef.current) return; // Ignore clicks if we were dragging
if (activeItem === itemId) {
closeDrawer();
} else if (activeItem) {
setActiveItem(itemId);
} else {
openDrawer(itemId);
}
}, [activeItem, closeDrawer, openDrawer]);
const handleMouseDown = useCallback((e: React.MouseEvent | React.TouchEvent) => {
// Don't initiate drag if clicking resizing handle or scrollbar
if ((e.target as HTMLElement).closest('.no-drag')) return;
// Only allow dragging when an item is already selected (drawer is open)
if (!activeItem) return;
setIsResizing(true);
setIsAnimating(false);
dragThresholdRef.current = false;
startXRef.current = 'touches' in e ? e.touches[0].clientX : e.clientX;
startWidthRef.current = drawerWidth;
}, [drawerWidth, activeItem]);
useEffect(() => {
if (!isResizing) return;
const handleMouseMove = (e: MouseEvent | TouchEvent) => {
const clientX = 'touches' in e ? e.touches[0].clientX : e.clientX;
const deltaX = startXRef.current - clientX;
// Check for drag threshold to distinguish click vs drag
if (Math.abs(deltaX) > 5) {
dragThresholdRef.current = true;
setIsDragging(true);
}
// Logic:
// - Moving left (positive deltaX) -> Width increases
// - Moving right (negative deltaX) -> Width decreases
// But only if we are starting from right edge.
// Since flex-row-reverse anchors to right, increasing width moves the handle left.
let newWidth = startWidthRef.current + deltaX;
newWidth = Math.max(0, Math.min(MAX_DRAWER_WIDTH, newWidth));
setDrawerWidth(newWidth);
};
const handleMouseUp = () => {
setIsResizing(false);
if (draggingTimeoutRef.current) {
clearTimeout(draggingTimeoutRef.current);
}
draggingTimeoutRef.current = setTimeout(() => setIsDragging(false), 0);
if (dragThresholdRef.current) {
// If we dragged, snap to state
if (drawerWidth < CLOSE_THRESHOLD) {
closeDrawer();
} else if (drawerWidth < MIN_DRAWER_WIDTH) {
setIsAnimating(true);
setDrawerWidth(MIN_DRAWER_WIDTH);
if (animationTimeoutRef.current) {
clearTimeout(animationTimeoutRef.current);
}
animationTimeoutRef.current = setTimeout(() => setIsAnimating(false), 200);
} else {
// Keep current width but ensure item is active
if (!activeItem) {
// If dragged open from closed state without clicking specific item, default to docs
setActiveItem('docs');
}
}
} else {
// If it was just a click (no drag), handleItemClick will trigger
}
dragThresholdRef.current = false;
};
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
document.addEventListener('touchmove', handleMouseMove);
document.addEventListener('touchend', handleMouseUp);
return () => {
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
document.removeEventListener('touchmove', handleMouseMove);
document.removeEventListener('touchend', handleMouseUp);
};
}, [isResizing, drawerWidth, closeDrawer, activeItem]);
// Disable text selection during drag
useEffect(() => {
if (isDragging) {
document.body.style.userSelect = 'none';
document.body.style.cursor = 'ew-resize';
} else {
document.body.style.userSelect = '';
document.body.style.cursor = '';
}
return () => {
document.body.style.userSelect = '';
document.body.style.cursor = '';
};
}, [isDragging]);
if (!mounted) return null;
const isOpen = drawerWidth > 0;
const currentItem = sidebarItems.find(i => i.id === activeItem);
// Calculate content opacity for smooth fade-out as width approaches close threshold
const contentOpacity = Math.min(1, Math.max(0, (drawerWidth - CLOSE_THRESHOLD) / (MIN_DRAWER_WIDTH - CLOSE_THRESHOLD)));
// Shared drawer content component
const drawerContent = isOpen && activeItem && (
<div
className="flex flex-col h-full w-full min-w-[360px] transition-opacity duration-150"
style={{ opacity: contentOpacity }}
>
{/* Header */}
<div className="flex items-center justify-between px-5 py-4 border-b border-foreground/[0.06] shrink-0 bg-background/40">
<div className="flex items-center gap-2.5">
{currentItem && (
<>
<div className={cn("p-1.5 rounded-lg bg-foreground/[0.04]")}>
<currentItem.icon className={cn("h-4 w-4", currentItem.color)} />
</div>
<span className="font-semibold text-foreground">
{currentItem.label}
</span>
</>
)}
</div>
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0 text-muted-foreground hover:text-foreground hover:bg-foreground/[0.06] rounded-lg no-drag"
onClick={closeDrawer}
>
<XIcon className="h-4 w-4" />
</Button>
</div>
{/* Content */}
<div className="flex-1 overflow-y-auto p-5 overflow-x-hidden no-drag cursor-auto">
{activeItem === 'docs' && <UnifiedDocsWidget isActive={true} />}
{activeItem === 'feedback' && <FeatureRequestBoard isActive={true} />}
{activeItem === 'changelog' && <ChangelogWidget isActive={true} initialData={changelogData} />}
{activeItem === 'support' && <FeedbackForm />}
</div>
</div>
);
// Shared handle component
const handleComponent = (
<div
className={cn(
"flex items-center shrink-0 z-10",
isOpen ? "h-full -mr-px" : "h-auto",
!isSplitScreenMode && "pointer-events-auto"
)}
onMouseDown={handleMouseDown}
onTouchStart={handleMouseDown}
>
{/* The Handle Pill */}
<div className={cn(
"flex flex-col items-center gap-3 px-2 py-3 bg-foreground/[0.03] backdrop-blur-xl border border-foreground/5 shadow-sm transition-all duration-300 select-none",
// Only show grab cursor when an item is selected (drawer can be resized)
activeItem && "cursor-grab active:cursor-grabbing",
// Shape morphing
isOpen ? "rounded-l-2xl rounded-r-none border-r-0 translate-x-px" : "rounded-full mr-3"
)}>
{sidebarItems.map(item => (
<Tooltip key={item.id}>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="sm"
className={cn(
"h-10 w-10 p-0 text-muted-foreground transition-all duration-[50ms] rounded-xl relative group",
item.hoverBg,
activeItem === item.id && "bg-foreground/10 text-foreground shadow-sm ring-1 ring-foreground/5",
// Glow effect for changelog with new updates
item.id === 'changelog' && hasNewVersions && "ring-2 ring-green-500/30 bg-green-500/10"
)}
onClick={(e) => {
e.stopPropagation();
handleItemClick(item.id);
}}
>
<item.icon className={cn("h-5 w-5 transition-transform duration-[50ms] group-hover:scale-110", item.color)} />
{item.id === 'changelog' && hasNewVersions && (
<span className="absolute -top-1 -right-1 flex h-3 w-3">
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75" />
<span className="relative inline-flex rounded-full h-3 w-3 bg-green-500" />
</span>
)}
</Button>
</TooltipTrigger>
<TooltipContent side="left" className="z-[60] mr-2">
{item.id === 'changelog' && hasNewVersions ? `${item.label} (New updates available!)` : item.label}
</TooltipContent>
</Tooltip>
))}
{versionCheckResult && (
<div className={cn(
"mt-auto pt-2 px-2 py-1 text-[10px] rounded-full font-mono font-medium opacity-60 hover:opacity-100 transition-opacity",
versionCheckResult.severe ? "text-red-500" : "text-orange-500"
)}>
v{packageJson.version}
</div>
)}
</div>
</div>
);
const contextValue = { drawerWidth, isSplitScreenMode };
// Split-screen mode: inline layout that pushes content
// Only show drawer container when open or animating (to allow close animation)
const showDrawerContainerSplit = isOpen || isAnimating;
if (isSplitScreenMode) {
return (
<StackCompanionContext.Provider value={contextValue}>
<aside
className={cn(
"sticky top-20 h-[calc(100vh-6rem)] mr-3 flex flex-row-reverse items-stretch shrink-0",
isAnimating && !isResizing && "transition-[width] duration-300 ease-out",
className
)}
style={{ width: drawerWidth > 0 ? drawerWidth + 56 : 56 }} // 56px for handle width
>
{/* Drawer Content */}
{showDrawerContainerSplit && (
<div
className={cn(
"h-full bg-gray-100/80 dark:bg-foreground/5 backdrop-blur-xl border border-border/10 dark:border-foreground/5 overflow-hidden relative rounded-2xl shadow-sm",
isAnimating && !isResizing && "transition-[width] duration-300 ease-out"
)}
style={{ width: drawerWidth }}
>
<div className="absolute inset-y-0 left-0 w-px bg-gradient-to-b from-transparent via-foreground/10 to-transparent opacity-50" />
{drawerContent}
</div>
)}
{/* Handle */}
{handleComponent}
</aside>
</StackCompanionContext.Provider>
);
}
// Overlay mode: fixed position sliding drawer (default for smaller screens)
// Only show drawer container when open or animating (to allow close animation)
const showDrawerContainer = isOpen || isAnimating;
return (
<StackCompanionContext.Provider value={contextValue}>
{/* Main Container - Fixed Right Edge, Flex Reverse to push handle left */}
<div className={cn("fixed inset-y-0 right-0 z-50 flex flex-row-reverse items-center pointer-events-none", className)}>
{/* 1. Drawer Content (Rightmost in layout, stays anchored to right) */}
{showDrawerContainer && (
<div
className={cn(
"h-full overflow-hidden pointer-events-auto relative bg-background/80 backdrop-blur-xl border-l border-foreground/[0.08] shadow-2xl",
isAnimating && !isResizing && "transition-[width] duration-300 ease-out"
)}
style={{ width: drawerWidth }}
>
{/* Inner shadow/gradient for depth */}
<div className="absolute inset-y-0 left-0 w-px bg-gradient-to-b from-transparent via-foreground/10 to-transparent opacity-50" />
{drawerContent}
</div>
)}
{/* 2. Stack Companion Handle (Left of Drawer) */}
{handleComponent}
</div>
</StackCompanionContext.Provider>
);
}