diff --git a/homebrew/Formula/mininas.rb b/homebrew/Formula/mininas.rb index 8217b1e..3fb02f6 100644 --- a/homebrew/Formula/mininas.rb +++ b/homebrew/Formula/mininas.rb @@ -18,8 +18,8 @@ def install libexec.install "packages/api/dist/cli.js" libexec.install "packages/api/dist/schema.sql" - # Install web static assets - (libexec/"web").install Dir["packages/web/dist/*"] + # Install web static assets (unified Expo app) + (libexec/"web").install Dir["packages/app/dist/*"] # Install node_modules for native addons (better-sqlite3, sharp) cd "packages/api" do diff --git a/package.json b/package.json index 9e31f40..14c03fc 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,7 @@ "scripts": { "dev": "turbo dev", "build": "turbo build", - "start": "pnpm build && (pnpm --filter api start & pnpm --filter web preview)", + "start": "pnpm build && WEB_DIST_DIR=packages/app/dist pnpm --filter api start", "lint": "biome check .", "lint:fix": "biome check --fix .", "format": "biome format .", diff --git a/packages/api/src/middleware/static.ts b/packages/api/src/middleware/static.ts index 33cf3cc..6aae408 100644 --- a/packages/api/src/middleware/static.ts +++ b/packages/api/src/middleware/static.ts @@ -66,19 +66,14 @@ export function createStaticMiddleware(distDir: string) { let filePath = tryFile(distDir, pathname) - // SPA fallback: /volumes/X/Y/Z -> /volumes/index.html - if (!filePath && pathname.startsWith('/volumes/') && !path.extname(pathname)) { - filePath = path.join(distDir, 'volumes', 'index.html') + // SPA fallback: any non-file route → root index.html + if (!filePath && !path.extname(pathname)) { + filePath = path.join(distDir, 'index.html') + if (!isFile(filePath)) return next() } if (!filePath) { - // Try index.html for root - if (pathname === '/') { - filePath = path.join(distDir, 'index.html') - if (!isFile(filePath)) return next() - } else { - return next() - } + return next() } const ext = path.extname(filePath) diff --git a/packages/app/.gitignore b/packages/app/.gitignore new file mode 100644 index 0000000..d48833b --- /dev/null +++ b/packages/app/.gitignore @@ -0,0 +1,8 @@ +.expo/ +dist/ + +# @generated expo-cli sync-2b81b286409207a5da26e14c78851eb30d8ccbdb +# The following patterns were generated by expo-cli + +expo-env.d.ts +# @end expo-cli \ No newline at end of file diff --git a/packages/app/app.config.js b/packages/app/app.config.js new file mode 100644 index 0000000..16564c2 --- /dev/null +++ b/packages/app/app.config.js @@ -0,0 +1,45 @@ +export default { + expo: { + name: 'MiniNAS', + slug: 'mininas', + version: '0.1.0', + orientation: 'default', + scheme: 'mininas', + userInterfaceStyle: 'light', + newArchEnabled: true, + ios: { + supportsTablet: true, + bundleIdentifier: 'com.mininas.app', + }, + android: { + adaptiveIcon: { + backgroundColor: '#ffffff', + }, + package: 'com.mininas.app', + }, + web: { + bundler: 'metro', + output: 'static', + favicon: './src/assets/favicon.png', + }, + plugins: [ + 'expo-router', + [ + 'expo-build-properties', + { + ios: { + deploymentTarget: '15.1', + }, + }, + ], + ], + experiments: { + typedRoutes: true, + }, + extra: { + router: { + origin: false, + }, + }, + }, +} diff --git a/packages/app/metro.config.js b/packages/app/metro.config.js new file mode 100644 index 0000000..18076a8 --- /dev/null +++ b/packages/app/metro.config.js @@ -0,0 +1,75 @@ +const { getDefaultConfig } = require('expo/metro-config') +const path = require('path') + +const projectRoot = __dirname +const monorepoRoot = path.resolve(projectRoot, '../..') + +module.exports = (() => { + const config = getDefaultConfig(projectRoot) + const { resolver } = config + + // pnpm monorepo: tell Metro where to find packages + config.watchFolders = [monorepoRoot] + config.resolver.nodeModulesPaths = [ + path.resolve(projectRoot, 'node_modules'), + path.resolve(monorepoRoot, 'node_modules'), + ] + + // Dev server middleware: proxy /api and /dav requests to the MiniNAS backend + config.server = { + ...config.server, + enhanceMiddleware: (middleware) => { + return (req, res, next) => { + // Proxy API requests to backend + if (req.url?.startsWith('/api/') || req.url?.startsWith('/dav/')) { + const http = require('http') + const proxyReq = http.request( + { + hostname: 'localhost', + port: 3001, + path: req.url, + method: req.method, + headers: req.headers, + }, + (proxyRes) => { + res.writeHead(proxyRes.statusCode, proxyRes.headers) + proxyRes.pipe(res, { end: true }) + }, + ) + req.pipe(proxyReq, { end: true }) + return + } + return middleware(req, res, next) + } + }, + } + + config.resolver = { + ...resolver, + resolveRequest: (context, moduleName, platform) => { + if (platform === 'web') { + // Alias react-native to react-native-web on web + if (moduleName === 'react-native') { + return context.resolveRequest(context, 'react-native-web', platform) + } + + // Mock native-only modules on web + const webMocks = { + 'expo-haptics': path.resolve(__dirname, 'mocks/expo-haptics.web.js'), + 'expo-splash-screen': path.resolve(__dirname, 'mocks/expo-splash-screen.web.js'), + 'react-native-screens': path.resolve(__dirname, 'mocks/react-native-screens.web.js'), + } + + if (webMocks[moduleName]) { + return { + type: 'sourceFile', + filePath: webMocks[moduleName], + } + } + } + return context.resolveRequest(context, moduleName, platform) + }, + } + + return config +})() diff --git a/packages/app/mocks/expo-haptics.web.js b/packages/app/mocks/expo-haptics.web.js new file mode 100644 index 0000000..a544b2f --- /dev/null +++ b/packages/app/mocks/expo-haptics.web.js @@ -0,0 +1,11 @@ +module.exports = { + impactAsync: () => {}, + notificationAsync: () => {}, + selectionAsync: () => {}, + ImpactFeedbackStyle: { Light: 'light', Medium: 'medium', Heavy: 'heavy' }, + NotificationFeedbackType: { + Success: 'success', + Warning: 'warning', + Error: 'error', + }, +} diff --git a/packages/app/mocks/expo-splash-screen.web.js b/packages/app/mocks/expo-splash-screen.web.js new file mode 100644 index 0000000..121114a --- /dev/null +++ b/packages/app/mocks/expo-splash-screen.web.js @@ -0,0 +1,4 @@ +module.exports = { + preventAutoHideAsync: () => Promise.resolve(), + hideAsync: () => Promise.resolve(), +} diff --git a/packages/app/mocks/react-native-screens.web.js b/packages/app/mocks/react-native-screens.web.js new file mode 100644 index 0000000..7aede9b --- /dev/null +++ b/packages/app/mocks/react-native-screens.web.js @@ -0,0 +1,4 @@ +module.exports = { + enableScreens: () => {}, + enableFreeze: () => {}, +} diff --git a/packages/app/package.json b/packages/app/package.json new file mode 100644 index 0000000..b7832d9 --- /dev/null +++ b/packages/app/package.json @@ -0,0 +1,54 @@ +{ + "name": "@mininas/app", + "version": "0.0.1", + "private": true, + "main": "expo-router/entry", + "scripts": { + "dev": "expo start", + "dev:web": "expo start --web --port 4321", + "ios": "expo run:ios", + "android": "expo run:android", + "build": "expo export --platform web", + "build:web": "expo export --platform web" + }, + "dependencies": { + "expo": "~53.0.0", + "expo-router": "~5.1.0", + "expo-constants": "~17.1.0", + "expo-linking": "~7.1.0", + "expo-status-bar": "~2.2.0", + "expo-splash-screen": "~0.30.0", + "expo-clipboard": "~7.1.0", + "expo-document-picker": "~13.1.0", + "expo-file-system": "~18.1.0", + "expo-sharing": "~13.1.0", + "expo-haptics": "~14.1.0", + "expo-image": "~2.4.0", + "expo-build-properties": "~0.14.0", + "expo-font": "~13.3.0", + "react": "19.0.0", + "react-dom": "19.0.0", + "react-native": "0.79.6", + "react-native-web": "~0.20.0", + "react-native-safe-area-context": "5.4.0", + "react-native-screens": "~4.11.0", + "react-native-gesture-handler": "~2.24.0", + "react-native-reanimated": "~3.17.0", + "@react-navigation/native": "^7.0.0", + "@tanstack/react-query": "^5.66.0", + "@simplewebauthn/browser": "^13.1.0", + "tus-js-client": "^4.3.0", + "lucide-react-native": "^0.474.0", + "react-native-svg": "15.12.1", + "tamagui": "2.0.0-rc.17", + "@tamagui/animations-css": "2.0.0-rc.17", + "@tamagui/animations-react-native": "2.0.0-rc.17", + "@tamagui/config": "2.0.0-rc.17" + }, + "devDependencies": { + "@babel/core": "^7.26.0", + "@types/react": "~19.0.0", + "@types/react-dom": "~19.0.0", + "typescript": "^5.7.0" + } +} diff --git a/packages/app/src/app/_layout.tsx b/packages/app/src/app/_layout.tsx new file mode 100644 index 0000000..7b6bc89 --- /dev/null +++ b/packages/app/src/app/_layout.tsx @@ -0,0 +1,21 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { Stack } from 'expo-router' +import { StatusBar } from 'expo-status-bar' +import { SafeAreaProvider } from 'react-native-safe-area-context' + +const queryClient = new QueryClient({ + defaultOptions: { + queries: { staleTime: 30_000, retry: 1 }, + }, +}) + +export default function RootLayout() { + return ( + + + + + + + ) +} diff --git a/packages/app/src/app/admin.tsx b/packages/app/src/app/admin.tsx new file mode 100644 index 0000000..8f616a1 --- /dev/null +++ b/packages/app/src/app/admin.tsx @@ -0,0 +1,522 @@ +import { useRouter } from 'expo-router' +import { + ArrowLeft, + Check, + ChevronDown, + ChevronRight, + Eye, + EyeOff, + HardDrive, + KeyRound, + Loader2, + Mail, + Plus, + Shield, + Trash2, + UserPlus, + Users, +} from 'lucide-react-native' +import { useState } from 'react' +import { + ActivityIndicator, + Alert, + Pressable, + ScrollView, + StyleSheet, + Text, + TextInput, + View, +} from 'react-native' +import UpdateSection from '@/components/UpdateSection' +import Badge from '@/components/ui/Badge' +import Tabs from '@/components/ui/Tabs' +import { + useAddVolume, + useAdminInvites, + useAdminUsers, + useAdminVolumes, + useAvailableVolumes, + useCreateInvite, + useDeleteInvite, + useDeleteUser, + useGrantVolumeAccess, + useRemoveVolume, + useResetPasskeys, + useRevokeVolumeAccess, + useSetVolumeVisibility, + useVolumeAccess, +} from '@/hooks/useAdmin' +import { useAuth } from '@/hooks/useAuth' +import type { AdminVolume } from '@/lib/api' +import { APP_NAME } from '@/lib/config' +import { formatDate } from '@/lib/format' +import { Colors, Outlines, Typography } from '@/theme' + +// --- Volume Access --- +function VolumeAccessPanel({ + volumeId, + allUsers, +}: { + volumeId: string + allUsers: { id: string; username: string; role?: string }[] +}) { + const { data, isLoading } = useVolumeAccess(volumeId) + const grantMutation = useGrantVolumeAccess() + const revokeMutation = useRevokeVolumeAccess() + const [selectedUserId, setSelectedUserId] = useState('') + + const accessUserIds = new Set(data?.users?.map((u) => u.id) || []) + const nonAdminUsers = allUsers.filter((u) => u.role !== 'admin') + const availableUsers = nonAdminUsers.filter((u) => !accessUserIds.has(u.id)) + + return ( + + Access List + {isLoading ? ( + + ) : !data?.users?.length ? ( + No users have explicit access. + ) : ( + data.users.map((u) => ( + + {u.username} + revokeMutation.mutate({ volumeId, userId: u.id })}> + + + + )) + )} + + ) +} + +// --- Volumes --- +function VolumesSection() { + const { data, isLoading } = useAdminVolumes() + const removeMutation = useRemoveVolume() + const visibilityMutation = useSetVolumeVisibility() + const { data: usersData } = useAdminUsers() + const [expandedVolume, setExpandedVolume] = useState(null) + + const handleRemove = (vol: AdminVolume) => { + Alert.alert('Remove Volume', `Remove "${vol.label}"? Files on disk won't be deleted.`, [ + { text: 'Cancel', style: 'cancel' }, + { text: 'Remove', style: 'destructive', onPress: () => removeMutation.mutate(vol.id) }, + ]) + } + + const toggleVisibility = (vol: AdminVolume) => { + const next = vol.visibility === 'public' ? 'private' : 'public' + visibilityMutation.mutate({ id: vol.id, visibility: next }) + } + + return ( + + + + + Volumes + + + + {isLoading ? ( + + ) : !data?.volumes?.length ? ( + No volumes configured. + ) : ( + data.volumes.map((vol) => ( + + + setExpandedVolume(expandedVolume === vol.id ? null : vol.id)} + > + {expandedVolume === vol.id ? ( + + ) : ( + + )} + + + {vol.label} + + {vol.id} · {vol.path} + + + toggleVisibility(vol)} + style={[ + styles.visBadge, + vol.visibility === 'public' ? styles.visBadgePublic : styles.visBadgePrivate, + ]} + > + {vol.visibility === 'public' ? ( + + ) : ( + + )} + + {vol.visibility} + + + handleRemove(vol)} style={styles.deleteBtn}> + + + + {expandedVolume === vol.id && vol.visibility === 'private' && ( + ({ + id: u.id, + username: u.username, + role: u.role, + }))} + /> + )} + {expandedVolume === vol.id && vol.visibility === 'public' && ( + + Public volumes are accessible to all users. + + )} + + )) + )} + + ) +} + +// --- Users --- +function UsersSection() { + const { data, isLoading } = useAdminUsers() + const deleteMutation = useDeleteUser() + const resetMutation = useResetPasskeys() + + const handleDelete = (user: { id: string; username: string }) => { + Alert.alert('Delete User', `Delete "${user.username}"? This cannot be undone.`, [ + { text: 'Cancel', style: 'cancel' }, + { text: 'Delete', style: 'destructive', onPress: () => deleteMutation.mutate(user.id) }, + ]) + } + + const handleResetPasskeys = (user: { id: string; username: string }) => { + Alert.alert('Reset Passkeys', `Reset all passkeys for "${user.username}"?`, [ + { text: 'Cancel', style: 'cancel' }, + { text: 'Reset', onPress: () => resetMutation.mutate(user.id) }, + ]) + } + + return ( + + + + + Users + + + + {isLoading ? ( + + ) : !data?.users?.length ? ( + No users found. + ) : ( + data.users.map((user) => ( + + + + {user.username} + {user.role === 'admin' && admin} + + Created {formatDate(user.created_at)} + + handleResetPasskeys(user)} style={styles.resetBtn}> + + Reset Passkeys + + handleDelete(user)} + disabled={user.role === 'admin'} + style={[styles.deleteBtn, user.role === 'admin' && { opacity: 0.3 }]} + > + + + + )) + )} + + ) +} + +// --- Invites --- +function InvitesSection() { + const { data, isLoading } = useAdminInvites() + const createMutation = useCreateInvite() + const deleteMutation = useDeleteInvite() + const [username, setUsername] = useState('') + + const handleCreate = async () => { + if (!username.trim()) return + await createMutation.mutateAsync({ username: username.trim(), expiresInHours: 24 }) + setUsername('') + } + + const handleDelete = (id: string) => { + Alert.alert('Delete Invite', 'Delete this invite?', [ + { text: 'Cancel', style: 'cancel' }, + { text: 'Delete', style: 'destructive', onPress: () => deleteMutation.mutate(id) }, + ]) + } + + const getStatus = (invite: { used_at: string | null; expires_at: string }) => { + if (invite.used_at) return 'used' + if (new Date(invite.expires_at) < new Date()) return 'expired' + return 'pending' + } + + return ( + + + + + Invites + + + + + + + {createMutation.isPending ? ( + + ) : ( + + )} + Create + + + + {isLoading ? ( + + ) : !data?.invites?.length ? ( + No invites yet. + ) : ( + data.invites.map((invite) => { + const status = getStatus(invite) + const variantMap = { pending: 'info', used: 'success', expired: 'default' } as const + return ( + + + + {invite.username} + {status} + + Expires {formatDate(invite.expires_at)} + + handleDelete(invite.id)} style={styles.deleteBtn}> + + + + ) + }) + )} + + ) +} + +// --- Main Admin Screen --- +const adminTabs = [ + { id: 'storage', label: 'Storage' }, + { id: 'users', label: 'Users' }, + { id: 'system', label: 'System' }, +] + +export default function AdminScreen() { + const router = useRouter() + const { isAuthenticated, isLoading: authLoading, user } = useAuth() + const [activeTab, setActiveTab] = useState('storage') + + if (authLoading) { + return ( + + + + ) + } + + if (!isAuthenticated || user?.role !== 'admin') { + router.replace('/') + return null + } + + return ( + + + router.back()} style={styles.backBtn}> + + + + Admin + + + + + + {activeTab === 'storage' && } + {activeTab === 'users' && ( + <> + + + + )} + {activeTab === 'system' && } + + + ) +} + +const styles = StyleSheet.create({ + screen: { flex: 1, backgroundColor: Colors.BackgroundColor.primary }, + screenContent: { + maxWidth: 720, + alignSelf: 'center', + width: '100%', + padding: 16, + paddingBottom: 40, + }, + screenHeader: { flexDirection: 'row', alignItems: 'center', gap: 10, marginBottom: 24 }, + backBtn: { padding: 6, borderRadius: Outlines.borderRadius.md }, + screenTitle: { fontSize: 20, fontWeight: '600', color: Colors.TextColor.primary }, + centered: { flex: 1, alignItems: 'center', justifyContent: 'center' }, + tabContent: { marginTop: 24, gap: 24 }, + card: { + backgroundColor: '#ffffff', + borderWidth: 1, + borderColor: Colors.BorderColor.primary, + borderRadius: Outlines.borderRadius.lg, + ...Outlines.shadow.sm, + }, + cardHeader: { + paddingHorizontal: 20, + paddingVertical: 12, + borderBottomWidth: 1, + borderBottomColor: Colors.BorderColor.secondary, + }, + cardTitleRow: { flexDirection: 'row', alignItems: 'center', gap: 8 }, + cardTitle: { fontSize: 14, fontWeight: '600', color: Colors.TextColor.primary }, + volumeRow: { + paddingHorizontal: 20, + paddingVertical: 12, + borderBottomWidth: StyleSheet.hairlineWidth, + borderBottomColor: Colors.BorderColor.secondary, + }, + volumeInfo: { flexDirection: 'row', alignItems: 'center', gap: 12 }, + volLabel: { fontSize: 14, fontWeight: '500', color: Colors.TextColor.primary }, + volPath: { + fontSize: 11, + color: Colors.TextColor.tertiary, + fontFamily: Typography.caption.fontFamily, + }, + visBadge: { + flexDirection: 'row', + alignItems: 'center', + gap: 4, + paddingHorizontal: 8, + paddingVertical: 4, + borderRadius: Outlines.borderRadius.md, + borderWidth: 1, + }, + visBadgePublic: { borderColor: '#a7f3d0', backgroundColor: '#ecfdf5' }, + visBadgePrivate: { + borderColor: Colors.BorderColor.primary, + backgroundColor: Colors.BackgroundColor.secondary, + }, + visTextPublic: { fontSize: 11, color: '#047857' }, + visTextPrivate: { fontSize: 11, color: Colors.TextColor.secondary }, + accessPanel: { + marginTop: 12, + paddingLeft: 16, + borderLeftWidth: 2, + borderLeftColor: Colors.BorderColor.secondary, + }, + accessTitle: { + fontSize: 11, + fontWeight: '500', + color: Colors.TextColor.secondary, + marginBottom: 8, + }, + accessRow: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + paddingVertical: 4, + }, + accessUsername: { fontSize: 13, color: Colors.TextColor.primary }, + userRow: { + flexDirection: 'row', + alignItems: 'center', + paddingHorizontal: 20, + paddingVertical: 12, + borderBottomWidth: StyleSheet.hairlineWidth, + borderBottomColor: Colors.BorderColor.secondary, + }, + userNameRow: { flexDirection: 'row', alignItems: 'center', gap: 8 }, + userName: { fontSize: 14, fontWeight: '500', color: Colors.TextColor.primary }, + userMeta: { fontSize: 11, color: Colors.TextColor.tertiary, marginTop: 2 }, + resetBtn: { + flexDirection: 'row', + alignItems: 'center', + gap: 4, + paddingHorizontal: 8, + paddingVertical: 4, + borderRadius: Outlines.borderRadius.md, + borderWidth: 1, + borderColor: Colors.BorderColor.primary, + marginRight: 8, + }, + resetBtnText: { fontSize: 11, color: Colors.TextColor.secondary }, + deleteBtn: { padding: 6, borderRadius: Outlines.borderRadius.md }, + createForm: { + flexDirection: 'row', + gap: 8, + paddingHorizontal: 20, + paddingVertical: 12, + borderBottomWidth: 1, + borderBottomColor: Colors.BorderColor.secondary, + }, + formInput: { + flex: 1, + backgroundColor: Colors.BackgroundColor.secondary, + borderWidth: 1, + borderColor: Colors.BorderColor.primary, + borderRadius: Outlines.borderRadius.md, + paddingHorizontal: 12, + paddingVertical: 6, + fontSize: 13, + color: Colors.TextColor.primary, + }, + createBtn: { + flexDirection: 'row', + alignItems: 'center', + gap: 6, + backgroundColor: Colors.BrandColor[600], + paddingHorizontal: 12, + paddingVertical: 6, + borderRadius: Outlines.borderRadius.md, + }, + createBtnText: { color: '#ffffff', fontSize: 13, fontWeight: '500' }, + emptyText: { fontSize: 12, color: Colors.TextColor.tertiary }, + emptyCenter: { textAlign: 'center', padding: 32, fontSize: 13, color: Colors.TextColor.tertiary }, +}) diff --git a/packages/app/src/app/index.tsx b/packages/app/src/app/index.tsx new file mode 100644 index 0000000..2d3e3f5 --- /dev/null +++ b/packages/app/src/app/index.tsx @@ -0,0 +1,271 @@ +import { useQuery } from '@tanstack/react-query' +import { useRouter } from 'expo-router' +import { HardDrive, Loader2, LogOut, Settings, Shield } from 'lucide-react-native' +import { useEffect } from 'react' +import { ActivityIndicator, Pressable, ScrollView, StyleSheet, Text, View } from 'react-native' +import { useSafeAreaInsets } from 'react-native-safe-area-context' +import { useAuth } from '@/hooks/useAuth' +import { api, type VolumeInfo } from '@/lib/api' +import { APP_NAME } from '@/lib/config' +import { formatBytes } from '@/lib/format' +import { Colors, Outlines, Sizing } from '@/theme' + +function VolumeTile({ volume }: { volume: VolumeInfo }) { + const router = useRouter() + const usagePercent = volume.totalBytes > 0 ? (volume.usedBytes / volume.totalBytes) * 100 : 0 + const barColor = + usagePercent > 90 + ? Colors.StatusColor.error + : usagePercent > 75 + ? Colors.StatusColor.warning + : Colors.BrandColor[500] + + return ( + router.push(`/volumes/${encodeURIComponent(volume.id)}` as any)} + style={styles.volumeTile} + > + + + + + {volume.label} + + + + + + + {formatBytes(volume.usedBytes)} used of {formatBytes(volume.totalBytes)} + + + + ) +} + +export default function HomeScreen() { + const { isAuthenticated, isLoading: authLoading, user, logout } = useAuth() + const router = useRouter() + const insets = useSafeAreaInsets() + + const { data, isLoading } = useQuery({ + queryKey: ['volumes'], + queryFn: () => api.getVolumes(), + enabled: isAuthenticated, + }) + + useEffect(() => { + if (!authLoading && !isAuthenticated) { + router.replace('/login') + } + }, [authLoading, isAuthenticated, router]) + + const volumes = data?.volumes || [] + + // Single volume — redirect straight into it + useEffect(() => { + if (!isLoading && volumes.length === 1) { + router.replace(`/volumes/${encodeURIComponent(volumes[0].id)}` as any) + } + }, [isLoading, volumes, router]) + + if (authLoading) { + return ( + + + + ) + } + + if (!isAuthenticated) return null + + return ( + + {/* Header */} + + {APP_NAME} + + {user?.role === 'admin' && ( + router.push('/admin')} style={styles.iconButton}> + + + )} + router.push('/settings')} style={styles.iconButton}> + + + + + + + + + {/* Content */} + {isLoading ? ( + + {[0, 1, 2].map((i) => ( + + + + + + + + + ))} + + ) : volumes.length === 0 ? ( + + + No volumes available + {user?.role === 'admin' && ( + Add volumes in the admin panel + )} + + ) : ( + <> + VOLUMES + + {volumes.map((v) => ( + + ))} + + + )} + + ) +} + +const styles = StyleSheet.create({ + container: { + flex: 1, + backgroundColor: Colors.BackgroundColor.secondary, + }, + content: { + paddingHorizontal: Sizing.gutters.base, + paddingVertical: Sizing.layout.x24, + }, + centered: { + flex: 1, + alignItems: 'center', + justifyContent: 'center', + }, + header: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + marginBottom: Sizing.layout.x40, + }, + appTitle: { + fontSize: 20, + fontWeight: '600', + color: Colors.TextColor.primary, + }, + headerActions: { + flexDirection: 'row', + alignItems: 'center', + gap: Sizing.layout.x8, + }, + iconButton: { + width: 44, + height: 44, + alignItems: 'center', + justifyContent: 'center', + borderRadius: Outlines.borderRadius.md, + }, + sectionTitle: { + fontSize: 12, + fontWeight: '500', + color: Colors.TextColor.secondary, + letterSpacing: 1, + marginBottom: Sizing.layout.x16, + }, + volumeGrid: { + gap: Sizing.layout.x16, + }, + volumeTile: { + backgroundColor: Colors.BackgroundColor.primary, + borderRadius: Outlines.borderRadius.xl, + borderWidth: Outlines.borderWidth.normal, + borderColor: Colors.BorderColor.primary, + padding: Sizing.layout.x20, + gap: Sizing.layout.x12, + ...Outlines.shadow.sm, + }, + volumeTileHeader: { + flexDirection: 'row', + alignItems: 'center', + gap: Sizing.layout.x12, + }, + volumeIcon: { + width: 40, + height: 40, + borderRadius: Outlines.borderRadius.lg, + backgroundColor: Colors.BrandColor[50], + alignItems: 'center', + justifyContent: 'center', + }, + volumeLabel: { + fontSize: 18, + fontWeight: '600', + color: Colors.TextColor.primary, + }, + usageBarBg: { + height: 8, + borderRadius: 4, + backgroundColor: Colors.BackgroundColor.tertiary, + overflow: 'hidden', + }, + usageBarFill: { + height: 8, + borderRadius: 4, + }, + usageText: { + fontSize: 14, + color: Colors.TextColor.secondary, + marginTop: 6, + }, + empty: { + alignItems: 'center', + justifyContent: 'center', + paddingVertical: 80, + }, + emptyTitle: { + fontSize: 16, + fontWeight: '500', + color: Colors.TextColor.secondary, + marginTop: 12, + }, + emptySubtitle: { + fontSize: 14, + color: Colors.TextColor.tertiary, + marginTop: 4, + }, + loadingGrid: { + gap: Sizing.layout.x16, + }, + skeletonTile: { + backgroundColor: Colors.BackgroundColor.primary, + borderRadius: Outlines.borderRadius.xl, + borderWidth: Outlines.borderWidth.normal, + borderColor: Colors.BorderColor.primary, + padding: Sizing.layout.x20, + gap: Sizing.layout.x12, + }, + skeletonRow: { + flexDirection: 'row', + alignItems: 'center', + gap: Sizing.layout.x12, + }, + skeletonBox: { + backgroundColor: Colors.BorderColor.primary, + borderRadius: Outlines.borderRadius.md, + }, +}) diff --git a/packages/app/src/app/login.tsx b/packages/app/src/app/login.tsx new file mode 100644 index 0000000..514ecf5 --- /dev/null +++ b/packages/app/src/app/login.tsx @@ -0,0 +1,121 @@ +import { useRouter } from 'expo-router' +import { Fingerprint, Loader2 } from 'lucide-react-native' +import { useState } from 'react' +import { ActivityIndicator, Pressable, StyleSheet, Text, View } from 'react-native' +import { useSafeAreaInsets } from 'react-native-safe-area-context' +import { APP_NAME } from '@/lib/config' +import { authenticatePasskey } from '@/lib/passkeys' +import { Colors, Outlines, Sizing } from '@/theme' + +export default function LoginScreen() { + const [status, setStatus] = useState<'idle' | 'loading' | 'error'>('idle') + const [error, setError] = useState('') + const router = useRouter() + const insets = useSafeAreaInsets() + + const handleLogin = async () => { + setStatus('loading') + setError('') + try { + const verified = await authenticatePasskey() + if (verified) { + router.replace('/') + } else { + setStatus('error') + setError('Authentication was not verified') + } + } catch (err) { + setStatus('error') + setError(err instanceof Error ? err.message : 'Authentication failed') + } + } + + return ( + + + + {APP_NAME} + Sign in with your passkey + + + + + {status === 'loading' ? ( + + ) : ( + + )} + + {status === 'loading' ? 'Waiting for device...' : 'Sign In'} + + + + {error ? {error} : null} + + + + ) +} + +const styles = StyleSheet.create({ + container: { + flex: 1, + backgroundColor: Colors.BackgroundColor.secondary, + alignItems: 'center', + justifyContent: 'center', + paddingHorizontal: Sizing.gutters.base, + }, + inner: { + maxWidth: 400, + width: '100%', + }, + heading: { + alignItems: 'center', + marginBottom: 32, + }, + title: { + fontSize: 24, + fontWeight: '700', + color: Colors.TextColor.primary, + marginBottom: 8, + }, + subtitle: { + fontSize: 16, + color: Colors.TextColor.secondary, + }, + card: { + backgroundColor: Colors.BackgroundColor.primary, + borderWidth: Outlines.borderWidth.normal, + borderColor: Colors.BorderColor.primary, + borderRadius: Outlines.borderRadius.lg, + padding: 24, + ...Outlines.shadow.sm, + }, + loginButton: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'center', + gap: 12, + paddingVertical: 14, + backgroundColor: Colors.BrandColor[600], + borderRadius: Outlines.borderRadius.lg, + }, + loginButtonDisabled: { + opacity: 0.5, + }, + loginButtonText: { + color: '#ffffff', + fontSize: 16, + fontWeight: '500', + }, + error: { + marginTop: 12, + fontSize: 14, + color: Colors.StatusColor.error, + textAlign: 'center', + }, +}) diff --git a/packages/app/src/app/settings.tsx b/packages/app/src/app/settings.tsx new file mode 100644 index 0000000..a624a72 --- /dev/null +++ b/packages/app/src/app/settings.tsx @@ -0,0 +1,253 @@ +import * as Clipboard from 'expo-clipboard' +import { useRouter } from 'expo-router' +import { ArrowLeft, Check, Copy, HardDrive, Key, Plus, Trash2 } from 'lucide-react-native' +import { useState } from 'react' +import { + ActivityIndicator, + Alert, + Platform, + Pressable, + ScrollView, + StyleSheet, + Text, + TextInput, + View, +} from 'react-native' +import Tabs from '@/components/ui/Tabs' +import { useAuth } from '@/hooks/useAuth' +import { + useCreateWebDAVToken, + useRevokeWebDAVToken, + useWebDAVTokens, +} from '@/hooks/useWebDAVTokens' +import { getApiBase } from '@/lib/api' +import { APP_NAME } from '@/lib/config' +import { formatDate } from '@/lib/format' +import { Colors, Outlines, Typography } from '@/theme' + +function AccessTokens() { + const { data, isLoading } = useWebDAVTokens() + const createMutation = useCreateWebDAVToken() + const revokeMutation = useRevokeWebDAVToken() + const [label, setLabel] = useState('') + const [newToken, setNewToken] = useState(null) + const [copied, setCopied] = useState(false) + + const handleCreate = async () => { + if (!label.trim()) return + const result = await createMutation.mutateAsync(label.trim()) + setNewToken(result.token) + setLabel('') + } + + const handleCopy = async (text: string) => { + await Clipboard.setStringAsync(text) + setCopied(true) + setTimeout(() => setCopied(false), 2000) + } + + const handleRevoke = (id: string) => { + Alert.alert('Revoke Token', 'Revoke this token? Any clients using it will be disconnected.', [ + { text: 'Cancel', style: 'cancel' }, + { text: 'Revoke', style: 'destructive', onPress: () => revokeMutation.mutate(id) }, + ]) + } + + return ( + + {/* Create Token */} + + Create Access Token + + + + {createMutation.isPending ? ( + + ) : ( + + )} + Create + + + + {newToken && ( + + + Token created! Copy it now — it won't be shown again. + + + + {newToken} + + handleCopy(newToken)} style={styles.copyBtn}> + {copied ? : } + + + setNewToken(null)}> + Dismiss + + + )} + + + {/* Token List */} + + Active Tokens + {isLoading ? ( + + ) : !data?.tokens.length ? ( + No tokens yet. Create one to connect via WebDAV. + ) : ( + data.tokens.map((token) => ( + + + + {token.label} + + Created {formatDate(token.created_at)} + {token.last_used_at ? ` · Last used ${formatDate(token.last_used_at)}` : ''} + + + handleRevoke(token.id)} style={styles.deleteBtn}> + + + + )) + )} + + + ) +} + +export default function SettingsScreen() { + const router = useRouter() + const { isAuthenticated, isLoading: authLoading, user } = useAuth() + + if (authLoading) { + return ( + + + + ) + } + + if (!isAuthenticated) { + router.replace('/login') + return null + } + + return ( + + + router.back()} style={styles.backBtn}> + + + + Network Drive Access + + + + + ) +} + +const styles = StyleSheet.create({ + screen: { flex: 1, backgroundColor: Colors.BackgroundColor.primary }, + screenContent: { + maxWidth: 640, + alignSelf: 'center', + width: '100%', + padding: 16, + paddingBottom: 40, + }, + screenHeader: { flexDirection: 'row', alignItems: 'center', gap: 10, marginBottom: 24 }, + backBtn: { padding: 6, borderRadius: Outlines.borderRadius.md }, + screenTitle: { fontSize: 20, fontWeight: '600', color: Colors.TextColor.primary }, + centered: { flex: 1, alignItems: 'center', justifyContent: 'center' }, + section: { gap: 16 }, + card: { + backgroundColor: '#ffffff', + borderWidth: 1, + borderColor: Colors.BorderColor.primary, + borderRadius: Outlines.borderRadius.lg, + padding: 20, + ...Outlines.shadow.sm, + }, + cardTitle: { fontSize: 14, fontWeight: '600', color: Colors.TextColor.primary, marginBottom: 12 }, + createRow: { flexDirection: 'row', gap: 8 }, + input: { + flex: 1, + backgroundColor: Colors.BackgroundColor.secondary, + borderWidth: 1, + borderColor: Colors.BorderColor.primary, + borderRadius: Outlines.borderRadius.md, + paddingHorizontal: 12, + paddingVertical: 6, + fontSize: 13, + color: Colors.TextColor.primary, + }, + createBtn: { + flexDirection: 'row', + alignItems: 'center', + gap: 6, + backgroundColor: Colors.BrandColor[600], + paddingHorizontal: 12, + paddingVertical: 6, + borderRadius: Outlines.borderRadius.md, + }, + createBtnText: { color: '#ffffff', fontSize: 13, fontWeight: '500' }, + tokenCreated: { + marginTop: 16, + backgroundColor: '#ecfdf5', + borderWidth: 1, + borderColor: '#a7f3d0', + borderRadius: Outlines.borderRadius.lg, + padding: 16, + }, + tokenCreatedTitle: { fontSize: 13, fontWeight: '500', color: '#065f46', marginBottom: 8 }, + tokenRow: { flexDirection: 'row', alignItems: 'center', gap: 8 }, + tokenValue: { + flex: 1, + fontFamily: Typography.caption.fontFamily, + fontSize: 12, + color: '#064e3b', + backgroundColor: '#ffffff', + borderWidth: 1, + borderColor: '#a7f3d0', + borderRadius: Outlines.borderRadius.sm, + paddingHorizontal: 12, + paddingVertical: 6, + }, + copyBtn: { padding: 6, borderRadius: Outlines.borderRadius.md }, + dismissText: { fontSize: 11, color: '#047857', marginTop: 8 }, + tokenItem: { + flexDirection: 'row', + alignItems: 'center', + gap: 12, + paddingVertical: 12, + borderTopWidth: StyleSheet.hairlineWidth, + borderTopColor: Colors.BorderColor.secondary, + }, + tokenLabel: { fontSize: 13, fontWeight: '500', color: Colors.TextColor.primary }, + tokenMeta: { fontSize: 11, color: Colors.TextColor.tertiary, marginTop: 2 }, + deleteBtn: { padding: 6, borderRadius: Outlines.borderRadius.md }, + emptyText: { textAlign: 'center', padding: 32, fontSize: 13, color: Colors.TextColor.tertiary }, +}) diff --git a/packages/app/src/app/setup.tsx b/packages/app/src/app/setup.tsx new file mode 100644 index 0000000..73ca369 --- /dev/null +++ b/packages/app/src/app/setup.tsx @@ -0,0 +1,200 @@ +import { useRouter } from 'expo-router' +import { CheckCircle, Fingerprint, ShieldX } from 'lucide-react-native' +import { useEffect, useState } from 'react' +import { ActivityIndicator, Pressable, StyleSheet, Text, View } from 'react-native' +import { useSafeAreaInsets } from 'react-native-safe-area-context' +import { APP_NAME } from '@/lib/config' +import { checkSetupNeeded, registerPasskey } from '@/lib/passkeys' +import { Colors, Outlines, Sizing } from '@/theme' + +export default function SetupScreen() { + const [status, setStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle') + const [error, setError] = useState('') + const [setupDisabled, setSetupDisabled] = useState(false) + const [checking, setChecking] = useState(true) + const router = useRouter() + const insets = useSafeAreaInsets() + + useEffect(() => { + checkSetupNeeded().then((needed) => { + if (!needed) setSetupDisabled(true) + setChecking(false) + }) + }, []) + + const handleRegister = async () => { + setStatus('loading') + setError('') + try { + const verified = await registerPasskey() + if (verified) { + setStatus('success') + setTimeout(() => router.replace('/'), 1000) + } else { + setStatus('error') + setError('Registration was not verified') + } + } catch (err) { + setStatus('error') + setError(err instanceof Error ? err.message : 'Registration failed') + } + } + + if (checking) { + return ( + + + + ) + } + + if (setupDisabled) { + return ( + + + + Setup Unavailable + An admin account has already been configured. + + + + + + If you need to log in, go to the login page. + router.replace('/login')} style={styles.linkButton}> + Go to Login + + + + + ) + } + + return ( + + + + Welcome to {APP_NAME} + + Set up your passkey to secure your NAS. This will use your device's biometric + authentication. + + + + + {status === 'success' ? ( + + + Passkey registered! + Redirecting... + + ) : ( + <> + + {status === 'loading' ? ( + + ) : ( + + )} + + {status === 'loading' ? 'Waiting for device...' : 'Register Passkey'} + + + {error ? {error} : null} + + )} + + + + ) +} + +const styles = StyleSheet.create({ + centered: { + flex: 1, + backgroundColor: Colors.BackgroundColor.secondary, + alignItems: 'center', + justifyContent: 'center', + paddingHorizontal: Sizing.gutters.base, + }, + inner: { + maxWidth: 400, + width: '100%', + }, + heading: { + alignItems: 'center', + marginBottom: 32, + }, + title: { + fontSize: 24, + fontWeight: '700', + color: Colors.TextColor.primary, + marginBottom: 8, + textAlign: 'center', + }, + subtitle: { + fontSize: 16, + color: Colors.TextColor.secondary, + textAlign: 'center', + }, + card: { + backgroundColor: Colors.BackgroundColor.primary, + borderWidth: Outlines.borderWidth.normal, + borderColor: Colors.BorderColor.primary, + borderRadius: Outlines.borderRadius.lg, + padding: 24, + ...Outlines.shadow.sm, + }, + iconCenter: { + alignItems: 'center', + paddingVertical: 16, + }, + successTitle: { + fontSize: 18, + fontWeight: '500', + color: Colors.TextColor.primary, + marginTop: 12, + }, + helperText: { + fontSize: 14, + color: Colors.TextColor.tertiary, + textAlign: 'center', + marginTop: 8, + }, + primaryButton: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'center', + gap: 12, + paddingVertical: 14, + backgroundColor: Colors.BrandColor[600], + borderRadius: Outlines.borderRadius.lg, + }, + primaryButtonText: { + color: '#ffffff', + fontSize: 16, + fontWeight: '500', + }, + disabled: { + opacity: 0.5, + }, + error: { + marginTop: 12, + fontSize: 14, + color: Colors.StatusColor.error, + textAlign: 'center', + }, + linkButton: { + alignItems: 'center', + marginTop: 16, + }, + linkText: { + fontSize: 14, + fontWeight: '500', + color: Colors.BrandColor[600], + }, +}) diff --git a/packages/app/src/app/volumes/[...path].tsx b/packages/app/src/app/volumes/[...path].tsx new file mode 100644 index 0000000..190a5b4 --- /dev/null +++ b/packages/app/src/app/volumes/[...path].tsx @@ -0,0 +1,512 @@ +import { useLocalSearchParams, useRouter } from 'expo-router' +import { + Download, + FolderPlus, + HardDrive, + LayoutGrid, + List, + LogOut, + RefreshCw, + Settings, + Shield, + Trash2, + Upload, + UploadCloud, + X, +} from 'lucide-react-native' +import { useCallback, useEffect, useMemo, useState } from 'react' +import { + ActivityIndicator, + Platform, + Pressable, + ScrollView, + StyleSheet, + Text, + View, +} from 'react-native' +import { useSafeAreaInsets } from 'react-native-safe-area-context' +import Breadcrumbs from '@/components/Breadcrumbs' +import FileGrid from '@/components/FileGrid' +import FileList from '@/components/FileList' +import PreviewModal from '@/components/PreviewModal' +import SearchBar from '@/components/SearchBar' +import ShareDialog from '@/components/ShareDialog' +import UploadProgress from '@/components/UploadProgress' +import UploadZone from '@/components/UploadZone' +import EmptyState from '@/components/ui/EmptyState' +import { FileGridSkeleton, FileListSkeleton } from '@/components/ui/Skeleton' +import ToastContainer from '@/components/ui/Toast' +import VolumeSelector from '@/components/VolumeSelector' +import { useAuth } from '@/hooks/useAuth' +import { useCreateDirectory, useDeleteFile, useFiles } from '@/hooks/useFiles' +import { useSelection } from '@/hooks/useSelection' +import { useToast } from '@/hooks/useToast' +import { useUpload } from '@/hooks/useUpload' +import type { FileEntry } from '@/lib/api' +import { api } from '@/lib/api' +import { APP_NAME } from '@/lib/config' +import { Colors, Outlines, Sizing } from '@/theme' + +function parseParams(params: Record): { + volume: string + path: string +} { + const pathSegments = params.path + if (!pathSegments) return { volume: '', path: '' } + + const segments = Array.isArray(pathSegments) ? pathSegments : [pathSegments] + const volume = decodeURIComponent(segments[0] || '') + const filePath = segments.slice(1).map(decodeURIComponent).join('/') + return { volume, path: filePath } +} + +export default function FileBrowserScreen() { + const params = useLocalSearchParams() + const router = useRouter() + const insets = useSafeAreaInsets() + const { isAuthenticated, isLoading: authLoading, user, logout } = useAuth() + + const { volume, path: currentPath } = useMemo( + () => parseParams(params as Record), + [params], + ) + + const { data, isLoading, error, refetch } = useFiles(volume, currentPath) + const { toasts, addToast, removeToast } = useToast() + const deleteMutation = useDeleteFile(volume, currentPath) + const mkdirMutation = useCreateDirectory(volume, currentPath) + const { uploads, addFiles, pauseUpload, resumeUpload, cancelUpload, clearCompleted } = useUpload( + volume, + currentPath, + refetch, + ) + const [showUploadZone, setShowUploadZone] = useState(false) + const [previewFile, setPreviewFile] = useState(null) + const [shareFile, setShareFile] = useState(null) + const [viewMode, setViewMode] = useState<'list' | 'grid'>('list') + const [refreshSpinning, setRefreshSpinning] = useState(false) + const { + selected, + toggle: toggleSelection, + selectRange, + selectAll, + clear: clearSelection, + count: selectionCount, + lastToggled, + } = useSelection() + + useEffect(() => { + if (!authLoading && !isAuthenticated) { + router.replace('/login') + } + }, [authLoading, isAuthenticated, router]) + + const navigateTo = useCallback( + (newPath: string) => { + setPreviewFile(null) + clearSelection() + const segments = newPath + ? `${encodeURIComponent(volume)}/${newPath.split('/').map(encodeURIComponent).join('/')}` + : encodeURIComponent(volume) + router.push(`/volumes/${segments}` as any) + }, + [volume, clearSelection, router], + ) + + const handleVolumeSelect = useCallback( + (id: string) => { + setPreviewFile(null) + router.replace(`/volumes/${encodeURIComponent(id)}` as any) + }, + [router], + ) + + const handleRename = useCallback( + (file: FileEntry) => { + // On web, use prompt. On native, this would need a modal input. + if (Platform.OS === 'web') { + const newName = window.prompt('Rename to:', file.name) + if (newName && newName !== file.name) { + const parentPath = file.path.includes('/') + ? file.path.split('/').slice(0, -1).join('/') + : '' + const destination = parentPath ? `${parentPath}/${newName}` : newName + api.moveFile(volume, file.path, destination).then( + () => { + addToast('success', `Renamed to "${newName}"`) + refetch() + }, + (err) => addToast('error', `Rename failed: ${(err as Error).message}`), + ) + } + } + }, + [volume, addToast, refetch], + ) + + const handleNewFolder = useCallback(() => { + if (Platform.OS === 'web') { + const name = window.prompt('New folder name:') + if (name) { + mkdirMutation.mutate(name, { + onSuccess: () => addToast('success', `Created folder "${name}"`), + onError: (err) => addToast('error', `Failed to create folder: ${(err as Error).message}`), + }) + } + } + }, [mkdirMutation, addToast]) + + const pathParts = currentPath.split('/').filter(Boolean) + const breadcrumbs = pathParts.map((part, i) => ({ + label: part, + path: pathParts.slice(0, i + 1).join('/'), + })) + + if (authLoading) { + return ( + + + + ) + } + + if (!isAuthenticated) return null + + return ( + + 0 && { paddingBottom: 80 }]} + > + {/* Header */} + + router.push('/')} style={styles.logoArea}> + {APP_NAME} + + + + {user?.role === 'admin' && ( + router.push('/admin')} style={styles.iconButton}> + + + )} + router.push('/settings')} style={styles.iconButton}> + + + + + + + + + {/* Search */} + {volume ? ( + + + + ) : null} + + {/* Toolbar */} + + + + {volume ? ( + setShowUploadZone(!showUploadZone)} + style={[styles.toolbarButton, showUploadZone && styles.toolbarButtonActive]} + > + + + ) : null} + + + + + setViewMode('list')} + style={[styles.viewToggleBtn, viewMode === 'list' && styles.viewToggleBtnActive]} + > + + + setViewMode('grid')} + style={[styles.viewToggleBtn, viewMode === 'grid' && styles.viewToggleBtnActive]} + > + + + + { + setRefreshSpinning(true) + refetch().finally(() => setTimeout(() => setRefreshSpinning(false), 400)) + }} + style={styles.iconButton} + > + + + + + + {/* Upload Zone */} + {showUploadZone && volume ? ( + + { + addFiles(files) + setShowUploadZone(false) + }} + /> + + ) : null} + + {/* Content */} + {!volume ? ( + + ) : isLoading ? ( + viewMode === 'list' ? ( + + ) : ( + + ) + ) : error ? ( + + Error loading files: {(error as Error).message} + + ) : viewMode === 'list' ? ( + + deleteMutation.mutate(path, { + onSuccess: () => addToast('success', 'File deleted'), + onError: (err) => addToast('error', `Delete failed: ${(err as Error).message}`), + }) + } + onPreview={setPreviewFile} + onShare={setShareFile} + selectable + selected={selected} + onToggle={toggleSelection} + onShiftSelect={selectRange} + lastToggled={lastToggled} + onSelectAll={(paths) => (paths.length > 0 ? selectAll(paths) : clearSelection())} + /> + ) : ( + + )} + + + {/* Bulk Action Bar */} + {selectionCount > 0 ? ( + + {selectionCount} selected + + { + const paths = Array.from(selected) + for (const path of paths) { + try { + await api.deleteFile(volume, path) + } catch {} + } + clearSelection() + refetch() + addToast('success', `Deleted ${paths.length} items`) + }} + style={styles.bulkDeleteBtn} + > + + Delete + + + + + + + ) : null} + + {/* Preview Modal */} + {previewFile ? ( + setPreviewFile(null)} /> + ) : null} + + {/* Share Dialog */} + {shareFile ? ( + setShareFile(null)} /> + ) : null} + + {/* Upload Progress */} + + + + + ) +} + +const styles = StyleSheet.create({ + container: { + flex: 1, + backgroundColor: Colors.BackgroundColor.secondary, + }, + scrollView: { + flex: 1, + }, + content: { + paddingHorizontal: Sizing.gutters.base, + paddingVertical: Sizing.layout.x24, + maxWidth: 1152, + width: '100%', + alignSelf: 'center', + }, + centered: { + flex: 1, + alignItems: 'center', + justifyContent: 'center', + }, + header: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + gap: 12, + marginBottom: Sizing.layout.x24, + }, + logoArea: { + flexDirection: 'row', + alignItems: 'center', + gap: 10, + }, + appTitle: { + fontSize: 20, + fontWeight: '600', + color: Colors.TextColor.primary, + }, + headerActions: { + flexDirection: 'row', + alignItems: 'center', + gap: 8, + }, + iconButton: { + width: 44, + height: 44, + alignItems: 'center', + justifyContent: 'center', + borderRadius: Outlines.borderRadius.md, + }, + searchRow: { + marginBottom: Sizing.layout.x16, + }, + toolbar: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + marginBottom: Sizing.layout.x16, + }, + toolbarActions: { + flexDirection: 'row', + alignItems: 'center', + gap: 8, + marginLeft: 16, + }, + toolbarButton: { + flexDirection: 'row', + alignItems: 'center', + gap: 6, + paddingHorizontal: 12, + paddingVertical: 6, + borderRadius: Outlines.borderRadius.md, + borderWidth: Outlines.borderWidth.normal, + borderColor: Colors.BorderColor.primary, + backgroundColor: Colors.BackgroundColor.primary, + }, + toolbarButtonActive: { + backgroundColor: Colors.BrandColor[600], + borderColor: Colors.BrandColor[600], + }, + viewToggle: { + flexDirection: 'row', + borderWidth: Outlines.borderWidth.normal, + borderColor: Colors.BorderColor.primary, + borderRadius: Outlines.borderRadius.md, + backgroundColor: Colors.BackgroundColor.primary, + overflow: 'hidden', + }, + viewToggleBtn: { + padding: 6, + }, + viewToggleBtnActive: { + backgroundColor: Colors.BackgroundColor.tertiary, + }, + uploadZoneContainer: { + marginBottom: Sizing.layout.x16, + }, + errorContainer: { + alignItems: 'center', + paddingVertical: 80, + }, + errorText: { + fontSize: 14, + color: Colors.StatusColor.error, + }, + bulkBar: { + position: 'absolute', + bottom: 0, + left: 0, + right: 0, + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + paddingHorizontal: Sizing.gutters.base, + paddingTop: 12, + backgroundColor: 'rgba(255,255,255,0.95)', + borderTopWidth: Outlines.borderWidth.normal, + borderTopColor: Colors.BorderColor.primary, + ...Outlines.shadow.md, + }, + bulkBarText: { + fontSize: 14, + fontWeight: '500', + color: Colors.BrandColor[700], + }, + bulkBarActions: { + flexDirection: 'row', + alignItems: 'center', + gap: 8, + }, + bulkDeleteBtn: { + flexDirection: 'row', + alignItems: 'center', + gap: 6, + paddingHorizontal: 12, + paddingVertical: 8, + backgroundColor: Colors.StatusColor.error, + borderRadius: Outlines.borderRadius.md, + }, + bulkDeleteText: { + color: '#fff', + fontSize: 14, + fontWeight: '500', + }, +}) diff --git a/packages/app/src/components/Breadcrumbs.tsx b/packages/app/src/components/Breadcrumbs.tsx new file mode 100644 index 0000000..7623a67 --- /dev/null +++ b/packages/app/src/components/Breadcrumbs.tsx @@ -0,0 +1,81 @@ +import { ChevronRight, Home } from 'lucide-react-native' +import { Pressable, ScrollView, StyleSheet, Text, View } from 'react-native' +import { Colors, Typography } from '@/theme' + +interface BreadcrumbSegment { + label: string + path: string +} + +interface BreadcrumbsProps { + segments: BreadcrumbSegment[] + onNavigate: (path: string) => void +} + +export default function Breadcrumbs({ segments, onNavigate }: BreadcrumbsProps) { + return ( + + + onNavigate('')} style={styles.crumb}> + + + + {segments.map((segment, index) => { + const isLast = index === segments.length - 1 + return ( + + + {isLast ? ( + + {segment.label} + + ) : ( + onNavigate(segment.path)} style={styles.crumb}> + + {segment.label} + + + )} + + ) + })} + + + ) +} + +const styles = StyleSheet.create({ + container: { + flexGrow: 0, + }, + inner: { + flexDirection: 'row', + alignItems: 'center', + gap: 4, + }, + segmentRow: { + flexDirection: 'row', + alignItems: 'center', + gap: 4, + }, + crumb: { + paddingHorizontal: 8, + paddingVertical: 4, + borderRadius: 4, + }, + crumbText: { + fontSize: 13, + color: Colors.TextColor.secondary, + fontFamily: Typography.body.fontFamily, + maxWidth: 160, + }, + currentText: { + fontSize: 13, + fontWeight: '600', + color: Colors.TextColor.primary, + fontFamily: Typography.body.fontFamily, + paddingHorizontal: 8, + paddingVertical: 4, + maxWidth: 200, + }, +}) diff --git a/packages/app/src/components/FileGrid.tsx b/packages/app/src/components/FileGrid.tsx new file mode 100644 index 0000000..d093cd4 --- /dev/null +++ b/packages/app/src/components/FileGrid.tsx @@ -0,0 +1,181 @@ +import { Folder } from 'lucide-react-native' +import { useCallback, useState } from 'react' +import { Image, Pressable, StyleSheet, Text, View } from 'react-native' +import EmptyState from '@/components/ui/EmptyState' +import type { FileEntry } from '@/lib/api' +import { api } from '@/lib/api' +import { getFileIcon, hasThumbnailSupport } from '@/lib/fileIcons' +import { formatBytes } from '@/lib/format' +import { Colors, Outlines, Typography } from '@/theme' + +interface FileGridProps { + entries: FileEntry[] + volume: string + onNavigate: (path: string) => void + onPreview?: (file: FileEntry) => void + selectable?: boolean + selected?: Set + onToggle?: (path: string) => void + onShiftSelect?: (paths: string[]) => void + lastToggled?: string | null +} + +function FileGridItem({ + entry, + volume, + onNavigate, + onPreview, + selectable, + isSelected, + onToggle, +}: { + entry: FileEntry + volume: string + onNavigate: (path: string) => void + onPreview?: (file: FileEntry) => void + selectable?: boolean + isSelected?: boolean + onToggle?: (path: string) => void +}) { + const [thumbError, setThumbError] = useState(false) + const showThumb = hasThumbnailSupport(entry) && !thumbError + + const handlePress = () => { + if (entry.isDirectory) { + onNavigate(entry.path) + } else if (onPreview) { + onPreview(entry) + } + } + + const handleLongPress = () => { + onToggle?.(entry.path) + } + + return ( + + {selectable && isSelected && ( + + + ✓ + + + )} + + {showThumb ? ( + setThumbError(true)} + /> + ) : ( + getFileIcon(entry, 32) + )} + + + {entry.name} + + {!entry.isDirectory && {formatBytes(entry.size)}} + + ) +} + +export default function FileGrid({ + entries, + volume, + onNavigate, + onPreview, + selectable, + selected, + onToggle, + onShiftSelect, + lastToggled, +}: FileGridProps) { + if (entries.length === 0) { + return + } + + return ( + + {entries.map((entry) => ( + + ))} + + ) +} + +const styles = StyleSheet.create({ + grid: { + flexDirection: 'row', + flexWrap: 'wrap', + gap: 8, + }, + gridItem: { + width: '31%', + alignItems: 'center', + gap: 6, + padding: 10, + borderRadius: Outlines.borderRadius.lg, + position: 'relative', + }, + gridItemSelected: { + backgroundColor: '#eff6ff', + borderWidth: 2, + borderColor: Colors.BrandColor[200], + }, + checkOverlay: { + position: 'absolute', + top: 4, + left: 4, + zIndex: 10, + }, + checkCircle: { + width: 20, + height: 20, + borderRadius: 10, + backgroundColor: Colors.BrandColor[600], + alignItems: 'center', + justifyContent: 'center', + }, + checkText: { + color: '#ffffff', + fontSize: 12, + fontWeight: '700', + }, + thumbContainer: { + width: 64, + height: 64, + borderRadius: Outlines.borderRadius.lg, + backgroundColor: Colors.BackgroundColor.tertiary, + alignItems: 'center', + justifyContent: 'center', + overflow: 'hidden', + }, + thumbImage: { + width: 64, + height: 64, + }, + itemName: { + fontSize: 12, + color: Colors.TextColor.primary, + textAlign: 'center', + fontFamily: Typography.body.fontFamily, + }, + itemSize: { + fontSize: 11, + color: Colors.TextColor.tertiary, + }, +}) diff --git a/packages/app/src/components/FileList.tsx b/packages/app/src/components/FileList.tsx new file mode 100644 index 0000000..cc70858 --- /dev/null +++ b/packages/app/src/components/FileList.tsx @@ -0,0 +1,287 @@ +import { ArrowDown, ArrowUp, ArrowUpDown, Download, Folder, Trash2 } from 'lucide-react-native' +import { useCallback, useMemo, useState } from 'react' +import { Alert, Image, Pressable, StyleSheet, Text, View } from 'react-native' +import EmptyState from '@/components/ui/EmptyState' +import type { FileEntry } from '@/lib/api' +import { api } from '@/lib/api' +import { getFileIcon, hasThumbnailSupport } from '@/lib/fileIcons' +import { formatBytes, formatDate, formatDateShort } from '@/lib/format' +import { Colors, Outlines, Typography } from '@/theme' + +type SortField = 'name' | 'size' | 'modified' +type SortDir = 'asc' | 'desc' + +interface FileListProps { + entries: FileEntry[] + volume: string + onNavigate: (path: string) => void + onDelete: (path: string) => void + onPreview?: (file: FileEntry) => void + onShare?: (file: FileEntry) => void + selectable?: boolean + selected?: Set + onToggle?: (path: string) => void + onShiftSelect?: (paths: string[]) => void + lastToggled?: string | null + onSelectAll?: (paths: string[]) => void +} + +function FileListRow({ + entry, + volume, + onNavigate, + onDelete, + onPreview, + selectable, + isSelected, + onToggle, +}: { + entry: FileEntry + volume: string + onNavigate: (path: string) => void + onDelete: (path: string) => void + onPreview?: (file: FileEntry) => void + selectable?: boolean + isSelected?: boolean + onToggle?: (path: string) => void +}) { + const [thumbError, setThumbError] = useState(false) + const showThumb = hasThumbnailSupport(entry) && !thumbError + + const handlePress = () => { + if (entry.isDirectory) { + onNavigate(entry.path) + } else if (onPreview) { + onPreview(entry) + } + } + + const handleDelete = () => { + Alert.alert('Delete', `Delete "${entry.name}"?`, [ + { text: 'Cancel', style: 'cancel' }, + { text: 'Delete', style: 'destructive', onPress: () => onDelete(entry.path) }, + ]) + } + + return ( + + {selectable && ( + onToggle?.(entry.path)} style={styles.checkbox} hitSlop={8}> + + {isSelected && ✓} + + + )} + + {showThumb ? ( + setThumbError(true)} + /> + ) : ( + {getFileIcon(entry)} + )} + + + {entry.name} + + + {entry.isDirectory + ? formatDateShort(entry.modifiedAt) + : `${formatBytes(entry.size)} · ${formatDateShort(entry.modifiedAt)}`} + + + + + + + + ) +} + +export default function FileList({ + entries, + volume, + onNavigate, + onDelete, + onPreview, + onShare, + selectable, + selected, + onToggle, + onShiftSelect, + lastToggled, + onSelectAll, +}: FileListProps) { + const [sortField, setSortField] = useState('name') + const [sortDir, setSortDir] = useState('asc') + + const toggleSort = (field: SortField) => { + if (sortField === field) { + setSortDir((d) => (d === 'asc' ? 'desc' : 'asc')) + } else { + setSortField(field) + setSortDir('asc') + } + } + + const sortedEntries = useMemo(() => { + const dirs = entries.filter((e) => e.isDirectory) + const files = entries.filter((e) => !e.isDirectory) + + const compare = (a: FileEntry, b: FileEntry): number => { + let result = 0 + switch (sortField) { + case 'name': + result = a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }) + break + case 'size': + result = a.size - b.size + break + case 'modified': + result = new Date(a.modifiedAt).getTime() - new Date(b.modifiedAt).getTime() + break + } + return sortDir === 'asc' ? result : -result + } + + return [...dirs.sort(compare), ...files.sort(compare)] + }, [entries, sortField, sortDir]) + + if (entries.length === 0) { + return + } + + const SortIcon = ({ field }: { field: SortField }) => { + const color = sortField === field ? Colors.TextColor.secondary : Colors.TextColor.tertiary + if (sortField !== field) return + return sortDir === 'asc' ? ( + + ) : ( + + ) + } + + return ( + + {/* Header */} + + {selectable && } + toggleSort('name')} style={styles.sortBtn}> + Name + + + toggleSort('size')} style={styles.sortBtn}> + Size + + + + + {/* Rows */} + {sortedEntries.map((entry) => ( + + ))} + + ) +} + +const styles = StyleSheet.create({ + header: { + flexDirection: 'row', + alignItems: 'center', + paddingBottom: 8, + borderBottomWidth: 1, + borderBottomColor: Colors.BorderColor.primary, + paddingHorizontal: 12, + gap: 8, + }, + sortBtn: { + flexDirection: 'row', + alignItems: 'center', + gap: 4, + }, + headerText: { + fontSize: 12, + fontWeight: '500', + color: Colors.TextColor.secondary, + fontFamily: Typography.caption.fontFamily, + }, + row: { + flexDirection: 'row', + alignItems: 'center', + paddingVertical: 10, + paddingHorizontal: 12, + borderBottomWidth: StyleSheet.hairlineWidth, + borderBottomColor: Colors.BorderColor.secondary, + }, + rowSelected: { + backgroundColor: '#eff6ff', + }, + checkbox: { + marginRight: 8, + }, + checkboxBox: { + width: 18, + height: 18, + borderRadius: 4, + borderWidth: 1.5, + borderColor: Colors.BorderColor.primary, + alignItems: 'center', + justifyContent: 'center', + }, + checkboxChecked: { + backgroundColor: Colors.BrandColor[600], + borderColor: Colors.BrandColor[600], + }, + checkmark: { + color: '#ffffff', + fontSize: 12, + fontWeight: '700', + }, + nameCell: { + flex: 1, + flexDirection: 'row', + alignItems: 'center', + gap: 10, + }, + iconWrap: { + width: 32, + height: 32, + alignItems: 'center', + justifyContent: 'center', + }, + thumbnail: { + width: 32, + height: 32, + borderRadius: 4, + backgroundColor: Colors.BackgroundColor.tertiary, + }, + nameText: { + flex: 1, + }, + fileName: { + fontSize: 14, + color: Colors.TextColor.primary, + fontFamily: Typography.body.fontFamily, + }, + fileMeta: { + fontSize: 11, + color: Colors.TextColor.tertiary, + marginTop: 1, + }, + actionBtn: { + padding: 8, + marginLeft: 8, + }, +}) diff --git a/packages/app/src/components/PreviewModal.tsx b/packages/app/src/components/PreviewModal.tsx new file mode 100644 index 0000000..b702c35 --- /dev/null +++ b/packages/app/src/components/PreviewModal.tsx @@ -0,0 +1,136 @@ +import { Download, X } from 'lucide-react-native' +import { Image, Linking, Modal, Platform, Pressable, StyleSheet, Text, View } from 'react-native' +import { api, type FileEntry } from '@/lib/api' +import { Colors, Outlines, Typography } from '@/theme' + +interface PreviewModalProps { + file: FileEntry + volume: string + onClose: () => void +} + +export default function PreviewModal({ file, volume, onClose }: PreviewModalProps) { + const downloadUrl = api.getDownloadUrl(volume, file.path) + const inlineUrl = api.getInlineUrl(volume, file.path) + const mime = file.mimeType || '' + + const handleDownload = () => { + Linking.openURL(downloadUrl) + } + + const renderContent = () => { + if (mime.startsWith('image/')) { + return + } + + return ( + + Preview not available for this file type + + + Download + + + ) + } + + return ( + + + e.stopPropagation()}> + {/* Header */} + + + {file.name} + + + + + + + + + + + + {/* Body */} + {renderContent()} + + + + ) +} + +const styles = StyleSheet.create({ + overlay: { + flex: 1, + backgroundColor: 'rgba(0,0,0,0.6)', + justifyContent: 'center', + alignItems: 'center', + padding: 16, + }, + content: { + backgroundColor: '#ffffff', + borderRadius: Outlines.borderRadius.lg, + width: '100%', + maxWidth: 600, + maxHeight: '90%', + overflow: 'hidden', + ...Outlines.shadow.xl, + }, + header: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + paddingHorizontal: 16, + paddingVertical: 12, + borderBottomWidth: 1, + borderBottomColor: Colors.BorderColor.primary, + }, + title: { + flex: 1, + fontSize: 13, + fontWeight: '500', + color: Colors.TextColor.primary, + marginRight: 16, + }, + headerActions: { + flexDirection: 'row', + gap: 8, + }, + headerBtn: { + padding: 6, + borderRadius: Outlines.borderRadius.sm, + }, + body: { + alignItems: 'center', + justifyContent: 'center', + }, + imagePreview: { + width: '100%', + height: 400, + }, + noPreview: { + padding: 32, + alignItems: 'center', + }, + noPreviewText: { + fontSize: 14, + color: Colors.TextColor.secondary, + marginBottom: 16, + }, + downloadBtn: { + flexDirection: 'row', + alignItems: 'center', + gap: 8, + backgroundColor: Colors.BrandColor[600], + paddingHorizontal: 16, + paddingVertical: 8, + borderRadius: Outlines.borderRadius.md, + }, + downloadBtnText: { + color: '#ffffff', + fontSize: 13, + fontWeight: '500', + }, +}) diff --git a/packages/app/src/components/SearchBar.tsx b/packages/app/src/components/SearchBar.tsx new file mode 100644 index 0000000..9c4a9f9 --- /dev/null +++ b/packages/app/src/components/SearchBar.tsx @@ -0,0 +1,171 @@ +import { Search, X } from 'lucide-react-native' +import { useEffect, useRef, useState } from 'react' +import { Pressable, StyleSheet, Text, TextInput, View } from 'react-native' +import { useSearch } from '@/hooks/useSearch' +import { getFileIcon } from '@/lib/fileIcons' +import { Colors, Outlines, Typography } from '@/theme' + +interface SearchBarProps { + volume: string + onNavigate: (path: string) => void +} + +export default function SearchBar({ volume, onNavigate }: SearchBarProps) { + const [query, setQuery] = useState('') + const [debouncedQuery, setDebouncedQuery] = useState('') + const [isOpen, setIsOpen] = useState(false) + + useEffect(() => { + const timer = setTimeout(() => setDebouncedQuery(query), 300) + return () => clearTimeout(timer) + }, [query]) + + const { data, isLoading } = useSearch(debouncedQuery, volume) + + return ( + + + + { + setQuery(text) + setIsOpen(true) + }} + onFocus={() => query && setIsOpen(true)} + placeholder="Search files..." + placeholderTextColor={Colors.TextColor.tertiary} + style={styles.input} + /> + {query.length > 0 && ( + { + setQuery('') + setIsOpen(false) + }} + hitSlop={8} + > + + + )} + + + {isOpen && debouncedQuery.length > 0 && ( + + {isLoading ? ( + Searching... + ) : !data?.results.length ? ( + No results + ) : ( + data.results.map((result) => { + const isDir = result.is_directory === 1 + const dirPath = isDir ? result.path : result.path.split('/').slice(0, -1).join('/') + + return ( + { + onNavigate(dirPath) + setIsOpen(false) + setQuery('') + }} + style={styles.resultItem} + > + + {getFileIcon( + { + name: result.name, + path: result.path, + isDirectory: isDir, + size: 0, + modifiedAt: '', + mimeType: null, + }, + 16, + )} + + + + {result.name} + + + {result.path} + + + + ) + }) + )} + + )} + + ) +} + +const styles = StyleSheet.create({ + container: { + flex: 1, + maxWidth: 400, + position: 'relative', + zIndex: 10, + }, + inputRow: { + flexDirection: 'row', + alignItems: 'center', + gap: 8, + backgroundColor: '#ffffff', + borderWidth: 1, + borderColor: Colors.BorderColor.primary, + borderRadius: Outlines.borderRadius.md, + paddingHorizontal: 12, + paddingVertical: 6, + }, + input: { + flex: 1, + fontSize: 13, + color: Colors.TextColor.primary, + fontFamily: Typography.body.fontFamily, + padding: 0, + }, + dropdown: { + position: 'absolute', + top: '100%', + left: 0, + right: 0, + marginTop: 4, + backgroundColor: '#ffffff', + borderWidth: 1, + borderColor: Colors.BorderColor.primary, + borderRadius: Outlines.borderRadius.md, + maxHeight: 320, + ...Outlines.shadow.lg, + }, + dropdownMsg: { + paddingHorizontal: 16, + paddingVertical: 12, + fontSize: 13, + color: Colors.TextColor.tertiary, + }, + resultItem: { + flexDirection: 'row', + alignItems: 'center', + gap: 10, + paddingHorizontal: 16, + paddingVertical: 8, + }, + resultIcon: { + width: 16, + alignItems: 'center', + }, + resultText: { + flex: 1, + }, + resultName: { + fontSize: 13, + color: Colors.TextColor.primary, + }, + resultPath: { + fontSize: 11, + color: Colors.TextColor.tertiary, + }, +}) diff --git a/packages/app/src/components/ShareDialog.tsx b/packages/app/src/components/ShareDialog.tsx new file mode 100644 index 0000000..ba0ccb8 --- /dev/null +++ b/packages/app/src/components/ShareDialog.tsx @@ -0,0 +1,252 @@ +import * as Clipboard from 'expo-clipboard' +import { Check, Copy, Link2, X } from 'lucide-react-native' +import { useState } from 'react' +import { + ActivityIndicator, + Modal, + Platform, + Pressable, + StyleSheet, + Text, + TextInput, + View, +} from 'react-native' +import { type FileEntry, getApiBase } from '@/lib/api' +import { Colors, Outlines, Typography } from '@/theme' + +interface ShareDialogProps { + file: FileEntry + volume: string + onClose: () => void +} + +export default function ShareDialog({ file, volume, onClose }: ShareDialogProps) { + const [password, setPassword] = useState('') + const [maxDownloads, setMaxDownloads] = useState('') + const [expiresIn, setExpiresIn] = useState('24') + const [shareUrl, setShareUrl] = useState('') + const [creating, setCreating] = useState(false) + const [copied, setCopied] = useState(false) + const [error, setError] = useState('') + + const handleCreate = async () => { + setCreating(true) + setError('') + try { + const res = await fetch(`${getApiBase()}/share`, { + method: 'POST', + credentials: 'include', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + volume, + path: file.path, + password: password || undefined, + maxDownloads: maxDownloads ? parseInt(maxDownloads) : undefined, + expiresIn: expiresIn ? parseInt(expiresIn) : undefined, + }), + }) + + if (!res.ok) { + const data = await res.json() + throw new Error(data.error || 'Failed to create share') + } + + const data = await res.json() + setShareUrl(data.url || `${getApiBase()}/share/${data.share.id}/download`) + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to create share') + } finally { + setCreating(false) + } + } + + const handleCopy = async () => { + await Clipboard.setStringAsync(shareUrl) + setCopied(true) + setTimeout(() => setCopied(false), 2000) + } + + return ( + + + e.stopPropagation()}> + {/* Header */} + + Share File + + + + + + + {file.name} + + + {shareUrl ? ( + + Share URL + + + + {copied ? : } + {copied ? 'Copied' : 'Copy'} + + + + ) : ( + + + Password (optional) + + + + + Max downloads (optional) + + + + {error ? {error} : null} + + + {creating ? ( + + ) : ( + + )} + Create Share Link + + + )} + + + + ) +} + +const styles = StyleSheet.create({ + overlay: { + flex: 1, + backgroundColor: 'rgba(0,0,0,0.6)', + justifyContent: 'center', + alignItems: 'center', + padding: 16, + }, + dialog: { + backgroundColor: '#ffffff', + borderRadius: Outlines.borderRadius.lg, + width: '100%', + maxWidth: 420, + padding: 24, + ...Outlines.shadow.xl, + }, + header: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + marginBottom: 12, + }, + headerTitle: { + fontSize: 18, + fontWeight: '600', + color: Colors.TextColor.primary, + }, + fileName: { + fontSize: 13, + color: Colors.TextColor.secondary, + marginBottom: 16, + }, + section: { + gap: 12, + }, + label: { + fontSize: 12, + color: Colors.TextColor.secondary, + marginBottom: 4, + }, + urlRow: { + flexDirection: 'row', + gap: 8, + }, + urlInput: { + flex: 1, + backgroundColor: Colors.BackgroundColor.secondary, + borderWidth: 1, + borderColor: Colors.BorderColor.primary, + borderRadius: Outlines.borderRadius.md, + paddingHorizontal: 12, + paddingVertical: 8, + fontSize: 13, + color: Colors.TextColor.primary, + }, + copyBtn: { + flexDirection: 'row', + alignItems: 'center', + gap: 6, + backgroundColor: Colors.BrandColor[600], + paddingHorizontal: 12, + paddingVertical: 8, + borderRadius: Outlines.borderRadius.md, + }, + copyBtnText: { + color: '#ffffff', + fontSize: 13, + fontWeight: '500', + }, + field: { + marginBottom: 4, + }, + textInput: { + backgroundColor: '#ffffff', + borderWidth: 1, + borderColor: Colors.BorderColor.primary, + borderRadius: Outlines.borderRadius.md, + paddingHorizontal: 12, + paddingVertical: 8, + fontSize: 13, + color: Colors.TextColor.primary, + }, + errorText: { + fontSize: 13, + color: Colors.StatusColor.error, + }, + createBtn: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'center', + gap: 8, + backgroundColor: Colors.BrandColor[600], + paddingVertical: 10, + borderRadius: Outlines.borderRadius.md, + marginTop: 4, + }, + createBtnDisabled: { + opacity: 0.5, + }, + createBtnText: { + color: '#ffffff', + fontSize: 14, + fontWeight: '500', + }, +}) diff --git a/packages/app/src/components/UpdateSection.tsx b/packages/app/src/components/UpdateSection.tsx new file mode 100644 index 0000000..0e99d4c --- /dev/null +++ b/packages/app/src/components/UpdateSection.tsx @@ -0,0 +1,146 @@ +import { useMutation, useQuery } from '@tanstack/react-query' +import { Package, RefreshCw } from 'lucide-react-native' +import { useEffect, useRef, useState } from 'react' +import { ActivityIndicator, Alert, Pressable, StyleSheet, Text, View } from 'react-native' +import Button from '@/components/ui/Button' +import { api } from '@/lib/api' +import { APP_NAME } from '@/lib/config' +import { Colors, Outlines, Typography } from '@/theme' + +export default function UpdateSection() { + const [restarting, setRestarting] = useState(false) + const pollRef = useRef | null>(null) + + const { data, isLoading } = useQuery({ + queryKey: ['version'], + queryFn: () => api.getVersion(), + }) + + useEffect(() => { + if (!restarting) return + + const startDelay = setTimeout(() => { + pollRef.current = setInterval(async () => { + try { + await api.getVersion() + // Server is back — would reload on web + setRestarting(false) + } catch { + // Still down + } + }, 2000) + }, 3000) + + return () => { + clearTimeout(startDelay) + if (pollRef.current) clearInterval(pollRef.current) + } + }, [restarting]) + + const updateMutation = useMutation({ + mutationFn: () => api.triggerUpdate(), + onSuccess: () => setRestarting(true), + }) + + const handleUpdate = () => { + Alert.alert('Update', `Update ${APP_NAME} and restart the server?`, [ + { text: 'Cancel', style: 'cancel' }, + { text: 'Update', onPress: () => updateMutation.mutate() }, + ]) + } + + return ( + + + + Software Update + + + + + + Current version:{' '} + {isLoading ? ( + loading... + ) : ( + {data?.version || 'unknown'} + )} + + + + {restarting ? ( + + + Restarting... + + ) : ( + + )} + + + {updateMutation.isError && ( + + Failed to trigger update. Is {APP_NAME} installed via Homebrew? + + )} + + ) +} + +const styles = StyleSheet.create({ + card: { + backgroundColor: '#ffffff', + borderWidth: 1, + borderColor: Colors.BorderColor.primary, + borderRadius: Outlines.borderRadius.lg, + padding: 20, + ...Outlines.shadow.sm, + }, + headerRow: { + flexDirection: 'row', + alignItems: 'center', + gap: 10, + marginBottom: 12, + }, + heading: { + fontSize: 14, + fontWeight: '600', + color: Colors.TextColor.primary, + }, + body: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + }, + label: { + fontSize: 13, + color: Colors.TextColor.secondary, + }, + loadingText: { + color: Colors.TextColor.tertiary, + }, + versionText: { + fontFamily: Typography.caption.fontFamily, + fontWeight: '500', + color: Colors.TextColor.primary, + }, + restartingRow: { + flexDirection: 'row', + alignItems: 'center', + gap: 8, + }, + restartingText: { + fontSize: 13, + color: '#d97706', + }, + errorText: { + marginTop: 8, + fontSize: 13, + color: Colors.StatusColor.error, + }, +}) diff --git a/packages/app/src/components/UploadProgress.tsx b/packages/app/src/components/UploadProgress.tsx new file mode 100644 index 0000000..11fd00c --- /dev/null +++ b/packages/app/src/components/UploadProgress.tsx @@ -0,0 +1,216 @@ +import { + AlertCircle, + CheckCircle, + ChevronDown, + ChevronUp, + Pause, + Play, + X, +} from 'lucide-react-native' +import { useState } from 'react' +import { Pressable, StyleSheet, Text, View } from 'react-native' +import type { UploadItem } from '@/hooks/useUpload' +import { formatBytes } from '@/lib/format' +import { Colors, Outlines } from '@/theme' + +interface UploadProgressProps { + uploads: UploadItem[] + onPause: (id: string) => void + onResume: (id: string) => void + onCancel: (id: string) => void + onClearCompleted: () => void +} + +export default function UploadProgress({ + uploads, + onPause, + onResume, + onCancel, + onClearCompleted, +}: UploadProgressProps) { + const [collapsed, setCollapsed] = useState(false) + + if (uploads.length === 0) return null + + const active = uploads.filter((u) => u.status === 'uploading' || u.status === 'pending') + const completed = uploads.filter((u) => u.status === 'complete') + + return ( + + {/* Header */} + setCollapsed(!collapsed)} style={styles.header}> + + {active.length > 0 + ? `Uploading ${active.length} file${active.length > 1 ? 's' : ''}...` + : `${completed.length} upload${completed.length > 1 ? 's' : ''} complete`} + + + {completed.length > 0 && ( + { + e.stopPropagation?.() + onClearCompleted() + }} + > + Clear completed + + )} + {collapsed ? ( + + ) : ( + + )} + + + + {/* Items */} + {!collapsed && ( + + {uploads.map((item) => ( + + {item.status === 'complete' && ( + + )} + {item.status === 'error' && ( + + )} + + + + {item.file.name} + + + + + + + {item.progress}% · {formatBytes(item.file.size)} + + + {item.error && {item.error}} + + + + {item.status === 'uploading' && ( + onPause(item.id)} style={styles.controlBtn}> + + + )} + {item.status === 'paused' && ( + onResume(item.id)} style={styles.controlBtn}> + + + )} + {item.status !== 'complete' && ( + onCancel(item.id)} style={styles.controlBtn}> + + + )} + + + ))} + + )} + + ) +} + +const styles = StyleSheet.create({ + container: { + position: 'absolute', + bottom: 0, + left: 0, + right: 0, + backgroundColor: '#ffffff', + borderTopWidth: 1, + borderTopColor: Colors.BorderColor.primary, + ...Outlines.shadow.lg, + }, + header: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + paddingHorizontal: 16, + paddingVertical: 10, + }, + headerText: { + fontSize: 13, + fontWeight: '500', + color: Colors.TextColor.primary, + }, + headerRight: { + flexDirection: 'row', + alignItems: 'center', + gap: 8, + }, + clearText: { + fontSize: 11, + color: Colors.TextColor.tertiary, + }, + list: { + maxHeight: 256, + paddingHorizontal: 16, + paddingBottom: 12, + }, + item: { + flexDirection: 'row', + alignItems: 'center', + gap: 12, + paddingVertical: 8, + borderTopWidth: StyleSheet.hairlineWidth, + borderTopColor: Colors.BorderColor.secondary, + }, + itemInfo: { + flex: 1, + }, + itemName: { + fontSize: 13, + color: Colors.TextColor.primary, + }, + progressRow: { + flexDirection: 'row', + alignItems: 'center', + gap: 8, + marginTop: 4, + }, + progressTrack: { + flex: 1, + height: 6, + backgroundColor: Colors.BackgroundColor.tertiary, + borderRadius: 3, + overflow: 'hidden', + }, + progressFill: { + height: '100%', + borderRadius: 3, + }, + progressText: { + fontSize: 11, + color: Colors.TextColor.tertiary, + }, + errorText: { + fontSize: 11, + color: Colors.StatusColor.error, + marginTop: 2, + }, + controls: { + flexDirection: 'row', + gap: 4, + }, + controlBtn: { + padding: 4, + }, +}) diff --git a/packages/app/src/components/UploadZone.tsx b/packages/app/src/components/UploadZone.tsx new file mode 100644 index 0000000..acd7517 --- /dev/null +++ b/packages/app/src/components/UploadZone.tsx @@ -0,0 +1,74 @@ +import * as DocumentPicker from 'expo-document-picker' +import { Upload } from 'lucide-react-native' +import { Platform, Pressable, StyleSheet, Text, View } from 'react-native' +import { Colors, Outlines, Typography } from '@/theme' + +interface UploadZoneProps { + onFilesSelected: (files: File[]) => void +} + +export default function UploadZone({ onFilesSelected }: UploadZoneProps) { + const handlePickFiles = async () => { + try { + const result = await DocumentPicker.getDocumentAsync({ + multiple: true, + copyToCacheDirectory: true, + }) + + if (!result.canceled && result.assets) { + // On web, DocumentPicker returns File objects in the assets + // On native, we get URI-based assets — wrap them for the upload hook + const files = result.assets.map((asset) => { + if (asset.file) return asset.file as File + // Create a minimal File-like object for native + return { + name: asset.name, + size: asset.size ?? 0, + type: asset.mimeType ?? 'application/octet-stream', + uri: asset.uri, + } as unknown as File + }) + onFilesSelected(files) + } + } catch (_err) { + // User cancelled or error + } + } + + return ( + + + Select files to upload + + Choose Files + + + ) +} + +const styles = StyleSheet.create({ + container: { + borderWidth: 2, + borderStyle: 'dashed', + borderColor: Colors.BorderColor.primary, + borderRadius: Outlines.borderRadius.lg, + padding: 32, + alignItems: 'center', + gap: 12, + }, + text: { + fontSize: 14, + color: Colors.TextColor.secondary, + }, + button: { + backgroundColor: Colors.BrandColor[600], + paddingHorizontal: 16, + paddingVertical: 8, + borderRadius: Outlines.borderRadius.md, + }, + buttonText: { + color: '#ffffff', + fontSize: 13, + fontWeight: '500', + }, +}) diff --git a/packages/app/src/components/VolumeSelector.tsx b/packages/app/src/components/VolumeSelector.tsx new file mode 100644 index 0000000..6b7b554 --- /dev/null +++ b/packages/app/src/components/VolumeSelector.tsx @@ -0,0 +1,85 @@ +import { useQuery } from '@tanstack/react-query' +import { ChevronDown, HardDrive } from 'lucide-react-native' +import { useEffect } from 'react' +import { ActivityIndicator, Pressable, StyleSheet, Text, View } from 'react-native' +import { api, type VolumeInfo } from '@/lib/api' +import { formatBytes } from '@/lib/format' +import { Colors, Outlines, Typography } from '@/theme' + +interface VolumeSelectorProps { + selectedVolume: string + onSelect: (volumeId: string) => void +} + +export default function VolumeSelector({ selectedVolume, onSelect }: VolumeSelectorProps) { + const { data, isLoading } = useQuery({ + queryKey: ['volumes'], + queryFn: () => api.getVolumes(), + }) + + const volumes = data?.volumes || [] + + useEffect(() => { + if (volumes.length > 0 && !selectedVolume) { + onSelect(volumes[0].id) + } + }, [volumes, selectedVolume, onSelect]) + + if (isLoading) { + return ( + + + + Loading volumes... + + ) + } + + if (volumes.length === 0) { + return ( + + + No volumes configured + + ) + } + + const current = volumes.find((v) => v.id === selectedVolume) + + return ( + + + + {current?.label ?? 'Select volume'} + + {current && ( + + {formatBytes(current.usedBytes)} / {formatBytes(current.totalBytes)} + + )} + + ) +} + +const styles = StyleSheet.create({ + container: { + flexDirection: 'row', + alignItems: 'center', + gap: 8, + }, + loadingText: { + fontSize: 13, + color: Colors.TextColor.tertiary, + }, + volumeLabel: { + fontSize: 14, + fontWeight: '500', + color: Colors.TextColor.primary, + fontFamily: Typography.body.fontFamily, + maxWidth: 160, + }, + volumeSize: { + fontSize: 12, + color: Colors.TextColor.tertiary, + }, +}) diff --git a/packages/app/src/components/ui/Badge.tsx b/packages/app/src/components/ui/Badge.tsx new file mode 100644 index 0000000..f191fed --- /dev/null +++ b/packages/app/src/components/ui/Badge.tsx @@ -0,0 +1,57 @@ +import { StyleSheet, Text, type TextStyle, View, type ViewStyle } from 'react-native' +import { Colors, Outlines, Typography } from '@/theme' + +const variantStyles: Record = { + default: { + container: { backgroundColor: Colors.BackgroundColor.tertiary }, + text: { color: Colors.TextColor.secondary }, + }, + primary: { + container: { backgroundColor: Colors.BrandColor[50] }, + text: { color: Colors.BrandColor[700] }, + }, + success: { + container: { backgroundColor: Colors.StatusColor.successLight }, + text: { color: Colors.StatusColor.success }, + }, + warning: { + container: { backgroundColor: Colors.StatusColor.warningLight }, + text: { color: Colors.StatusColor.warning }, + }, + error: { + container: { backgroundColor: Colors.StatusColor.errorLight }, + text: { color: Colors.StatusColor.error }, + }, + info: { + container: { backgroundColor: Colors.StatusColor.infoLight }, + text: { color: Colors.StatusColor.info }, + }, +} + +interface BadgeProps { + variant?: keyof typeof variantStyles + children: React.ReactNode +} + +export default function Badge({ variant = 'default', children }: BadgeProps) { + const vStyle = variantStyles[variant] + return ( + + {children} + + ) +} + +const styles = StyleSheet.create({ + container: { + paddingHorizontal: 6, + paddingVertical: 2, + borderRadius: Outlines.borderRadius.sm, + alignSelf: 'flex-start', + }, + text: { + fontSize: 11, + fontWeight: '600', + fontFamily: Typography.caption.fontFamily, + }, +}) diff --git a/packages/app/src/components/ui/Button.tsx b/packages/app/src/components/ui/Button.tsx new file mode 100644 index 0000000..f0eaacb --- /dev/null +++ b/packages/app/src/components/ui/Button.tsx @@ -0,0 +1,107 @@ +import { + ActivityIndicator, + Pressable, + StyleSheet, + Text, + type TextStyle, + type ViewStyle, +} from 'react-native' +import { Colors, Outlines, Typography } from '@/theme' + +const variantStyles: Record = { + primary: { + container: { backgroundColor: Colors.BrandColor[600] }, + text: { color: '#ffffff' }, + }, + secondary: { + container: { + backgroundColor: '#ffffff', + borderWidth: Outlines.borderWidth.normal, + borderColor: Colors.BorderColor.primary, + }, + text: { color: Colors.TextColor.primary }, + }, + ghost: { + container: { backgroundColor: 'transparent' }, + text: { color: Colors.TextColor.secondary }, + }, + danger: { + container: { backgroundColor: Colors.StatusColor.error }, + text: { color: '#ffffff' }, + }, +} + +const sizeStyles: Record = { + sm: { container: { paddingHorizontal: 8, paddingVertical: 4 }, text: { fontSize: 12 } }, + md: { container: { paddingHorizontal: 12, paddingVertical: 6 }, text: { fontSize: 13 } }, + lg: { container: { paddingHorizontal: 16, paddingVertical: 8 }, text: { fontSize: 14 } }, + icon: { container: { padding: 6 }, text: {} }, +} + +interface ButtonProps { + variant?: keyof typeof variantStyles + size?: keyof typeof sizeStyles + loading?: boolean + disabled?: boolean + onPress?: () => void + children: React.ReactNode +} + +export default function Button({ + variant = 'primary', + size = 'md', + loading = false, + disabled, + onPress, + children, +}: ButtonProps) { + const isDisabled = disabled || loading + const vStyle = variantStyles[variant] + const sStyle = sizeStyles[size] + + return ( + [ + styles.base, + vStyle.container, + sStyle.container, + pressed && styles.pressed, + isDisabled && styles.disabled, + ]} + > + {loading && ( + + )} + {typeof children === 'string' ? ( + {children} + ) : ( + children + )} + + ) +} + +const styles = StyleSheet.create({ + base: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'center', + borderRadius: Outlines.borderRadius.md, + gap: 6, + }, + text: { + fontFamily: Typography.button.fontFamily, + fontWeight: Typography.button.fontWeight as TextStyle['fontWeight'], + }, + pressed: { + opacity: 0.85, + }, + disabled: { + opacity: 0.5, + }, + loader: { + marginRight: 4, + }, +}) diff --git a/packages/app/src/components/ui/EmptyState.tsx b/packages/app/src/components/ui/EmptyState.tsx new file mode 100644 index 0000000..900f25f --- /dev/null +++ b/packages/app/src/components/ui/EmptyState.tsx @@ -0,0 +1,46 @@ +import type { LucideIcon } from 'lucide-react-native' +import { StyleSheet, Text, View } from 'react-native' +import { Colors, Typography } from '@/theme' + +interface EmptyStateProps { + icon: LucideIcon + title: string + description?: string + action?: React.ReactNode +} + +export default function EmptyState({ icon: Icon, title, description, action }: EmptyStateProps) { + return ( + + + {title} + {description && {description}} + {action && {action}} + + ) +} + +const styles = StyleSheet.create({ + container: { + alignItems: 'center', + justifyContent: 'center', + paddingVertical: 80, + }, + title: { + marginTop: 12, + fontSize: 15, + fontWeight: '500', + fontFamily: Typography.body.fontFamily, + color: Colors.TextColor.secondary, + }, + description: { + marginTop: 4, + fontSize: 13, + color: Colors.TextColor.tertiary, + textAlign: 'center', + maxWidth: 280, + }, + action: { + marginTop: 16, + }, +}) diff --git a/packages/app/src/components/ui/Skeleton.tsx b/packages/app/src/components/ui/Skeleton.tsx new file mode 100644 index 0000000..45965f8 --- /dev/null +++ b/packages/app/src/components/ui/Skeleton.tsx @@ -0,0 +1,106 @@ +import { useEffect, useRef } from 'react' +import { Animated, StyleSheet, View } from 'react-native' +import { Colors, Outlines } from '@/theme' + +function Skeleton({ + width, + height, + style, +}: { + width?: number | string + height?: number + style?: any +}) { + const opacity = useRef(new Animated.Value(0.3)).current + + useEffect(() => { + const animation = Animated.loop( + Animated.sequence([ + Animated.timing(opacity, { toValue: 1, duration: 800, useNativeDriver: true }), + Animated.timing(opacity, { toValue: 0.3, duration: 800, useNativeDriver: true }), + ]), + ) + animation.start() + return () => animation.stop() + }, [opacity]) + + return ( + + ) +} + +export function FileListSkeleton({ rows = 8 }: { rows?: number }) { + return ( + + + + + + + {Array.from({ length: rows }, (_, i) => `row-${i}`).map((id) => ( + + + + + + ))} + + ) +} + +export function FileGridSkeleton({ items = 10 }: { items?: number }) { + return ( + + {Array.from({ length: items }, (_, i) => `item-${i}`).map((id) => ( + + + + + + ))} + + ) +} + +export default Skeleton + +const styles = StyleSheet.create({ + skeleton: { + backgroundColor: Colors.BorderColor.primary, + borderRadius: Outlines.borderRadius.sm, + }, + headerRow: { + flexDirection: 'row', + alignItems: 'center', + gap: 16, + paddingBottom: 12, + borderBottomWidth: 1, + borderBottomColor: Colors.BorderColor.primary, + paddingHorizontal: 12, + }, + row: { + flexDirection: 'row', + alignItems: 'center', + gap: 12, + paddingVertical: 12, + borderBottomWidth: 1, + borderBottomColor: Colors.BorderColor.secondary, + paddingHorizontal: 12, + }, + iconPlaceholder: { + borderRadius: Outlines.borderRadius.sm, + }, + grid: { + flexDirection: 'row', + flexWrap: 'wrap', + gap: 12, + }, + gridItem: { + alignItems: 'center', + gap: 8, + padding: 12, + width: '30%', + }, +}) diff --git a/packages/app/src/components/ui/Tabs.tsx b/packages/app/src/components/ui/Tabs.tsx new file mode 100644 index 0000000..07eafcb --- /dev/null +++ b/packages/app/src/components/ui/Tabs.tsx @@ -0,0 +1,59 @@ +import { Pressable, StyleSheet, Text, View } from 'react-native' +import { Colors, Typography } from '@/theme' + +interface Tab { + id: string + label: string +} + +interface TabsProps { + tabs: Tab[] + activeTab: string + onChange: (id: string) => void +} + +export default function Tabs({ tabs, activeTab, onChange }: TabsProps) { + return ( + + {tabs.map((tab) => { + const isActive = activeTab === tab.id + return ( + onChange(tab.id)} style={styles.tab}> + {tab.label} + {isActive && } + + ) + })} + + ) +} + +const styles = StyleSheet.create({ + container: { + flexDirection: 'row', + borderBottomWidth: 1, + borderBottomColor: Colors.BorderColor.primary, + }, + tab: { + paddingHorizontal: 16, + paddingVertical: 10, + position: 'relative', + }, + tabText: { + fontSize: 13, + fontWeight: '500', + fontFamily: Typography.body.fontFamily, + color: Colors.TextColor.secondary, + }, + activeTabText: { + color: Colors.BrandColor[600], + }, + indicator: { + position: 'absolute', + bottom: 0, + left: 0, + right: 0, + height: 2, + backgroundColor: Colors.BrandColor[600], + }, +}) diff --git a/packages/app/src/components/ui/Toast.tsx b/packages/app/src/components/ui/Toast.tsx new file mode 100644 index 0000000..ebcea33 --- /dev/null +++ b/packages/app/src/components/ui/Toast.tsx @@ -0,0 +1,83 @@ +import { AlertCircle, CheckCircle, Info, X } from 'lucide-react-native' +import { Pressable, StyleSheet, Text, type TextStyle, View, type ViewStyle } from 'react-native' +import type { Toast as ToastType } from '@/hooks/useToast' +import { Colors, Outlines } from '@/theme' + +const typeConfig: Record< + ToastType['type'], + { bg: string; border: string; text: string; Icon: typeof CheckCircle } +> = { + success: { + bg: Colors.StatusColor.successLight, + border: '#a7f3d0', + text: '#065f46', + Icon: CheckCircle, + }, + error: { + bg: Colors.StatusColor.errorLight, + border: '#fecaca', + text: '#991b1b', + Icon: AlertCircle, + }, + info: { + bg: Colors.StatusColor.infoLight, + border: '#bfdbfe', + text: '#1e40af', + Icon: Info, + }, +} + +interface ToastContainerProps { + toasts: ToastType[] + onDismiss: (id: string) => void +} + +export default function ToastContainer({ toasts, onDismiss }: ToastContainerProps) { + if (toasts.length === 0) return null + + return ( + + {toasts.map((toast) => { + const config = typeConfig[toast.type] + const Icon = config.Icon + return ( + + + {toast.message} + onDismiss(toast.id)} hitSlop={8}> + + + + ) + })} + + ) +} + +const styles = StyleSheet.create({ + container: { + position: 'absolute', + top: 16, + right: 16, + left: 16, + zIndex: 50, + gap: 8, + }, + toast: { + flexDirection: 'row', + alignItems: 'center', + gap: 8, + paddingHorizontal: 16, + paddingVertical: 12, + borderRadius: Outlines.borderRadius.lg, + borderWidth: 1, + ...Outlines.shadow.md, + }, + message: { + flex: 1, + fontSize: 13, + }, +}) diff --git a/packages/web/src/hooks/useAdmin.ts b/packages/app/src/hooks/useAdmin.ts similarity index 99% rename from packages/web/src/hooks/useAdmin.ts rename to packages/app/src/hooks/useAdmin.ts index b3d684d..875787d 100644 --- a/packages/web/src/hooks/useAdmin.ts +++ b/packages/app/src/hooks/useAdmin.ts @@ -1,5 +1,5 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' -import { api } from '../lib/api' +import { api } from '@/lib/api' // --- Volumes --- diff --git a/packages/web/src/hooks/useAuth.ts b/packages/app/src/hooks/useAuth.ts similarity index 77% rename from packages/web/src/hooks/useAuth.ts rename to packages/app/src/hooks/useAuth.ts index c7fb654..b04a4e1 100644 --- a/packages/web/src/hooks/useAuth.ts +++ b/packages/app/src/hooks/useAuth.ts @@ -1,9 +1,10 @@ import { useQuery, useQueryClient } from '@tanstack/react-query' -import { withBase } from '../lib/basePath' -import { checkSession, logout as logoutFn } from '../lib/passkeys' +import { useRouter } from 'expo-router' +import { checkSession, logout as logoutFn } from '@/lib/passkeys' export function useAuth() { const queryClient = useQueryClient() + const router = useRouter() const { data, isLoading } = useQuery({ queryKey: ['auth', 'session'], @@ -18,7 +19,7 @@ export function useAuth() { authenticated: false, user: null, }) - window.location.href = withBase('/login') + router.replace('/login') } return { diff --git a/packages/web/src/hooks/useFiles.ts b/packages/app/src/hooks/useFiles.ts similarity index 97% rename from packages/web/src/hooks/useFiles.ts rename to packages/app/src/hooks/useFiles.ts index bea3eb4..69a6b3b 100644 --- a/packages/web/src/hooks/useFiles.ts +++ b/packages/app/src/hooks/useFiles.ts @@ -1,5 +1,5 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' -import { api } from '../lib/api' +import { api } from '@/lib/api' export function useFiles(volume: string, path: string) { return useQuery({ diff --git a/packages/web/src/hooks/useSearch.ts b/packages/app/src/hooks/useSearch.ts similarity index 84% rename from packages/web/src/hooks/useSearch.ts rename to packages/app/src/hooks/useSearch.ts index f7b69a3..04525f4 100644 --- a/packages/web/src/hooks/useSearch.ts +++ b/packages/app/src/hooks/useSearch.ts @@ -1,5 +1,5 @@ import { useQuery } from '@tanstack/react-query' -import { withBase } from '../lib/basePath' +import { getApiBase } from '@/lib/api' interface SearchResult { id: number @@ -17,7 +17,7 @@ async function searchFiles(query: string, volume?: string): Promise<{ results: S const params = new URLSearchParams({ q: query }) if (volume) params.set('volume', volume) - const res = await fetch(withBase(`/api/v1/search?${params}`), { credentials: 'include' }) + const res = await fetch(`${getApiBase()}/search?${params}`, { credentials: 'include' }) if (!res.ok) throw new Error('Search failed') return res.json() } diff --git a/packages/web/src/hooks/useSelection.ts b/packages/app/src/hooks/useSelection.ts similarity index 100% rename from packages/web/src/hooks/useSelection.ts rename to packages/app/src/hooks/useSelection.ts diff --git a/packages/web/src/hooks/useToast.ts b/packages/app/src/hooks/useToast.ts similarity index 100% rename from packages/web/src/hooks/useToast.ts rename to packages/app/src/hooks/useToast.ts diff --git a/packages/web/src/hooks/useUpload.ts b/packages/app/src/hooks/useUpload.ts similarity index 80% rename from packages/web/src/hooks/useUpload.ts rename to packages/app/src/hooks/useUpload.ts index 6ebe2af..42bba2d 100644 --- a/packages/web/src/hooks/useUpload.ts +++ b/packages/app/src/hooks/useUpload.ts @@ -1,6 +1,7 @@ import { useCallback, useRef, useState } from 'react' +import { Platform } from 'react-native' import * as tus from 'tus-js-client' -import { withBase } from '../lib/basePath' +import { getApiBase } from '@/lib/api' export interface UploadItem { id: string @@ -21,19 +22,19 @@ export function useUpload(volume: string, directory: string, onComplete?: () => const addFiles = useCallback( (files: File[]) => { + const endpoint = Platform.OS === 'web' ? '/api/v1/upload/' : `${getApiBase()}/upload/` + const newUploads: UploadItem[] = files.map((file) => { const id = `upload-${++idCounter.current}` const upload = new tus.Upload(file, { - endpoint: withBase('/api/v1/upload/'), + endpoint, retryDelays: [0, 3000, 5000, 10000, 20000], - chunkSize: 5 * 1024 * 1024, // 5MB chunks + chunkSize: 5 * 1024 * 1024, metadata: { filename: file.name, filetype: file.type, volume, directory, - // Preserve folder structure for directory uploads (e.g. "Photos/vacation/img.jpg") - ...(file.webkitRelativePath ? { relativePath: file.webkitRelativePath } : {}), }, onBeforeRequest: (req) => { const xhr = req.getUnderlyingObject() as XMLHttpRequest @@ -48,25 +49,15 @@ export function useUpload(volume: string, directory: string, onComplete?: () => onComplete?.() }, onError: (error) => { - updateUpload(id, { - status: 'error', - error: error.message, - }) + updateUpload(id, { status: 'error', error: error.message }) }, }) - return { - id, - file, - progress: 0, - status: 'pending' as const, - upload, - } + return { id, file, progress: 0, status: 'pending' as const, upload } }) setUploads((prev) => [...prev, ...newUploads]) - // Start all uploads for (const item of newUploads) { item.upload!.start() updateUpload(item.id, { status: 'uploading' }) @@ -112,12 +103,5 @@ export function useUpload(volume: string, directory: string, onComplete?: () => setUploads((prev) => prev.filter((u) => u.status !== 'complete')) }, []) - return { - uploads, - addFiles, - pauseUpload, - resumeUpload, - cancelUpload, - clearCompleted, - } + return { uploads, addFiles, pauseUpload, resumeUpload, cancelUpload, clearCompleted } } diff --git a/packages/web/src/hooks/useWebDAVTokens.ts b/packages/app/src/hooks/useWebDAVTokens.ts similarity index 95% rename from packages/web/src/hooks/useWebDAVTokens.ts rename to packages/app/src/hooks/useWebDAVTokens.ts index 158cbe4..3c04ad7 100644 --- a/packages/web/src/hooks/useWebDAVTokens.ts +++ b/packages/app/src/hooks/useWebDAVTokens.ts @@ -1,5 +1,5 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' -import { api } from '../lib/api' +import { api } from '@/lib/api' export function useWebDAVTokens() { return useQuery({ diff --git a/packages/web/src/lib/api.ts b/packages/app/src/lib/api.ts similarity index 87% rename from packages/web/src/lib/api.ts rename to packages/app/src/lib/api.ts index 1606bdd..182140e 100644 --- a/packages/web/src/lib/api.ts +++ b/packages/app/src/lib/api.ts @@ -1,15 +1,23 @@ -import { withBase } from './basePath' +import { Platform } from 'react-native' +import { BASE_PATH } from './config' -const API_BASE = withBase('/api/v1') +let _serverUrl = '' + +export function setServerUrl(url: string) { + _serverUrl = url.replace(/\/$/, '') +} + +export function getApiBase(): string { + if (Platform.OS === 'web') return `${BASE_PATH}/api/v1` + return `${_serverUrl}/api/v1` +} -/** Encode each segment of a file path for use in URLs */ function encodePath(filePath: string): string { if (!filePath) return '' return filePath.split('/').map(encodeURIComponent).join('/') } -/** Build a //[/] URL, avoiding trailing slashes */ -function volumeUrl(prefix: string, volume: string, filePath: string = ''): string { +function volumeUrl(prefix: string, volume: string, filePath = ''): string { const encoded = encodePath(filePath) return encoded ? `/${prefix}/${encodeURIComponent(volume)}/${encoded}` @@ -27,7 +35,7 @@ class ApiError extends Error { } async function request(path: string, options?: RequestInit): Promise { - const res = await fetch(`${API_BASE}${path}`, { + const res = await fetch(`${getApiBase()}${path}`, { credentials: 'include', ...options, headers: { @@ -107,7 +115,7 @@ export interface VolumeAccessUser { } export const api = { - listFiles(volume: string, path: string = ''): Promise { + listFiles(volume: string, path = ''): Promise { return request(volumeUrl('files', volume, path)) }, @@ -134,15 +142,15 @@ export const api = { }, getDownloadUrl(volume: string, path: string): string { - return `${API_BASE}${volumeUrl('download', volume, path)}` + return `${getApiBase()}${volumeUrl('download', volume, path)}` }, getInlineUrl(volume: string, path: string): string { - return `${API_BASE}${volumeUrl('download', volume, path)}?inline` + return `${getApiBase()}${volumeUrl('download', volume, path)}?inline` }, getPreviewUrl(volume: string, path: string, size: 'small' | 'medium' = 'small'): string { - return `${API_BASE}${volumeUrl('preview', volume, path)}?size=${size}` + return `${getApiBase()}${volumeUrl('preview', volume, path)}?size=${size}` }, createWebDAVToken(label: string): Promise<{ id: string; label: string; token: string }> { @@ -152,9 +160,7 @@ export const api = { }) }, - listWebDAVTokens(): Promise<{ - tokens: WebDAVToken[] - }> { + listWebDAVTokens(): Promise<{ tokens: WebDAVToken[] }> { return request('/webdav-tokens') }, @@ -170,8 +176,6 @@ export const api = { return request('/admin/update', { method: 'POST' }) }, - // --- Admin: Volumes --- - adminListVolumes(): Promise<{ volumes: AdminVolume[] }> { return request('/admin/volumes') }, @@ -212,14 +216,10 @@ export const api = { adminRevokeVolumeAccess(volumeId: string, userId: string): Promise<{ ok: boolean }> { return request( `/admin/volumes/${encodeURIComponent(volumeId)}/access/${encodeURIComponent(userId)}`, - { - method: 'DELETE', - }, + { method: 'DELETE' }, ) }, - // --- Admin: Users --- - adminListUsers(): Promise<{ users: AdminUser[] }> { return request('/admin/users') }, @@ -234,8 +234,6 @@ export const api = { return request(`/admin/users/${encodeURIComponent(userId)}/reset-passkeys`, { method: 'POST' }) }, - // --- Admin: Invites --- - adminListInvites(): Promise<{ invites: AdminInvite[] }> { return request('/admin/invites') }, diff --git a/packages/app/src/lib/config.ts b/packages/app/src/lib/config.ts new file mode 100644 index 0000000..4402757 --- /dev/null +++ b/packages/app/src/lib/config.ts @@ -0,0 +1,16 @@ +import { Platform } from 'react-native' + +declare global { + interface Window { + __BASE_PATH__?: string + __APP_NAME__?: string + } +} + +export const BASE_PATH: string = + Platform.OS === 'web' && typeof window !== 'undefined' ? (window.__BASE_PATH__ ?? '') : '' + +export const APP_NAME: string = + Platform.OS === 'web' && typeof window !== 'undefined' + ? (window.__APP_NAME__ ?? 'MiniNAS') + : 'MiniNAS' diff --git a/packages/web/src/lib/fileIcons.tsx b/packages/app/src/lib/fileIcons.tsx similarity index 76% rename from packages/web/src/lib/fileIcons.tsx rename to packages/app/src/lib/fileIcons.tsx index 95e03a4..9ff42fd 100644 --- a/packages/web/src/lib/fileIcons.tsx +++ b/packages/app/src/lib/fileIcons.tsx @@ -7,18 +7,18 @@ import { FileText, FileVideo, Folder, -} from 'lucide-react' +} from 'lucide-react-native' import type { FileEntry } from './api' const iconColorMap: Record = { - folder: 'text-blue-500', - image: 'text-purple-500', - video: 'text-pink-500', - audio: 'text-green-500', - text: 'text-amber-500', - archive: 'text-orange-500', - code: 'text-cyan-600', - default: 'text-gray-400', + folder: '#3b82f6', + image: '#a855f7', + video: '#ec4899', + audio: '#22c55e', + text: '#f59e0b', + archive: '#f97316', + code: '#0891b2', + default: '#9ca3af', } function getFileCategory(entry: FileEntry): string { @@ -34,7 +34,7 @@ function getFileCategory(entry: FileEntry): string { return 'default' } -const iconComponents: Record> = { +const iconComponents: Record = { folder: Folder, image: FileImage, video: FileVideo, @@ -49,7 +49,7 @@ export function getFileIcon(entry: FileEntry, size = 20) { const category = getFileCategory(entry) const Icon = iconComponents[category] const color = iconColorMap[category] - return + return } export function hasThumbnailSupport(entry: FileEntry): boolean { diff --git a/packages/app/src/lib/format.ts b/packages/app/src/lib/format.ts new file mode 100644 index 0000000..90a9eac --- /dev/null +++ b/packages/app/src/lib/format.ts @@ -0,0 +1,25 @@ +export function formatBytes(bytes: number): string { + if (bytes === 0) return '0 B' + const k = 1024 + const sizes = ['B', 'KB', 'MB', 'GB', 'TB'] + const i = Math.floor(Math.log(bytes) / Math.log(k)) + return `${parseFloat((bytes / k ** i).toFixed(1))} ${sizes[i]}` +} + +export function formatDate(iso: string | null): string { + if (!iso) return 'Never' + return new Date(iso).toLocaleDateString(undefined, { + year: 'numeric', + month: 'short', + day: 'numeric', + hour: '2-digit', + minute: '2-digit', + }) +} + +export function formatDateShort(iso: string): string { + return new Date(iso).toLocaleDateString(undefined, { + month: 'short', + day: 'numeric', + }) +} diff --git a/packages/app/src/lib/passkeys.native.ts b/packages/app/src/lib/passkeys.native.ts new file mode 100644 index 0000000..67e3516 --- /dev/null +++ b/packages/app/src/lib/passkeys.native.ts @@ -0,0 +1,41 @@ +import { getApiBase } from './api' + +function authBase() { + return `${getApiBase()}/auth` +} + +export async function registerPasskey(): Promise { + // TODO: Implement native passkey registration via ASAuthorizationController (iOS) + // or FIDO2 API (Android) using an Expo module + throw new Error( + 'Passkey registration is not yet implemented on native. Use the web app to register.', + ) +} + +export async function authenticatePasskey(): Promise { + // TODO: Implement native passkey authentication + throw new Error( + 'Passkey authentication is not yet implemented on native. Use the web app to sign in.', + ) +} + +export async function checkSession(): Promise<{ + authenticated: boolean + user: { id: string; username: string; role: string } | null +}> { + const res = await fetch(`${authBase()}/session`, { credentials: 'include' }) + return res.json() +} + +export async function checkSetupNeeded(): Promise { + const res = await fetch(`${authBase()}/setup-needed`, { credentials: 'include' }) + const data = await res.json() + return data.setupNeeded +} + +export async function logout(): Promise { + await fetch(`${authBase()}/logout`, { + method: 'POST', + credentials: 'include', + }) +} diff --git a/packages/web/src/lib/passkeys.ts b/packages/app/src/lib/passkeys.ts similarity index 71% rename from packages/web/src/lib/passkeys.ts rename to packages/app/src/lib/passkeys.ts index 805d131..4db1584 100644 --- a/packages/web/src/lib/passkeys.ts +++ b/packages/app/src/lib/passkeys.ts @@ -1,11 +1,12 @@ import { startAuthentication, startRegistration } from '@simplewebauthn/browser' -import { withBase } from './basePath' +import { getApiBase } from './api' -const API_BASE = withBase('/api/v1/auth') +function authBase() { + return `${getApiBase()}/auth` +} export async function registerPasskey(): Promise { - // Get registration options - const optionsRes = await fetch(`${API_BASE}/registration/options`, { + const optionsRes = await fetch(`${authBase()}/registration/options`, { credentials: 'include', }) if (!optionsRes.ok) { @@ -14,11 +15,9 @@ export async function registerPasskey(): Promise { } const options = await optionsRes.json() - // Start WebAuthn registration const credential = await startRegistration({ optionsJSON: options }) - // Verify with server - const verifyRes = await fetch(`${API_BASE}/registration/verify`, { + const verifyRes = await fetch(`${authBase()}/registration/verify`, { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, @@ -35,8 +34,7 @@ export async function registerPasskey(): Promise { } export async function authenticatePasskey(): Promise { - // Get authentication options - const optionsRes = await fetch(`${API_BASE}/authentication/options`, { + const optionsRes = await fetch(`${authBase()}/authentication/options`, { credentials: 'include', }) if (!optionsRes.ok) { @@ -45,11 +43,9 @@ export async function authenticatePasskey(): Promise { } const options = await optionsRes.json() - // Start WebAuthn authentication const credential = await startAuthentication({ optionsJSON: options }) - // Verify with server - const verifyRes = await fetch(`${API_BASE}/authentication/verify`, { + const verifyRes = await fetch(`${authBase()}/authentication/verify`, { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, @@ -69,18 +65,18 @@ export async function checkSession(): Promise<{ authenticated: boolean user: { id: string; username: string; role: string } | null }> { - const res = await fetch(`${API_BASE}/session`, { credentials: 'include' }) + const res = await fetch(`${authBase()}/session`, { credentials: 'include' }) return res.json() } export async function checkSetupNeeded(): Promise { - const res = await fetch(`${API_BASE}/setup-needed`, { credentials: 'include' }) + const res = await fetch(`${authBase()}/setup-needed`, { credentials: 'include' }) const data = await res.json() return data.setupNeeded } export async function logout(): Promise { - await fetch(`${API_BASE}/logout`, { + await fetch(`${authBase()}/logout`, { method: 'POST', credentials: 'include', }) diff --git a/packages/app/src/theme/colors.ts b/packages/app/src/theme/colors.ts new file mode 100644 index 0000000..6dd58bf --- /dev/null +++ b/packages/app/src/theme/colors.ts @@ -0,0 +1,52 @@ +export const BrandColor = { + 50: '#eef4fb', + 100: '#d9e6f5', + 200: '#b8cfeb', + 300: '#8ab1dd', + 400: '#6895cb', + 500: '#4a7ab5', + 600: '#3b6399', + 700: '#2f4f7a', + 800: '#1e3554', + 900: '#142640', + 950: '#0b1726', +} as const + +export const AccentColor = { + 400: '#5acece', + 500: '#40b8b8', + 600: '#2f9e9e', +} as const + +export const BackgroundColor = { + primary: '#ffffff', + secondary: '#f9fafb', + tertiary: '#f3f4f6', +} as const + +export const TextColor = { + primary: '#111827', + secondary: '#6b7280', + tertiary: '#9ca3af', + inverse: '#ffffff', +} as const + +export const BorderColor = { + primary: '#e5e7eb', + secondary: '#f3f4f6', +} as const + +export const StatusColor = { + success: '#059669', + successLight: '#d1fae5', + successText: '#065f46', + error: '#ef4444', + errorLight: '#fee2e2', + errorText: '#991b1b', + warning: '#f59e0b', + warningLight: '#fef3c7', + warningText: '#92400e', + info: '#3b82f6', + infoLight: '#dbeafe', + infoText: '#1e40af', +} as const diff --git a/packages/app/src/theme/index.ts b/packages/app/src/theme/index.ts new file mode 100644 index 0000000..f66a7c2 --- /dev/null +++ b/packages/app/src/theme/index.ts @@ -0,0 +1,6 @@ +import * as Colors from './colors' +import * as Outlines from './outlines' +import * as Sizing from './sizing' +import * as Typography from './typography' + +export { Colors, Outlines, Sizing, Typography } diff --git a/packages/app/src/theme/outlines.ts b/packages/app/src/theme/outlines.ts new file mode 100644 index 0000000..568095f --- /dev/null +++ b/packages/app/src/theme/outlines.ts @@ -0,0 +1,34 @@ +import { Platform, StyleSheet } from 'react-native' + +export const borderRadius = { + sm: 6, + md: 8, + lg: 12, + xl: 16, + xxl: 24, + full: 9999, +} as const + +export const borderWidth = { + thin: StyleSheet.hairlineWidth, + normal: 1, +} as const + +function makeShadow(offsetY: number, radius: number, opacity: number, elevation: number) { + if (Platform.OS === 'android') { + return { elevation } + } + return { + shadowColor: '#000', + shadowOffset: { width: 0, height: offsetY }, + shadowOpacity: opacity, + shadowRadius: radius, + } +} + +export const shadow = { + sm: makeShadow(1, 2, 0.05, 1), + md: makeShadow(2, 4, 0.1, 3), + lg: makeShadow(4, 8, 0.15, 6), + xl: makeShadow(8, 16, 0.2, 10), +} as const diff --git a/packages/app/src/theme/sizing.ts b/packages/app/src/theme/sizing.ts new file mode 100644 index 0000000..8f6a6c6 --- /dev/null +++ b/packages/app/src/theme/sizing.ts @@ -0,0 +1,26 @@ +export const layout = { + x1: 1, + x2: 2, + x4: 4, + x8: 8, + x12: 12, + x16: 16, + x20: 20, + x24: 24, + x32: 32, + x40: 40, + x48: 48, + x64: 64, + x80: 80, +} as const + +export const gutters = { + base: 16, + half: 8, + double: 32, +} as const + +export const touchable = { + minHeight: 44, + minWidth: 44, +} as const diff --git a/packages/app/src/theme/typography.ts b/packages/app/src/theme/typography.ts new file mode 100644 index 0000000..bd311ee --- /dev/null +++ b/packages/app/src/theme/typography.ts @@ -0,0 +1,50 @@ +import { Platform } from 'react-native' + +const fontFamily = Platform.select({ + ios: undefined, // System font (San Francisco) + android: undefined, // System font (Roboto) + web: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif', +}) + +export const title = { + fontSize: 24, + fontWeight: '700' as const, + fontFamily, +} + +export const heading = { + fontSize: 20, + fontWeight: '600' as const, + fontFamily, +} + +export const body = { + fontSize: 14, + fontWeight: '400' as const, + fontFamily, +} + +export const bodySmall = { + fontSize: 12, + fontWeight: '400' as const, + fontFamily, +} + +export const caption = { + fontSize: 11, + fontWeight: '400' as const, + fontFamily, +} + +export const button = { + fontSize: 14, + fontWeight: '500' as const, + fontFamily, +} + +export const fontWeight = { + regular: '400' as const, + medium: '500' as const, + semibold: '600' as const, + bold: '700' as const, +} diff --git a/packages/app/tsconfig.json b/packages/app/tsconfig.json new file mode 100644 index 0000000..dee9f39 --- /dev/null +++ b/packages/app/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "expo/tsconfig.base", + "compilerOptions": { + "strict": true, + "baseUrl": ".", + "paths": { + "@/*": ["./src/*"] + } + }, + "include": ["**/*.ts", "**/*.tsx", ".expo/types/**/*.ts", "expo-env.d.ts"] +} diff --git a/packages/web/astro.config.mjs b/packages/web/astro.config.mjs deleted file mode 100644 index 4ab16e3..0000000 --- a/packages/web/astro.config.mjs +++ /dev/null @@ -1,94 +0,0 @@ -import fs from 'node:fs' -import http from 'node:http' -import os from 'node:os' -import path from 'node:path' -import react from '@astrojs/react' -import tailwind from '@astrojs/tailwind' -import { defineConfig } from 'astro/config' - -function loadAppName() { - // Read from ~/.mininas/config.json, then .env (same priority as API config) - let name = 'MiniNAS' - try { - const cfg = JSON.parse( - fs.readFileSync(path.join(os.homedir(), '.mininas', 'config.json'), 'utf-8'), - ) - if (cfg.APP_NAME) name = cfg.APP_NAME - } catch {} - try { - const env = fs.readFileSync(path.resolve(import.meta.dirname, '../../.env'), 'utf-8') - const match = env.match(/^APP_NAME=(.+)$/m) - if (match) name = match[1].trim() - } catch {} - // Real env var wins - if (process.env.APP_NAME) name = process.env.APP_NAME - return name -} - -// Rewrite /volumes/X/Y/Z to /volumes so the catch-all [...path].astro -// page is served for all sub-paths (used in both dev and preview). -function volumesFallback(req, _res, next) { - if (req.url?.startsWith('/volumes/') && !req.url.includes('.')) { - req.url = '/volumes' - } - next() -} - -export default defineConfig({ - devToolbar: { enabled: false }, - integrations: [react(), tailwind()], - server: { port: 4321, host: '0.0.0.0' }, - vite: { - define: { - __APP_NAME_DEFAULT__: JSON.stringify(loadAppName()), - }, - plugins: [ - { - name: 'volumes-spa-fallback', - configureServer(server) { - server.middlewares.use(volumesFallback) - }, - }, - { - name: 'webdav-proxy', - configureServer(server) { - // Raw HTTP proxy for /dav so that WebDAV methods (OPTIONS, - // PROPFIND, LOCK, etc.) are forwarded before Vite's built-in - // CORS/OPTIONS handling can intercept them. - server.middlewares.use((req, res, next) => { - if (!req.url || !req.url.startsWith('/dav')) { - return next() - } - const proxyReq = http.request( - { - hostname: 'localhost', - port: 3001, - path: req.url, - method: req.method, - headers: { ...req.headers, host: 'localhost:3001' }, - }, - (proxyRes) => { - res.writeHead(proxyRes.statusCode, proxyRes.headers) - proxyRes.pipe(res) - }, - ) - proxyReq.on('error', () => { - res.writeHead(502) - res.end('Bad Gateway') - }) - req.pipe(proxyReq) - }) - }, - }, - ], - server: { - allowedHosts: ['.ts.net'], - proxy: { - '/api': { - target: 'http://localhost:3001', - changeOrigin: true, - }, - }, - }, - }, -}) diff --git a/packages/web/package.json b/packages/web/package.json deleted file mode 100644 index a6fe54d..0000000 --- a/packages/web/package.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "@mininas/web", - "version": "0.0.1", - "private": true, - "type": "module", - "scripts": { - "dev": "astro dev", - "build": "astro build", - "preview": "node preview.mjs --host" - }, - "dependencies": { - "astro": "^5.3.0", - "@astrojs/react": "^4.2.0", - "@astrojs/tailwind": "^6.0.0", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "@tanstack/react-query": "^5.66.0", - "tailwindcss": "^3.4.0", - "lucide-react": "^0.474.0", - "@simplewebauthn/browser": "^13.1.0", - "tus-js-client": "^4.3.0" - }, - "devDependencies": { - "@types/react": "^19.0.0", - "@types/react-dom": "^19.0.0", - "typescript": "^5.7.0" - } -} diff --git a/packages/web/preview.mjs b/packages/web/preview.mjs deleted file mode 100644 index 481c812..0000000 --- a/packages/web/preview.mjs +++ /dev/null @@ -1,92 +0,0 @@ -import { readFileSync, statSync } from 'node:fs' -import { createServer } from 'node:http' -import { extname, join } from 'node:path' - -const dist = new URL('./dist', import.meta.url).pathname -const port = parseInt(process.argv.find((a) => a.match(/^\d+$/)) || '4321') -const host = process.argv.includes('--host') ? '0.0.0.0' : '127.0.0.1' - -// Optional base path support -function normalizeBasePath(raw) { - if (!raw) return '' - let p = raw.trim() - if (!p.startsWith('/')) p = '/' + p - return p.replace(/\/+$/, '') -} -const basePath = normalizeBasePath(process.env.BASE_PATH || '') - -const mimeTypes = { - '.html': 'text/html', - '.js': 'application/javascript', - '.css': 'text/css', - '.json': 'application/json', - '.png': 'image/png', - '.jpg': 'image/jpeg', - '.svg': 'image/svg+xml', - '.woff2': 'font/woff2', - '.woff': 'font/woff', - '.ico': 'image/x-icon', -} - -function isFile(p) { - try { - return statSync(p).isFile() - } catch { - return false - } -} - -function tryFile(urlPath) { - let file = join(dist, urlPath) - if (isFile(file)) return file - file = join(dist, urlPath, 'index.html') - if (isFile(file)) return file - return null -} - -createServer((req, res) => { - const url = new URL(req.url, `http://${req.headers.host}`) - let pathname = url.pathname - - // Strip basePath before file lookup - if (basePath && pathname.startsWith(basePath)) { - pathname = pathname.slice(basePath.length) || '/' - } - - let filePath = tryFile(pathname) - - // SPA fallback: /volumes/X/Y/Z -> /volumes/index.html - if (!filePath && pathname.startsWith('/volumes/') && !extname(pathname)) { - filePath = join(dist, 'volumes', 'index.html') - } - - if (!filePath) { - res.writeHead(404, { 'Content-Type': 'text/plain' }) - res.end('Not Found') - return - } - - const ext = extname(filePath) - const mime = mimeTypes[ext] || 'application/octet-stream' - let body = readFileSync(filePath) - - // Inject __BASE_PATH__ into HTML files - if (ext === '.html') { - let html = body.toString('utf-8') - html = html.replace('', ``) - if (basePath) { - html = html.replace(/href="\//g, `href="${basePath}/`) - html = html.replace(/src="\//g, `src="${basePath}/`) - } - body = html - } - - res.writeHead(200, { - 'Content-Type': mime, - 'Cache-Control': ext === '.html' ? 'no-cache' : 'public, max-age=31536000, immutable', - }) - res.end(body) -}).listen(port, host, () => { - const prefix = basePath || '' - console.log(`Preview server: http://${host}:${port}${prefix}/`) -}) diff --git a/packages/web/public/apple-touch-icon.png b/packages/web/public/apple-touch-icon.png deleted file mode 100644 index 83562fa..0000000 Binary files a/packages/web/public/apple-touch-icon.png and /dev/null differ diff --git a/packages/web/public/favicon-16x16.png b/packages/web/public/favicon-16x16.png deleted file mode 100644 index edc5ff0..0000000 Binary files a/packages/web/public/favicon-16x16.png and /dev/null differ diff --git a/packages/web/public/favicon-32x32.png b/packages/web/public/favicon-32x32.png deleted file mode 100644 index b1f4136..0000000 Binary files a/packages/web/public/favicon-32x32.png and /dev/null differ diff --git a/packages/web/public/favicon.ico b/packages/web/public/favicon.ico deleted file mode 100644 index b22a64b..0000000 Binary files a/packages/web/public/favicon.ico and /dev/null differ diff --git a/packages/web/public/icon-192.png b/packages/web/public/icon-192.png deleted file mode 100644 index 363a64c..0000000 Binary files a/packages/web/public/icon-192.png and /dev/null differ diff --git a/packages/web/public/icon-512.png b/packages/web/public/icon-512.png deleted file mode 100644 index 71a5b44..0000000 Binary files a/packages/web/public/icon-512.png and /dev/null differ diff --git a/packages/web/public/logo.png b/packages/web/public/logo.png deleted file mode 100644 index b8e730a..0000000 Binary files a/packages/web/public/logo.png and /dev/null differ diff --git a/packages/web/public/manifest.json b/packages/web/public/manifest.json deleted file mode 100644 index 6d2d089..0000000 --- a/packages/web/public/manifest.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "name": "MiniNAS", - "short_name": "MiniNAS", - "description": "Personal Network Attached Storage", - "start_url": "/", - "display": "standalone", - "background_color": "#030712", - "theme_color": "#030712", - "orientation": "any", - "icons": [ - { - "src": "/favicon-16x16.png", - "sizes": "16x16", - "type": "image/png" - }, - { - "src": "/favicon-32x32.png", - "sizes": "32x32", - "type": "image/png" - }, - { - "src": "/icon-192.png", - "sizes": "192x192", - "type": "image/png" - }, - { - "src": "/icon-512.png", - "sizes": "512x512", - "type": "image/png", - "purpose": "any maskable" - } - ] -} diff --git a/packages/web/src/components/AdminPanel.tsx b/packages/web/src/components/AdminPanel.tsx deleted file mode 100644 index 4b62706..0000000 --- a/packages/web/src/components/AdminPanel.tsx +++ /dev/null @@ -1,749 +0,0 @@ -import { QueryClient, QueryClientProvider } from '@tanstack/react-query' -import { - ArrowLeft, - Check, - ChevronDown, - ChevronRight, - Eye, - EyeOff, - HardDrive, - KeyRound, - Loader2, - Mail, - Plus, - Shield, - Trash2, - UserPlus, - Users, - X, -} from 'lucide-react' -import { useCallback, useEffect, useState } from 'react' -import { - useAddVolume, - useAdminInvites, - useAdminUsers, - useAdminVolumes, - useAvailableVolumes, - useCreateInvite, - useDeleteInvite, - useDeleteUser, - useGrantVolumeAccess, - useRemoveVolume, - useResetPasskeys, - useRevokeVolumeAccess, - useSetVolumeVisibility, - useVolumeAccess, -} from '../hooks/useAdmin' -import { useAuth } from '../hooks/useAuth' -import type { AdminVolume } from '../lib/api' -import { APP_NAME } from '../lib/appName' -import { withBase } from '../lib/basePath' -import UpdateSection from './UpdateSection' -import Badge from './ui/Badge' -import Tabs from './ui/Tabs' - -const queryClient = new QueryClient({ - defaultOptions: { queries: { staleTime: 30_000, retry: 1 } }, -}) - -function formatDate(dateStr: string | null): string { - if (!dateStr) return 'Never' - return new Date(dateStr).toLocaleDateString(undefined, { - year: 'numeric', - month: 'short', - day: 'numeric', - hour: '2-digit', - minute: '2-digit', - }) -} - -function getInviteStatus(invite: { - used_at: string | null - expires_at: string -}): 'used' | 'expired' | 'pending' { - if (invite.used_at) return 'used' - if (new Date(invite.expires_at) < new Date()) return 'expired' - return 'pending' -} - -// --- Volume Access Sub-component --- - -function VolumeAccessPanel({ - volumeId, - allUsers, -}: { - volumeId: string - allUsers: { id: string; username: string; role?: string }[] -}) { - const { data, isLoading } = useVolumeAccess(volumeId) - const grantMutation = useGrantVolumeAccess() - const revokeMutation = useRevokeVolumeAccess() - const [selectedUserId, setSelectedUserId] = useState('') - - const accessUserIds = new Set(data?.users?.map((u) => u.id) || []) - const nonAdminUsers = allUsers.filter((u) => u.role !== 'admin') - const availableUsers = nonAdminUsers.filter((u) => !accessUserIds.has(u.id)) - - const handleGrant = () => { - if (!selectedUserId) return - grantMutation.mutate({ volumeId, userId: selectedUserId }) - setSelectedUserId('') - } - - return ( -
-

