Add dark mode, export preview, and keyboard navigation

- Add theme store with light/dark/system modes and ThemeToggle component
- Prevent flash of wrong theme on initial load via inline script
- Add ExportPreviewModal for previewing session exports before download
- Add copy-to-clipboard functionality to session export
- Implement keyboard shortcuts for tree navigation (1-9 options, Esc back, Enter continue)
- Display keyboard hints in tree navigation UI
- Fix findNode to safely handle undefined structure parameter
- Update page title to "Apoklisis"

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Michael Chihlas
2026-01-28 21:19:57 -05:00
parent 4cee013733
commit 5a0dff1da9
9 changed files with 455 additions and 40 deletions

View File

@@ -4,7 +4,19 @@
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>frontend</title>
<title>Apoklisis</title>
<script>
// Prevent flash of wrong theme on initial load
(function() {
try {
const stored = JSON.parse(localStorage.getItem('theme-storage') || '{}');
const theme = stored.state?.theme || 'system';
const isDark = theme === 'dark' ||
(theme === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches);
if (isDark) document.documentElement.classList.add('dark');
} catch (e) {}
})();
</script>
</head>
<body>
<div id="root"></div>

View File

@@ -2,9 +2,11 @@ import { useEffect } from 'react'
import { RouterProvider } from 'react-router-dom'
import { router } from '@/router'
import { useAuthStore } from '@/store/authStore'
import { useThemeStore } from '@/store/themeStore'
function App() {
const { isAuthenticated, fetchUser, setLoading } = useAuthStore()
const { theme, setTheme } = useThemeStore()
useEffect(() => {
// On app load, check if we have a token and fetch user data
@@ -18,6 +20,19 @@ function App() {
}
}, [])
// Listen for system theme changes
useEffect(() => {
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
const handleChange = () => {
if (theme === 'system') {
setTheme('system') // Re-apply to update resolvedTheme
}
}
mediaQuery.addEventListener('change', handleChange)
return () => mediaQuery.removeEventListener('change', handleChange)
}, [theme, setTheme])
return <RouterProvider router={router} />
}

View File

@@ -0,0 +1,36 @@
import { Sun, Moon, Monitor } from 'lucide-react'
import { useThemeStore } from '@/store/themeStore'
import { cn } from '@/lib/utils'
export function ThemeToggle() {
const { theme, setTheme } = useThemeStore()
const options = [
{ value: 'light' as const, icon: Sun, label: 'Light' },
{ value: 'dark' as const, icon: Moon, label: 'Dark' },
{ value: 'system' as const, icon: Monitor, label: 'System' },
]
return (
<div className="flex items-center rounded-md border border-input bg-background p-1">
{options.map(({ value, icon: Icon, label }) => (
<button
key={value}
onClick={() => setTheme(value)}
className={cn(
'rounded p-1.5 transition-colors',
theme === value
? 'bg-accent text-accent-foreground'
: 'text-muted-foreground hover:text-foreground'
)}
aria-label={`Switch to ${label} theme`}
aria-pressed={theme === value}
>
<Icon className="h-4 w-4" />
</button>
))}
</div>
)
}
export default ThemeToggle

View File

