@diagramers/admin
Version:
Diagramers Admin Template - React starter for admin dashboards.
878 lines (721 loc) • 19.9 kB
Markdown
# AI_PROMPT.md - /admin
## Overview
The /admin package is a comprehensive React-based admin dashboard template with modern UI/UX, extensive customization options, and full integration with the Diagramers ecosystem. Built with React 18, TypeScript, and a modular architecture for rapid development of professional admin interfaces. This document provides guidance for AI assistants working with this package.
## Core Architecture
### Project Structure
```
src/
├── components/ # Reusable UI components
│ ├── ui/ # Base UI components
│ ├── layout/ # Layout components
│ └── [custom-components]/ # Custom components
├── pages/ # Page components
├── services/ # API services
├── hooks/ # Custom React hooks
├── utils/ # Utility functions
├── types/ # TypeScript types
├── styles/ # CSS/SCSS files
├── assets/ # Static assets
└── App.tsx # Main application
```
### Key Technologies
- **React 18** - Latest React with concurrent features and hooks
- **TypeScript** - Full TypeScript support with strict typing
- **Modern Build System** - Webpack 5 with hot reload and optimization
- **CSS-in-JS** - Styled-components and CSS modules support
- **Responsive Design** - Mobile-first responsive layout system
## UI/UX Components
### Layout Components
```jsx
import { Layout, Sidebar, Header, Footer } from '@diagramers/admin';
// Main layout
<Layout>
<Sidebar />
<div className="main-content">
<Header />
<main>{children}</main>
<Footer />
</div>
</Layout>
```
### Data Components
```jsx
import { DataTable, DataGrid, DataChart } from '@diagramers/admin';
// Data table with sorting and filtering
<DataTable
data={products}
columns={productColumns}
sortable
filterable
pagination
/>
// Interactive chart
<DataChart
type="line"
data={chartData}
options={chartOptions}
/>
```
### Form Components
```jsx
import { Form, Input, Select, Button } from '@diagramers/admin';
// Dynamic form
<Form onSubmit={handleSubmit}>
<Input name="name" label="Name" required />
<Select name="category" label="Category" options={categories} />
<Button type="submit">Save</Button>
</Form>
```
### Navigation Components
```jsx
import { Navigation, Menu, Breadcrumb } from '@diagramers/admin';
// Sidebar navigation
<Navigation>
<Menu items={menuItems} />
</Navigation>
// Breadcrumb navigation
<Breadcrumb items={breadcrumbItems} />
```
## Authentication & Security
### Login Component
```jsx
import { LoginForm } from '@diagramers/admin';
<LoginForm
onLogin={handleLogin}
providers={['internal', 'google', 'github']}
rememberMe
forgotPassword
/>
```
### Protected Routes
```jsx
import { ProtectedRoute, useAuth } from '@diagramers/admin';
// Protected route component
<ProtectedRoute
path="/dashboard"
component={Dashboard}
roles={['admin', 'user']}
permissions={['read:dashboard']}
/>
// Use auth hook
const { user, isAuthenticated, login, logout } = useAuth();
```
### Role-Based Access
```jsx
import { usePermissions } from '@diagramers/admin';
const { hasPermission, hasRole } = usePermissions();
// Check permissions
{hasPermission('create:users') && (
<Button onClick={createUser}>Create User</Button>
)}
// Check roles
{hasRole('admin') && (
<AdminPanel />
)}
```
## Dashboard Features
### Analytics Dashboard
```jsx
import { AnalyticsDashboard } from '@diagramers/admin';
<AnalyticsDashboard
metrics={[
{ title: 'Total Users', value: 1250, change: '+12%' },
{ title: 'Revenue', value: '$45,230', change: '+8%' },
{ title: 'Orders', value: 89, change: '+5%' },
]}
charts={[
{ type: 'line', data: revenueData, title: 'Revenue Trend' },
{ type: 'bar', data: userData, title: 'User Growth' },
]}
/>
```
### Data Management
```jsx
import { DataManager } from '@diagramers/admin';
<DataManager
endpoint="/api/users"
columns={userColumns}
actions={['create', 'edit', 'delete', 'export']}
filters={['search', 'role', 'status']}
bulkActions={['activate', 'deactivate', 'delete']}
/>
```
### Real-time Updates
```jsx
import { useWebSocket } from '@diagramers/admin';
const { data, isConnected } = useWebSocket('/api/notifications');
// Real-time notifications
{data.map(notification => (
<Notification key={notification.id} {...notification} />
))}
```
## Customization & Theming
### Theme Customization
```scss
// src/sass/themes/_custom.scss
:root {
// Primary colors
--primary-color: #007bff;
--primary-hover: #0056b3;
--primary-light: #e3f2fd;
// Secondary colors
--secondary-color: #6c757d;
--secondary-hover: #545b62;
// Success colors
--success-color: #28a745;
--success-hover: #1e7e34;
// Danger colors
--danger-color: #dc3545;
--danger-hover: #c82333;
// Typography
--font-family: 'Inter', sans-serif;
--font-size-base: 1rem;
--line-height-base: 1.5;
// Spacing
--spacing-xs: 0.25rem;
--spacing-sm: 0.5rem;
--spacing-md: 1rem;
--spacing-lg: 1.5rem;
--spacing-xl: 3rem;
}
```
### Component Styling
```scss
// src/sass/components/_custom.scss
.custom-button {
background: var(--primary-color);
border: none;
border-radius: 8px;
padding: 12px 24px;
font-weight: 600;
transition: all 0.2s ease;
&:hover {
background: var(--primary-hover);
transform: translateY(-1px);
}
}
.custom-card {
background: white;
border-radius: 12px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
padding: 24px;
margin-bottom: 24px;
}
```
### Layout Customization
```jsx
// src/layout/Layout.js
import { Layout, Sidebar, Header } from '@diagramers/admin';
const CustomLayout = ({ children }) => (
<Layout className="custom-layout">
<Sidebar
className="custom-sidebar"
logo="/img/logo/custom-logo.svg"
menuItems={customMenuItems}
/>
<div className="main-content">
<Header
className="custom-header"
userMenu={customUserMenu}
notifications={customNotifications}
/>
<main className="content-area">
{children}
</main>
</div>
</Layout>
);
```
## API Integration
### API Service Setup
```javascript
// src/services/api.js
import { ApiService } from '@diagramers/admin';
const api = new ApiService({
baseURL: process.env.REACT_APP_API_URL,
timeout: 10000,
headers: {
'Content-Type': 'application/json',
},
});
// Add request interceptor for authentication
api.interceptors.request.use((config) => {
const token = localStorage.getItem('auth_token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
// Add response interceptor for error handling
api.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
// Handle unauthorized access
window.location.href = '/login';
}
return Promise.reject(error);
}
);
export default api;
```
### Data Fetching
```jsx
import { useApi } from '@diagramers/admin';
const { data, loading, error, refetch } = useApi('/api/users');
// With parameters
const { data: users } = useApi('/api/users', {
params: { page: 1, limit: 10, search: 'john' }
});
// With mutations
const { mutate, isLoading } = useApi('/api/users', {
method: 'POST',
onSuccess: () => {
// Handle success
},
onError: (error) => {
// Handle error
},
});
```
### Real-time Integration
```jsx
import { useWebSocket } from '@diagramers/admin';
const { data, isConnected, send } = useWebSocket('/api/notifications', {
onMessage: (message) => {
// Handle incoming messages
console.log('Received:', message);
},
onConnect: () => {
console.log('Connected to WebSocket');
},
onDisconnect: () => {
console.log('Disconnected from WebSocket');
},
});
// Send message
send({ type: 'notification', data: { message: 'Hello!' } });
```
## Responsive Design
### Mobile-First Approach
```scss
// src/sass/layout/_responsive.scss
.container {
width: 100%;
padding: 0 16px;
margin: 0 auto;
(min-width: 576px) {
max-width: 540px;
}
(min-width: 768px) {
max-width: 720px;
}
(min-width: 992px) {
max-width: 960px;
}
(min-width: 1200px) {
max-width: 1140px;
}
}
.sidebar {
(max-width: 768px) {
transform: translateX(-100%);
position: fixed;
z-index: 1000;
&.open {
transform: translateX(0);
}
}
}
```
### Touch-Friendly Components
```jsx
import { TouchableButton, SwipeableCard } from '@diagramers/admin';
// Touch-friendly button
<TouchableButton
size="large"
onPress={handlePress}
feedback="haptic"
>
Press Me
</TouchableButton>
// Swipeable card
<SwipeableCard
onSwipeLeft={() => handleDelete()}
onSwipeRight={() => handleEdit()}
>
<CardContent />
</SwipeableCard>
```
## Testing
### Component Testing
```jsx
import { render, screen, fireEvent } from '@testing-library/react';
import { LoginForm } from '@diagramers/admin';
test('login form submits with correct data', () => {
const mockOnLogin = jest.fn();
render(<LoginForm onLogin={mockOnLogin} />);
fireEvent.change(screen.getByLabelText('Email'), {
target: { value: 'test@example.com' },
});
fireEvent.change(screen.getByLabelText('Password'), {
target: { value: 'password123' },
});
fireEvent.click(screen.getByRole('button', { name: /login/i }));
expect(mockOnLogin).toHaveBeenCalledWith({
email: 'test@example.com',
password: 'password123',
});
});
```
### Integration Testing
```jsx
import { render, screen, waitFor } from '@testing-library/react';
import { DataTable } from '@diagramers/admin';
test('data table loads and displays data', async () => {
const mockData = [
{ id: 1, name: 'John Doe', email: 'john@example.com' },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com' },
];
render(<DataTable data={mockData} />);
await waitFor(() => {
expect(screen.getByText('John Doe')).toBeInTheDocument();
expect(screen.getByText('Jane Smith')).toBeInTheDocument();
});
});
```
## Performance Optimization
### Code Splitting
```jsx
import { lazy, Suspense } from 'react';
// Lazy load components
const Dashboard = lazy(() => import('./pages/Dashboard'));
const Users = lazy(() => import('./pages/Users'));
const Settings = lazy(() => import('./pages/Settings'));
// Suspense wrapper
<Suspense fallback={<LoadingSpinner />}>
<Dashboard />
</Suspense>
```
### Memoization
```jsx
import { useMemo, useCallback } from 'react';
// Memoize expensive calculations
const expensiveValue = useMemo(() => {
return data.reduce((sum, item) => sum + item.value, 0);
}, [data]);
// Memoize callbacks
const handleClick = useCallback((id) => {
// Handle click
}, []);
```
### Image Optimization
```jsx
import { OptimizedImage } from '@diagramers/admin';
<OptimizedImage
src="/img/avatar.jpg"
alt="User Avatar"
width={100}
height={100}
lazy
placeholder="/img/avatar-placeholder.jpg"
/>
```
## Security
### Security Headers
```javascript
// public/index.html
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';">
<meta http-equiv="X-Content-Type-Options" content="nosniff">
<meta http-equiv="X-Frame-Options" content="DENY">
<meta http-equiv="X-XSS-Protection" content="1; mode=block">
```
### Input Validation
```jsx
import { useForm } from '@diagramers/admin';
const { register, handleSubmit, errors } = useForm();
<form onSubmit={handleSubmit(onSubmit)}>
<input
{...register('email', {
required: 'Email is required',
pattern: {
value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
message: 'Invalid email address',
},
})}
/>
{errors.email && <span>{errors.email.message}</span>}
</form>
```
### XSS Prevention
```jsx
import { sanitizeHtml } from '@diagramers/admin';
// Sanitize user input
const sanitizedContent = sanitizeHtml(userInput);
// Safe rendering
<div dangerouslySetInnerHTML={{ __html: sanitizedContent }} />
```
## Configuration
### Environment Variables
```bash
# API Configuration
REACT_APP_API_URL=http://localhost:3000
REACT_APP_PROJECT_NAME=My Admin Dashboard
# Authentication
REACT_APP_JWT_SECRET=your-jwt-secret
REACT_APP_AUTH_PROVIDER=internal
# Features
REACT_APP_ENABLE_ANALYTICS=true
REACT_APP_ENABLE_NOTIFICATIONS=true
REACT_APP_ENABLE_REAL_TIME=true
# External Services
REACT_APP_SOCKET_URL=ws://localhost:3000
REACT_APP_SENTRY_DSN=your-sentry-dsn
```
### API Configuration
```javascript
// src/config.js
export const SERVICE_URL = process.env.REACT_APP_API_URL || 'http://localhost:3000';
export const REACT_HELMET_PROPS = {
defaultTitle: process.env.REACT_APP_PROJECT_NAME || 'Admin Dashboard',
titleTemplate: `%s | ${process.env.REACT_APP_PROJECT_NAME || 'Admin Dashboard'}`,
};
```
### Theme Configuration
```scss
// src/sass/themes/_custom.scss
:root {
--primary-color: #007bff;
--secondary-color: #6c757d;
--success-color: #28a745;
--danger-color: #dc3545;
--warning-color: #ffc107;
--info-color: #17a2b8;
--light-color: #f8f9fa;
--dark-color: #343a40;
}
```
## Deployment
### Build Configuration
```javascript
// webpack.config.js
module.exports = {
mode: 'production',
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
},
},
},
},
output: {
filename: '[name].[contenthash].js',
chunkFilename: '[name].[contenthash].chunk.js',
},
};
```
### Environment-Specific Builds
```bash
# Development build
npm run build:dev
# Staging build
npm run build:staging
# Production build
npm run build:prod
# Analyze bundle
npm run build:analyze
```
### Docker Deployment
```dockerfile
# Dockerfile
FROM node:18-alpine as builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build:prod
FROM nginx:alpine
COPY --from=builder /app/build /usr/share/nginx/html
COPY nginx.conf /etc/nginx/nginx.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
```
## Common Patterns
### Error Handling
```jsx
// Error boundary component
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
console.error('Error caught by boundary:', error, errorInfo);
}
render() {
if (this.state.hasError) {
return <ErrorFallback />;
}
return this.props.children;
}
}
```
### Loading States
```jsx
// Loading component
const LoadingSpinner = () => (
<div className="loading-spinner">
<div className="spinner"></div>
<p>Loading...</p>
</div>
);
// Usage with conditional rendering
{loading ? <LoadingSpinner /> : <DataTable data={data} />}
```
### Form Handling
```jsx
// Form with validation
const UserForm = () => {
const { register, handleSubmit, errors, reset } = useForm();
const onSubmit = async (data) => {
try {
await createUser(data);
reset();
showSuccess('User created successfully');
} catch (error) {
showError('Failed to create user');
}
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Input
{...register('name', { required: 'Name is required' })}
error={errors.name?.message}
/>
<Button type="submit">Create User</Button>
</form>
);
};
```
## Troubleshooting
### Common Issues
#### Build Issues
1. **Module not found** - Check import paths and dependencies
2. **TypeScript errors** - Verify type definitions and imports
3. **CSS not loading** - Check SCSS compilation and imports
4. **Environment variables** - Ensure REACT_APP_ prefix
#### Runtime Issues
1. **API connection** - Verify API URL and CORS settings
2. **Authentication** - Check JWT token and auth flow
3. **WebSocket connection** - Verify WebSocket URL and connection
4. **Performance** - Check bundle size and code splitting
#### Styling Issues
1. **Theme not applying** - Check CSS variable definitions
2. **Responsive design** - Verify media queries and breakpoints
3. **Component styling** - Check CSS class names and specificity
### Debug Mode
```bash
# Enable debug logging
REACT_APP_DEBUG=true npm start
# Enable detailed error messages
REACT_APP_SHOW_ERRORS=true npm start
```
### Performance Issues
1. **Bundle size** - Use bundle analyzer
2. **Rendering performance** - Check component optimization
3. **Memory leaks** - Monitor component lifecycle
4. **Network requests** - Optimize API calls
## Best Practices
### Code Organization
- **Component structure** - Follow consistent patterns
- **File naming** - Use descriptive names
- **Import organization** - Group imports logically
- **TypeScript usage** - Leverage type safety
### Performance
- **Code splitting** - Lazy load components
- **Memoization** - Use React.memo and useMemo
- **Bundle optimization** - Minimize bundle size
- **Image optimization** - Use appropriate formats
### Security
- **Input validation** - Validate all user inputs
- **XSS prevention** - Sanitize user content
- **Authentication** - Secure token handling
- **HTTPS** - Use secure connections
### Accessibility
- **Semantic HTML** - Use proper HTML elements
- **ARIA labels** - Provide screen reader support
- **Keyboard navigation** - Ensure keyboard accessibility
- **Color contrast** - Maintain readable contrast ratios
## Integration Examples
### Backend Integration
```javascript
// API service configuration
const apiService = new ApiService({
baseURL: process.env.REACT_APP_API_URL,
timeout: 10000,
headers: {
'Content-Type': 'application/json',
},
});
// Authentication integration
const authService = new AuthService(apiService);
const { user, login, logout } = useAuth(authService);
```
### Third-Party Services
```javascript
// Analytics integration
import { Analytics } from '@diagramers/admin';
Analytics.track('page_view', { page: 'dashboard' });
Analytics.track('user_action', { action: 'create_user' });
// Error tracking
import { ErrorTracker } from '@diagramers/admin';
ErrorTracker.captureException(error);
ErrorTracker.setUser({ id: user.id, email: user.email });
```
### Real-time Features
```javascript
// WebSocket integration
const { data, isConnected } = useWebSocket('/api/notifications');
// Real-time updates
useEffect(() => {
if (data) {
updateNotifications(data);
}
}, [data]);
// Push notifications
import { useNotifications } from '@diagramers/admin';
const { requestPermission, showNotification } = useNotifications();
```
## Future Enhancements
### Planned Features
- **Advanced chart library integration**
- **Drag & drop interface builder**
- **Advanced form builder**
- **Workflow automation**
- **Advanced reporting system**
- **Multi-language support**
- **Advanced theming system**
- **Component marketplace**
- **Advanced analytics**
- **Mobile app companion**
### Performance Improvements
- **Virtual scrolling for large datasets**
- **Advanced caching strategies**
- **Progressive web app features**
- **Service worker integration**
- **Advanced bundle optimization**
### Developer Experience
- **Component storybook**
- **Advanced debugging tools**
- **Performance monitoring**
- **Error tracking integration**
- **Advanced testing utilities**
This AI_PROMPT.md provides comprehensive guidance for AI assistants working with the /admin package, covering all major features, patterns, and best practices.