Access List

- {isLoading ? ( - - ) : !data?.users?.length ? ( -

No users have explicit access.

- ) : ( -
- {data.users.map((u) => ( -
- {u.username} - -
- ))} -
- )} - {availableUsers.length > 0 && ( -
- - -
- )} -
- ) -} - -// --- Add Volume Modal --- - -function labelToId(label: string): string { - return label - .toLowerCase() - .replace(/[^a-z0-9]+/g, '-') - .replace(/^-+|-+$/g, '') -} - -function AddVolumeModal({ - onClose, - addMutation, -}: { - onClose: () => void - addMutation: ReturnType -}) { - const { data, isLoading } = useAvailableVolumes(true) - const [selectedPath, setSelectedPath] = useState(null) - const [selectedName, setSelectedName] = useState('') - const [label, setLabel] = useState('') - const [customId, setCustomId] = useState('') - const [useCustomId, setUseCustomId] = useState(false) - - const inferredId = labelToId(label) - const finalId = useCustomId ? customId.trim() : inferredId - - const handleSelect = (vol: { name: string; path: string }) => { - setSelectedPath(vol.path) - setSelectedName(vol.name) - setLabel(vol.name) - setCustomId('') - setUseCustomId(false) - } - - const handleSubmit = async () => { - if (!selectedPath || !label.trim() || !finalId) return - await addMutation.mutateAsync({ - id: finalId, - label: label.trim(), - path: selectedPath, - }) - onClose() - } - - const handleEscape = useCallback( - (e: KeyboardEvent) => { - if (e.key === 'Escape') onClose() - }, - [onClose], - ) - - useEffect(() => { - document.addEventListener('keydown', handleEscape) - return () => document.removeEventListener('keydown', handleEscape) - }, [handleEscape]) - - return ( -
-
e.stopPropagation()} - > - {/* Header */} -
-

