First commit

This commit is contained in:
shaw
2025-12-18 13:50:39 +08:00
parent 569f4882e5
commit 642842c29e
218 changed files with 86902 additions and 0 deletions

View File

@@ -0,0 +1,194 @@
# Pinia Stores Documentation
This directory contains all Pinia stores for the Sub2API frontend application.
## Stores Overview
### 1. Auth Store (`auth.ts`)
Manages user authentication state, login/logout, and token persistence.
**State:**
- `user: User | null` - Current authenticated user
- `token: string | null` - JWT authentication token
**Computed:**
- `isAuthenticated: boolean` - Whether user is currently authenticated
**Actions:**
- `login(credentials)` - Authenticate user with username/password
- `register(userData)` - Register new user account
- `logout()` - Clear authentication and logout
- `checkAuth()` - Restore session from localStorage
- `refreshUser()` - Fetch latest user data from server
### 2. App Store (`app.ts`)
Manages global UI state including sidebar, loading indicators, and toast notifications.
**State:**
- `sidebarCollapsed: boolean` - Sidebar collapsed state
- `loading: boolean` - Global loading state
- `toasts: Toast[]` - Active toast notifications
**Computed:**
- `hasActiveToasts: boolean` - Whether any toasts are active
**Actions:**
- `toggleSidebar()` - Toggle sidebar state
- `setSidebarCollapsed(collapsed)` - Set sidebar state explicitly
- `setLoading(isLoading)` - Set loading state
- `showToast(type, message, duration?)` - Show toast notification
- `showSuccess(message, duration?)` - Show success toast
- `showError(message, duration?)` - Show error toast
- `showInfo(message, duration?)` - Show info toast
- `showWarning(message, duration?)` - Show warning toast
- `hideToast(id)` - Hide specific toast
- `clearAllToasts()` - Clear all toasts
- `withLoading(operation)` - Execute async operation with loading state
- `withLoadingAndError(operation, errorMessage?)` - Execute with loading and error handling
- `reset()` - Reset store to defaults
## Usage Examples
### Auth Store
```typescript
import { useAuthStore } from '@/stores';
// In component setup
const authStore = useAuthStore();
// Initialize on app startup
authStore.checkAuth();
// Login
try {
await authStore.login({ username: 'user', password: 'pass' });
console.log('Logged in:', authStore.user);
} catch (error) {
console.error('Login failed:', error);
}
// Check authentication
if (authStore.isAuthenticated) {
console.log('User is logged in:', authStore.user?.username);
}
// Logout
authStore.logout();
```
### App Store
```typescript
import { useAppStore } from '@/stores';
// In component setup
const appStore = useAppStore();
// Sidebar control
appStore.toggleSidebar();
appStore.setSidebarCollapsed(true);
// Loading state
appStore.setLoading(true);
// ... do work
appStore.setLoading(false);
// Or use helper
await appStore.withLoading(async () => {
const data = await fetchData();
return data;
});
// Toast notifications
appStore.showSuccess('Operation completed!');
appStore.showError('Something went wrong!', 5000);
appStore.showInfo('FYI: This is informational');
appStore.showWarning('Be careful!');
// Custom toast
const toastId = appStore.showToast('info', 'Custom message', undefined); // No auto-dismiss
// Later...
appStore.hideToast(toastId);
```
### Combined Usage in Vue Component
```vue
<script setup lang="ts">
import { useAuthStore, useAppStore } from '@/stores';
import { onMounted } from 'vue';
const authStore = useAuthStore();
const appStore = useAppStore();
onMounted(() => {
// Check for existing session
authStore.checkAuth();
});
async function handleLogin(username: string, password: string) {
try {
await appStore.withLoading(async () => {
await authStore.login({ username, password });
});
appStore.showSuccess('Welcome back!');
} catch (error) {
appStore.showError('Login failed. Please check your credentials.');
}
}
async function handleLogout() {
authStore.logout();
appStore.showInfo('You have been logged out.');
}
</script>
<template>
<div>
<button @click="appStore.toggleSidebar">
Toggle Sidebar
</button>
<div v-if="appStore.loading">Loading...</div>
<div v-if="authStore.isAuthenticated">
Welcome, {{ authStore.user?.username }}!
<button @click="handleLogout">Logout</button>
</div>
<div v-else>
<button @click="handleLogin('user', 'pass')">Login</button>
</div>
</div>
</template>
```
## Persistence
- **Auth Store**: Token and user data are automatically persisted to `localStorage`
- Keys: `auth_token`, `auth_user`
- Restored on `checkAuth()` call
- **App Store**: No persistence (UI state resets on page reload)
## TypeScript Support
All stores are fully typed with TypeScript. Import types from `@/types`:
```typescript
import type { User, Toast, ToastType } from '@/types';
```
## Testing
Stores can be reset to initial state:
```typescript
// Auth store
authStore.logout(); // Clears all auth state
// App store
appStore.reset(); // Resets to defaults
```

221
frontend/src/stores/app.ts Normal file
View File

