Add codebase mapping documents

This commit is contained in:
2026-03-13 01:08:16 +08:00
commit afe1603bbe
7 changed files with 1349 additions and 0 deletions

View File

@@ -0,0 +1,129 @@
# Architecture
**Analysis Date:** 2025-03-13
## Pattern Overview
**Overall:** Component-based SPA with centralized routing
**Key Characteristics:**
- Single-page application using React Router v7
- View-based architecture where each view is a self-contained component
- Centralized navigation with collapsible sidebar
- Dark-first theme designed for industrial touch displays
- No state management library (local state only)
- UI components from shadcn/ui pattern with Radix primitives
## Layers
**Application Layer:**
- Purpose: Entry point and routing configuration
- Location: `sample_interface/src/app/`
- Contains: App.tsx, routes.ts
- Depends on: Components layer, Views layer
- Used by: Vite build system
**Layout Layer:**
- Purpose: Shell components providing page structure
- Location: `sample_interface/src/app/components/`
- Contains: DashboardLayout.tsx, Sidebar.tsx, Header.tsx, NavigationButtons.tsx
- Depends on: UI component layer
- Used by: React Router
**Views Layer:**
- Purpose: Page-level components representing routes
- Location: `sample_interface/src/app/components/views/`
- Contains: RainfallView.tsx, GraphView.tsx, ADCSettingView.tsx, LoginView.tsx, etc.
- Depends on: UI component layer
- Used by: React Router via routes.ts
**UI Component Layer:**
- Purpose: Reusable primitive and composite components
- Location: `sample_interface/src/app/components/ui/`
- Contains: button.tsx, card.tsx, input.tsx, sidebar.tsx (shadcn), ~40+ components
- Depends on: Radix UI primitives, Tailwind CSS
- Used by: Views, Layouts, other UI components
**Style Layer:**
- Purpose: Global styles and design tokens
- Location: `sample_interface/src/styles/`
- Contains: index.css, tailwind.css, theme.css
- Depends on: Tailwind CSS v4
- Used by: All components
## Data Flow
**Navigation Flow:**
1. User clicks sidebar menu item
2. React Router `<Link>` handles navigation
3. `routes.ts` matches path to view component
4. `DashboardLayout` renders with `<Outlet />` for view
5. View component mounts and renders content
6. UI components receive props and render
**State Management:**
- **Local component state only** - No Redux, Zustand, or Context API for global state
- Sidebar collapsed state: `DashboardLayout.tsx` (useState)
- Menu expanded items: `Sidebar.tsx` (useState)
- Form data: Managed within each view component
- Time/status: `Header.tsx` (useState + useEffect)
## Key Abstractions
**View Component Pattern:**
- Purpose: Page-level route handlers
- Examples: `sample_interface/src/app/components/views/RainfallView.tsx`, `sample_interface/src/app/components/views/ADCSettingView.tsx`
- Pattern: Function component that returns JSX with Card-based layouts
**UI Component Pattern (shadcn/ui):**
- Purpose: Atomic reusable components
- Examples: `sample_interface/src/app/components/ui/button.tsx`, `sample_interface/src/app/components/ui/card.tsx`
- Pattern: Compositional components with `cn()` utility for class merging
- Sub-pattern: Each component exports named exports (e.g., `Card`, `CardHeader`, `CardContent`)
**Utility Pattern:**
- Purpose: Shared helper functions
- Examples: `sample_interface/src/app/components/ui/utils.ts` (cn function)
- Pattern: Named exports, single responsibility
## Entry Points
**Application Entry:**
- Location: `sample_interface/src/app/App.tsx`
- Triggers: Vite dev server or production build
- Responsibilities: Provides RouterProvider with configured router
**Routing Entry:**
- Location: `sample_interface/src/app/routes.ts`
- Triggers: Browser URL changes
- Responsibilities: Defines all routes, maps paths to view components
**Style Entry:**
- Location: `sample_interface/src/styles/index.css`
- Triggers: Component rendering
- Responsibilities: Imports fonts, Tailwind, theme variables
## Error Handling
**Strategy:** No centralized error handling detected
**Patterns:**
- Components render static content with no error boundaries
- Form validation handled inline within views
- No try/catch blocks observed in view components
- Image fallback component: `sample_interface/src/app/components/figma/ImageWithFallback.tsx`
## Cross-Cutting Concerns
**Logging:** Console-based (no logging framework detected)
**Validation:** Inline form validation within view components
**Authentication:** UI-only in LoginView.tsx, no auth flow implemented
**Theming:** Tailwind CSS with dark color palette (gray-900, gray-950 base)
---
*Architecture analysis: 2025-03-13*

View File

