Enhance Next.js configuration and dependencies for improved functionality and localization support. Added support for internationalization with next-intl, updated global styles, and integrated new fonts. Removed default home page and updated README with project details and setup instructions.
This commit is contained in:
1 parent
2911dea00b
commit
44f4fa98e2
320 files changed
+31666
-220
No files matched your search
@@ -0,0 +1,28 @@
|
||||
---
|
||||
name: design-system-rules
|
||||
description: >-
|
||||
Project design-system rules for AUT Open Education: shadcn/ui + Tailwind only.
|
||||
Use when changing UI, styling, colors, cards, navigation, forms, or loading
|
||||
states. Read docs/design-system-rules.md and skill shadcn-ui before visual work.
|
||||
---
|
||||
|
||||
# Design System Rules
|
||||
|
||||
## Instructions
|
||||
|
||||
1. **Before any UI change**, read:
|
||||
- `docs/design-system-rules.md`
|
||||
- skill `shadcn-ui` (`.agents/skills/shadcn-ui/SKILL.md`)
|
||||
- Theme: `src/app/globals.css` (shadcn CSS variables only)
|
||||
2. Build from `@/components/ui/*` + Tailwind. Add missing pieces with `npx shadcn@latest add`.
|
||||
3. Colors: `bg-primary`, `text-muted-foreground`, `bg-muted`, `bg-chart-3` — never `ds-*` or `--brand-*`.
|
||||
4. Extract substantial UI into molecules/organisms; keep pages thin (`.cursor/rules/ui-architecture.mdc`).
|
||||
5. Material Design skill is methodology only — do not replace AUT colors mapped into shadcn tokens.
|
||||
6. Complete the checklist in §4 of `docs/design-system-rules.md` before finishing.
|
||||
|
||||
## Anti-patterns
|
||||
|
||||
- Reviving `.ds-*` utilities or `--brand-*` parallel tokens
|
||||
- Inventing new hex in components (use theme vars / SVG `var(--accent)`)
|
||||
- Full section border boxes when `Card` / `Separator` / spacing suffice
|
||||
- Physical `ml/mr/pl/pr` on RTL without an LTR island
|
||||
@@ -0,0 +1,175 @@
|
||||
---
|
||||
name: frontend-excellence
|
||||
description: Modern frontend patterns for React Server Components, performance optimization, and Core Web Vitals
|
||||
---
|
||||
|
||||
# Frontend Excellence
|
||||
|
||||
## React Server Components
|
||||
|
||||
Server Components run on the server and send rendered HTML to the client. They can directly access databases, filesystems, and internal APIs without exposing them to the browser.
|
||||
|
||||
```tsx
|
||||
// app/products/page.tsx (Server Component by default)
|
||||
async function ProductsPage() {
|
||||
const products = await db.query("SELECT * FROM products WHERE active = true");
|
||||
return (
|
||||
<main>
|
||||
<h1>Products</h1>
|
||||
<ProductList products={products} />
|
||||
<AddToCartButton /> {/* Client Component */}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Rules:
|
||||
- Server Components cannot use `useState`, `useEffect`, or browser APIs
|
||||
- Mark interactive components with `'use client'` at the top of the file
|
||||
- Pass serializable props from Server to Client Components (no functions, no classes)
|
||||
- Keep `'use client'` boundary as deep in the tree as possible
|
||||
|
||||
## Streaming SSR
|
||||
|
||||
```tsx
|
||||
import { Suspense } from 'react';
|
||||
|
||||
export default function Dashboard() {
|
||||
return (
|
||||
<div>
|
||||
<Header /> {/* renders immediately */}
|
||||
<Suspense fallback={<ChartSkeleton />}>
|
||||
<AnalyticsChart /> {/* streams when ready */}
|
||||
</Suspense>
|
||||
<Suspense fallback={<TableSkeleton />}>
|
||||
<RecentOrders /> {/* streams independently */}
|
||||
</Suspense>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Each `Suspense` boundary streams independently. Place boundaries around data-fetching components to avoid blocking the entire page.
|
||||
|
||||
## Code Splitting
|
||||
|
||||
```tsx
|
||||
import dynamic from 'next/dynamic';
|
||||
|
||||
const HeavyEditor = dynamic(() => import('@/components/Editor'), {
|
||||
loading: () => <EditorSkeleton />,
|
||||
ssr: false,
|
||||
});
|
||||
|
||||
const AdminPanel = dynamic(() => import('@/components/AdminPanel'));
|
||||
```
|
||||
|
||||
Split on:
|
||||
- Route boundaries (automatic in Next.js App Router)
|
||||
- Conditionally rendered components (modals, drawers, admin panels)
|
||||
- Heavy libraries (chart libraries, rich text editors, maps)
|
||||
- Below-the-fold content
|
||||
|
||||
## Bundle Optimization
|
||||
|
||||
```javascript
|
||||
// next.config.js
|
||||
module.exports = {
|
||||
experimental: {
|
||||
optimizePackageImports: ['lucide-react', '@heroicons/react', 'lodash-es'],
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
Checklist:
|
||||
- Run `npx next build` and review the output size per route
|
||||
- Use `@next/bundle-analyzer` to identify large dependencies
|
||||
- Replace `moment` with `date-fns` or `dayjs` (save ~200KB)
|
||||
- Import specific functions: `import { debounce } from 'lodash-es/debounce'`
|
||||
- Prefer CSS over JS for animations (no runtime cost)
|
||||
- Tree-shake icon libraries: `import { Search } from 'lucide-react'`
|
||||
|
||||
## Core Web Vitals Targets
|
||||
|
||||
| Metric | Good | Needs Work | Poor |
|
||||
|--------|------|------------|------|
|
||||
| LCP (Largest Contentful Paint) | <2.5s | 2.5-4.0s | >4.0s |
|
||||
| INP (Interaction to Next Paint) | <200ms | 200-500ms | >500ms |
|
||||
| CLS (Cumulative Layout Shift) | <0.1 | 0.1-0.25 | >0.25 |
|
||||
|
||||
## LCP Optimization
|
||||
|
||||
- Preload hero images: `<link rel="preload" as="image" href="..." />`
|
||||
- Use `priority` prop on above-the-fold `<Image>` components
|
||||
- Inline critical CSS, defer non-critical stylesheets
|
||||
- Avoid client-side rendering for above-the-fold content
|
||||
- Set explicit `width`/`height` on images to prevent layout shifts
|
||||
|
||||
## Image Optimization
|
||||
|
||||
```tsx
|
||||
import Image from 'next/image';
|
||||
|
||||
<Image
|
||||
src="/hero.jpg"
|
||||
alt="Descriptive alt text"
|
||||
width={1200}
|
||||
height={630}
|
||||
priority // preload for LCP images
|
||||
sizes="(max-width: 768px) 100vw, 50vw"
|
||||
placeholder="blur"
|
||||
blurDataURL={base64} // inline tiny placeholder
|
||||
/>
|
||||
```
|
||||
|
||||
- Use `next/image` or equivalent (automatic WebP/AVIF, responsive srcset)
|
||||
- Set `sizes` attribute to avoid downloading oversized images
|
||||
- Use `placeholder="blur"` with a base64 data URL for perceived performance
|
||||
- Lazy load below-the-fold images (default behavior)
|
||||
|
||||
## Font Loading Strategy
|
||||
|
||||
```tsx
|
||||
// app/layout.tsx
|
||||
import { Inter } from 'next/font/google';
|
||||
|
||||
const inter = Inter({
|
||||
subsets: ['latin'],
|
||||
display: 'swap', // show fallback font immediately
|
||||
preload: true,
|
||||
variable: '--font-inter',
|
||||
});
|
||||
|
||||
export default function RootLayout({ children }) {
|
||||
return (
|
||||
<html className={inter.variable}>
|
||||
<body>{children}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
- Use `next/font` for zero-CLS font loading with automatic subsetting
|
||||
- Set `display: 'swap'` to avoid invisible text during load
|
||||
- Self-host fonts instead of loading from Google CDN (saves DNS lookup)
|
||||
- Limit to 2 font families maximum
|
||||
|
||||
## CLS Prevention
|
||||
|
||||
- Always set `width` and `height` on images and videos
|
||||
- Use `aspect-ratio` CSS for responsive media containers
|
||||
- Reserve space for dynamic content (ads, embeds) with `min-height`
|
||||
- Avoid inserting content above existing content after load
|
||||
- Use CSS `contain: layout` for components that change size
|
||||
|
||||
## Performance Monitoring
|
||||
|
||||
```typescript
|
||||
import { onCLS, onINP, onLCP } from 'web-vitals';
|
||||
|
||||
onCLS(console.log);
|
||||
onINP(console.log);
|
||||
onLCP(console.log);
|
||||
```
|
||||
|
||||
Measure real user metrics (RUM), not just lab scores. Vercel Analytics and Google Search Console provide field data.
|
||||
@@ -0,0 +1,165 @@
|
||||
---
|
||||
name: material-design
|
||||
description: >-
|
||||
Material Design 3 / M3 Expressive principles, color roles, typography scale,
|
||||
elevation, motion, and anti-patterns. Use when designing or reviewing UI,
|
||||
building design tokens, choosing component patterns, accessibility defaults,
|
||||
or when the user mentions Material, M3, design system foundation, or visual consistency.
|
||||
---
|
||||
# Material Design
|
||||
|
||||
## OVERVIEW
|
||||
Google's comprehensive open-source design system providing guidelines, components, and tools for building high-quality digital experiences. Launched 2014, evolved to Material 3 (2021), Material 3 Expressive (2025). Unified approach across Android, web, iOS, and Flutter platforms.
|
||||
|
||||
**Why this matters**: Accelerates development with pre-built components, ensures accessibility compliance, maintains cross-platform consistency, backed by extensive documentation and community support.
|
||||
|
||||
## WHEN TO USE
|
||||
- Designing Android applications (native design language)
|
||||
- Creating cross-platform products requiring consistent experience
|
||||
- Building design systems from established foundation
|
||||
- Rapid prototyping with pre-built specifications
|
||||
- Products requiring strong accessibility defaults (WCAG-compliant)
|
||||
- Teams needing shared designer-developer vocabulary
|
||||
- Brands wanting modern design without starting from scratch
|
||||
|
||||
**Trigger**: Need to ship polished UI quickly or maintain consistency across multiple platforms.
|
||||
|
||||
## KEY PRINCIPLES
|
||||
|
||||
### 1. Material is the Metaphor
|
||||
**Concept**: Digital elements behave like physical materials with tactile qualities, depth, and realistic motion.
|
||||
|
||||
**Application**:
|
||||
- Surfaces have elevation (z-axis positioning creating shadows)
|
||||
- Elements respond to touch with ripple effects
|
||||
- Transitions maintain spatial relationships
|
||||
- Depth communicates hierarchy and focus
|
||||
|
||||
**Implementation**: Cards at 2dp elevation, FAB at 6dp, navigation drawer at 16dp, modals at 24dp.
|
||||
|
||||
### 2. Bold, Graphic, Intentional
|
||||
**Concept**: Use vibrant colors, prominent typography, and deliberate white space to create clear visual hierarchy.
|
||||
|
||||
**Application**:
|
||||
- Dynamic color system generates cohesive palettes
|
||||
- Typography scale with consistent hierarchy (Display, Headline, Title, Body, Label)
|
||||
- Purposeful use of color to guide attention
|
||||
- Generous spacing for clarity
|
||||
|
||||
**Implementation**: Extract brand colors, generate 65 tokens (13 tones × 5 roles), apply type scale.
|
||||
|
||||
### 3. Motion Provides Meaning
|
||||
**Concept**: Animation is not decoration—it guides understanding and maintains context.
|
||||
|
||||
**Application**:
|
||||
- Spring physics for organic, responsive feel (Material 3 Expressive)
|
||||
- Shared element transitions maintain spatial continuity
|
||||
- Motion emphasizes hierarchy and relationships
|
||||
- Respect prefers-reduced-motion for accessibility
|
||||
|
||||
**Implementation**: Replace duration-based easing with spring animations, use morphing shapes.
|
||||
|
||||
## EXECUTION STEPS
|
||||
|
||||
### Phase 1: Establish Foundation
|
||||
1. **Define color palette** - Use Theme Builder to extract from brand assets
|
||||
2. **Set up typography scale** - Choose Display/Headline/Title/Body/Label sizes
|
||||
3. **Configure shape system** - Define corner radius scale (None to Full)
|
||||
4. **Implement elevation system** - Establish z-axis hierarchy
|
||||
|
||||
### Phase 2: Build Component Library
|
||||
5. **Import Material components** - Use Material UI (React), MDC-Web, or Flutter Material
|
||||
6. **Customize theme tokens** - Override color, typography, shape as needed
|
||||
7. **Test accessibility** - Verify contrast ratios, keyboard navigation, screen readers
|
||||
8. **Create responsive layouts** - Apply 12-column grid with breakpoints (Compact/Medium/Expanded)
|
||||
|
||||
### Phase 3: Implement Motion & Refinement
|
||||
9. **Add spring physics** - Replace linear animations with organic motion
|
||||
10. **Implement state changes** - Hover, focus, active, disabled states
|
||||
11. **Test cross-platform** - Verify consistency across web/iOS/Android
|
||||
12. **Document patterns** - Catalog custom implementations for team reference
|
||||
|
||||
## SUCCESS METRICS
|
||||
- **Development velocity** - 2-3x faster with pre-built components
|
||||
- **Accessibility compliance** - WCAG AA/AAA pass rate ≥ 95%
|
||||
- **Cross-platform consistency** - User recognition across platforms ≥ 85%
|
||||
- **Design-dev handoff time** - 50%+ reduction vs. custom designs
|
||||
- **User task completion** - Familiar patterns increase success rates
|
||||
|
||||
## REAL-WORLD EXAMPLES
|
||||
|
||||
### Google Photos
|
||||
Comprehensive Material 3 implementation demonstrating dynamic color theming that adapts to user wallpaper. Spring animations for photo grid interactions.
|
||||
|
||||
### Todoist
|
||||
Cross-platform task manager using Material Design Web for consistency. Custom color theming while maintaining Material component patterns.
|
||||
|
||||
### Cash App
|
||||
Fintech product using Material elevation and components but customizing colors and shapes for brand differentiation. Passed accessibility audit first attempt.
|
||||
|
||||
## ANTI-PATTERNS
|
||||
**What NOT to do**:
|
||||
- **Mixing design systems** - Combining Material with HIG or Fluent creates inconsistency
|
||||
- **Arbitrary elevation** - Random z-axis values break hierarchy
|
||||
- **Color without testing** - Skipping contrast ratio verification
|
||||
- **Ignoring breakpoints** - Fixed layouts that break on tablets
|
||||
- **Custom motion timing** - Replacing Material physics with linear easing
|
||||
- **Recreating components** - Building from scratch vs. using libraries
|
||||
- **Overriding accessibility** - Changing touch targets or keyboard navigation
|
||||
- **Treating as rigid** - Material is flexible; customize thoughtfully
|
||||
|
||||
## EDGE CASES
|
||||
- **Strong brand identity** - Customize color/shape/typography but keep interaction patterns
|
||||
- **iOS-first products** - Material works on iOS but consider HIG for platform conventions
|
||||
- **High-security contexts** - Material's bold colors may conflict with conservative aesthetics
|
||||
- **Low-bandwidth environments** - Material components can be heavy; consider lite versions
|
||||
- **Highly specialized interfaces** - Complex data tools may need custom components
|
||||
|
||||
## INTEGRATION
|
||||
**Pairs well with**:
|
||||
- **Design Tokens** - Material 3 built on token architecture
|
||||
- **Atomic Design** - Component hierarchy methodology
|
||||
- **Storybook** - Document Material components
|
||||
- **Figma UI Kits** - Design with official Material templates
|
||||
- **Accessibility Standards** - WCAG compliance built-in
|
||||
|
||||
**Contrasts with**:
|
||||
- **Human Interface Guidelines** - Apple's iOS/macOS design language
|
||||
- **Fluent Design** - Microsoft's Windows design system
|
||||
- **Custom design systems** - Bespoke vs. established framework
|
||||
|
||||
## TOOLS & RESOURCES
|
||||
- **Official site**: m3.material.io (comprehensive documentation)
|
||||
- **Theme Builder**: Material Theme Builder (Figma plugin)
|
||||
- **Component libraries**: Material UI (React), MDC-Web, Flutter Material
|
||||
- **Design kits**: Official Figma/Sketch UI kits
|
||||
- **Color tool**: Material palette generator
|
||||
- **Motion guidelines**: Material motion system documentation
|
||||
|
||||
## 2025 UPDATE: Material 3 Expressive
|
||||
Announced at The Android Show (May 2025) for Android 16 and Wear OS 6:
|
||||
- Spring-based physics replacing duration-based easing
|
||||
- 35 new morphing shapes with fluid transitions
|
||||
- Enhanced color expressiveness with more vibrant defaults
|
||||
- Improved animation smoothness and responsiveness
|
||||
|
||||
## FURTHER READING
|
||||
- **Primary Source**: Material Design 3 documentation (m3.material.io)
|
||||
- **Implementation**: Material Components libraries for each platform
|
||||
- **Case Studies**: Google Design Medium publication
|
||||
- **Related**: *Design Systems* by Alla Kholmatova
|
||||
- **Advanced**: Building Design Systems (Brad Frost)
|
||||
|
||||
## SCORING RATIONALE
|
||||
**Total: 47/50**
|
||||
|
||||
| Criterion | Score | Reasoning |
|
||||
|-----------|-------|-----------|
|
||||
| Practitioner | 10/10 | Google ships Material across all products; battle-tested at scale |
|
||||
| Clarity | 10/10 | Comprehensive docs, code examples, design kits, clear specifications |
|
||||
| ROI | 10/10 | 2-3x faster development, accessibility built-in, reduces design debt |
|
||||
| Novelty | 7/10 | Innovative in 2014; now standard but evolving with Expressive |
|
||||
| Cross-Domain | 10/10 | Works across web, mobile, desktop, wearables, automotive |
|
||||
|
||||
**Evidence**: Billions of Android devices, adoption by non-Google products (Todoist, Cash App), open-source community, continuous evolution (Material 3 Expressive 2025).
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
---
|
||||
name: mobile-development
|
||||
description: Mobile development patterns for React Native and Flutter including navigation, state management, and responsive design
|
||||
---
|
||||
|
||||
# Mobile Development
|
||||
|
||||
## React Native Component Structure
|
||||
|
||||
```tsx
|
||||
import { View, Text, FlatList, StyleSheet, Platform } from "react-native";
|
||||
import { SafeAreaView } from "react-native-safe-area-context";
|
||||
|
||||
interface Product {
|
||||
id: string;
|
||||
name: string;
|
||||
price: number;
|
||||
image: string;
|
||||
}
|
||||
|
||||
function ProductList({ products }: { products: Product[] }) {
|
||||
return (
|
||||
<SafeAreaView style={styles.container}>
|
||||
<FlatList
|
||||
data={products}
|
||||
keyExtractor={(item) => item.id}
|
||||
renderItem={({ item }) => <ProductCard product={item} />}
|
||||
contentContainerStyle={styles.list}
|
||||
ItemSeparatorComponent={() => <View style={styles.separator} />}
|
||||
ListEmptyComponent={<EmptyState message="No products found" />}
|
||||
initialNumToRender={10}
|
||||
maxToRenderPerBatch={10}
|
||||
windowSize={5}
|
||||
/>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: "#fff",
|
||||
},
|
||||
list: {
|
||||
padding: 16,
|
||||
},
|
||||
separator: {
|
||||
height: 12,
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Use `FlatList` for scrollable lists (never `ScrollView` with `.map()`). Set `windowSize` and `maxToRenderPerBatch` for large lists.
|
||||
|
||||
## React Native Navigation
|
||||
|
||||
```tsx
|
||||
import { NavigationContainer } from "@react-navigation/native";
|
||||
import { createNativeStackNavigator } from "@react-navigation/native-stack";
|
||||
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
|
||||
|
||||
type RootStackParams = {
|
||||
Tabs: undefined;
|
||||
ProductDetail: { productId: string };
|
||||
Cart: undefined;
|
||||
};
|
||||
|
||||
const Stack = createNativeStackNavigator<RootStackParams>();
|
||||
const Tab = createBottomTabNavigator();
|
||||
|
||||
function TabNavigator() {
|
||||
return (
|
||||
<Tab.Navigator screenOptions={{ headerShown: false }}>
|
||||
<Tab.Screen name="Home" component={HomeScreen} />
|
||||
<Tab.Screen name="Search" component={SearchScreen} />
|
||||
<Tab.Screen name="Profile" component={ProfileScreen} />
|
||||
</Tab.Navigator>
|
||||
);
|
||||
}
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<NavigationContainer>
|
||||
<Stack.Navigator>
|
||||
<Stack.Screen name="Tabs" component={TabNavigator} options={{ headerShown: false }} />
|
||||
<Stack.Screen name="ProductDetail" component={ProductDetailScreen} />
|
||||
<Stack.Screen name="Cart" component={CartScreen} options={{ presentation: "modal" }} />
|
||||
</Stack.Navigator>
|
||||
</NavigationContainer>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Flutter Widget Pattern
|
||||
|
||||
```dart
|
||||
class ProductCard extends StatelessWidget {
|
||||
final Product product;
|
||||
final VoidCallback onTap;
|
||||
|
||||
const ProductCard({
|
||||
super.key,
|
||||
required this.product,
|
||||
required this.onTap,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return GestureDetector(
|
||||
onTap: onTap,
|
||||
child: Card(
|
||||
elevation: 2,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
ClipRRect(
|
||||
borderRadius: const BorderRadius.vertical(top: Radius.circular(8)),
|
||||
child: Image.network(
|
||||
product.imageUrl,
|
||||
height: 200,
|
||||
width: double.infinity,
|
||||
fit: BoxFit.cover,
|
||||
errorBuilder: (_, __, ___) => const Icon(Icons.broken_image, size: 64),
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(product.name, style: Theme.of(context).textTheme.titleMedium),
|
||||
const SizedBox(height: 4),
|
||||
Text("\$${product.price.toStringAsFixed(2)}",
|
||||
style: Theme.of(context).textTheme.bodyLarge),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Responsive Layout
|
||||
|
||||
```tsx
|
||||
import { useWindowDimensions } from "react-native";
|
||||
|
||||
function useResponsive() {
|
||||
const { width } = useWindowDimensions();
|
||||
return {
|
||||
isPhone: width < 768,
|
||||
isTablet: width >= 768 && width < 1024,
|
||||
isDesktop: width >= 1024,
|
||||
columns: width < 768 ? 1 : width < 1024 ? 2 : 3,
|
||||
};
|
||||
}
|
||||
|
||||
function ProductGrid({ products }: { products: Product[] }) {
|
||||
const { columns } = useResponsive();
|
||||
|
||||
return (
|
||||
<FlatList
|
||||
data={products}
|
||||
numColumns={columns}
|
||||
key={columns}
|
||||
keyExtractor={(item) => item.id}
|
||||
renderItem={({ item }) => (
|
||||
<View style={{ flex: 1, maxWidth: `${100 / columns}%`, padding: 8 }}>
|
||||
<ProductCard product={item} />
|
||||
</View>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Platform-Specific Code
|
||||
|
||||
```tsx
|
||||
import { Platform } from "react-native";
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
shadow: Platform.select({
|
||||
ios: {
|
||||
shadowColor: "#000",
|
||||
shadowOffset: { width: 0, height: 2 },
|
||||
shadowOpacity: 0.1,
|
||||
shadowRadius: 4,
|
||||
},
|
||||
android: {
|
||||
elevation: 4,
|
||||
},
|
||||
default: {},
|
||||
}),
|
||||
});
|
||||
```
|
||||
|
||||
## Anti-Patterns
|
||||
|
||||
- Using `ScrollView` with `.map()` for dynamic lists (use `FlatList` or `SectionList`)
|
||||
- Storing all state in a global store instead of colocating with components
|
||||
- Not handling safe areas (notch, status bar, home indicator)
|
||||
- Inline styles on every render (define with `StyleSheet.create`)
|
||||
- Blocking the JS thread with heavy computation (use `InteractionManager`)
|
||||
- Ignoring platform-specific UX conventions (iOS back swipe, Android back button)
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] `FlatList` used for all scrollable lists with `keyExtractor`
|
||||
- [ ] Navigation typed with TypeScript route params
|
||||
- [ ] Safe area insets handled with `SafeAreaView`
|
||||
- [ ] Styles defined with `StyleSheet.create` (not inline objects)
|
||||
- [ ] Responsive layouts adapt to phone, tablet, and desktop
|
||||
- [ ] Platform-specific styles handled with `Platform.select`
|
||||
- [ ] Images cached and loaded with error/loading states
|
||||
- [ ] Heavy computation offloaded from the JS thread
|
||||
@@ -0,0 +1,161 @@
|
||||
---
|
||||
name: nextjs-mastery
|
||||
description: Next.js 14+ App Router patterns including RSC, ISR, middleware, parallel routes, and data fetching
|
||||
---
|
||||
|
||||
# Next.js Mastery
|
||||
|
||||
## App Router Structure
|
||||
|
||||
```
|
||||
app/
|
||||
layout.tsx # Root layout (wraps all pages)
|
||||
page.tsx # Home route /
|
||||
loading.tsx # Route-level Suspense fallback
|
||||
error.tsx # Route-level error boundary
|
||||
not-found.tsx # Custom 404
|
||||
(marketing)/
|
||||
about/page.tsx # /about (grouped without URL segment)
|
||||
dashboard/
|
||||
layout.tsx # Nested layout for /dashboard/*
|
||||
page.tsx # /dashboard
|
||||
@analytics/page.tsx # Parallel route slot
|
||||
@activity/page.tsx # Parallel route slot
|
||||
settings/
|
||||
page.tsx # /dashboard/settings
|
||||
api/
|
||||
webhooks/route.ts # Route handler (POST /api/webhooks)
|
||||
```
|
||||
|
||||
Route groups `(name)` organize code without affecting URLs. Parallel routes `@slot` render multiple pages simultaneously.
|
||||
|
||||
## Server Components and Data Fetching
|
||||
|
||||
```tsx
|
||||
async function ProductPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await params;
|
||||
const product = await db.product.findUnique({ where: { id } });
|
||||
|
||||
if (!product) notFound();
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1>{product.name}</h1>
|
||||
<p>{product.description}</p>
|
||||
<Suspense fallback={<ReviewsSkeleton />}>
|
||||
<Reviews productId={id} />
|
||||
</Suspense>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
async function Reviews({ productId }: { productId: string }) {
|
||||
const reviews = await db.review.findMany({ where: { productId } });
|
||||
return (
|
||||
<ul>
|
||||
{reviews.map(r => <li key={r.id}>{r.text} - {r.rating}/5</li>)}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Server Components are the default. They run on the server, can access databases directly, and send zero JavaScript to the client.
|
||||
|
||||
## ISR and Caching
|
||||
|
||||
```tsx
|
||||
export const revalidate = 3600;
|
||||
|
||||
async function BlogPage() {
|
||||
const posts = await fetch("https://api.example.com/posts", {
|
||||
next: { revalidate: 3600, tags: ["posts"] },
|
||||
}).then(r => r.json());
|
||||
|
||||
return <PostList posts={posts} />;
|
||||
}
|
||||
```
|
||||
|
||||
```tsx
|
||||
import { revalidateTag, revalidatePath } from "next/cache";
|
||||
|
||||
export async function createPost(formData: FormData) {
|
||||
"use server";
|
||||
await db.post.create({ data: { title: formData.get("title") as string } });
|
||||
revalidateTag("posts");
|
||||
revalidatePath("/blog");
|
||||
}
|
||||
```
|
||||
|
||||
## Middleware
|
||||
|
||||
```typescript
|
||||
import { NextResponse } from "next/server";
|
||||
import type { NextRequest } from "next/server";
|
||||
|
||||
export function middleware(request: NextRequest) {
|
||||
const token = request.cookies.get("session")?.value;
|
||||
|
||||
if (request.nextUrl.pathname.startsWith("/dashboard") && !token) {
|
||||
return NextResponse.redirect(new URL("/login", request.url));
|
||||
}
|
||||
|
||||
const response = NextResponse.next();
|
||||
response.headers.set("x-request-id", crypto.randomUUID());
|
||||
return response;
|
||||
}
|
||||
|
||||
export const config = {
|
||||
matcher: ["/dashboard/:path*", "/api/:path*"],
|
||||
};
|
||||
```
|
||||
|
||||
Middleware runs at the edge before every matched request. Keep it lightweight.
|
||||
|
||||
## Server Actions
|
||||
|
||||
```tsx
|
||||
"use server";
|
||||
|
||||
import { z } from "zod";
|
||||
import { revalidatePath } from "next/cache";
|
||||
|
||||
const schema = z.object({
|
||||
email: z.string().email(),
|
||||
name: z.string().min(2).max(100),
|
||||
});
|
||||
|
||||
export async function updateProfile(prevState: any, formData: FormData) {
|
||||
const parsed = schema.safeParse(Object.fromEntries(formData));
|
||||
if (!parsed.success) {
|
||||
return { errors: parsed.error.flatten().fieldErrors };
|
||||
}
|
||||
|
||||
await db.user.update({
|
||||
where: { email: parsed.data.email },
|
||||
data: { name: parsed.data.name },
|
||||
});
|
||||
|
||||
revalidatePath("/profile");
|
||||
return { success: true };
|
||||
}
|
||||
```
|
||||
|
||||
## Anti-Patterns
|
||||
|
||||
- Adding `'use client'` to top-level layout or page components
|
||||
- Fetching data on the client when it can be done in a Server Component
|
||||
- Using `useEffect` for data fetching instead of Server Components or `use()`
|
||||
- Not wrapping slow async components with `<Suspense>`
|
||||
- Putting heavy logic in middleware (it runs on every matched request)
|
||||
- Ignoring `loading.tsx` and `error.tsx` conventions
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] Server Components used by default; `'use client'` only on interactive leaves
|
||||
- [ ] Data fetching happens in Server Components with proper caching
|
||||
- [ ] `<Suspense>` boundaries wrap independent async sections
|
||||
- [ ] `loading.tsx` and `error.tsx` exist for key routes
|
||||
- [ ] Middleware is lightweight and only handles auth/redirects/headers
|
||||
- [ ] Server Actions validate input with Zod before database writes
|
||||
- [ ] `revalidateTag` or `revalidatePath` called after mutations
|
||||
- [ ] Route groups and parallel routes used to organize complex layouts
|
||||
@@ -0,0 +1,33 @@
|
||||
---
|
||||
name: shadcn-ui
|
||||
description: >-
|
||||
Use shadcn/ui + Tailwind only for this project's UI. Triggers on UI, styling,
|
||||
components, cards, forms, navigation, theming, or when the user mentions
|
||||
shadcn, ui/*, or design tokens. Do not invent parallel ds-* or --brand-* systems.
|
||||
---
|
||||
|
||||
# shadcn/ui for AUT Management Website
|
||||
|
||||
## Source of truth
|
||||
|
||||
- Docs: https://ui.shadcn.com/docs/installation and https://ui.shadcn.com/docs/installation/next
|
||||
- Config: `components.json` (style `base-nova`, CSS vars, RTL)
|
||||
- Styles: `src/app/globals.css` — only Tailwind + `shadcn/tailwind.css` + theme CSS variables
|
||||
- Primitives: `src/components/ui/*` via `npx shadcn@latest add <name>`
|
||||
|
||||
## Rules
|
||||
|
||||
1. Build UI from `@/components/ui/*` + Tailwind utilities only.
|
||||
2. Colors: `bg-primary`, `text-muted-foreground`, `bg-muted`, `border-border`, `bg-card` — never `--brand-*` or `brand-*` classes.
|
||||
3. Do not create or revive `.ds-*` utilities, SurfaceCard, or DotCta patterns.
|
||||
4. Prefer `Card`, `Button`, `Separator`, `Sheet`, `NavigationMenu`, `Input`, `Label`, `Tabs`, `Skeleton`, `Badge`.
|
||||
5. Add missing primitives with the CLI; do not hand-copy stale component APIs.
|
||||
6. Keep Persian RTL (`dir="rtl"` on layout; `components.json` `"rtl": true`).
|
||||
7. AUT identity lives only in shadcn theme variables (`--primary`, `--accent`, …).
|
||||
|
||||
## Anti-patterns
|
||||
|
||||
- Parallel design tokens (`--brand-*`, `ds-card`, `ds-hero`, `ds-cta`)
|
||||
- Full section boxes with `border border-border` when spacing/`Separator`/`Card` suffice
|
||||
- Always-on motion (ken-burns, default lift on every card)
|
||||
---
|
||||
Reference in new issue
Block a user