Add Volume

- -
- - {/* Body */} -
- {/* Step 1: Select a volume */} -
-

Select a volume

- {isLoading ? ( -
- -
- ) : !data?.volumes?.length ? ( -

No available volumes found.

- ) : ( -
- {data.volumes.map((vol) => ( - - ))} -
- )} -
- - {/* Step 2: Label & ID (shown after selection) */} - {selectedPath && ( -
-
- - setLabel(e.target.value)} - placeholder={selectedName} - className="w-full bg-gray-50 border border-gray-200 rounded-md px-3 py-1.5 text-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-brand-500" - /> -
- -
- - Set custom ID -
- - {useCustomId ? ( -
- setCustomId(e.target.value)} - placeholder="custom-id" - className="w-full bg-gray-50 border border-gray-200 rounded-md px-3 py-1.5 text-sm font-mono placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-brand-500" - /> -
- ) : ( - inferredId && ( -

- ID: {inferredId} -

- ) - )} -
- )} - - {addMutation.isError && ( -

{(addMutation.error as Error).message}

- )} -
- - {/* Footer */} -
- - -
-
-
- ) -} - -// --- Volumes Section --- - -function VolumesSection() { - const { data, isLoading } = useAdminVolumes() - const addMutation = useAddVolume() - const removeMutation = useRemoveVolume() - const visibilityMutation = useSetVolumeVisibility() - const { data: usersData } = useAdminUsers() - const [expandedVolume, setExpandedVolume] = useState(null) - const [showAddModal, setShowAddModal] = useState(false) - - const handleRemove = (vol: AdminVolume) => { - if ( - confirm( - `Remove volume "${vol.label}" (${vol.id})? This only removes it from ${APP_NAME} — files on disk are not deleted.`, - ) - ) { - removeMutation.mutate(vol.id) - } - } - - const toggleVisibility = (vol: AdminVolume) => { - const next = vol.visibility === 'public' ? 'private' : 'public' - visibilityMutation.mutate({ id: vol.id, visibility: next }) - } - - return ( -
-
-
- -