@@ -0,0 +1,208 @@
# Codebase Concerns
**Analysis Date:** 2026-03-13
## Tech Debt
**Mock Data Throughout Application:**
- Issue: All views contain hardcoded mock data instead of real API integrations
- Files:
- `src/app/components/views/FlashMemoryView.tsx` (lines 6-25)
- `src/app/components/views/RainfallView.tsx` (lines 5-10, 43-49)
- `src/app/components/views/ADCSettingView.tsx` (lines 8-13)
- `src/app/components/views/CalibrationView.tsx` (lines 6-11)
- `src/app/components/views/StationInfoView.tsx` (lines 5-14)
- `src/app/components/views/Header.tsx` (lines 56, 77, 91, 97)
- Impact: Application is not functional for production use; requires complete rewrite of data layer
- Fix approach: Implement API client layer, create custom hooks for data fetching (useApi, useSensorData), replace all mock constants with API calls
**Missing API Integration Layer:**
- Issue: No HTTP client configured, no API service layer exists
- Files: All view files in `src/app/components/views/`
- Impact: Forms don't submit, data doesn't persist, application is read-only demo
- Fix approach: Add axios or fetch wrapper, create service modules in `src/app/services/` for each domain (sensors, settings, auth)
**Placeholder Components:**
- Issue: GraphView contains only placeholder content with no chart implementation
- File: `src/app/components/views/GraphView.tsx` (lines 17-19)
- Impact: Core feature is non-functional despite chart component existing (`src/app/components/ui/chart.tsx`)
- Fix approach: Integrate Recharts with actual data source
## Known Issues
**Exposed Default Credentials:**
- Issue: Login page displays hardcoded default credentials in the UI
- File: `src/app/components/views/LoginView.tsx` (lines 54-56)
- Content: "Default credentials: admin / admin"
- Impact: Security vulnerability - exposes authentication credentials to all users
- Fix approach: Remove credential hints from UI, implement secure password reset flow, store credentials server-side only
**Non-Functional Interactive Elements:**
- Issue: Buttons and actions don't perform actual operations
- Files:
- `src/app/components/views/FlashMemoryView.tsx`: Download and Delete buttons (lines 80-87) are non-functional
- `src/app/components/views/SettingView.tsx`: Factory Reset and Reboot System buttons (lines 67-71) lack confirmation dialogs
- `src/app/components/views/GPRSSettingView.tsx`: Test Connection button (lines 60-62) has no implementation
- Impact: Users receive no feedback, destructive actions can occur accidentally
- Fix approach: Implement action handlers, add confirmation dialogs for destructive operations, add toast notifications for user feedback
## Security Considerations
**No Authentication Implementation:**
- Risk: Login form is UI-only with no auth logic
- File: `src/app/components/views/LoginView.tsx` - form submission not handled
- Current mitigation: None
- Recommendations: Implement JWT or session-based auth, add ProtectedRoute wrapper, store auth token securely (httpOnly cookies preferred)
**Missing Input Validation:**
- Risk: All forms accept any input without validation
- Files: All form-containing views (`*SettingView.tsx`)
- Current mitigation: None
- Recommendations: Add Zod or Yup schemas for form validation, validate on blur and submit, display inline error messages
**No HTTPS Enforcement:**
- Risk: Application may run over unencrypted connections
- Current mitigation: None visible
- Recommendations: Add HSTS headers, enforce HTTPS in production builds, validate API URLs use HTTPS
**Hardcoded Sensitive-Looking Configuration:**
- Risk: Device configuration values exposed in source
- Files:
- `src/app/components/views/StationInfoView.tsx`: Hardcoded station coordinates and serial numbers (lines 5-14)
- `src/app/components/views/Header.tsx`: Hardcoded station ID "STN-001" (line 56)
- Current mitigation: None
- Recommendations: Move configuration to environment variables or secure config endpoint
## Performance Bottlenecks
**Large Component Files:**
- Problem: sidebar.tsx is 726 lines, violating single responsibility principle
- File: `src/app/components/ui/sidebar.tsx`
- Cause: Multiple components (SidebarProvider, Sidebar, SidebarTrigger, SidebarRail, etc.) in one file
- Improvement path: Split into separate files: `sidebar-provider.tsx`, `sidebar-trigger.tsx`, `sidebar-menu.tsx`, etc.
**No Code Splitting:**
- Problem: All routes loaded upfront in single bundle
- File: `src/app/routes.ts` - static imports of all view components
- Cause: No lazy loading or dynamic imports
- Improvement path: Use React.lazy() and Suspense for route-based code splitting
**Direct DOM Manipulation:**
- Problem: NavigationButtons uses imperative DOM access instead of React refs
- File: `src/app/components/views/NavigationButtons.tsx` (lines 8-19)
- Code: `document.getElementById("details-panel")`
- Improvement path: Use React ref forwarded from DashboardLayout, or use scroll context
## Fragile Areas
**Chart Component Null Returns:**
- Files: `src/app/components/ui/chart.tsx` (lines 78, 133, 153, 168, 267)
- Issue: Multiple early `return null` statements may cause React reconciliation issues
- Safe modification: Ensure parent components handle null returns gracefully, add error boundaries
**Form State Management:**
- Issue: All forms use uncontrolled inputs with defaultValue only
- Files: All `*SettingView.tsx` files
- Why fragile: Form state not tracked, can't validate, can't persist, can't show pending state
- Safe modification: Convert to controlled inputs with useState, or use React Hook Form library
**Hardcoded Route Paths:**
- Issue: Route paths defined in multiple places
- Files:
- `src/app/routes.ts` - route definitions
- `src/app/components/Sidebar.tsx` (lines 39-87) - navigation links
- Why fragile: Route changes require updates in multiple files, easy to miss one
- Safe modification: Create `src/app/constants/routes.ts` with path constants, use throughout app
**No Error Boundaries:**
- Issue: Single component error can crash entire application
- Current state: No ErrorBoundary component found
- Safe modification: Add error boundaries at route level and around complex components
## Scaling Limits
**Current Capacity:**
- 72 source files, ~13,300 lines of TypeScript
- No test coverage
- All data hardcoded (no real data volume)
**Limitations:**
- No pagination implementation for data lists
- No virtualization for long lists
- No caching strategy
**Scaling Path:**
- Implement React Query or SWR for server state management
- Add virtualized lists for large datasets
- Implement proper pagination in data views
## Dependencies at Risk
**React Router v7 Migration:**
- Current: `react-router` version 7.13.0
- Risk: Recently released major version, API may change
- Impact: Route definitions in `src/app/routes.ts` use newer createBrowserRouter API
- Migration plan: Monitor for breaking changes, lock version if needed
**Tailwind CSS v4:**
- Current: Version 4.1.12 with @theme inline syntax
- Risk: New major version with different configuration approach
- Impact: theme.css uses new v4 syntax
- Migration plan: Maintain lockfile, test before upgrades
## Missing Critical Features
**Real-Time Data Updates:**
- Problem: Dashboard shows static values, no live sensor data
- Blocks: Production deployment for monitoring use cases
- Priority: High
**Form Validation:**
- Problem: No validation on any input fields
- Files: All `*SettingView.tsx` files
- Blocks: Data integrity, user experience
- Priority: High
**Error Handling:**
- Problem: No error states, no user feedback for failures
- Blocks: Production reliability
- Priority: High
**API Integration:**
- Problem: No backend communication
- Blocks: All CRUD operations
- Priority: Critical
**Authentication/Authorization:**
- Problem: Login form is decorative only
- Blocks: Security requirements
- Priority: Critical
**Confirmation Dialogs:**
- Problem: Destructive actions (Factory Reset, Reboot, Delete) have no confirmation
- Files: `src/app/components/views/SettingView.tsx`, `src/app/components/views/FlashMemoryView.tsx`
- Priority: Medium
## Test Coverage Gaps
**No Testing Infrastructure:**
- What's not tested: Everything (100% gap)
- Files: Zero test files found
- Risk: No regression protection, no confidence in changes
- Priority: Critical
**Recommended Testing Stack:**
- Unit tests: Vitest + React Testing Library for components
- Integration tests: Test form submissions, navigation flows
- E2E tests: Playwright for critical user journeys
**Critical Test Priorities:**
1. Form validation and submission flows
2. Authentication state management
3. Data fetching and error handling
4. Navigation and routing
5. Settings persistence
---
*Concerns audit: 2026-03-13*

