feat: add ShareSessionModal and integrate into SessionDetailPage

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
chihlasm
2026-02-14 16:13:32 -05:00
parent d1b849a5f8
commit 7eb77dd782
2 changed files with 465 additions and 181 deletions

View File

@@ -0,0 +1,431 @@
import { useState, useEffect } from 'react'
import { X, Copy, Check, Globe, Users, Clock, Trash2, Link2 } from 'lucide-react'
import type { SessionShare, SessionShareVisibility } from '@/types'
import { sessionsApi } from '@/api/sessions'
import { buildSessionShareUrl, filterSharesForSession } from '@/lib/sessionShare'
import { cn } from '@/lib/utils'
import { toast } from '@/lib/toast'
interface ShareSessionModalProps {
sessionId: string
sessionLabel: string // e.g. ticket number or "Session Details"
isOpen: boolean
onClose: () => void
}
type ExpirationPreset = 'never' | '1day' | '7days' | '30days' | 'custom'
function getRelativeTime(dateString: string): string {
const now = Date.now()
const date = new Date(dateString).getTime()
const diffMs = now - date
const diffSeconds = Math.floor(diffMs / 1000)
const diffMinutes = Math.floor(diffSeconds / 60)
const diffHours = Math.floor(diffMinutes / 60)
const diffDays = Math.floor(diffHours / 24)
if (diffSeconds < 60) return 'just now'
if (diffMinutes < 60) return `${diffMinutes} minute${diffMinutes === 1 ? '' : 's'} ago`
if (diffHours < 24) return `${diffHours} hour${diffHours === 1 ? '' : 's'} ago`
if (diffDays < 30) return `${diffDays} day${diffDays === 1 ? '' : 's'} ago`
const diffMonths = Math.floor(diffDays / 30)
return `${diffMonths} month${diffMonths === 1 ? '' : 's'} ago`
}
function getExpirationLabel(expiresAt: string | null): { text: string; isExpired: boolean } {
if (!expiresAt) return { text: 'No expiration', isExpired: false }
const now = Date.now()
const expiry = new Date(expiresAt).getTime()
if (expiry <= now) return { text: 'Expired', isExpired: true }
const diffMs = expiry - now
const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
const diffDays = Math.floor(diffHours / 24)
if (diffDays > 0) return { text: `Expires in ${diffDays} day${diffDays === 1 ? '' : 's'}`, isExpired: false }
if (diffHours > 0) return { text: `Expires in ${diffHours} hour${diffHours === 1 ? '' : 's'}`, isExpired: false }
return { text: 'Expires soon', isExpired: false }
}
function computeExpiresAt(preset: ExpirationPreset, customDatetime: string): string | undefined {
if (preset === 'never') return undefined
if (preset === 'custom') {
if (!customDatetime) return undefined
return new Date(customDatetime).toISOString()
}
const now = new Date()
switch (preset) {
case '1day':
now.setDate(now.getDate() + 1)
break
case '7days':
now.setDate(now.getDate() + 7)
break
case '30days':
now.setDate(now.getDate() + 30)
break
}
return now.toISOString()
}
export function ShareSessionModal({ sessionId, sessionLabel, isOpen, onClose }: ShareSessionModalProps) {
const [shares, setShares] = useState<SessionShare[]>([])
const [isLoadingShares, setIsLoadingShares] = useState(false)
const [isGenerating, setIsGenerating] = useState(false)
const [copiedShareId, setCopiedShareId] = useState<string | null>(null)
// Form state
const [visibility, setVisibility] = useState<SessionShareVisibility>('account')
const [shareName, setShareName] = useState('')
const [expirationPreset, setExpirationPreset] = useState<ExpirationPreset>('never')
const [customDatetime, setCustomDatetime] = useState('')
const [visibilityError, setVisibilityError] = useState<string | null>(null)
useEffect(() => {
if (isOpen) {
loadShares()
// Reset form state
setVisibility('account')
setShareName('')
setExpirationPreset('never')
setCustomDatetime('')
setVisibilityError(null)
setCopiedShareId(null)
}
}, [isOpen, sessionId])
const loadShares = async () => {
setIsLoadingShares(true)
try {
const allShares = await sessionsApi.listMyShares()
const sessionShares = filterSharesForSession(allShares, sessionId)
// Sort newest first
sessionShares.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
setShares(sessionShares)
} catch (err) {
console.error('Failed to load shares:', err)
} finally {
setIsLoadingShares(false)
}
}
const handleGenerateLink = async () => {
setIsGenerating(true)
setVisibilityError(null)
try {
const expires_at = computeExpiresAt(expirationPreset, customDatetime)
const newShare = await sessionsApi.createShare(sessionId, {
visibility,
share_name: shareName.trim() || undefined,
expires_at,
})
setShares([newShare, ...shares])
toast.success('Share link generated')
// Reset form
setShareName('')
setExpirationPreset('never')
setCustomDatetime('')
} catch (err: unknown) {
const error = err as { response?: { status?: number; data?: { detail?: string } } }
if (
error.response?.status === 403 &&
error.response?.data?.detail?.toLowerCase().includes('public session sharing')
) {
setVisibilityError(error.response.data.detail ?? 'Organization does not allow public session sharing')
} else {
console.error('Failed to generate share link:', err)
toast.error('Failed to generate share link')
}
} finally {
setIsGenerating(false)
}
}
const handleCopyUrl = async (share: SessionShare) => {
try {
const url = buildSessionShareUrl(share)
await navigator.clipboard.writeText(url)
setCopiedShareId(share.id)
toast.success('Link copied to clipboard')
setTimeout(() => setCopiedShareId(null), 2000)
} catch (err) {
console.error('Failed to copy link:', err)
toast.error('Failed to copy link')
}
}
const handleRevoke = async (shareId: string) => {
try {
await sessionsApi.revokeShare(shareId)
setShares(shares.filter((s) => s.id !== shareId))
toast.success('Share link revoked')
} catch (err) {
console.error('Failed to revoke share:', err)
toast.error('Failed to revoke share')
}
}
if (!isOpen) return null
const presetButtons: { value: ExpirationPreset; label: string }[] = [
{ value: 'never', label: 'Never' },
{ value: '1day', label: '1 day' },
{ value: '7days', label: '7 days' },
{ value: '30days', label: '30 days' },
{ value: 'custom', label: 'Custom' },
]
return (
<div className="fixed inset-0 z-50 flex items-center justify-center">
{/* Backdrop */}
<div
className="absolute inset-0 bg-black/80 backdrop-blur-sm"
onClick={onClose}
/>
{/* Modal */}
<div className="relative w-full max-w-lg glass-card rounded-2xl shadow-lg">
{/* Header */}
<div className="flex items-center justify-between border-b border-white/[0.06] px-6 py-4">
<div>
<h2 className="text-lg font-semibold text-white">Share Session</h2>
<p className="text-sm text-white/40">{sessionLabel}</p>
</div>
<button
onClick={onClose}
className="rounded-md p-1 text-white/40 hover:bg-white/[0.06] hover:text-white"
>
<X className="h-5 w-5" />
</button>
</div>
{/* Body */}
<div className="max-h-[60vh] overflow-y-auto px-6 py-4 space-y-6">
{/* Create Share Form */}
<div className="space-y-4">
{/* Visibility */}
<div>
<label className="mb-2 block text-sm font-medium text-white">
Visibility
</label>
<div className="space-y-2">
<button
onClick={() => { setVisibility('account'); setVisibilityError(null) }}
className={cn(
'flex w-full items-center gap-3 rounded-md border px-4 py-3 text-left transition-colors',
visibility === 'account'
? 'border-white/20 bg-white/10 text-white'
: 'border-white/[0.06] bg-transparent text-white/50 hover:border-white/20 hover:bg-white/[0.06]'
)}
>
<Users className="h-4 w-4" />
<div className="flex-1">
<div className="text-sm font-medium">Account Only</div>
<div className="text-xs text-white/40">Visible to your team</div>
</div>
{visibility === 'account' && (
<div className="h-2 w-2 rounded-full bg-white" />
)}
</button>
<button
onClick={() => { setVisibility('public'); setVisibilityError(null) }}
className={cn(
'flex w-full items-center gap-3 rounded-md border px-4 py-3 text-left transition-colors',
visibility === 'public'
? 'border-white/20 bg-white/10 text-white'
: 'border-white/[0.06] bg-transparent text-white/50 hover:border-white/20 hover:bg-white/[0.06]'
)}
>
<Globe className="h-4 w-4" />
<div className="flex-1">
<div className="text-sm font-medium">Public</div>
<div className="text-xs text-white/40">Anyone with the link</div>
</div>
{visibility === 'public' && (
<div className="h-2 w-2 rounded-full bg-white" />
)}
</button>
</div>
{visibilityError && (
<p className="mt-2 text-sm text-red-400">{visibilityError}</p>
)}
</div>
{/* Share Name */}
<div>
<label className="mb-2 block text-sm font-medium text-white">
Share Name <span className="text-white/40">(optional)</span>
</label>
<input
type="text"
value={shareName}
onChange={(e) => setShareName(e.target.value.slice(0, 100))}
placeholder="e.g. Training link, Customer escalation"
className={cn(
'w-full rounded-md border border-white/10 bg-black/50 px-3 py-2 text-sm text-white placeholder-white/30',
'focus:border-white/30 focus:outline-none focus:ring-1 focus:ring-white/20'
)}
maxLength={100}
/>
</div>
{/* Expiration */}
<div>
<label className="mb-2 block text-sm font-medium text-white">
Expiration
</label>
<div className="flex flex-wrap gap-2">
{presetButtons.map((preset) => (
<button
key={preset.value}
onClick={() => setExpirationPreset(preset.value)}
className={cn(
'rounded-md border px-3 py-1.5 text-sm transition-colors',
expirationPreset === preset.value
? 'border-white/20 bg-white/10 text-white'
: 'border-white/10 text-white/50 hover:border-white/20 hover:bg-white/[0.06]'
)}
>
{preset.label}
</button>
))}
</div>
{expirationPreset === 'custom' && (
<input
type="datetime-local"
value={customDatetime}
onChange={(e) => setCustomDatetime(e.target.value)}
className={cn(
'mt-2 w-full rounded-md border border-white/10 bg-black/50 px-3 py-2 text-sm text-white',
'focus:border-white/30 focus:outline-none focus:ring-1 focus:ring-white/20',
'[color-scheme:dark]'
)}
/>
)}
</div>
{/* Generate Button */}
<button
onClick={handleGenerateLink}
disabled={isGenerating || (expirationPreset === 'custom' && !customDatetime)}
className={cn(
'flex w-full items-center justify-center gap-2 rounded-md bg-white px-4 py-2 text-sm font-medium text-black',
'hover:bg-white/90 disabled:opacity-50 disabled:cursor-not-allowed'
)}
>
<Link2 className="h-4 w-4" />
{isGenerating ? 'Generating...' : 'Generate Link'}
</button>
</div>
{/* Existing Shares */}
{shares.length > 0 && (
<div>
<h3 className="mb-3 text-sm font-medium text-white">
Active Shares ({shares.length})
</h3>
<div className="space-y-3">
{shares.map((share) => {
const expiration = getExpirationLabel(share.expires_at)
const isCopied = copiedShareId === share.id
return (
<div
key={share.id}
className="glass-card rounded-xl p-4 space-y-2"
>
<div className="flex items-start justify-between gap-2">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className={cn(
'inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs',
share.visibility === 'public'
? 'bg-white/10 text-white/70'
: 'bg-white/10 text-white/70'
)}>
{share.visibility === 'public' ? (
<Globe className="h-3 w-3" />
) : (
<Users className="h-3 w-3" />
)}
{share.visibility === 'public' ? 'Public' : 'Account'}
</span>
<span className="truncate text-sm font-medium text-white">
{share.share_name || 'Untitled share'}
</span>
</div>
<div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-white/40">
<span>{getRelativeTime(share.created_at)}</span>
<span>
{share.view_count > 0
? `${share.view_count} view${share.view_count === 1 ? '' : 's'}`
: 'Not viewed yet'}
</span>
<span className={cn(
'flex items-center gap-1',
expiration.isExpired && 'text-red-400'
)}>
<Clock className="h-3 w-3" />
{expiration.text}
</span>
</div>
</div>
<div className="flex items-center gap-1 shrink-0">
<button
onClick={() => handleCopyUrl(share)}
title="Copy share URL"
className={cn(
'rounded-md border border-white/10 p-1.5 text-sm transition-colors',
isCopied
? 'border-emerald-500/30 bg-emerald-500/10 text-emerald-400'
: 'text-white/50 hover:bg-white/10 hover:text-white'
)}
>
{isCopied ? (
<Check className="h-3.5 w-3.5" />
) : (
<Copy className="h-3.5 w-3.5" />
)}
</button>
<button
onClick={() => handleRevoke(share.id)}
title="Revoke share"
className="rounded-md border border-white/10 p-1.5 text-white/50 hover:bg-red-500/10 hover:border-red-500/30 hover:text-red-400 transition-colors"
>
<Trash2 className="h-3.5 w-3.5" />
</button>
</div>
</div>
</div>
)
})}
</div>
</div>
)}
{/* Loading state */}
{isLoadingShares && shares.length === 0 && (
<div className="flex items-center justify-center py-4">
<div className="h-5 w-5 animate-spin rounded-full border-2 border-white/20 border-t-white" />
</div>
)}
</div>
{/* Footer */}
<div className="flex justify-end gap-3 border-t border-white/[0.06] px-6 py-4">
<button
onClick={onClose}
className={cn(
'rounded-md border border-white/10 px-4 py-2 text-sm font-medium text-white/60',
'hover:bg-white/10 hover:text-white'
)}
>
Close
</button>
</div>
</div>
</div>
)
}
export default ShareSessionModal