@@ -0,0 +1,221 @@
/**
* Application State Store
* Manages global UI state including sidebar, loading indicators, and toast notifications
*/
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import type { Toast, ToastType } from '@/types';
export const useAppStore = defineStore('app', () => {
// ==================== State ====================
const sidebarCollapsed = ref<boolean>(false);
const loading = ref<boolean>(false);
const toasts = ref<Toast[]>([]);
// Auto-incrementing ID for toasts
let toastIdCounter = 0;
// ==================== Computed ====================
const hasActiveToasts = computed(() => toasts.value.length > 0);
const loadingCount = ref<number>(0);
// ==================== Actions ====================
/**
* Toggle sidebar collapsed state
*/
function toggleSidebar(): void {
sidebarCollapsed.value = !sidebarCollapsed.value;
}
/**
* Set sidebar collapsed state explicitly
* @param collapsed - Whether sidebar should be collapsed
*/
function setSidebarCollapsed(collapsed: boolean): void {
sidebarCollapsed.value = collapsed;
}
/**
* Set global loading state
* @param isLoading - Whether app is in loading state
*/
function setLoading(isLoading: boolean): void {
if (isLoading) {
loadingCount.value++;
} else {
loadingCount.value = Math.max(0, loadingCount.value - 1);
}
loading.value = loadingCount.value > 0;
}
/**
* Show a toast notification
* @param type - Type of toast (success, error, info, warning)
* @param message - Toast message content
* @param duration - Auto-dismiss duration in ms (undefined = no auto-dismiss)
* @returns Toast ID for manual dismissal
*/
function showToast(
type: ToastType,
message: string,
duration?: number
): string {
const id = `toast-${++toastIdCounter}`;
const toast: Toast = {
id,
type,
message,
duration,
startTime: duration !== undefined ? Date.now() : undefined,
};
toasts.value.push(toast);
// Auto-dismiss if duration is specified
if (duration !== undefined) {
setTimeout(() => {
hideToast(id);
}, duration);
}
return id;
}
/**
* Show a success toast
* @param message - Success message
* @param duration - Auto-dismiss duration in ms (default: 3000)
*/
function showSuccess(message: string, duration: number = 3000): string {
return showToast('success', message, duration);
}
/**
* Show an error toast
* @param message - Error message
* @param duration - Auto-dismiss duration in ms (default: 5000)
*/
function showError(message: string, duration: number = 5000): string {
return showToast('error', message, duration);
}
/**
* Show an info toast
* @param message - Info message
* @param duration - Auto-dismiss duration in ms (default: 3000)
*/
function showInfo(message: string, duration: number = 3000): string {
return showToast('info', message, duration);
}
/**
* Show a warning toast
* @param message - Warning message
* @param duration - Auto-dismiss duration in ms (default: 4000)
*/
function showWarning(message: string, duration: number = 4000): string {
return showToast('warning', message, duration);
}
/**
* Hide a specific toast by ID
* @param id - Toast ID to hide
*/
function hideToast(id: string): void {
const index = toasts.value.findIndex((t) => t.id === id);
if (index !== -1) {
toasts.value.splice(index, 1);
}
}
/**
* Clear all toasts
*/
function clearAllToasts(): void {
toasts.value = [];
}
/**
* Execute an async operation with loading state
* Automatically manages loading indicator
* @param operation - Async operation to execute
* @returns Promise resolving to operation result
*/
async function withLoading<T>(operation: () => Promise<T>): Promise<T> {
setLoading(true);
try {
return await operation();
} finally {
setLoading(false);
}
}
/**
* Execute an async operation with loading and error handling
* Shows error toast on failure
* @param operation - Async operation to execute
* @param errorMessage - Custom error message (optional)
* @returns Promise resolving to operation result or null on error
*/
async function withLoadingAndError<T>(
operation: () => Promise<T>,
errorMessage?: string
): Promise<T | null> {
setLoading(true);
try {
return await operation();
} catch (error) {
const message =
errorMessage ||
(error as { message?: string }).message ||
'An error occurred';
showError(message);
return null;
} finally {
setLoading(false);
}
}
/**
* Reset app state to defaults
* Useful for cleanup or testing
*/
function reset(): void {
sidebarCollapsed.value = false;
loading.value = false;
loadingCount.value = 0;
toasts.value = [];
}
// ==================== Return Store API ====================
return {
// State
sidebarCollapsed,
loading,
toasts,
// Computed
hasActiveToasts,
// Actions
toggleSidebar,
setSidebarCollapsed,
setLoading,
showToast,
showSuccess,
showError,
showInfo,
showWarning,
hideToast,
clearAllToasts,
withLoading,
withLoadingAndError,
reset,
};
});

219
frontend/src/stores/auth.ts Normal file
View File