View File

@@ -0,0 +1,256 @@
# Coding Conventions
**Analysis Date:** 2026-03-13
## Overview
This codebase follows conventions documented in `/sample_interface/guidelines/Guidelines.md` with React/TypeScript patterns optimized for a touchscreen industrial dashboard interface.
## Naming Patterns
### Files
- **Components:** PascalCase with `.tsx` extension (e.g., `RainfallView.tsx`, `Header.tsx`)
- **Views:** `[Feature]View.tsx` pattern (e.g., `SettingView.tsx`, `LoginView.tsx`)
- **UI Components:** Lowercase with hyphen separation (e.g., `button.tsx`, `card.tsx`)
- **Utilities:** camelCase (e.g., `utils.ts`)
- **Configuration:** `.config.ts` or `.config.mjs` (e.g., `vite.config.ts`, `postcss.config.mjs`)
### Functions & Variables
- **Functions:** camelCase (e.g., `scrollUp()`, `toggleExpanded()`, `formatTime()`)
- **React Components:** PascalCase (e.g., `function Card()`, `function Header()`)
- **State Variables:** camelCase with `is`/`has`/`should` prefix for booleans
- `const [sidebarCollapsed, setSidebarCollapsed] = useState(false)`
- `const [isOnline, setIsOnline] = useState(true)`
- `const [selectedFile, setSelectedFile] = useState(...)`
- **Constants:** camelCase for objects/arrays, UPPERCASE for true constants
- `const menuItems = [...]`
- `const scrollAmount = 300`
### Props & Types
- **Props Interface:** `[ComponentName]Props` (e.g., `SidebarProps`, `MenuItem`)
- **Type Parameters:** PascalCase (e.g., `TFieldValues`, `TName`)
- **Event Handlers:** `on[Action]` prefix (e.g., `onToggle`, `onClick`)
## Code Style
### Formatting
- **No automated linting/formatting configured** (no ESLint, Prettier, or Biome detected)
- Indentation: 2 spaces
- Semicolons: Used consistently
- Quotes: Double quotes for strings
- Trailing commas: Not used consistently
### Component Structure
```typescript
// Named function declaration (preferred)
function Button({ className, variant, ...props }: ButtonProps) {
return <Comp className={cn(buttonVariants({ variant, className }))} {...props} />;
}
// Arrow function for simpler components
export const router = createBrowserRouter([...]);
// Export at end of file for UI components
export { Button, buttonVariants };
```
## Import Organization
### Order
1. **React imports:** `import * as React from "react"`
2. **External libraries:** Radix UI, React Router, Lucide icons
3. **Internal components:** Relative paths from current file
4. **Utilities:** Local utility functions
### Examples
```typescript
// From button.tsx
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "./utils";
// From views
import { Card, CardContent } from "../ui/card";
import { Button } from "../ui/button";
import { Settings } from "lucide-react";
```
### Path Aliases
- `@/` maps to `src/` directory (configured in `vite.config.ts`)
- Currently used in minimal places; relative imports preferred in existing code
## Component Patterns
### shadcn/ui Pattern
Components follow the shadcn/ui design pattern:
```typescript
// 1. Import React as namespace
import * as React from "react";
// 2. Use React.ComponentProps for HTML element props
function Card({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card" // Data attribute for debugging
className={cn("base-classes", className)} // cn() utility for class merging
{...props}
/>
);
}
// 3. Export at end
export { Card, CardHeader, ... };
```
### View Components
Views follow consistent structure:
```typescript
export function ViewName() {
// Local state and data
const data = [...];
return (
<div className="space-y-4">
{/* Header with icon and title */}
<div className="flex items-center gap-3">
<Icon className="w-6 h-6 text-blue-400" />
<h1 className="text-2xl font-bold text-white">Title</h1>
</div>
{/* Content cards */}
<Card>...</Card>
</div>
);
}
```
## Styling Conventions
### Tailwind CSS Usage
- **Primary styling method:** Tailwind utility classes
- **Dark theme default:** All components styled for dark UI
- **Custom colors:** Extended via CSS variables in `theme.css`
### Color Palette
- Backgrounds: `bg-gray-900` (primary), `bg-gray-950` (elevated), `bg-gray-800` (inputs)
- Primary actions: `bg-blue-600 hover:bg-blue-700`
- Success: `text-green-400`, Warning: `text-yellow-400`, Error: `text-red-400`
- Borders: `border-gray-700`
### Class Name Utility
All UI components use `cn()` utility from `utils.ts`:
```typescript
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
```
### Touchscreen-First Design
- Minimum touch targets: 44x44px (preferably 56x56px)
- Button sizing: `h-14 w-14` for navigation, `h-9` for standard buttons
- Spacing: `p-3` or `p-4` for adequate touch area
## State Management
### Local State
- React `useState` for component-level state
- `useEffect` for side effects (timers, subscriptions)
- No global state management library detected
### Router State
- React Router v7 for routing
- `useLocation()` for current path
- URL as source of truth for navigation state
## Error Handling
### Patterns
- Minimal explicit error handling in UI code
- Form validation via react-hook-form (in `form.tsx`)
- Console errors for development debugging
### Type Safety
- TypeScript strict mode implied by usage
- Type imports using `type` keyword: `import { type ClassValue }`
- Generic components with proper type constraints
## Comments
### Guidelines
- Minimal inline comments
- Component purpose inferred from file name and structure
- Complex logic may have inline explanations
### JSDoc/TSDoc
- Not used extensively
- Type definitions provide documentation
## Function Design
### Size
- Components: Typically 30-120 lines
- View components: 50-110 lines each
- UI components: 20-90 lines each
### Parameters
- Destructured props with explicit typing
- Spread operator for passing through remaining props
- Default values inline in destructuring
### Return Values
- JSX.Element for React components
- Void for event handlers
- Typed arrays/objects for data functions
## Module Design
### Exports
- Named exports for all components (no default exports except App.tsx)
- Grouped exports at end of file for UI components
- Re-exports from barrel files not used
### File Organization
```
src/app/
├── App.tsx # Default export, entry point
├── routes.ts # Named export for router config
├── components/
│ ├── [Layout].tsx # Named exports
│ ├── ui/ # UI primitives
│ │ └── [component].tsx
│ └── views/ # Page views
│ └── [View].tsx
└── styles/
└── *.css
```
## Special Conventions
### Touchscreen Interface
- No scrollbars visible (hidden via CSS)
- Navigation via fixed Up/Down buttons
- Fixed button positioning: `fixed top-20 right-4`
### Data Display Pattern
- Icon + Title header for all views
- Card-based content organization
- Color-coded data categories
### Status Indicators
- Icon + text pattern: `<Wifi className="w-3 h-3 text-green-500" />`
- Dot indicators: `w-2 h-2 rounded-full`
## Configuration Files
- **`vite.config.ts`:** Build configuration with path alias
- **`postcss.config.mjs`:** PostCSS (minimal - Tailwind handles processing)
- **`package.json`:** Scripts limited to `build`
- **No lint/format config detected:** No ESLint, Prettier, or Biome configuration
---
*Convention analysis: 2026-03-13*