Volumes

-
- -
- - {showAddModal && ( - setShowAddModal(false)} addMutation={addMutation} /> - )} - - {/* Volume List */} - {isLoading ? ( -
- -
- ) : !data?.volumes?.length ? ( -
No volumes configured.
- ) : ( -
- {data.volumes.map((vol) => ( -
-
-
- -
-

{vol.label}

-

- {vol.id} · {vol.path} -

-
-
-
- - -
-
- {expandedVolume === vol.id && vol.visibility === 'public' && ( -
-

- Public volumes are accessible to all users — no access list needed. -

-
- )} - {expandedVolume === vol.id && vol.visibility === 'private' && ( - ({ - id: u.id, - username: u.username, - role: u.role, - }))} - /> - )} -
- ))} -
- )} -
- ) -} - -// --- Users Section --- - -function UsersSection() { - const { data, isLoading } = useAdminUsers() - const deleteMutation = useDeleteUser() - const resetMutation = useResetPasskeys() - - const handleDelete = (user: { id: string; username: string }) => { - if (confirm(`Delete user "${user.username}"? This cannot be undone.`)) { - deleteMutation.mutate(user.id) - } - } - - const handleResetPasskeys = (user: { id: string; username: string }) => { - if (confirm(`Reset all passkeys for "${user.username}"? They will need to re-register.`)) { - resetMutation.mutate(user.id) - } - } - - return ( -
-
- -