@@ -1,5 +1,6 @@
import { Link, useLocation, useNavigate, Outlet } from 'react-router-dom'
import { useAuthStore } from '@/store/authStore'
import { ThemeToggle } from '@/components/common/ThemeToggle'
import { cn } from '@/lib/utils'
export function AppLayout() {
@@ -48,6 +49,7 @@ export function AppLayout() {
<span className="hidden text-sm text-muted-foreground sm:block">
{user?.name || user?.email}
</span>
<ThemeToggle />
<button
onClick={handleLogout}
className={cn(

View File

@@ -0,0 +1,103 @@
import { useState } from 'react'
import { Copy, Download, Check } from 'lucide-react'
import { Modal } from '@/components/common/Modal'
import { cn } from '@/lib/utils'
interface ExportPreviewModalProps {
isOpen: boolean
onClose: () => void
content: string
filename: string
format: 'markdown' | 'text' | 'html'
onDownload: () => void
}
export function ExportPreviewModal({
isOpen,
onClose,
content,
filename,
format,
onDownload,
}: ExportPreviewModalProps) {
const [copied, setCopied] = useState(false)
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(content)
setCopied(true)
setTimeout(() => setCopied(false), 2000)
} catch (err) {
console.error('Failed to copy:', err)
}
}
const handleDownload = () => {
onDownload()
onClose()
}
// Reset copied state when modal closes
const handleClose = () => {
setCopied(false)
onClose()
}
return (
<Modal isOpen={isOpen} onClose={handleClose} title="Export Preview" size="xl">
{/* Filename and format info */}
<p className="mb-3 text-sm text-muted-foreground">
Filename: <span className="font-mono text-foreground">{filename}</span>
<span className="ml-3 rounded bg-secondary px-2 py-0.5 text-xs">
{format === 'markdown' ? 'Markdown' : format === 'html' ? 'HTML' : 'Plain Text'}
</span>
</p>
{/* Content Preview */}
<div
className={cn(
'max-h-96 overflow-auto rounded-md border border-input bg-muted/50 p-4',
'font-mono text-sm text-foreground'
)}
>
<pre className="whitespace-pre-wrap">{content}</pre>
</div>
{/* Actions */}
<div className="mt-4 flex items-center justify-end gap-2">
<button
onClick={handleCopy}
className={cn(
'flex items-center gap-2 rounded-md border border-input px-3 py-2 text-sm font-medium',
'bg-background text-foreground hover:bg-accent',
'focus:outline-none focus:ring-2 focus:ring-ring'
)}
>
{copied ? (
<>
<Check className="h-4 w-4 text-green-500" />
Copied!
</>
) : (
<>
<Copy className="h-4 w-4" />
Copy to Clipboard
</>
)}
</button>
<button
onClick={handleDownload}
className={cn(
'flex items-center gap-2 rounded-md bg-primary px-3 py-2 text-sm font-medium text-primary-foreground',
'hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-ring'
)}
>
<Download className="h-4 w-4" />
Download
</button>
</div>
</Modal>
)
}
export default ExportPreviewModal

View File

@@ -0,0 +1,90 @@
import { useEffect, useCallback } from 'react'
interface ShortcutConfig {
key: string
ctrl?: boolean
shift?: boolean
alt?: boolean
handler: () => void
enabled?: boolean
}
export function useKeyboardShortcuts(shortcuts: ShortcutConfig[]) {
const handleKeyDown = useCallback(
(e: KeyboardEvent) => {
// Don't trigger shortcuts when typing in inputs
const target = e.target as HTMLElement
if (
target.tagName === 'INPUT' ||
target.tagName === 'TEXTAREA' ||
target.isContentEditable
) {
return
}
for (const shortcut of shortcuts) {
if (shortcut.enabled === false) continue
const keyMatch = e.key === shortcut.key || e.key === shortcut.key.toLowerCase()
const ctrlMatch = !!shortcut.ctrl === (e.ctrlKey || e.metaKey)
const shiftMatch = !!shortcut.shift === e.shiftKey
const altMatch = !!shortcut.alt === e.altKey
if (keyMatch && ctrlMatch && shiftMatch && altMatch) {
e.preventDefault()
shortcut.handler()
return
}
}
},
[shortcuts]
)
useEffect(() => {
document.addEventListener('keydown', handleKeyDown)
return () => document.removeEventListener('keydown', handleKeyDown)
}, [handleKeyDown])
}
// Convenience hook for tree navigation specifically
export interface TreeNavigationShortcutsConfig {
onSelectOption: (index: number) => void
onGoBack: () => void
onContinue: () => void
optionCount: number
canGoBack: boolean
canContinue: boolean
}
export function useTreeNavigationShortcuts({
onSelectOption,
onGoBack,
onContinue,
optionCount,
canGoBack,
canContinue,
}: TreeNavigationShortcutsConfig) {
const shortcuts: ShortcutConfig[] = [
// Number keys 1-9 for options
...Array.from({ length: Math.min(optionCount, 9) }, (_, i) => ({
key: String(i + 1),
handler: () => onSelectOption(i),
})),
// Escape to go back
{
key: 'Escape',
handler: onGoBack,
enabled: canGoBack,
},
// Enter to continue (for action nodes)
{
key: 'Enter',
handler: onContinue,
enabled: canContinue,
},
]
useKeyboardShortcuts(shortcuts)
}
export default useKeyboardShortcuts

View File

@@ -1,6 +1,8 @@
import { useEffect, useState } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { Copy, Check, Eye } from 'lucide-react'
import { sessionsApi } from '@/api'
import { ExportPreviewModal } from '@/components/session/ExportPreviewModal'
import type { Session, SessionExport } from '@/types'
import { cn } from '@/lib/utils'
@@ -12,6 +14,9 @@ export function SessionDetailPage() {
const [error, setError] = useState<string | null>(null)
const [isExporting, setIsExporting] = useState(false)
const [exportFormat, setExportFormat] = useState<'markdown' | 'text' | 'html'>('markdown')
const [exportContent, setExportContent] = useState<string | null>(null)
const [showPreview, setShowPreview] = useState(false)
const [copied, setCopied] = useState(false)
useEffect(() => {
if (id) {
@@ -33,27 +38,30 @@ export function SessionDetailPage() {
}
}
const handleExport = async () => {
if (!session) return
const getFilename = () => {
if (!session) return 'export.txt'
const ext = exportFormat === 'markdown' ? 'md' : exportFormat === 'html' ? 'html' : 'txt'
return `session-${session.ticket_number || session.id}.${ext}`
}
const fetchExportContent = async () => {
if (!session) return null
const options: SessionExport = {
format: exportFormat,
include_timestamps: true,
include_tree_info: true,
}
return await sessionsApi.export(session.id, options)
}
const handlePreview = async () => {
setIsExporting(true)
try {
const options: SessionExport = {
format: exportFormat,
include_timestamps: true,
include_tree_info: true,
const content = await fetchExportContent()
if (content) {
setExportContent(content)
setShowPreview(true)
}
const content = await sessionsApi.export(session.id, options)
// Create download
const blob = new Blob([content], { type: 'text/plain' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `session-${session.ticket_number || session.id}.${exportFormat === 'markdown' ? 'md' : exportFormat === 'html' ? 'html' : 'txt'}`
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
URL.revokeObjectURL(url)
} catch (err) {
console.error('Export failed:', err)
} finally {
@@ -61,6 +69,35 @@ export function SessionDetailPage() {
}
}
const handleCopy = async () => {
setIsExporting(true)
try {
const content = await fetchExportContent()
if (content) {
await navigator.clipboard.writeText(content)
setCopied(true)
setTimeout(() => setCopied(false), 2000)
}
} catch (err) {
console.error('Copy failed:', err)
} finally {
setIsExporting(false)
}
}
const handleDownload = () => {
if (!exportContent || !session) return
const blob = new Blob([exportContent], { type: 'text/plain' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = getFilename()
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
URL.revokeObjectURL(url)
}
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleString()
}
@@ -127,6 +164,7 @@ export function SessionDetailPage() {
<select
value={exportFormat}
onChange={(e) => setExportFormat(e.target.value as typeof exportFormat)}
aria-label="Export format"
className={cn(
'rounded-md border border-input bg-background px-3 py-2 text-sm',
'focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary'
@@ -137,14 +175,26 @@ export function SessionDetailPage() {
<option value="html">HTML</option>
</select>
<button
onClick={handleExport}
onClick={handleCopy}
disabled={isExporting}
title="Copy to clipboard"
className={cn(
'rounded-md border border-input bg-background p-2 text-muted-foreground',
'hover:bg-accent hover:text-accent-foreground disabled:opacity-50'
)}
>
{copied ? <Check className="h-4 w-4 text-green-500" /> : <Copy className="h-4 w-4" />}
</button>
<button
onClick={handlePreview}
disabled={isExporting}
className={cn(
'rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground',
'flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground',
'hover:bg-primary/90 disabled:opacity-50'
)}
>
{isExporting ? 'Exporting...' : 'Export'}
<Eye className="h-4 w-4" />
{isExporting ? 'Loading...' : 'Preview'}
</button>
</div>
</div>
@@ -199,6 +249,16 @@ export function SessionDetailPage() {
)}
</div>
</div>
{/* Export Preview Modal */}
<ExportPreviewModal
isOpen={showPreview}
onClose={() => setShowPreview(false)}
content={exportContent || ''}
filename={getFilename()}
format={exportFormat}
onDownload={handleDownload}
/>
</div>
)
}

View File

@@ -1,6 +1,7 @@
import { useEffect, useState } from 'react'
import { useParams, useNavigate, useLocation } from 'react-router-dom'
import { treesApi, sessionsApi } from '@/api'
import { useTreeNavigationShortcuts } from '@/hooks/useKeyboardShortcuts'
import type { Tree, Session, DecisionRecord, TreeStructure } from '@/types'
import { cn } from '@/lib/utils'
@@ -80,7 +81,8 @@ export function TreeNavigationPage() {
}
}
const findNode = (nodeId: string, structure: TreeStructure = tree?.tree_structure!): TreeStructure | null => {
const findNode = (nodeId: string, structure?: TreeStructure): TreeStructure | null => {
if (!structure) return null
if (structure.id === nodeId) return structure
if (structure.children) {
for (const child of structure.children) {
@@ -91,15 +93,16 @@ export function TreeNavigationPage() {
return null
}
// Handler functions - defined before hook call to avoid temporal dead zone
const handleSelectOption = async (_optionId: string, optionLabel: string, nextNodeId: string) => {
if (!session || !tree) return
const currentNode = findNode(currentNodeId)
if (!currentNode) return
const node = findNode(currentNodeId, tree.tree_structure)
if (!node) return
const newDecision: DecisionRecord = {
node_id: currentNodeId,
question: currentNode.question || null,
question: node.question || null,
answer: optionLabel,
action_performed: null,
notes: notes || null,
@@ -130,26 +133,26 @@ export function TreeNavigationPage() {
const handleContinue = async (actionPerformed?: string) => {
if (!session || !tree) return
const currentNode = findNode(currentNodeId)
if (!currentNode || !currentNode.next_node_id) return
const node = findNode(currentNodeId, tree.tree_structure)
if (!node || !node.next_node_id) return
const newDecision: DecisionRecord = {
node_id: currentNodeId,
question: null,
answer: null,
action_performed: actionPerformed || currentNode.title || 'Action completed',
action_performed: actionPerformed || node.title || 'Action completed',
notes: notes || null,
automation_used: false,
timestamp: new Date().toISOString(),
attachments: [],
}
const newPath = [...pathTaken, currentNode.next_node_id]
const newPath = [...pathTaken, node.next_node_id]
const newDecisions = [...decisions, newDecision]
setPathTaken(newPath)
setDecisions(newDecisions)
setCurrentNodeId(currentNode.next_node_id)
setCurrentNodeId(node.next_node_id)
setNotes('')
try {
@@ -163,18 +166,18 @@ export function TreeNavigationPage() {
}
const handleComplete = async () => {
if (!session) return
if (!session || !tree) return
setIsCompleting(true)
setError(null)
try {
// Add final decision
const currentNode = findNode(currentNodeId)
if (currentNode) {
const node = findNode(currentNodeId, tree.tree_structure)
if (node) {
const finalDecision: DecisionRecord = {
node_id: currentNodeId,
question: null,
answer: null,
action_performed: currentNode.title || 'Session completed',
action_performed: node.title || 'Session completed',
notes: notes || null,
automation_used: false,
timestamp: new Date().toISOString(),
@@ -204,6 +207,31 @@ export function TreeNavigationPage() {
setCurrentNodeId(newPath[newPath.length - 1])
}
// Compute current node for keyboard shortcuts (must be before any returns for hooks rules)
const currentNode = tree ? findNode(currentNodeId, tree.tree_structure) : null
const currentOptions = currentNode?.options || []
// Keyboard shortcuts - must be called unconditionally (React hooks rules)
useTreeNavigationShortcuts({
onSelectOption: (index) => {
const option = currentOptions[index]
if (option && session && tree) {
handleSelectOption(option.id, option.label, option.next_node_id)
}
},
onGoBack: handleGoBack,
onContinue: () => {
if (currentNode?.type === 'action' && currentNode.next_node_id) {
handleContinue()
} else if (currentNode?.type === 'solution') {
handleComplete()
}
},
optionCount: currentOptions.length,
canGoBack: pathTaken.length > 1 && !showMetadataForm && !isLoading,
canContinue: !showMetadataForm && !isLoading && (currentNode?.type === 'action' || currentNode?.type === 'solution'),
})
if (isLoading) {
return (
<div className="flex h-64 items-center justify-center">
@@ -289,8 +317,6 @@ export function TreeNavigationPage() {
)
}
const currentNode = findNode(currentNodeId)
if (!currentNode) {
return (
<div className="container mx-auto px-4 py-8">
@@ -357,16 +383,22 @@ export function TreeNavigationPage() {
<p className="mb-4 text-sm text-muted-foreground">{currentNode.help_text}</p>
)}
<div className="mb-4 space-y-2">
{currentNode.options?.map((option) => (
{currentNode.options?.map((option, index) => (
<button
key={option.id}
onClick={() => handleSelectOption(option.id, option.label, option.next_node_id)}
className={cn(
'w-full rounded-md border border-input p-3 text-left transition-colors',
'hover:border-primary hover:bg-accent'
'hover:border-primary hover:bg-accent',
'flex items-center gap-3'
)}
>
{option.label}
{index < 9 && (
<span className="flex h-6 w-6 shrink-0 items-center justify-center rounded bg-muted text-xs font-medium text-muted-foreground">
{index + 1}
</span>
)}
<span>{option.label}</span>
</button>
))}
</div>
@@ -476,6 +508,18 @@ export function TreeNavigationPage() {
Go back
</button>
)}
{/* Keyboard Shortcuts Hint */}
<div className="mt-4 border-t border-border pt-3 text-xs text-muted-foreground">
<span className="font-medium">Keyboard:</span>{' '}
{currentNode.type === 'decision' && currentOptions.length > 0 && (
<span>1-{Math.min(currentOptions.length, 9)} select option</span>
)}
{pathTaken.length > 1 && <span>, Esc go back</span>}
{(currentNode.type === 'action' || currentNode.type === 'solution') && (
<span>, Enter {currentNode.type === 'solution' ? 'complete' : 'continue'}</span>
)}
</div>
</div>
</div>
)

View File

@@ -0,0 +1,53 @@
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
type Theme = 'light' | 'dark' | 'system'
interface ThemeState {
theme: Theme
resolvedTheme: 'light' | 'dark'
setTheme: (theme: Theme) => void
}
const getSystemTheme = (): 'light' | 'dark' => {
if (typeof window === 'undefined') return 'light'
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
}
const applyTheme = (theme: Theme): 'light' | 'dark' => {
const resolved = theme === 'system' ? getSystemTheme() : theme
const root = document.documentElement
if (resolved === 'dark') {
root.classList.add('dark')
} else {
root.classList.remove('dark')
}
return resolved
}
export const useThemeStore = create<ThemeState>()(
persist(
(set) => ({
theme: 'system',
resolvedTheme: getSystemTheme(),
setTheme: (theme: Theme) => {
const resolvedTheme = applyTheme(theme)
set({ theme, resolvedTheme })
},
}),
{
name: 'theme-storage',
onRehydrateStorage: () => (state) => {
// Apply theme on initial load after rehydration
if (state) {
applyTheme(state.theme)
}
},
}
)
)
export default useThemeStore