View File

@@ -0,0 +1,190 @@
# External Integrations
**Analysis Date:** 2026-03-13
## APIs & External Services
**Backend API Integration:**
- **Status:** Not yet implemented
- **Evidence:** No fetch/axios/API client code found in source files
- **Pattern Used:** Static mock data in view components
**Current Data Approach:**
- All data is hardcoded/mock data within components
- Examples:
- `RainfallView.tsx` - Static rainfall data array
- `StationInfoView.tsx` - Hardcoded station information
- `FlashMemoryView.tsx` - Mock file list and content
- `ADCSettingView.tsx` - Mock ADC channel readings
- `CalibrationView.tsx` - Mock sensor calibration status
**Planned Integration Points:**
Based on view structure, expected API endpoints include:
- `/api/rainfall` - Rainfall measurement data
- `/api/station` - Station configuration and status
- `/api/adc` - ADC channel readings
- `/api/calibration` - Sensor calibration data
- `/api/files` - Flash memory file management
- `/api/gprs` - GPRS settings and connectivity
- `/api/network` - Network configuration
- `/api/auth` - Authentication (login/logout)
## Data Storage
**Databases:**
- **Type:** None detected in frontend
- **Pattern:** This is a pure frontend application
- **Expected Backend:** RTU device likely exposes REST API or WebSocket
**File Storage:**
- **Frontend:** Local filesystem access not implemented
- **Flash Memory View:** Mock file browser interface (UI only)
- **Expected:** File download/upload via API to device storage
**Caching:**
- **Current:** React state only (useState)
- **No external caching libraries detected**
## Authentication & Identity
**Auth Provider:**
- **Status:** UI only - Login form present but not functional
- **Location:** `src/app/components/views/LoginView.tsx`
- **Current:** Static credentials display ("admin / admin")
- **Implementation:** Basic form without API integration
**Auth Pattern:**
- Username/password form
- "Remember me" checkbox (localStorage potential)
- Login status indicator in header (mock state)
- Expected: JWT or session-based auth with backend
## Monitoring & Observability
**Error Tracking:**
- **Service:** None detected
- **Implementation:** No error boundaries or logging framework
**Logs:**
- **Approach:** Console logging only (default)
- **No structured logging detected**
## Communication Protocols
**GPRS/Cellular:**
- **UI Location:** `src/app/components/views/GPRSSettingView.tsx`
- **Configuration:** Server URL, Port, Upload Interval settings
- **Integration:** Form UI only - no actual GPRS client code
**Network Setup:**
- **UI Location:** `src/app/components/views/NetworkSetupView.tsx`
- **Expected:** IP configuration, DNS, Gateway settings
**Mobile Setting:**
- **UI Location:** `src/app/components/views/MobileSettingView.tsx`
- **Purpose:** SMS/cellular configuration for RTU
## Hardware Integration
**ADC (Analog-to-Digital Converter):**
- **UI Location:** `src/app/components/views/ADCSettingView.tsx`
- **Channels:** 4 channels displayed (Water Level, Temperature, Pressure, Flow Rate)
- **Integration:** Voltage and raw value display expected from hardware
**Sensors:**
- **Rainfall Sensor** - `RainfallView.tsx`, `RainfallSettingView.tsx`
- **Water Level Sensor** - `LevelSettingView.tsx`
- **Temperature/Pressure** - `ADCSettingView.tsx`
- **Evaporation Sensor** - `EVAPSettingView.tsx`
- **Siren Control** - `SirenSettingView.tsx`
**Status Monitoring:**
- Header displays: Online status, battery voltage, solar voltage
- Mock state only - no real hardware polling
## Environment Configuration
**Required Environment Variables (Expected):**
Based on typical RTU applications:
```
VITE_API_BASE_URL=http://device.local/api
VITE_WS_URL=ws://device.local/ws
VITE_DEVICE_ID=STN-001
```
**Current State:**
- No `.env` files present
- No environment variable usage detected
- All values hardcoded
**Secrets Location:**
- Not applicable (no backend integration yet)
## Webhooks & Callbacks
**Incoming:**
- None detected
- Expected: WebSocket for real-time sensor data
**Outgoing:**
- None detected
- Expected: HTTP POST for data upload to server
## CI/CD & Deployment
**Hosting:**
- **Platform:** Figma Make (inferred from package name `@figma/my-make-file`)
- **Build Command:** `vite build`
- **Output:** Static SPA files in `dist/`
**CI Pipeline:**
- None detected (no `.github/workflows`, `.gitlab-ci.yml`, etc.)
## Integration Gaps
**Missing Critical Integrations:**
1. **Backend API Client**
- Missing: fetch/axios configuration
- Impact: Application shows only static data
- Recommendation: Add API client with error handling
2. **WebSocket Connection**
- Missing: Real-time sensor data updates
- Impact: Manual refresh required for data updates
- Recommendation: Implement WebSocket for live data
3. **Authentication Flow**
- Missing: Login/logout API integration
- Impact: Auth is UI-only
- Recommendation: Connect to device auth endpoint
4. **File Operations**
- Missing: Download/delete API calls
- Impact: Flash memory is read-only mock
- Recommendation: Implement file API client
5. **Hardware Commands**
- Missing: Save settings to device
- Impact: Settings forms don't persist
- Recommendation: Add POST endpoints for configuration
## Third-Party Services Summary
**Currently Integrated:**
| Service | Purpose | Location |
|---------|---------|----------|
| Lucide React | Icons | All view components |
| Radix UI | Accessible components | `src/app/components/ui/` |
**Recommended for Integration:**
| Service | Purpose | Use Case |
|---------|---------|----------|
| axios/fetch | HTTP client | API communication |
| SWR/React Query | Data fetching | Caching and synchronization |
| zod | Validation | API response validation |
| WebSocket API | Real-time | Sensor data streaming |
---
*Integration audit: 2026-03-13*