View File

@@ -1,11 +1,15 @@
import { useEffect, useState } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { Copy, Check, Eye, Save } from 'lucide-react'
import { Copy, Check, Eye, Save, Share2 } from 'lucide-react'
import { sessionsApi } from '@/api/sessions'
import { stepsApi } from '@/api/steps'
import { ExportPreviewModal } from '@/components/session/ExportPreviewModal'
import { SaveSessionAsTreeModal } from '@/components/session/SaveSessionAsTreeModal'
import { ShareSessionModal } from '@/components/session/ShareSessionModal'
import { SessionTimeline } from '@/components/session/SessionTimeline'
import { StepRatingModal } from '@/components/session/StepRatingModal'
import { ActionMenu } from '@/components/common/ActionMenu'
import type { MenuAction } from '@/components/common/ActionMenu'
import { useUserPreferencesStore } from '@/store/userPreferencesStore'
import type { Session, SessionExport, SaveAsTreeRequest, Step, RedactionSummary } from '@/types'
import { hasRatedSession, markSessionRated } from '@/lib/sessionRatings'
@@ -30,7 +34,7 @@ export function SessionDetailPage() {
const [showRatingModal, setShowRatingModal] = useState(false)
const [isSavingRatings, setIsSavingRatings] = useState(false)
const [librarySteps, setLibrarySteps] = useState<Step[]>([])
const [copiedStepIndex, setCopiedStepIndex] = useState<number | null>(null)
const [showShareModal, setShowShareModal] = useState(false)
const [maxStepIndex, setMaxStepIndex] = useState<number | null>(null)
const [detailLevel, setDetailLevel] = useState<'standard' | 'full'>('standard')
const [includeSummary, setIncludeSummary] = useState(false)
@@ -257,26 +261,6 @@ export function SessionDetailPage() {
}
}
const handleCopyStep = async (decision: Session['decisions'][number], index: number) => {
const lines: string[] = []
if (decision.question) lines.push(`Question: ${decision.question}`)
if (decision.answer) lines.push(`Answer: ${decision.answer}`)
if (decision.action_performed) lines.push(`Action: ${decision.action_performed}`)
if (decision.notes) lines.push(`Notes: ${decision.notes}`)
if (decision.command_output) lines.push(`Output:\n${decision.command_output}`)
try {
await navigator.clipboard.writeText(lines.join('\n'))
setCopiedStepIndex(index)
setTimeout(() => setCopiedStepIndex(null), 2000)
} catch {
// Clipboard access denied
}
}
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleString()
}
const formatDuration = (durationSeconds: number | null | undefined) => {
if (durationSeconds == null || durationSeconds < 0) return null
if (durationSeconds < 60) return `${durationSeconds}s`
@@ -381,20 +365,20 @@ export function SessionDetailPage() {
{/* Actions */}
<div className="flex flex-col gap-2 sm:flex-row sm:items-center">
{/* Save as Tree - Only for completed sessions */}
{session.completed_at && (
<button
onClick={() => setShowSaveAsTreeModal(true)}
disabled={isSavingTree}
className={cn(
'flex items-center gap-2 rounded-md border border-white/10 bg-transparent px-4 py-2 text-sm font-medium text-white/60',
'hover:bg-white/10 hover:text-white disabled:opacity-50'
)}
>
<Save className="h-4 w-4" />
Save as Tree
</button>
)}
<ActionMenu
actions={[
{
label: 'Share',
icon: Share2,
onClick: () => setShowShareModal(true),
},
...(session.completed_at ? [{
label: 'Save as Tree',
icon: Save,
onClick: () => setShowSaveAsTreeModal(true),
}] as MenuAction[] : []),
]}
/>
{/* Copy for Ticket */}
<button
@@ -482,151 +466,12 @@ export function SessionDetailPage() {
</div>
{/* Timeline / Step Checklist */}
<div className="mb-8">
{(session.tree_snapshot as unknown as Record<string, unknown>).tree_type === 'procedural' ? (
<>
<h2 className="mb-4 text-lg font-semibold text-white">Procedure Steps</h2>
<div className="space-y-2">
{session.decisions.map((decision, index) => {
const isCompleted = decision.answer === 'completed'
return (
<div
key={index}
className={cn(
'glass-card rounded-xl p-4',
isCompleted && 'border-l-2 border-emerald-400/50'
)}
>
<div className="flex items-start gap-3">
<span className={cn(
'mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-full text-xs font-medium',
isCompleted ? 'bg-emerald-400/10 text-emerald-400' : 'bg-white/10 text-white/50'
)}>
{isCompleted ? '\u2713' : index + 1}
</span>
<div className="min-w-0 flex-1">
<p className="font-medium text-white">{decision.question || 'Step'}</p>
{decision.notes && (
<p className="mt-1.5 rounded bg-white/5 p-2 text-sm text-white/40">
Notes: {decision.notes}
</p>
)}
{decision.command_output && (
<p className="mt-1 text-sm text-white/40">
Verification: {decision.command_output}
</p>
)}
{decision.duration_seconds != null && (
<p className="mt-1 text-xs text-white/30">
Duration: {formatDuration(decision.duration_seconds)}
</p>
)}
</div>
<button
onClick={() => handleCopyStep(decision, index)}
title="Copy step to clipboard"
className="rounded p-1 text-white/30 hover:bg-white/10 hover:text-white"
>
{copiedStepIndex === index ? (
<Check className="h-4 w-4 text-emerald-400" />
) : (
<Copy className="h-4 w-4" />
)}
</button>
</div>
</div>
)
})}
{session.completed_at && (
<div className="flex items-center gap-3 pl-2 pt-2 text-sm">
<span className="h-3 w-3 rounded-full bg-emerald-500" />
<span className="text-emerald-400">
Procedure completed: {formatDate(session.completed_at)}
</span>
</div>
)}
</div>
</>
) : (
<>
<h2 className="mb-4 text-lg font-semibold text-white">Decision Timeline</h2>
<div className="space-y-4">
<div className="flex items-center gap-3 text-sm">
<span className="h-3 w-3 rounded-full bg-white" />
<span className="text-white/40">
Session started: {formatDate(session.started_at)}
</span>
</div>
{session.decisions.map((decision, index) => (
<div key={index} className="ml-1 border-l-2 border-white/[0.06] pl-6">
<div className="relative">
<span className="absolute -left-[1.625rem] top-1 h-2 w-2 rounded-full bg-white/20" />
<div className="glass-card rounded-xl p-4">
<div className="flex items-start justify-between gap-2">
<div className="flex-1">
{decision.question && (
<p className="font-medium text-white">{decision.question}</p>
)}
{decision.answer && (
<p className="mt-1 text-sm text-white">Answer: {decision.answer}</p>
)}
{decision.action_performed && (
<p className="mt-1 text-sm text-white/40">
Action: {decision.action_performed}
</p>
)}
{decision.notes && (
<p className="mt-2 rounded bg-white/5 p-2 text-sm text-white/40">
Notes: {decision.notes}
</p>
)}
{decision.command_output && (
<div className="mt-2">
<p className="mb-1 text-xs font-medium text-white/50">Command Output</p>
<pre className="overflow-x-auto rounded bg-white/5 p-2 text-xs font-mono text-white/60 whitespace-pre-wrap">
{decision.command_output}
</pre>
</div>
)}
{decision.duration_seconds != null && (
<p className="mt-2 text-xs text-white/50">
Duration: {formatDuration(decision.duration_seconds)}
</p>
)}
<p className="mt-2 text-xs text-white/40">
{formatDate(decision.timestamp)}
</p>
</div>
<button
onClick={() => handleCopyStep(decision, index)}
title="Copy step to clipboard"
className="rounded p-1 text-white/30 hover:bg-white/10 hover:text-white"
>
{copiedStepIndex === index ? (
<Check className="h-4 w-4 text-emerald-400" />
) : (
<Copy className="h-4 w-4" />
)}
</button>
</div>
</div>
</div>
</div>
))}
{session.completed_at && (
<div className="flex items-center gap-3 text-sm">
<span className="h-3 w-3 rounded-full bg-green-500" />
<span className="text-emerald-400">
Session completed: {formatDate(session.completed_at)}
</span>
</div>
)}
</div>
</>
)}
</div>
<SessionTimeline
decisions={session.decisions}
treeType={(session.tree_snapshot as unknown as Record<string, unknown>).tree_type as string}
startedAt={session.started_at}
completedAt={session.completed_at}
/>
{/* Export Preview Modal */}
<ExportPreviewModal
@@ -660,6 +505,14 @@ export function SessionDetailPage() {
librarySteps={librarySteps}
isSaving={isSavingRatings}
/>
{/* Share Session Modal */}
<ShareSessionModal
sessionId={session.id}
sessionLabel={session.ticket_number || 'Session Details'}
isOpen={showShareModal}
onClose={() => setShowShareModal(false)}
/>
</div>
)
}