Users

-
- - {isLoading ? ( -
- -
- ) : !data?.users?.length ? ( -
No users found.
- ) : ( -
- {data.users.map((user) => ( -
-
-
-

{user.username}

- {user.role === 'admin' && admin} -
-

Created {formatDate(user.created_at)}

-
-
- - -
-
- ))} -
- )} - - {(deleteMutation.isError || resetMutation.isError) && ( -
-

- {((deleteMutation.error || resetMutation.error) as Error)?.message} -

-
- )} -
- ) -} - -// --- Invites Section --- - -function InvitesSection() { - const { data, isLoading } = useAdminInvites() - const createMutation = useCreateInvite() - const deleteMutation = useDeleteInvite() - - const [username, setUsername] = useState('') - const [expiresInHours, setExpiresInHours] = useState('24') - - const handleCreate = async () => { - if (!username.trim()) return - const hours = parseInt(expiresInHours, 10) - await createMutation.mutateAsync({ - username: username.trim(), - expiresInHours: isNaN(hours) ? undefined : hours, - }) - setUsername('') - } - - const handleDelete = (id: string) => { - if (confirm('Delete this invite?')) { - deleteMutation.mutate(id) - } - } - - const statusBadge = (status: 'pending' | 'used' | 'expired') => { - const variantMap = { pending: 'info', used: 'success', expired: 'default' } as const - return {status} - } - - return ( -
-
- -