150
.planning/codebase/STACK.md Normal file
View File

@@ -0,0 +1,150 @@
# Technology Stack
**Analysis Date:** 2026-03-13
## Languages
**Primary:**
- TypeScript (React) - All application logic and components
- CSS - Styling via Tailwind CSS with custom theme variables
**Secondary:**
- JavaScript - Build tool configuration
## Runtime
**Environment:**
- Node.js (latest LTS recommended)
**Package Manager:**
- pnpm (evidenced by `pnpm.overrides` in `package.json`)
- Lockfile: Not committed to repository
## Frameworks
**Core:**
- **React 18.3.1** - UI library with hooks and functional components
- Peer dependency (optional, for compatibility with Figma Make)
- **React Router 7.13.0** - Client-side routing with Data API mode
- Router configuration in `src/app/routes.ts`
- Uses `createBrowserRouter` for SPA navigation
**UI Component Framework:**
- **Radix UI** - Headless accessible UI primitives
- 23 Radix primitives including: accordion, dialog, dropdown-menu, select, tabs, tooltip, etc.
- Provides accessibility and keyboard navigation out of the box
**Styling:**
- **Tailwind CSS 4.1.12** - Utility-first CSS framework
- Integrated via `@tailwindcss/vite` plugin
- Custom theme configuration in `src/styles/theme.css`
- Uses CSS variables for theming with light/dark mode support
- Animation support via `tw-animate-css`
**Animation:**
- **Framer Motion ("motion" package 12.23.24)** - React animation library
## Build Tools
**Build System:**
- **Vite 6.3.5** - Fast development server and production bundler
- Config: `vite.config.ts`
- Uses `@vitejs/plugin-react` for React support
- Path alias `@` configured to `./src`
- Asset support: `.svg`, `.csv` files
**CSS Processing:**
- **PostCSS** - CSS transformation (via Vite plugin)
- Config: `postcss.config.mjs` (empty - Tailwind v4 handles this automatically)
## Key Dependencies
**Critical UI Components:**
- `@radix-ui/react-*` (23 packages) - Accessible UI primitives
- `class-variance-authority` 0.7.1 - Type-safe Tailwind variant generation
- `clsx` 2.1.1 - Conditional class name joining
- `tailwind-merge` 3.2.0 - Tailwind class deduplication
- `lucide-react` 0.487.0 - Icon library
**Form & Input:**
- `react-hook-form` 7.55.0 - Form state management and validation
- `cmdk` 1.1.1 - Command palette/Combobox component
- `input-otp` 1.4.2 - OTP input component
**Data Visualization:**
- `recharts` 2.15.2 - React charting library
**Date Handling:**
- `date-fns` 3.6.0 - Date formatting and manipulation
- `react-day-picker` 8.10.1 - Date picker component
**Theming:**
- `next-themes` 0.4.6 - Theme switching (dark/light mode)
**Notifications:**
- `sonner` 2.0.3 - Toast notifications
**Carousels & Layout:**
- `embla-carousel-react` 8.6.0 - Touch carousel
- `react-resizable-panels` 2.1.7 - Resizable panel layouts
- `react-responsive-masonry` 2.7.1 - Masonry grid layout
**Drag & Drop:**
- `react-dnd` 16.0.1 + `react-dnd-html5-backend` 16.0.1 - Drag and drop functionality
**Drawer/Modal:**
- `vaul` 1.1.2 - Drawer component for mobile
**Slider:**
- `react-slick` 0.31.0 - Image/content carousel
**Optional/Peer Dependencies:**
- `@emotion/react` / `@emotion/styled` - CSS-in-JS (for MUI compatibility)
- `@mui/material` / `@mui/icons-material` - Material UI (peer dependency for Figma Make)
## Configuration
**Environment:**
- No `.env` file detected in repository
- Configuration appears to be hardcoded or passed at build time
- No environment-specific configs visible
**Build:**
- `vite.config.ts` - Vite configuration with React and Tailwind plugins
- `postcss.config.mjs` - Empty config (Tailwind v4 handles PostCSS internally)
- `tsconfig.json` - Not present in repository (TypeScript handled by Vite)
## Platform Requirements
**Development:**
- Node.js (latest LTS)
- pnpm package manager
- Modern browser with ES2020+ support
**Production:**
- Static file hosting (SPA)
- Target: 7-inch industrial touchscreen displays (800x480 to 1024x600)
- Optimized for landscape orientation
- Touch-friendly interface design
**Browser Support:**
- Modern Chromium-based browsers (Chrome, Edge)
- WebKit (Safari)
- Firefox (ESR)
## Notable Architecture Decisions
**Design System:**
- Uses shadcn/ui pattern (Radix + Tailwind + CVA)
- Custom theme tokens defined in CSS variables
- Dark theme by default for industrial use
- Touch-optimized sizing (minimum 44x44px touch targets)
**Component Organization:**
- UI components: `src/app/components/ui/`
- View components: `src/app/components/views/`
- Layout components: `src/app/components/` (root level)
---
*Stack analysis: 2026-03-13*