@@ -0,0 +1,219 @@
/**
* Authentication Store
* Manages user authentication state, login/logout, and token persistence
*/
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { authAPI } from '@/api';
import type { User, LoginRequest, RegisterRequest } from '@/types';
const AUTH_TOKEN_KEY = 'auth_token';
const AUTH_USER_KEY = 'auth_user';
const AUTO_REFRESH_INTERVAL = 60 * 1000; // 60 seconds
export const useAuthStore = defineStore('auth', () => {
// ==================== State ====================
const user = ref<User | null>(null);
const token = ref<string | null>(null);
let refreshIntervalId: ReturnType<typeof setInterval> | null = null;
// ==================== Computed ====================
const isAuthenticated = computed(() => {
return !!token.value && !!user.value;
});
const isAdmin = computed(() => {
return user.value?.role === 'admin';
});
// ==================== Actions ====================
/**
* Initialize auth state from localStorage
* Call this on app startup to restore session
* Also starts auto-refresh and immediately fetches latest user data
*/
function checkAuth(): void {
const savedToken = localStorage.getItem(AUTH_TOKEN_KEY);
const savedUser = localStorage.getItem(AUTH_USER_KEY);
if (savedToken && savedUser) {
try {
token.value = savedToken;
user.value = JSON.parse(savedUser);
// Immediately refresh user data from backend (async, don't block)
refreshUser().catch((error) => {
console.error('Failed to refresh user on init:', error);
});
// Start auto-refresh interval
startAutoRefresh();
} catch (error) {
console.error('Failed to parse saved user data:', error);
clearAuth();
}
}
}
/**
* Start auto-refresh interval for user data
* Refreshes user data every 60 seconds
*/
function startAutoRefresh(): void {
// Clear existing interval if any
stopAutoRefresh();
refreshIntervalId = setInterval(() => {
if (token.value) {
refreshUser().catch((error) => {
console.error('Auto-refresh user failed:', error);
});
}
}, AUTO_REFRESH_INTERVAL);
}
/**
* Stop auto-refresh interval
*/
function stopAutoRefresh(): void {
if (refreshIntervalId) {
clearInterval(refreshIntervalId);
refreshIntervalId = null;
}
}
/**
* User login
* @param credentials - Login credentials (username and password)
* @returns Promise resolving to the authenticated user
* @throws Error if login fails
*/
async function login(credentials: LoginRequest): Promise<User> {
try {
const response = await authAPI.login(credentials);
// Store token and user
token.value = response.access_token;
user.value = response.user;
// Persist to localStorage
localStorage.setItem(AUTH_TOKEN_KEY, response.access_token);
localStorage.setItem(AUTH_USER_KEY, JSON.stringify(response.user));
// Start auto-refresh interval
startAutoRefresh();
return response.user;
} catch (error) {
// Clear any partial state on error
clearAuth();
throw error;
}
}
/**
* User registration
* @param userData - Registration data (username, email, password)
* @returns Promise resolving to the newly registered and authenticated user
* @throws Error if registration fails
*/
async function register(userData: RegisterRequest): Promise<User> {
try {
const response = await authAPI.register(userData);
// Store token and user
token.value = response.access_token;
user.value = response.user;
// Persist to localStorage
localStorage.setItem(AUTH_TOKEN_KEY, response.access_token);
localStorage.setItem(AUTH_USER_KEY, JSON.stringify(response.user));
// Start auto-refresh interval
startAutoRefresh();
return response.user;
} catch (error) {
// Clear any partial state on error
clearAuth();
throw error;
}
}
/**
* User logout
* Clears all authentication state and persisted data
*/
function logout(): void {
// Call API logout (client-side cleanup)
authAPI.logout();
// Clear state
clearAuth();
}
/**
* Refresh current user data
* Fetches latest user info from the server
* @returns Promise resolving to the updated user
* @throws Error if not authenticated or request fails
*/
async function refreshUser(): Promise<User> {
if (!token.value) {
throw new Error('Not authenticated');
}
try {
const updatedUser = await authAPI.getCurrentUser();
user.value = updatedUser;
// Update localStorage
localStorage.setItem(AUTH_USER_KEY, JSON.stringify(updatedUser));
return updatedUser;
} catch (error) {
// If refresh fails with 401, clear auth state
if ((error as { status?: number }).status === 401) {
clearAuth();
}
throw error;
}
}
/**
* Clear all authentication state
* Internal helper function
*/
function clearAuth(): void {
// Stop auto-refresh
stopAutoRefresh();
token.value = null;
user.value = null;
localStorage.removeItem(AUTH_TOKEN_KEY);
localStorage.removeItem(AUTH_USER_KEY);
}
// ==================== Return Store API ====================
return {
// State
user,
token,
// Computed
isAuthenticated,
isAdmin,
// Actions
login,
register,
logout,
checkAuth,
refreshUser,
};
});

View File

@@ -0,0 +1,11 @@
/**
* Pinia Stores Export
* Central export point for all application stores
*/
export { useAuthStore } from './auth';
export { useAppStore } from './app';
// Re-export types for convenience
export type { User, LoginRequest, RegisterRequest, AuthResponse } from '@/types';
export type { Toast, ToastType, AppState } from '@/types';