Invites

-
- - {/* Create Invite Form */} -
-
- setUsername(e.target.value)} - onKeyDown={(e) => e.key === 'Enter' && handleCreate()} - placeholder="Username for invite" - className="flex-1 bg-gray-50 border border-gray-200 rounded-md px-3 py-1.5 text-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-brand-500" - /> - - -
- {createMutation.isError && ( -

{(createMutation.error as Error).message}

- )} -
- - {/* Invite List */} - {isLoading ? ( -
- -
- ) : !data?.invites?.length ? ( -
No invites yet.
- ) : ( -
- {data.invites.map((invite) => { - const status = getInviteStatus(invite) - return ( -
-
-
-

{invite.username}

- {statusBadge(status)} -
-

- Expires {formatDate(invite.expires_at)} - {invite.used_at && ` · Used ${formatDate(invite.used_at)}`} -

-
- -
- ) - })} -
- )} -
- ) -} - -// --- Main Admin Panel --- - -const adminTabs = [ - { id: 'storage', label: 'Storage' }, - { id: 'users', label: 'Users' }, - { id: 'system', label: 'System' }, -] - -function AdminPanelInner() { - const { isAuthenticated, isLoading: authLoading, user } = useAuth() - const [activeTab, setActiveTab] = useState('storage') - - if (authLoading) { - return ( -
- -
- ) - } - - if (!isAuthenticated) { - if (typeof window !== 'undefined') window.location.href = withBase('/login') - return null - } - - if (user?.role !== 'admin') { - if (typeof window !== 'undefined') window.location.href = withBase('/') - return null - } - - return ( -
- {/* Header */} -
- - - -
- -

Admin

-
-
- - - -
- {activeTab === 'storage' && } - {activeTab === 'users' && ( - <> - - - - )} - {activeTab === 'system' && } -
-
- ) -} - -export default function AdminPanel() { - return ( - - - - ) -} diff --git a/packages/web/src/components/Breadcrumbs.tsx b/packages/web/src/components/Breadcrumbs.tsx deleted file mode 100644 index 3d677d7..0000000 --- a/packages/web/src/components/Breadcrumbs.tsx +++ /dev/null @@ -1,120 +0,0 @@ -import { ChevronRight, Home, MoreHorizontal } from 'lucide-react' -import { useEffect, useRef, useState } from 'react' - -interface BreadcrumbSegment { - label: string - path: string -} - -interface BreadcrumbsProps { - segments: BreadcrumbSegment[] - onNavigate: (path: string) => void -} - -export default function Breadcrumbs({ segments, onNavigate }: BreadcrumbsProps) { - const [dropdownOpen, setDropdownOpen] = useState(false) - const dropdownRef = useRef(null) - - useEffect(() => { - const handleClickOutside = (e: MouseEvent) => { - if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) { - setDropdownOpen(false) - } - } - document.addEventListener('mousedown', handleClickOutside) - return () => document.removeEventListener('mousedown', handleClickOutside) - }, []) - - const showCollapsed = segments.length > 2 - - return ( - - ) -} diff --git a/packages/web/src/components/ContextMenu.tsx b/packages/web/src/components/ContextMenu.tsx deleted file mode 100644 index 5a1d7f6..0000000 --- a/packages/web/src/components/ContextMenu.tsx +++ /dev/null @@ -1,121 +0,0 @@ -import { Download, Eye, Link2, Pencil, Trash2 } from 'lucide-react' -import { useEffect, useRef } from 'react' -import type { FileEntry } from '../lib/api' - -interface ContextMenuProps { - x: number - y: number - file: FileEntry - onClose: () => void - onDownload: () => void - onDelete: () => void - onShare: () => void - onPreview: () => void - onRename: () => void -} - -export default function ContextMenu({ - x, - y, - file, - onClose, - onDownload, - onDelete, - onShare, - onPreview, - onRename, -}: ContextMenuProps) { - const ref = useRef(null) - - useEffect(() => { - const handleClick = (e: MouseEvent) => { - if (ref.current && !ref.current.contains(e.target as Node)) { - onClose() - } - } - const handleEsc = (e: KeyboardEvent) => { - if (e.key === 'Escape') onClose() - } - document.addEventListener('mousedown', handleClick) - document.addEventListener('keydown', handleEsc) - return () => { - document.removeEventListener('mousedown', handleClick) - document.removeEventListener('keydown', handleEsc) - } - }, [onClose]) - - // Adjust position to stay within viewport - const adjustedX = Math.min(x, window.innerWidth - 200) - const adjustedY = Math.min(y, window.innerHeight - 250) - - return ( -
- {!file.isDirectory && ( - - )} - {!file.isDirectory && ( - - )} - {!file.isDirectory && ( - - )} - -
- -
- ) -} diff --git a/packages/web/src/components/FileBrowser.tsx b/packages/web/src/components/FileBrowser.tsx deleted file mode 100644 index 88eae9e..0000000 --- a/packages/web/src/components/FileBrowser.tsx +++ /dev/null @@ -1,582 +0,0 @@ -import { QueryClient, QueryClientProvider } from '@tanstack/react-query' -import { - Download, - FolderPlus, - HardDrive, - LayoutGrid, - List, - Loader2, - LogOut, - RefreshCw, - Settings, - Shield, - Trash2, - Upload, - UploadCloud, - X, -} from 'lucide-react' -import { useCallback, useEffect, useMemo, useRef, useState } from 'react' -import { useAuth } from '../hooks/useAuth' -import { useCreateDirectory, useDeleteFile, useFiles } from '../hooks/useFiles' -import { useSelection } from '../hooks/useSelection' -import { useToast } from '../hooks/useToast' -import { useUpload } from '../hooks/useUpload' -import type { FileEntry } from '../lib/api' -import { api } from '../lib/api' -import { APP_NAME } from '../lib/appName' -import { BASE_PATH, withBase } from '../lib/basePath' -import { getFilesFromDataTransfer } from '../lib/drop' -import Breadcrumbs from './Breadcrumbs' -import ContextMenu from './ContextMenu' -import FileGrid from './FileGrid' -import FileList from './FileList' -import PreviewModal from './PreviewModal' -import SearchBar from './SearchBar' -import ShareDialog from './ShareDialog' -import UploadProgress from './UploadProgress' -import UploadZone from './UploadZone' -import EmptyState from './ui/EmptyState' -import { FileGridSkeleton, FileListSkeleton } from './ui/Skeleton' -import ToastContainer from './ui/Toast' -import VolumeSelector from './VolumeSelector' - -const queryClient = new QueryClient({ - defaultOptions: { - queries: { staleTime: 30_000, retry: 1 }, - }, -}) - -function parsePath(pathname: string): { volume: string; path: string } { - let p = pathname - if (BASE_PATH && p.startsWith(BASE_PATH)) { - p = p.slice(BASE_PATH.length) - } - const match = p.match(/^\/volumes\/([^/]+)(?:\/(.*))?$/) - if (!match) return { volume: '', path: '' } - return { - volume: decodeURIComponent(match[1]), - path: match[2] ? decodeURIComponent(match[2]).replace(/\/$/, '') : '', - } -} - -function buildUrl(vol: string, pathStr: string): string { - let url = '/volumes' - if (vol) { - url += `/${encodeURIComponent(vol)}` - if (pathStr) { - url += '/' + pathStr.split('/').map(encodeURIComponent).join('/') - } - } - return withBase(url) -} - -function FileBrowserInner() { - const { isAuthenticated, isLoading: authLoading, user, logout } = useAuth() - - // Single source of truth: the URL pathname. - // volume and currentPath are derived from it — no stale closure issues. - const [locationPath, setLocationPath] = useState(() => - typeof window !== 'undefined' ? window.location.pathname : '/volumes', - ) - const isInitialNav = useRef(true) - - const { volume, path: currentPath } = useMemo(() => parsePath(locationPath), [locationPath]) - - const { data, isLoading, error, refetch } = useFiles(volume, currentPath) - - const { toasts, addToast, removeToast } = useToast() - const deleteMutation = useDeleteFile(volume, currentPath) - const mkdirMutation = useCreateDirectory(volume, currentPath) - const { uploads, addFiles, pauseUpload, resumeUpload, cancelUpload, clearCompleted } = useUpload( - volume, - currentPath, - refetch, - ) - const [showUploadZone, setShowUploadZone] = useState(false) - const [previewFile, setPreviewFile] = useState(null) - const [shareFile, setShareFile] = useState(null) - const [viewMode, setViewMode] = useState<'list' | 'grid'>('list') - const [refreshSpinning, setRefreshSpinning] = useState(false) - const [contextMenu, setContextMenu] = useState<{ x: number; y: number; file: FileEntry } | null>( - null, - ) - const { - selected, - toggle: toggleSelection, - selectRange, - selectAll, - clear: clearSelection, - count: selectionCount, - lastToggled, - } = useSelection() - - const fileAreaRef = useRef(null) - - useEffect(() => { - if (selectionCount === 0) return - const onClick = (e: MouseEvent) => { - if (fileAreaRef.current?.contains(e.target as Node)) return - // Don't clear if clicking inside the bulk action bar - if ((e.target as HTMLElement).closest('[data-bulk-actions]')) return - clearSelection() - } - window.addEventListener('click', onClick) - return () => window.removeEventListener('click', onClick) - }, [selectionCount, clearSelection]) - - // Global drag-and-drop: show overlay when files are dragged anywhere on page - const [globalDragging, setGlobalDragging] = useState(false) - const dragCounter = useRef(0) - - useEffect(() => { - const onDragEnter = (e: DragEvent) => { - e.preventDefault() - dragCounter.current++ - if (e.dataTransfer?.types.includes('Files')) { - setGlobalDragging(true) - } - } - const onDragLeave = (e: DragEvent) => { - e.preventDefault() - dragCounter.current-- - if (dragCounter.current === 0) { - setGlobalDragging(false) - } - } - const onDragOver = (e: DragEvent) => { - e.preventDefault() - } - const onDrop = async (e: DragEvent) => { - e.preventDefault() - dragCounter.current = 0 - setGlobalDragging(false) - if (!volume || !e.dataTransfer) return - const files = await getFilesFromDataTransfer(e.dataTransfer) - if (files.length > 0) { - addFiles(files) - } - } - window.addEventListener('dragenter', onDragEnter) - window.addEventListener('dragleave', onDragLeave) - window.addEventListener('dragover', onDragOver) - window.addEventListener('drop', onDrop) - return () => { - window.removeEventListener('dragenter', onDragEnter) - window.removeEventListener('dragleave', onDragLeave) - window.removeEventListener('dragover', onDragOver) - window.removeEventListener('drop', onDrop) - } - }, [volume, addFiles]) - - // Navigate to a directory path within the current volume - const navigateTo = useCallback( - (newPath: string) => { - // Read volume fresh from current locationPath to avoid stale closures - const { volume: currentVol } = parsePath( - typeof window !== 'undefined' ? window.location.pathname : '/volumes', - ) - const url = buildUrl(currentVol, newPath) - history.pushState(null, '', url) - setLocationPath(url) - setPreviewFile(null) - clearSelection() - }, - [clearSelection], - ) - - // Handle volume selection - const handleVolumeSelect = useCallback((id: string) => { - const url = buildUrl(id, '') - if (isInitialNav.current) { - isInitialNav.current = false - history.replaceState(null, '', url) - } else { - history.pushState(null, '', url) - } - setLocationPath(url) - setPreviewFile(null) - }, []) - - // Handle browser back/forward - useEffect(() => { - const onPopState = () => { - setLocationPath(window.location.pathname) - setPreviewFile(null) - } - window.addEventListener('popstate', onPopState) - return () => window.removeEventListener('popstate', onPopState) - }, []) - - const handleContextMenu = useCallback((file: FileEntry, x: number, y: number) => { - setContextMenu({ x, y, file }) - }, []) - - const handleRename = useCallback( - (file: FileEntry) => { - const newName = prompt('Rename to:', file.name) - if (newName && newName !== file.name) { - const parentPath = file.path.includes('/') - ? file.path.split('/').slice(0, -1).join('/') - : '' - const destination = parentPath ? `${parentPath}/${newName}` : newName - api.moveFile(volume, file.path, destination).then( - () => { - addToast('success', `Renamed to "${newName}"`) - refetch() - }, - (err) => addToast('error', `Rename failed: ${(err as Error).message}`), - ) - } - }, - [volume, addToast, refetch], - ) - - const handleNewFolder = useCallback(() => { - const name = prompt('New folder name:') - if (name) { - mkdirMutation.mutate(name, { - onSuccess: () => addToast('success', `Created folder "${name}"`), - onError: (err) => addToast('error', `Failed to create folder: ${(err as Error).message}`), - }) - } - }, [mkdirMutation, addToast]) - - // Build breadcrumb segments - const pathParts = currentPath.split('/').filter(Boolean) - const breadcrumbs = pathParts.map((part, i) => ({ - label: part, - path: pathParts.slice(0, i + 1).join('/'), - })) - - if (authLoading) { - return ( -
- -
- ) - } - - if (!isAuthenticated) { - if (typeof window !== 'undefined') window.location.href = withBase('/login') - return null - } - - return ( -
0 ? 'pb-20' : ''}`}> - {/* Header */} -
- - {APP_NAME} -

{APP_NAME}

-
-
- - {user?.role === 'admin' && ( - - - - )} - - - - -
-
- - {/* Search */} - {volume && ( -
- -
- )} - - {/* Toolbar */} -
- {/* Breadcrumbs */} - - - {/* Actions */} -
- {volume && ( - - )} - -
- - -
- -
-
- - {/* Upload Zone */} - {showUploadZone && volume && ( -
- { - addFiles(files) - setShowUploadZone(false) - }} - /> -
- )} - - {/* Bulk Action Bar - fixed bottom */} -
0 ? 'translate-y-0' : 'translate-y-full'}`} - > -
-
- - {selectionCount} selected - -
- - - -
-
-
-
- - {/* Content */} -
- {!volume ? ( - - ) : isLoading ? ( - viewMode === 'list' ? ( - - ) : ( - - ) - ) : error ? ( -
- Error loading files: {(error as Error).message} -
- ) : viewMode === 'list' ? ( - - deleteMutation.mutate(path, { - onSuccess: () => addToast('success', 'File deleted'), - onError: (err) => addToast('error', `Delete failed: ${(err as Error).message}`), - }) - } - onPreview={setPreviewFile} - onShare={setShareFile} - onContextMenu={handleContextMenu} - selectable - selected={selected} - onToggle={toggleSelection} - onShiftSelect={selectRange} - lastToggled={lastToggled} - onSelectAll={(paths) => (paths.length > 0 ? selectAll(paths) : clearSelection())} - /> - ) : ( - - )} -
- {/* Preview Modal */} - {previewFile && ( - setPreviewFile(null)} /> - )} - - {/* Share Dialog */} - {shareFile && ( - setShareFile(null)} /> - )} - - {/* Context Menu */} - {contextMenu && ( - setContextMenu(null)} - onPreview={() => setPreviewFile(contextMenu.file)} - onDownload={() => { - window.open(api.getDownloadUrl(volume, contextMenu.file.path), '_blank') - }} - onShare={() => setShareFile(contextMenu.file)} - onRename={() => handleRename(contextMenu.file)} - onDelete={() => { - if (confirm(`Delete "${contextMenu.file.name}"?`)) { - deleteMutation.mutate(contextMenu.file.path, { - onSuccess: () => addToast('success', 'File deleted'), - onError: (err) => addToast('error', `Delete failed: ${(err as Error).message}`), - }) - } - }} - /> - )} - - {/* Upload Progress Panel */} - - - {/* Global drag-and-drop overlay */} - {globalDragging && volume && ( -
-
- -

Drop files to upload

-
-
- )} - - -
- ) -} - -export default function FileBrowser() { - return ( - - - - ) -} diff --git a/packages/web/src/components/FileGrid.tsx b/packages/web/src/components/FileGrid.tsx deleted file mode 100644 index 7a0065d..0000000 --- a/packages/web/src/components/FileGrid.tsx +++ /dev/null @@ -1,188 +0,0 @@ -import { Folder } from 'lucide-react' -import { useCallback, useRef, useState } from 'react' -import type { FileEntry } from '../lib/api' -import { api } from '../lib/api' -import { getFileIcon, hasThumbnailSupport } from '../lib/fileIcons' -import EmptyState from './ui/EmptyState' - -function formatBytes(bytes: number): string { - if (bytes === 0) return '' - const k = 1024 - const sizes = ['B', 'KB', 'MB', 'GB', 'TB'] - const i = Math.floor(Math.log(bytes) / Math.log(k)) - return `${parseFloat((bytes / k ** i).toFixed(1))} ${sizes[i]}` -} - -interface FileGridProps { - entries: FileEntry[] - volume: string - onNavigate: (path: string) => void - onPreview?: (file: FileEntry) => void - onContextMenu?: (file: FileEntry, x: number, y: number) => void - selectable?: boolean - selected?: Set - onToggle?: (path: string) => void - onShiftSelect?: (paths: string[]) => void - lastToggled?: string | null -} - -function FileGridItem({ - entry, - volume, - onNavigate, - onPreview, - onContextMenu, - selectable, - isSelected, - onCheckboxClick, -}: { - entry: FileEntry - volume: string - onNavigate: (path: string) => void - onPreview?: (file: FileEntry) => void - onContextMenu?: (file: FileEntry, x: number, y: number) => void - selectable?: boolean - isSelected?: boolean - onCheckboxClick?: (path: string, shiftKey: boolean) => void -}) { - const longPressTimer = useRef | null>(null) - const [thumbError, setThumbError] = useState(false) - - const handleTouchStart = useCallback( - (e: React.TouchEvent) => { - if (!onContextMenu) return - const touch = e.touches[0] - longPressTimer.current = setTimeout(() => { - onContextMenu(entry, touch.clientX, touch.clientY) - }, 500) - }, - [entry, onContextMenu], - ) - - const handleTouchEnd = useCallback(() => { - if (longPressTimer.current) { - clearTimeout(longPressTimer.current) - longPressTimer.current = null - } - }, []) - - const handleRightClick = useCallback( - (e: React.MouseEvent) => { - if (!onContextMenu) return - e.preventDefault() - onContextMenu(entry, e.clientX, e.clientY) - }, - [entry, onContextMenu], - ) - - const showThumb = hasThumbnailSupport(entry) && !thumbError - - return ( -
- {selectable && ( -
{ - if (e.shiftKey) e.preventDefault() - }} - onClick={(e) => { - e.stopPropagation() - onCheckboxClick?.(entry.path, e.shiftKey) - }} - > - -
- )} - -
- ) -} - -export default function FileGrid({ - entries, - volume, - onNavigate, - onPreview, - onContextMenu, - selectable, - selected, - onToggle, - onShiftSelect, - lastToggled, -}: FileGridProps) { - const handleCheckboxClick = useCallback( - (path: string, shiftKey: boolean) => { - if (shiftKey && lastToggled && onShiftSelect) { - const currentIndex = entries.findIndex((e) => e.path === path) - const lastIndex = entries.findIndex((e) => e.path === lastToggled) - if (currentIndex !== -1 && lastIndex !== -1) { - const start = Math.min(currentIndex, lastIndex) - const end = Math.max(currentIndex, lastIndex) - const rangePaths = entries.slice(start, end + 1).map((e) => e.path) - onShiftSelect(rangePaths) - return - } - } - onToggle?.(path) - }, - [entries, lastToggled, onShiftSelect, onToggle], - ) - - if (entries.length === 0) { - return - } - - return ( -
- {entries.map((entry) => ( - - ))} -
- ) -} diff --git a/packages/web/src/components/FileList.tsx b/packages/web/src/components/FileList.tsx deleted file mode 100644 index 6670f5c..0000000 --- a/packages/web/src/components/FileList.tsx +++ /dev/null @@ -1,379 +0,0 @@ -import { ArrowDown, ArrowUp, ArrowUpDown, Download, Folder, Link2, Trash2 } from 'lucide-react' -import { useCallback, useMemo, useRef, useState } from 'react' -import type { FileEntry } from '../lib/api' -import { api } from '../lib/api' -import { getFileIcon, hasThumbnailSupport } from '../lib/fileIcons' -import EmptyState from './ui/EmptyState' - -function formatBytes(bytes: number): string { - if (bytes === 0) return '\u2014' - const k = 1024 - const sizes = ['B', 'KB', 'MB', 'GB', 'TB'] - const i = Math.floor(Math.log(bytes) / Math.log(k)) - return `${parseFloat((bytes / k ** i).toFixed(1))} ${sizes[i]}` -} - -function formatDate(iso: string): string { - return new Date(iso).toLocaleDateString(undefined, { - year: 'numeric', - month: 'short', - day: 'numeric', - hour: '2-digit', - minute: '2-digit', - }) -} - -function formatDateShort(iso: string): string { - return new Date(iso).toLocaleDateString(undefined, { - month: 'short', - day: 'numeric', - }) -} - -type SortField = 'name' | 'size' | 'modified' -type SortDir = 'asc' | 'desc' - -interface FileListProps { - entries: FileEntry[] - volume: string - onNavigate: (path: string) => void - onDelete: (path: string) => void - onPreview?: (file: FileEntry) => void - onShare?: (file: FileEntry) => void - onContextMenu?: (file: FileEntry, x: number, y: number) => void - selectable?: boolean - selected?: Set - onToggle?: (path: string) => void - onShiftSelect?: (paths: string[]) => void - lastToggled?: string | null - onSelectAll?: (paths: string[]) => void -} - -function FileListRow({ - entry, - volume, - onNavigate, - onDelete, - onPreview, - onShare, - onContextMenu, - selectable, - isSelected, - onCheckboxClick, -}: { - entry: FileEntry - volume: string - onNavigate: (path: string) => void - onDelete: (path: string) => void - onPreview?: (file: FileEntry) => void - onShare?: (file: FileEntry) => void - onContextMenu?: (file: FileEntry, x: number, y: number) => void - selectable?: boolean - isSelected?: boolean - onCheckboxClick?: (path: string, shiftKey: boolean) => void -}) { - const longPressTimer = useRef | null>(null) - const [thumbError, setThumbError] = useState(false) - - const handleTouchStart = useCallback( - (e: React.TouchEvent) => { - if (!onContextMenu) return - const touch = e.touches[0] - longPressTimer.current = setTimeout(() => { - onContextMenu(entry, touch.clientX, touch.clientY) - }, 500) - }, - [entry, onContextMenu], - ) - - const handleTouchEnd = useCallback(() => { - if (longPressTimer.current) { - clearTimeout(longPressTimer.current) - longPressTimer.current = null - } - }, []) - - const handleRightClick = useCallback( - (e: React.MouseEvent) => { - if (!onContextMenu) return - e.preventDefault() - onContextMenu(entry, e.clientX, e.clientY) - }, - [entry, onContextMenu], - ) - - const showThumb = hasThumbnailSupport(entry) && !thumbError - - return ( - { - if (entry.isDirectory) { - onNavigate(entry.path) - } else if (onPreview) { - onPreview(entry) - } - }} - onContextMenu={handleRightClick} - onTouchStart={handleTouchStart} - onTouchEnd={handleTouchEnd} - onTouchMove={handleTouchEnd} - > - {selectable && ( - { - if (e.shiftKey) e.preventDefault() - }} - onClick={(e) => { - e.stopPropagation() - onCheckboxClick?.(entry.path, e.shiftKey) - }} - > - - - )} - -
- {showThumb ? ( -
- setThumbError(true)} - /> -
- ) : ( - getFileIcon(entry) - )} -
- {entry.name} - - {entry.isDirectory - ? formatDateShort(entry.modifiedAt) - : `${formatBytes(entry.size)} \u00B7 ${formatDateShort(entry.modifiedAt)}`} - -
-
- - - {entry.isDirectory - ? entry.childCount !== undefined - ? `${entry.childCount} item${entry.childCount !== 1 ? 's' : ''}` - : '\u2014' - : formatBytes(entry.size)} - - - {formatDate(entry.modifiedAt)} - - -
- {!entry.isDirectory && ( - e.stopPropagation()} - className="p-2 sm:p-1 rounded hover:bg-gray-200 text-gray-400 hover:text-gray-700 transition-colors" - title="Download" - > - - - )} - {!entry.isDirectory && onShare && ( - - )} - -
- - - ) -} - -export default function FileList({ - entries, - volume, - onNavigate, - onDelete, - onPreview, - onShare, - onContextMenu, - selectable, - selected, - onToggle, - onShiftSelect, - lastToggled, - onSelectAll, -}: FileListProps) { - const [sortField, setSortField] = useState('name') - const [sortDir, setSortDir] = useState('asc') - - const toggleSort = (field: SortField) => { - if (sortField === field) { - setSortDir((d) => (d === 'asc' ? 'desc' : 'asc')) - } else { - setSortField(field) - setSortDir('asc') - } - } - - const sortedEntries = useMemo(() => { - const dirs = entries.filter((e) => e.isDirectory) - const files = entries.filter((e) => !e.isDirectory) - - const compare = (a: FileEntry, b: FileEntry): number => { - let result = 0 - switch (sortField) { - case 'name': - result = a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }) - break - case 'size': - result = a.size - b.size - break - case 'modified': - result = new Date(a.modifiedAt).getTime() - new Date(b.modifiedAt).getTime() - break - } - return sortDir === 'asc' ? result : -result - } - - return [...dirs.sort(compare), ...files.sort(compare)] - }, [entries, sortField, sortDir]) - - const handleCheckboxClick = useCallback( - (path: string, shiftKey: boolean) => { - if (shiftKey && lastToggled && onShiftSelect) { - const currentIndex = sortedEntries.findIndex((e) => e.path === path) - const lastIndex = sortedEntries.findIndex((e) => e.path === lastToggled) - if (currentIndex !== -1 && lastIndex !== -1) { - const start = Math.min(currentIndex, lastIndex) - const end = Math.max(currentIndex, lastIndex) - const rangePaths = sortedEntries.slice(start, end + 1).map((e) => e.path) - onShiftSelect(rangePaths) - return - } - } - onToggle?.(path) - }, - [sortedEntries, lastToggled, onShiftSelect, onToggle], - ) - - if (entries.length === 0) { - return - } - - const allSelected = selected && entries.length > 0 && entries.every((e) => selected.has(e.path)) - - const SortIcon = ({ field }: { field: SortField }) => { - if (sortField !== field) return - return sortDir === 'asc' ? ( - - ) : ( - - ) - } - - return ( -
- - - - {selectable && ( - - )} - - - - - - - - {sortedEntries.map((entry) => ( - - ))} - -
{ - if (allSelected) { - onSelectAll?.([]) - } else { - onSelectAll?.(entries.map((e) => e.path)) - } - }} - > - - - - - - - -
-
- ) -} diff --git a/packages/web/src/components/PasskeyLogin.tsx b/packages/web/src/components/PasskeyLogin.tsx deleted file mode 100644 index 1be8c2e..0000000 --- a/packages/web/src/components/PasskeyLogin.tsx +++ /dev/null @@ -1,57 +0,0 @@ -import { Fingerprint, Loader2 } from 'lucide-react' -import { useState } from 'react' -import { APP_NAME } from '../lib/appName' -import { withBase } from '../lib/basePath' -import { authenticatePasskey } from '../lib/passkeys' - -export default function PasskeyLogin() { - const [status, setStatus] = useState<'idle' | 'loading' | 'error'>('idle') - const [error, setError] = useState('') - - const handleLogin = async () => { - setStatus('loading') - setError('') - try { - const verified = await authenticatePasskey() - if (verified) { - window.location.href = withBase('/') - } else { - setStatus('error') - setError('Authentication was not verified') - } - } catch (err) { - setStatus('error') - setError(err instanceof Error ? err.message : 'Authentication failed') - } - } - - return ( -
-
-
- {APP_NAME} -

{APP_NAME}

-

Sign in with your passkey

-
- -
- - - {error &&

{error}

} -
-
-
- ) -} diff --git a/packages/web/src/components/PasskeySetup.tsx b/packages/web/src/components/PasskeySetup.tsx deleted file mode 100644 index 95ef676..0000000 --- a/packages/web/src/components/PasskeySetup.tsx +++ /dev/null @@ -1,125 +0,0 @@ -import { CheckCircle, Fingerprint, Loader2, ShieldX } from 'lucide-react' -import { useEffect, useState } from 'react' -import { APP_NAME } from '../lib/appName' -import { withBase } from '../lib/basePath' -import { checkSetupNeeded, registerPasskey } from '../lib/passkeys' - -export default function PasskeySetup() { - const [status, setStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle') - const [error, setError] = useState('') - const [setupDisabled, setSetupDisabled] = useState(false) - const [checking, setChecking] = useState(true) - - useEffect(() => { - checkSetupNeeded().then((needed) => { - if (!needed) { - setSetupDisabled(true) - } - setChecking(false) - }) - }, []) - - const handleRegister = async () => { - setStatus('loading') - setError('') - try { - const verified = await registerPasskey() - if (verified) { - setStatus('success') - setTimeout(() => { - window.location.href = withBase('/') - }, 1000) - } else { - setStatus('error') - setError('Registration was not verified') - } - } catch (err) { - setStatus('error') - setError(err instanceof Error ? err.message : 'Registration failed') - } - } - - if (checking) { - return ( -
- -
- ) - } - - if (setupDisabled) { - return ( -
-
-
- {APP_NAME} -

Setup Unavailable

-

- An admin account has already been configured. Setup can only be run once during - initial installation. -

-
- -
-
- -

- If you need to log in, go to the{' '} - - login page - - . -

-
-
-
-
- ) - } - - return ( -
-
-
- {APP_NAME} -

Welcome to {APP_NAME}

-

- Set up your passkey to secure your NAS. This will use your device's biometric - authentication (Touch ID, Face ID, etc.) -

-
- -
- {status === 'success' ? ( -
- -

Passkey registered!

-

Redirecting...

-
- ) : ( - <> - - - {error &&

{error}

} - - )} -
-
-
- ) -} diff --git a/packages/web/src/components/PreviewModal.tsx b/packages/web/src/components/PreviewModal.tsx deleted file mode 100644 index 5b1d872..0000000 --- a/packages/web/src/components/PreviewModal.tsx +++ /dev/null @@ -1,120 +0,0 @@ -import { Download, X } from 'lucide-react' -import { useCallback, useEffect } from 'react' -import { api, type FileEntry } from '../lib/api' - -interface PreviewModalProps { - file: FileEntry - volume: string - onClose: () => void -} - -export default function PreviewModal({ file, volume, onClose }: PreviewModalProps) { - const downloadUrl = api.getDownloadUrl(volume, file.path) - const inlineUrl = api.getInlineUrl(volume, file.path) - const mime = file.mimeType || '' - - const handleKeyDown = useCallback( - (e: KeyboardEvent) => { - if (e.key === 'Escape') onClose() - }, - [onClose], - ) - - useEffect(() => { - document.addEventListener('keydown', handleKeyDown) - document.body.style.overflow = 'hidden' - return () => { - document.removeEventListener('keydown', handleKeyDown) - document.body.style.overflow = '' - } - }, [handleKeyDown]) - - const renderContent = () => { - if (mime.startsWith('image/')) { - return ( - {file.name} - ) - } - - if (mime.startsWith('video/')) { - return ( - - ) - } - - if (mime.startsWith('audio/')) { - return ( -
-

{file.name}

- -
- ) - } - - if (mime === 'application/pdf') { - return