View File

@@ -0,0 +1,167 @@
# Codebase Structure
**Analysis Date:** 2025-03-13
## Directory Layout
```
sample_interface/
├── src/
│ ├── app/
│ │ ├── App.tsx # Application entry point
│ │ ├── routes.ts # Route definitions
│ │ └── components/
│ │ ├── DashboardLayout.tsx # Main layout shell
│ │ ├── Header.tsx # Top status bar
│ │ ├── NavigationButtons.tsx # Scroll controls
│ │ ├── Sidebar.tsx # Navigation sidebar
│ │ ├── figma/
│ │ │ └── ImageWithFallback.tsx
│ │ ├── ui/ # 40+ shadcn/ui components
│ │ │ ├── button.tsx
│ │ │ ├── card.tsx
│ │ │ ├── input.tsx
│ │ │ ├── utils.ts
│ │ │ └── ...
│ │ └── views/ # Page/route components
│ │ ├── ADCSettingView.tsx
│ │ ├── CalibrationView.tsx
│ │ ├── DateTimeSettingView.tsx
│ │ ├── EVAPSettingView.tsx
│ │ ├── FlashMemoryView.tsx
│ │ ├── GPRSSettingView.tsx
│ │ ├── GraphView.tsx
│ │ ├── LevelSettingView.tsx
│ │ ├── LoginView.tsx
│ │ ├── MobileSettingView.tsx
│ │ ├── NetworkSetupView.tsx
│ │ ├── RainfallSettingView.tsx
│ │ ├── RainfallView.tsx
│ │ ├── SettingView.tsx
│ │ ├── SirenSettingView.tsx
│ │ └── StationInfoView.tsx
│ └── styles/
│ ├── index.css # Main stylesheet entry
│ ├── tailwind.css # Tailwind imports
│ └── theme.css # Theme variables
├── guidelines/
│ └── Guidelines.md # Design system documentation
├── package.json # Dependencies
├── postcss.config.mjs # PostCSS configuration
└── vite.config.ts # Vite build configuration
```
## Directory Purposes
**src/app/:**
- Purpose: Application logic and component tree
- Contains: Entry point, routing, components
- Key files: `App.tsx`, `routes.ts`
**src/app/components/:**
- Purpose: Layout and structural components
- Contains: DashboardLayout, Header, Sidebar, NavigationButtons
- Key files: `DashboardLayout.tsx`, `Sidebar.tsx`
**src/app/components/ui/:**
- Purpose: shadcn/ui primitive components
- Contains: 40+ UI components (button, card, input, etc.)
- Key files: `utils.ts` (cn function), `button.tsx`, `card.tsx`
- Pattern: Each component in separate file with PascalCase naming
**src/app/components/views/:**
- Purpose: Route/page-level components
- Contains: 16 view components (one per route)
- Key files: `RainfallView.tsx` (default), `LoginView.tsx`, `GraphView.tsx`
- Pattern: `{Name}View.tsx` naming convention
**src/app/components/figma/:**
- Purpose: Figma-related utilities
- Contains: `ImageWithFallback.tsx`
- Usage: Image loading with error fallback
**src/styles/:**
- Purpose: Global styles and CSS configuration
- Contains: CSS imports and theme definitions
- Key files: `index.css` (entry), `tailwind.css`, `theme.css`
**guidelines/:**
- Purpose: Design system documentation
- Contains: `Guidelines.md` (458 lines of design specs)
- Usage: Color palette, typography, spacing standards
## Key File Locations
**Entry Points:**
- `sample_interface/src/app/App.tsx`: React application root
- `sample_interface/src/app/routes.ts`: Route configuration
- `sample_interface/src/styles/index.css`: Style entry
**Configuration:**
- `sample_interface/vite.config.ts`: Vite build config with @ alias
- `sample_interface/package.json`: Dependencies (React 18, React Router 7, Radix, Tailwind 4)
- `sample_interface/postcss.config.mjs`: PostCSS configuration
**Core Layout:**
- `sample_interface/src/app/components/DashboardLayout.tsx`: Main layout with Outlet
- `sample_interface/src/app/components/Sidebar.tsx`: Navigation with 7 menu items
- `sample_interface/src/app/components/Header.tsx`: Status bar with time, connection, battery
**Core UI:**
- `sample_interface/src/app/components/ui/utils.ts`: `cn()` class merging utility
- `sample_interface/src/app/components/ui/button.tsx`: Primary button component
- `sample_interface/src/app/components/ui/card.tsx`: Card container component
## Naming Conventions
**Files:**
- Components: PascalCase.tsx (e.g., `RainfallView.tsx`, `Button.tsx`)
- Utilities: camelCase.ts (e.g., `utils.ts`)
- Config: kebab-case.ts (e.g., `vite.config.ts`)
- Styles: lowercase.css (e.g., `index.css`)
**Directories:**
- Lowercase: `ui/`, `views/`, `styles/`, `figma/`
**Exports:**
- Components: Named exports (e.g., `export function Button`)
- Utilities: Named exports (e.g., `export function cn`)
- View suffix: All route components end with `View` (e.g., `RainfallView`, `LoginView`)
## Where to Add New Code
**New Route/View:**
- Implementation: `sample_interface/src/app/components/views/{Name}View.tsx`
- Registration: `sample_interface/src/app/routes.ts` (add to children array)
- Menu item: `sample_interface/src/app/components/Sidebar.tsx` (add to menuItems array)
**New UI Component:**
- Implementation: `sample_interface/src/app/components/ui/{component}.tsx`
- Pattern: Follow shadcn/ui style with `cn()` utility
- Re-export from other components as needed
**New Layout Component:**
- Implementation: `sample_interface/src/app/components/{Component}.tsx`
- Import in: `DashboardLayout.tsx` or `Sidebar.tsx` as needed
**Styles/Theme:**
- Global styles: `sample_interface/src/styles/theme.css`
- Tailwind config: `sample_interface/vite.config.ts` (Tailwind v4 uses CSS config)
## Special Directories
**sample_interface/src/app/components/ui/:**
- Purpose: shadcn/ui component library
- Generated: Partially (shadcn init pattern)
- Committed: Yes
- Note: 40+ components from Radix UI primitives
**sample_interface/guidelines/:**
- Purpose: Design documentation
- Generated: No (manually maintained)
- Committed: Yes
- Note: Contains 458 lines of design system specs
---
*Structure analysis: 2025-03-13*

View File

@@ -0,0 +1,249 @@
# Testing Patterns
**Analysis Date:** 2026-03-13
## Test Infrastructure
**Status: NO TESTING INFRASTRUCTURE DETECTED**
The codebase currently lacks automated testing configuration and test files.
## Test Framework
**Runner:** Not configured
- No Jest configuration detected
- No Vitest configuration detected
- No Playwright/Cypress configuration detected
**Assertion Library:** Not configured
- No testing libraries in dependencies
**Run Commands:** Not available
- `package.json` only defines: `"build": "vite build"`
- No test scripts present
## Test File Organization
**Current State:**
- No test files in source code (`*.test.ts`, `*.spec.ts`, `*.test.tsx`, `*.spec.tsx`)
- All test file matches were from `node_modules/` (zod library tests)
**File Pattern:** Not established
**Test Directory Structure:** Not implemented
## Code Quality Indicators
### TODO/FIXME Comments
Minimal technical debt markers found:
- `MobileSettingView.tsx` line 31: `placeholder="+63 XXX XXX XXXX"` (placeholder text, not TODO)
### Code Complexity
View component line counts (reasonable for view components):
```
FlashMemoryView.tsx 112 lines
ADCSettingView.tsx 83 lines
LevelSettingView.tsx 78 lines
MobileSettingView.tsx 70 lines
RainfallSettingView.tsx 69 lines
NetworkSetupView.tsx 69 lines
DateTimeSettingView.tsx 65 lines
CalibrationView.tsx 63 lines
RainfallView.tsx 63 lines
SettingView.tsx 76 lines
LoginView.tsx 61 lines
GraphView.tsx 51 lines
EVAPSettingView.tsx 54 lines
SirenSettingView.tsx 71 lines
GPRSSettingView.tsx 68 lines
StationInfoView.tsx 40 lines
```
**Total view code:** ~1,092 lines across 16 view files
### Component Complexity
UI components (`src/app/components/ui/`):
- Range: 6 lines (`utils.ts`) to 168 lines (`form.tsx`)
- Most components: 20-90 lines
- Pattern: Small, focused components following shadcn/ui conventions
## Missing Testing Infrastructure
### Critical Gaps
1. **No unit test framework** - Components cannot be unit tested
2. **No integration tests** - Route integration untested
3. **No E2E tests** - User flows untested
4. **No test scripts** - No CI/CD integration possible
5. **No mocking strategy** - External dependencies not mockable
### Testing Dependencies to Add
For comprehensive testing, the following would be needed:
```json
{
"devDependencies": {
"vitest": "^2.x",
"@testing-library/react": "^14.x",
"@testing-library/jest-dom": "^6.x",
"@testing-library/user-event": "^14.x",
"jsdom": "^24.x"
}
}
```
Or alternatively with Jest:
```json
{
"devDependencies": {
"jest": "^29.x",
"@testing-library/react": "^14.x",
"@testing-library/jest-dom": "^6.x",
"ts-jest": "^29.x",
"jest-environment-jsdom": "^29.x"
}
}
```
## Recommended Testing Strategy
### Priority 1: Unit Tests for UI Components
Test critical UI primitives in `src/app/components/ui/`:
- `button.tsx` - Variant rendering, click handling
- `card.tsx` - Composition pattern
- `input.tsx` - Value handling, focus states
- `switch.tsx` - Toggle behavior
### Priority 2: View Component Tests
Test user interactions in views:
- Form submissions
- State changes
- Navigation triggers
### Priority 3: Integration Tests
Test route configuration:
- Route rendering
- Navigation flow
- Layout composition
## Testing Conventions to Establish
### Test File Naming
Recommended pattern (when tests are added):
- Co-located: `[Component].test.tsx` next to `[Component].tsx`
- Or separate: `__tests__/[Component].test.tsx`
### Test Structure (Recommended)
```typescript
// button.test.tsx - Example pattern to follow
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { Button } from './button';
describe('Button', () => {
it('renders with default variant', () => {
render(<Button>Click me</Button>);
expect(screen.getByText('Click me')).toBeInTheDocument();
});
it('handles click events', () => {
const handleClick = vi.fn();
render(<Button onClick={handleClick}>Click me</Button>);
fireEvent.click(screen.getByText('Click me'));
expect(handleClick).toHaveBeenCalled();
});
it('renders different variants', () => {
const { rerender } = render(<Button variant="destructive">Delete</Button>);
// Assert destructive styling
rerender(<Button variant="outline">Cancel</Button>);
// Assert outline styling
});
});
```
### Mocking Strategy (Recommended)
**External Libraries:**
- Mock `lucide-react` icons for snapshot stability
- Mock `@radix-ui` components at boundary
**Browser APIs:**
- Mock `document.getElementById()` for scroll tests
- Mock `window` events if needed
**Example Mock Pattern:**
```typescript
// Mock scroll behavior
const scrollByMock = vi.fn();
Object.defineProperty(document, 'getElementById', {
value: vi.fn(() => ({ scrollBy: scrollByMock })),
});
```
## Coverage Recommendations
### Minimum Targets
- **UI Components:** 80% coverage (small, critical components)
- **View Components:** 60% coverage (user interaction paths)
- **Utility Functions:** 90% coverage (business logic)
- **Routes:** Integration tests for all paths
### Critical Paths to Test
1. Login form submission
2. Sidebar navigation
3. File selection in FlashMemoryView
4. Settings toggle switches
5. Navigation button scrolling
## CI/CD Integration
### GitHub Actions (Recommended)
When tests are added, include in workflow:
```yaml
name: Test
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v2
- run: pnpm install
- run: pnpm test
- run: pnpm test:coverage
```
## Testing Documentation Gap
**Issue:** No testing guidelines in existing documentation
The `Guidelines.md` file (458 lines) covers:
- Design patterns
- Color palettes
- Component naming
- Touchscreen guidelines
But does NOT cover:
- Testing conventions
- Test file organization
- Mocking patterns
- Coverage requirements
## Action Items for Testing
1. **Add testing dependencies** (Vitest + React Testing Library recommended)
2. **Create `vitest.config.ts`** with jsdom environment
3. **Add test scripts** to `package.json`
4. **Write initial tests** for critical UI components
5. **Document testing patterns** in Guidelines.md
6. **Set up CI/CD** to run tests on PR
7. **Establish coverage thresholds**
---
*Testing analysis: 2026-03-13*
**Summary:** This codebase currently has no testing infrastructure. All testing patterns documented above are recommendations for implementation rather than observed conventions.