Programování
Expert
Cursor
Cursor IDE - Mastering Composer Mode a AI Features
Kompletní průvodce využitím Cursor IDE s důrazem na Composer Mode, AI chat, code generation a pokročilé workflow pro profesionální vývoj.
Prompt text
Délka: Dlouhý
Jsi expert na Cursor IDE a jeho AI-powered vývojářské nástroje. Pomoz mi vytvořit strategii pro maximální využití Cursor při vývoji softwaru.
Můj kontext:
- Typ projektu: [TYP - např. "full-stack webová aplikace", "microservices API", "mobilní app"]
- Tech stack: [STACK - např. "React, Node.js, PostgreSQL", "Python, FastAPI, MongoDB"]
- Velikost codebase: [VELIKOST - např. "malý startup projekt", "střední SaaS", "velká enterprise aplikace"]
- Team size: [TÝM - např. "solo developer", "3-5 členů", "10+ členů"]
- Hlavní výzvy: [VÝZVY - např. "rychlý prototyping", "refactoring legacy kódu", "debugging komplexních issues"]
Oblasti pro optimalizaci:
1. **Composer Mode** - Multi-file editing, architecture changes
2. **Chat Features** - Code explanation, debugging, learning
3. **Code Generation** - Boilerplate, tests, documentation
4. **Refactoring Tools** - Automated refactoring, code modernization
5. **Debugging Workflow** - AI-assisted debugging, error resolution
6. **Collaboration** - Team workflows, knowledge sharing
Vytvoř kompletní průvodce zahrnující:
- Praktické příklady pro můj tech stack
- Workflow patterns pro běžné úkoly
- Keyboard shortcuts a productivity tips
- Best practices pro různé typy úloh
- Integrace s dalšími nástroji (Git, terminal, etc.)
- Pokročilé techniky pro large codebase
Můj kontext:
- Typ projektu: [TYP - např. "full-stack webová aplikace", "microservices API", "mobilní app"]
- Tech stack: [STACK - např. "React, Node.js, PostgreSQL", "Python, FastAPI, MongoDB"]
- Velikost codebase: [VELIKOST - např. "malý startup projekt", "střední SaaS", "velká enterprise aplikace"]
- Team size: [TÝM - např. "solo developer", "3-5 členů", "10+ členů"]
- Hlavní výzvy: [VÝZVY - např. "rychlý prototyping", "refactoring legacy kódu", "debugging komplexních issues"]
Oblasti pro optimalizaci:
1. **Composer Mode** - Multi-file editing, architecture changes
2. **Chat Features** - Code explanation, debugging, learning
3. **Code Generation** - Boilerplate, tests, documentation
4. **Refactoring Tools** - Automated refactoring, code modernization
5. **Debugging Workflow** - AI-assisted debugging, error resolution
6. **Collaboration** - Team workflows, knowledge sharing
Vytvoř kompletní průvodce zahrnující:
- Praktické příklady pro můj tech stack
- Workflow patterns pro běžné úkoly
- Keyboard shortcuts a productivity tips
- Best practices pro různé typy úloh
- Integrace s dalšími nástroji (Git, terminal, etc.)
- Pokročilé techniky pro large codebase
Příklad použití
Vstup:
Typ projektu: Full-stack SaaS aplikace
Tech stack: Next.js 14 (App Router), TypeScript, tRPC, Prisma, PostgreSQL, TailwindCSS
Velikost codebase: Střední (50k+ řádků, 200+ souborů)
Team size: 4 vývojáři (2 frontend, 2 backend)
Hlavní výzvy: Rychlé přidávání features při zachování kvality kódu, refactoring existujícího kódu na nové patterns, onboarding nových členů týmu
Tech stack: Next.js 14 (App Router), TypeScript, tRPC, Prisma, PostgreSQL, TailwindCSS
Velikost codebase: Střední (50k+ řádků, 200+ souborů)
Team size: 4 vývojáři (2 frontend, 2 backend)
Hlavní výzvy: Rychlé přidávání features při zachování kvality kódu, refactoring existujícího kódu na nové patterns, onboarding nových členů týmu
Výstup:
# Cursor IDE Masterclass: Next.js + TypeScript SaaS Development
## 🎯 Úvod: Cursor jako Váš AI Development Environment
Cursor není jen fork VS Code s AI - je to kompletně nový způsob myšlení o vývoji softwaru. Kombinuje nejlepší z VS Code s pokročilými AI schopnostmi, které vám umožní:
- Refactorovat celé funkce jedním promptem
- Vyvíjet napříč multiple soubory současně
- Debugovat komplexní issues s AI asistentem
- Onboardovat nové členy týmu 10x rychleji
**Co se naučíte:**
- Jak využít Composer Mode pro architecture-level změny
- Workflow patterns pro každodenní development tasks
- Pokročilé techniky pro large codebase (50k+ LOC)
- Team collaboration strategies s Cursor
---
## 🎼 1. Composer Mode - The Game Changer
### 1.1 Co Je Composer Mode a Kdy Ho Použít
**Composer Mode** = Multi-file AI editor, který rozumí celému kontextu projektu.
**Použijte pro:**
- ✅ Přidávání nových features across multiple files
- ✅ Refactoring celých modulů
- ✅ Migrace na nové technologie/patterns
- ✅ Implementace komplexních business logic
**NEPOUŽÍVEJTE pro:**
- ❌ Jednoduché single-line edits (použijte inline edit)
- ❌ Quick fixes (použijte Cmd+K)
- ❌ Code exploration (použijte chat)
### 1.2 Základní Workflow - Feature Across Files
**Scenario:** Přidáváte "Team Collaboration" feature
**Krok 1: Otevřete Composer (Cmd+I)**
```
Prompt pro Composer:
---
Add team collaboration feature to the SaaS app. This includes:
1. Database schema (Prisma):
- Team model with name, members, settings
- TeamMember model with role, permissions
- Update User model with teamId foreign key
2. tRPC API (app/api/trpc):
- team router with CRUD operations
- teamMember router for invites, role management
- Authorization middleware for team-based access
3. UI Components (React):
- Team settings page with member list
- Invite member modal with email input
- Role selector dropdown (owner, admin, member)
- Team switcher in header
4. Business logic:
- Only team owners can delete teams
- Admins can invite/remove members
- Email invitations with unique tokens
- Automatic team creation on signup
Tech stack: Next.js 14 App Router, tRPC, Prisma, Zod validation, shadcn/ui components
Generate all necessary files and update existing ones.
---
```
**Co Composer udělá:**
1. **Analyzuje** celý codebase (všechny 200+ souborů)
2. **Plánuje** změny across multiple files
3. **Vygeneruje** nebo upraví:
- `prisma/schema.prisma` (nové modely)
- `lib/trpc/routers/team.ts` (nový router)
- `lib/trpc/routers/teamMember.ts` (nový router)
- `lib/trpc/routers/_app.ts` (merge routerů)
- `app/(dashboard)/team/page.tsx` (nová stránka)
- `components/features/team/InviteMemberModal.tsx`
- `components/features/team/TeamSwitcher.tsx`
- `components/features/team/MemberList.tsx`
- `types/team.ts` (type definitions)
4. **Respektuje** vaše existující patterns a conventions
**Krok 2: Review změn v diff view**
Composer ukáže všechny změny v přehledném diff view. **Důležité:**
- ✅ Zkontrolujte type safety
- ✅ Ověřte authorization logic
- ✅ Projděte si error handling
- ✅ Checknout migration steps (Prisma)
**Krok 3: Accept nebo Iteruj**
```
// Pokud něco chybí, pokračujte v Composer:
"Add unit tests for team router using vitest. Test authorization, validation, and edge cases."
// Composer automaticky vytvoří:
- lib/trpc/routers/team.test.ts (comprehensive tests)
```
### 1.3 Advanced Composer Patterns
**Pattern #1: Architecture Refactoring**
```
Prompt:
---
Refactor the authentication system from JWT to session-based auth:
Current: JWT tokens stored in localStorage
Target: HTTP-only cookies with session store (Redis)
Changes needed:
1. Remove JWT logic from auth router
2. Implement session middleware with express-session
3. Update login/logout endpoints to use sessions
4. Migrate frontend to use cookies instead of localStorage
5. Add CSRF protection
6. Update all API calls to include credentials
Preserve all existing functionality, just change the auth mechanism.
Generate migration guide for existing users.
---
```
Composer **automaticky refactoruje** 20+ souborů bez manual work!
**Pattern #2: Technology Migration**
```
Prompt:
---
Migrate from REST API to tRPC across the entire application:
Current: Express REST endpoints in /api folder
Target: tRPC routers with full type safety
Steps:
1. Convert all Express routes to tRPC procedures
2. Replace axios calls with tRPC client
3. Update error handling to use TRPCError
4. Add Zod validation for all inputs
5. Generate OpenAPI schema for documentation
6. Create migration script to preserve API compatibility
Tech stack: Next.js 14, TypeScript, Zod, tRPC v10
Maintain backwards compatibility with existing API consumers.
---
```
**Pattern #3: Feature Cloning**
```
Prompt:
---
We have a "Projects" feature. Clone it to create a similar "Workspaces" feature:
Source files:
- app/(dashboard)/projects/*
- lib/trpc/routers/project.ts
- components/features/projects/*
Replicate the exact same structure but for workspaces:
- Rename all references from "project" to "workspace"
- Update database schema
- Keep the same UI/UX patterns
- Maintain feature parity (CRUD, sharing, permissions)
Generate all new files and update necessary imports.
---
```
### 1.4 Composer Tips & Tricks
**Tip #1: Include Context Files**
Před použitím Composer **otevřete klíčové soubory** které chcete použít jako reference:
- `prisma/schema.prisma` (data models)
- `types/index.ts` (type definitions)
- `lib/trpc/routers/_app.ts` (API structure)
Cursor použije tyto soubory jako kontext pro generování.
**Tip #2: Iterative Refinement**
Neočekávejte perfektní output na první pokus. Používejte Composer **iterativně**:
```
1. První prompt: "Add feature X"
2. Review output
3. Druhý prompt: "Add error handling for edge case Y"
4. Review
5. Třetí prompt: "Add unit tests"
6. Accept changes
```
**Tip #3: Use @-mentions Pro Specifický Context**
```
Prompt:
---
@schema.prisma @auth.ts
Update user authentication to include 2FA.
Use the existing Prisma schema and auth patterns.
---
```
`@filename` říká Cursor: "použij tento soubor jako primary context".
---
## 💬 2. Chat Features - Your AI Pair Programmer
### 2.1 Chat vs Composer - Kdy Co Použít
| Feature | Chat (Cmd+L) | Composer (Cmd+I) |
|---------|--------------|------------------|
| Code explanation | ✅ Perfect | ❌ Overkill |
| Learning concepts | ✅ Best | ❌ Not suitable |
| Quick fixes | ✅ Good | ❌ Too heavy |
| Multi-file changes | ❌ Limited | ✅ Perfect |
| Debugging | ✅ Great | ⚠️ Depends |
| Architecture planning | ✅ Great | ⚠️ Better after plan |
**Golden Rule:** Chat = Thinking, Composer = Executing
### 2.2 Chat Workflow Patterns
**Pattern #1: Code Explanation**
```
You: Explain this tRPC middleware
[paste code]
AI: This middleware implements row-level security...
[detailed explanation]
You: How can I extend it to support team-based permissions?
AI: Here are 3 approaches:
1. Add teamId to context...
2. Create a higher-order middleware...
3. Use Prisma middleware for automatic filtering...
You: Show me approach #2 with code
AI: [generates implementation]
```
**Pattern #2: Debugging Workflow**
```
You: I'm getting "Cannot read property 'id' of undefined" in getUserProjects
AI: This error suggests that either:
1. `user` is undefined (auth issue)
2. `project.owner` is not populated (missing include)
Can you share:
- The getUserProjects function
- The tRPC context
- Recent changes to auth
You: [shares context]
AI: The issue is in your protectedProcedure middleware.
You're accessing ctx.session.user.id but session can be null.
Fix:
[shows code with proper null checking]
```
**Pattern #3: Architecture Discussion**
```
You: I need to implement real-time notifications. Should I use:
1. WebSockets
2. Server-Sent Events
3. Polling
4. Third-party service (Pusher)
Consider: Next.js 14 App Router, Vercel deployment, 1000+ users
AI: For your stack, I recommend Server-Sent Events (SSE):
Pros:
- Native Next.js support via Route Handlers
- Works with Vercel (unlike WebSockets)
- Simpler than WebSockets for one-way communication
- Built-in reconnection
Implementation:
[shows Next.js SSE example with tRPC integration]
Alternative for bi-directional: Use Vercel Edge Functions + Upstash Redis
[shows architecture diagram in text]
```
### 2.3 Advanced Chat Techniques
**Technique #1: Codebase Navigation**
```
You: @codebase Where is the user authentication logic?
AI: User authentication is implemented across these files:
1. lib/auth/session.ts - Session management
2. lib/trpc/middleware/auth.ts - tRPC auth middleware
3. app/api/auth/[...nextauth]/route.ts - NextAuth configuration
4. components/features/auth/LoginForm.tsx - Login UI
The main flow:
[explains authentication flow]
```
**Technique #2: Documentation Lookup**
```
You: @docs How do I use tRPC subscriptions in Next.js App Router?
AI: [searches tRPC docs]
tRPC subscriptions require WebSocket support...
[shows implementation with workaround for App Router]
```
**Technique #3: Git Integration**
```
You: @git What changed in the last commit that could break authentication?
AI: The last commit "Refactor auth middleware" modified:
1. lib/trpc/middleware/auth.ts
- Changed session validation logic
- Removed automatic user fetching
This could break auth because:
[explains breaking change]
Suggested fix:
[shows migration path]
```
---
## ⚡ 3. Code Generation - Boilerplate Automation
### 3.1 Component Generation
**Cmd+K inline generation:**
```typescript
// In your React component file, type comment:
// shadcn form component for project creation with name, description,
// use react-hook-form, zod validation, trpc mutation
// Press Cmd+K, AI generates:
"use client";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { Button } from "@/components/ui/button";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { api } from "@/lib/trpc/client";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
const formSchema = z.object({
name: z.string().min(1, "Name is required").max(100),
description: z.string().max(500).optional(),
});
type FormValues = z.infer<typeof formSchema>;
export function CreateProjectForm() {
const router = useRouter();
const form = useForm<FormValues>({
resolver: zodResolver(formSchema),
defaultValues: {
name: "",
description: "",
},
});
const createProject = api.project.create.useMutation({
onSuccess: (data) => {
toast.success("Project created successfully");
router.push(`/projects/${data.id}`);
},
onError: (error) => {
toast.error(error.message);
},
});
const onSubmit = (values: FormValues) => {
createProject.mutate(values);
};
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>Project Name</FormLabel>
<FormControl>
<Input placeholder="My Awesome Project" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="description"
render={({ field }) => (
<FormItem>
<FormLabel>Description</FormLabel>
<FormControl>
<Textarea
placeholder="Describe your project..."
className="resize-none"
{...field}
/>
</FormControl>
<FormDescription>
Optional description of your project
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit" disabled={createProject.isLoading}>
{createProject.isLoading ? "Creating..." : "Create Project"}
</Button>
</form>
</Form>
);
}
```
**One comment → Complete production-ready component!**
### 3.2 Test Generation
```typescript
// In your test file:
// Unit tests for CreateProjectForm component
// Test form validation, submission, error handling, loading states
// Use vitest, testing-library/react, MSW for API mocking
// Cmd+K generates complete test suite:
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { vi } from "vitest";
import { CreateProjectForm } from "./CreateProjectForm";
import { api } from "@/lib/trpc/client";
vi.mock("@/lib/trpc/client");
vi.mock("next/navigation", () => ({
useRouter: () => ({ push: vi.fn() }),
}));
describe("CreateProjectForm", () => {
it("renders form fields", () => {
render(<CreateProjectForm />);
expect(screen.getByLabelText("Project Name")).toBeInTheDocument();
expect(screen.getByLabelText("Description")).toBeInTheDocument();
expect(screen.getByRole("button", { name: /create/i })).toBeInTheDocument();
});
it("validates required fields", async () => {
const user = userEvent.setup();
render(<CreateProjectForm />);
const submitButton = screen.getByRole("button", { name: /create/i });
await user.click(submitButton);
expect(await screen.findByText("Name is required")).toBeInTheDocument();
});
it("submits form with valid data", async () => {
const user = userEvent.setup();
const mockMutate = vi.fn();
(api.project.create.useMutation as any).mockReturnValue({
mutate: mockMutate,
isLoading: false,
});
render(<CreateProjectForm />);
await user.type(screen.getByLabelText("Project Name"), "Test Project");
await user.type(screen.getByLabelText("Description"), "Test description");
await user.click(screen.getByRole("button", { name: /create/i }));
expect(mockMutate).toHaveBeenCalledWith({
name: "Test Project",
description: "Test description",
});
});
it("shows loading state during submission", async () => {
(api.project.create.useMutation as any).mockReturnValue({
mutate: vi.fn(),
isLoading: true,
});
render(<CreateProjectForm />);
expect(screen.getByRole("button", { name: /creating/i })).toBeDisabled();
});
it("handles submission errors", async () => {
const user = userEvent.setup();
const mockMutate = vi.fn();
const mockToast = vi.fn();
vi.mock("sonner", () => ({ toast: { error: mockToast } }));
(api.project.create.useMutation as any).mockReturnValue({
mutate: mockMutate,
isLoading: false,
error: new Error("Failed to create project"),
});
render(<CreateProjectForm />);
await user.type(screen.getByLabelText("Project Name"), "Test");
await user.click(screen.getByRole("button", { name: /create/i }));
await waitFor(() => {
expect(mockToast).toHaveBeenCalledWith("Failed to create project");
});
});
});
```
---
## 🔧 4. Refactoring Tools - Code Modernization
### 4.1 Automated Refactoring Patterns
**Pattern: Extract to Custom Hook**
```typescript
// Máte duplicitní logic across components:
// components/ProjectList.tsx a components/TaskList.tsx
// Select duplicated code, Cmd+K:
"Extract this data fetching logic into a custom hook useInfiniteQuery with TypeScript generics"
// Cursor vytvoří:
// hooks/useInfiniteQuery.ts
export function useInfiniteQuery<T>(
queryKey: string[],
fetcher: (page: number) => Promise<T[]>,
options?: { pageSize?: number }
) {
const [data, setData] = useState<T[]>([]);
const [page, setPage] = useState(1);
const [isLoading, setIsLoading] = useState(false);
const [hasMore, setHasMore] = useState(true);
const loadMore = useCallback(async () => {
if (isLoading || !hasMore) return;
setIsLoading(true);
try {
const newData = await fetcher(page);
setData(prev => [...prev, ...newData]);
setHasMore(newData.length === (options?.pageSize ?? 20));
setPage(prev => prev + 1);
} catch (error) {
console.error("Failed to load more:", error);
} finally {
setIsLoading(false);
}
}, [page, fetcher, isLoading, hasMore, options?.pageSize]);
return { data, isLoading, hasMore, loadMore };
}
// A automaticky refactoruje oba komponenty:
// components/ProjectList.tsx
const { data: projects, isLoading, hasMore, loadMore } = useInfiniteQuery(
["projects"],
(page) => api.project.list.query({ page }),
{ pageSize: 20 }
);
// components/TaskList.tsx
const { data: tasks, isLoading, hasMore, loadMore } = useInfiniteQuery(
["tasks"],
(page) => api.task.list.query({ page }),
{ pageSize: 20 }
);
```
### 4.2 Legacy Code Modernization
```
Chat prompt:
---
@oldComponent.js
Refactor this class component to functional component with hooks:
- Convert state to useState
- Convert componentDidMount to useEffect
- Convert class methods to functions
- Add TypeScript types
- Apply modern React patterns (memo, useCallback where appropriate)
- Maintain exact same functionality
---
// Cursor analyzuje class component a vygeneruje modern equivalent
```
---
## 🐛 5. Debugging Workflow
### 5.1 AI-Assisted Debugging
**Scenario: Production Bug**
```
Chat:
---
@logs/error.log @components/Dashboard.tsx
We're getting "Cannot read property 'map' of undefined" in production.
The error occurs intermittently on the dashboard page.
Error log shows it happens during initial render.
Help me identify the root cause and fix it.
---
AI Response:
The issue is a race condition in data fetching. Your Dashboard component
assumes `projects` array is always defined, but during initial SSR or when
API is slow, it can be undefined.
Root cause in Dashboard.tsx:47
```typescript
// ❌ Current code:
{projects.map(project => <ProjectCard key={project.id} project={project} />)}
// ✅ Recommended fix:
{(projects ?? []).map(project => <ProjectCard key={project.id} project={project} />)}
// Or better - add loading state:
{!projects ? (
<Skeleton />
) : projects.length === 0 ? (
<EmptyState />
) : (
projects.map(project => <ProjectCard key={project.id} project={project} />)
)}
```
Additional recommendations:
1. Add Suspense boundary around async components
2. Implement error boundary for graceful error handling
3. Add type guard for runtime safety
[Would you like me to implement these fixes across all similar patterns in the codebase?]
```
### 5.2 Performance Debugging
```
Chat:
---
@codebase
The project list page is slow (3-4 second load time).
Profile the application and suggest optimizations.
Key metrics:
- 500+ projects to display
- Each project has nested data (members, tasks, comments)
- Using tRPC for API calls
- Next.js App Router SSR
---
AI identifies issues:
1. N+1 query problem in tRPC router (fetching members separately)
2. Over-fetching data (loading all tasks when only count is needed)
3. No pagination implemented
4. Missing database indexes
Suggests optimized implementation:
[Shows optimized Prisma queries with includes, select, take/skip for pagination, indexes]
```
---
## 👥 6. Team Collaboration Workflows
### 6.1 Onboarding New Developers
**Day 1 Onboarding Guide Generation:**
```
Composer:
---
Generate a comprehensive onboarding guide for new developers:
1. Project overview (architecture, tech stack, key concepts)
2. Local development setup (step-by-step)
3. Code standards and conventions
4. Common tasks and how to do them (add feature, fix bug, deploy)
5. Important files to read first
6. Team practices (PR process, code review, testing)
Analyze the entire codebase (@codebase) and create a detailed guide
in ONBOARDING.md
---
// Cursor analyzuje 200+ souborů a vytvoří comprehensive guide
```
**Generated ONBOARDING.md includes:**
- Architecture diagram (ASCII art)
- Database schema visualization
- API endpoint overview
- UI component hierarchy
- Development workflow
- Troubleshooting common issues
**Time saved: 8+ hours** of manual documentation writing!
### 6.2 Code Review Assistance
```
Chat:
---
@git/pr/123
Review this pull request for:
1. Type safety issues
2. Security vulnerabilities
3. Performance problems
4. Code style violations
5. Missing tests
6. Breaking changes
Provide detailed feedback with code suggestions.
---
// AI analyzuje změny v PR a poskytne structured review
```
### 6.3 Knowledge Sharing
```
Chat:
---
@components/PaymentProcessor.tsx
Explain how payment processing works in this application.
Include:
- Flow diagram
- Security considerations
- Error handling strategy
- Testing approach
Format for team wiki documentation.
---
// AI vytvoří comprehensive documentation ready to paste into Notion/Confluence
```
---
## ⚙️ 7. Cursor Settings & Customization
### 7.1 Recommended Settings
```json
// .cursor/settings.json
{
"cursor.ai.model": "claude-3.5-sonnet", // Nejlepší pro complex tasks
"cursor.ai.useComposer": true,
"cursor.ai.includedFiles": 100, // Zvýšit pro large codebase
// Composer settings
"cursor.composer.maxTokens": 8000,
"cursor.composer.temperature": 0.3, // Nižší = více konzistentní
// Chat settings
"cursor.chat.showInlineChat": true,
"cursor.chat.contextWindow": "large",
// Code generation
"cursor.codeGeneration.autoImport": true,
"cursor.codeGeneration.respectEslint": true,
// Privacy
"cursor.privacy.enableTelemetry": false,
"cursor.privacy.neverSendCode": false // True pokud pracujete s sensitive codebase
}
```
### 7.2 Keyboard Shortcuts (macOS)
| Shortcut | Action | Use Case |
|----------|--------|----------|
| `Cmd+K` | Inline edit | Quick fixes, small changes |
| `Cmd+L` | Open chat | Questions, explanations, debugging |
| `Cmd+I` | Open Composer | Multi-file edits, features |
| `Cmd+Shift+L` | Chat with selection | Explain/refactor selected code |
| `Option+Cmd+I` | Quick question | Fast Q&A without opening full chat |
| `Cmd+` | Show AI suggestions | Review AI-generated code |
### 7.3 Project-Specific Rules
```
// .cursorrules file in project root
This is a Next.js 14 SaaS project with:
- TypeScript strict mode
- tRPC for API
- Prisma ORM
- Zod validation
- Shadcn/ui components
- TailwindCSS for styling
Code standards:
- Always use server components unless client-side interactivity is needed
- Validate all inputs with Zod
- Use tRPC procedures instead of API routes
- Follow shadcn/ui component patterns
- Prefer TypeScript utility types over custom type definitions
- Always add error boundaries around async components
- Use React Server Components for data fetching when possible
File structure conventions:
- API: lib/trpc/routers/*.ts
- Components: components/features/[feature]/*.tsx
- UI primitives: components/ui/*.tsx
- Types: types/*.ts
- Utils: lib/utils/*.ts
- Hooks: hooks/*.ts
Testing requirements:
- Unit tests for all business logic
- Integration tests for tRPC routers
- E2E tests for critical user flows
- Use vitest for unit/integration, Playwright for E2E
When generating code:
- Follow these conventions exactly
- Add appropriate error handling
- Include TypeScript types
- Write tests for new functionality
```
Cursor čte `.cursorrules` a **automaticky aplikuje** tyto standardy na veškerý generovaný kód!
---
## 📊 8. Measuring Success & Productivity
### 8.1 Metrics to Track
**Before Cursor (Week 1):**
- Features delivered: 3
- Bugs introduced: 8
- Code review time: 4 hours/week
- Time spent on boilerplate: 6 hours/week
- Developer satisfaction: 6/10
**After Cursor (Week 4):**
- Features delivered: 7 (+133%)
- Bugs introduced: 5 (-37%)
- Code review time: 2 hours/week (-50%)
- Time spent on boilerplate: 1 hour/week (-83%)
- Developer satisfaction: 9/10
**Key Performance Indicators:**
1. **Feature Velocity** - Story points per sprint
2. **Code Quality** - Bug rate, test coverage
3. **Developer Experience** - Satisfaction surveys
4. **Time Savings** - Hours saved on repetitive tasks
5. **Onboarding Time** - Time to first PR for new devs
### 8.2 ROI Calculation
**Cost:**
- Cursor Pro: $20/dev/month
- Team of 4: $80/month
**Savings:**
- 10 hours/dev/week × 4 devs = 40 hours/week
- At $50/hour = $2,000/week = **$8,000/month**
**ROI: 100x return on investment!**
---
## 🎓 Závěr: Your 30-Day Cursor Adoption Plan
### Week 1: Foundation
- [ ] Install Cursor, migrate from VS Code
- [ ] Configure settings and .cursorrules
- [ ] Complete 5 simple tasks with Chat
- [ ] Try Composer for 1 small feature
- [ ] Measure baseline productivity
### Week 2: Integration
- [ ] Use Composer for 3 multi-file features
- [ ] Generate tests with AI
- [ ] Refactor 1 module with Cursor
- [ ] Document learnings for team
- [ ] Track time savings
### Week 3: Collaboration
- [ ] Onboard 1 team member using AI-generated guide
- [ ] Use Cursor for code reviews
- [ ] Create team .cursorrules file
- [ ] Share best practices in team meeting
- [ ] Measure team productivity gains
### Week 4: Mastery
- [ ] Handle complex architecture changes with Composer
- [ ] Use AI for debugging production issues
- [ ] Optimize workflows based on metrics
- [ ] Document case studies for management
- [ ] Plan for org-wide rollout
**Success Criteria:**
- ✅ 50%+ time savings on boilerplate code
- ✅ 2x feature velocity without quality decrease
- ✅ Reduced onboarding time from weeks to days
- ✅ Team satisfaction score 8+/10
---
## 🚀 Next Level: Advanced Techniques
### Custom AI Instructions
Teach Cursor your team-specific patterns by showing examples in chat:
```
This is how we structure tRPC routers in our project:
[paste example router]
This is our error handling pattern:
[paste error handler]
This is our testing pattern:
[paste test example]
Remember these patterns and use them when generating code.
```
Cursor learns and applies patterns across future generations!
### Workflow Automation
Combine Cursor with shell scripts:
```bash
#!/bin/bash
# generate-feature.sh
FEATURE_NAME=$1
echo "Generating $FEATURE_NAME feature..."
# Open Composer with pre-filled prompt
cursor composer "Create a new $FEATURE_NAME feature following our project conventions.
Include:
- Database schema (Prisma)
- tRPC router with CRUD
- UI components
- Tests
- Documentation"
```
**Usage:** `./generate-feature.sh team-management`
### Integration with Other Tools
- **Linear/Jira:** Paste ticket → Cursor generates implementation
- **Figma:** Screenshot → Composer generates React components
- **Slack:** Error alert → Chat helps debug
- **GitHub:** PR description → Cursor generates code review
---
**Cursor není jen editor - je to kompletní AI development environment, který transformuje způsob, jakým píšete kód. Když ho kombinujete s dobrými praktikami a team collaboration, dosáhnete 2-3x produktivity při zachování (nebo zvýšení) kvality!** 🚀
S touto strategií pro váš Next.js + TypeScript + tRPC stack budete schopni:
- Vyvíjet features 2x rychleji
- Onboardovat nové členy za 2 dny místo 2 týdnů
- Refactorovat legacy code efektivně
- Debugovat komplexní issues s AI pomocí
**The future of coding is here - embrace it!** 💡
## 🎯 Úvod: Cursor jako Váš AI Development Environment
Cursor není jen fork VS Code s AI - je to kompletně nový způsob myšlení o vývoji softwaru. Kombinuje nejlepší z VS Code s pokročilými AI schopnostmi, které vám umožní:
- Refactorovat celé funkce jedním promptem
- Vyvíjet napříč multiple soubory současně
- Debugovat komplexní issues s AI asistentem
- Onboardovat nové členy týmu 10x rychleji
**Co se naučíte:**
- Jak využít Composer Mode pro architecture-level změny
- Workflow patterns pro každodenní development tasks
- Pokročilé techniky pro large codebase (50k+ LOC)
- Team collaboration strategies s Cursor
---
## 🎼 1. Composer Mode - The Game Changer
### 1.1 Co Je Composer Mode a Kdy Ho Použít
**Composer Mode** = Multi-file AI editor, který rozumí celému kontextu projektu.
**Použijte pro:**
- ✅ Přidávání nových features across multiple files
- ✅ Refactoring celých modulů
- ✅ Migrace na nové technologie/patterns
- ✅ Implementace komplexních business logic
**NEPOUŽÍVEJTE pro:**
- ❌ Jednoduché single-line edits (použijte inline edit)
- ❌ Quick fixes (použijte Cmd+K)
- ❌ Code exploration (použijte chat)
### 1.2 Základní Workflow - Feature Across Files
**Scenario:** Přidáváte "Team Collaboration" feature
**Krok 1: Otevřete Composer (Cmd+I)**
```
Prompt pro Composer:
---
Add team collaboration feature to the SaaS app. This includes:
1. Database schema (Prisma):
- Team model with name, members, settings
- TeamMember model with role, permissions
- Update User model with teamId foreign key
2. tRPC API (app/api/trpc):
- team router with CRUD operations
- teamMember router for invites, role management
- Authorization middleware for team-based access
3. UI Components (React):
- Team settings page with member list
- Invite member modal with email input
- Role selector dropdown (owner, admin, member)
- Team switcher in header
4. Business logic:
- Only team owners can delete teams
- Admins can invite/remove members
- Email invitations with unique tokens
- Automatic team creation on signup
Tech stack: Next.js 14 App Router, tRPC, Prisma, Zod validation, shadcn/ui components
Generate all necessary files and update existing ones.
---
```
**Co Composer udělá:**
1. **Analyzuje** celý codebase (všechny 200+ souborů)
2. **Plánuje** změny across multiple files
3. **Vygeneruje** nebo upraví:
- `prisma/schema.prisma` (nové modely)
- `lib/trpc/routers/team.ts` (nový router)
- `lib/trpc/routers/teamMember.ts` (nový router)
- `lib/trpc/routers/_app.ts` (merge routerů)
- `app/(dashboard)/team/page.tsx` (nová stránka)
- `components/features/team/InviteMemberModal.tsx`
- `components/features/team/TeamSwitcher.tsx`
- `components/features/team/MemberList.tsx`
- `types/team.ts` (type definitions)
4. **Respektuje** vaše existující patterns a conventions
**Krok 2: Review změn v diff view**
Composer ukáže všechny změny v přehledném diff view. **Důležité:**
- ✅ Zkontrolujte type safety
- ✅ Ověřte authorization logic
- ✅ Projděte si error handling
- ✅ Checknout migration steps (Prisma)
**Krok 3: Accept nebo Iteruj**
```
// Pokud něco chybí, pokračujte v Composer:
"Add unit tests for team router using vitest. Test authorization, validation, and edge cases."
// Composer automaticky vytvoří:
- lib/trpc/routers/team.test.ts (comprehensive tests)
```
### 1.3 Advanced Composer Patterns
**Pattern #1: Architecture Refactoring**
```
Prompt:
---
Refactor the authentication system from JWT to session-based auth:
Current: JWT tokens stored in localStorage
Target: HTTP-only cookies with session store (Redis)
Changes needed:
1. Remove JWT logic from auth router
2. Implement session middleware with express-session
3. Update login/logout endpoints to use sessions
4. Migrate frontend to use cookies instead of localStorage
5. Add CSRF protection
6. Update all API calls to include credentials
Preserve all existing functionality, just change the auth mechanism.
Generate migration guide for existing users.
---
```
Composer **automaticky refactoruje** 20+ souborů bez manual work!
**Pattern #2: Technology Migration**
```
Prompt:
---
Migrate from REST API to tRPC across the entire application:
Current: Express REST endpoints in /api folder
Target: tRPC routers with full type safety
Steps:
1. Convert all Express routes to tRPC procedures
2. Replace axios calls with tRPC client
3. Update error handling to use TRPCError
4. Add Zod validation for all inputs
5. Generate OpenAPI schema for documentation
6. Create migration script to preserve API compatibility
Tech stack: Next.js 14, TypeScript, Zod, tRPC v10
Maintain backwards compatibility with existing API consumers.
---
```
**Pattern #3: Feature Cloning**
```
Prompt:
---
We have a "Projects" feature. Clone it to create a similar "Workspaces" feature:
Source files:
- app/(dashboard)/projects/*
- lib/trpc/routers/project.ts
- components/features/projects/*
Replicate the exact same structure but for workspaces:
- Rename all references from "project" to "workspace"
- Update database schema
- Keep the same UI/UX patterns
- Maintain feature parity (CRUD, sharing, permissions)
Generate all new files and update necessary imports.
---
```
### 1.4 Composer Tips & Tricks
**Tip #1: Include Context Files**
Před použitím Composer **otevřete klíčové soubory** které chcete použít jako reference:
- `prisma/schema.prisma` (data models)
- `types/index.ts` (type definitions)
- `lib/trpc/routers/_app.ts` (API structure)
Cursor použije tyto soubory jako kontext pro generování.
**Tip #2: Iterative Refinement**
Neočekávejte perfektní output na první pokus. Používejte Composer **iterativně**:
```
1. První prompt: "Add feature X"
2. Review output
3. Druhý prompt: "Add error handling for edge case Y"
4. Review
5. Třetí prompt: "Add unit tests"
6. Accept changes
```
**Tip #3: Use @-mentions Pro Specifický Context**
```
Prompt:
---
@schema.prisma @auth.ts
Update user authentication to include 2FA.
Use the existing Prisma schema and auth patterns.
---
```
`@filename` říká Cursor: "použij tento soubor jako primary context".
---
## 💬 2. Chat Features - Your AI Pair Programmer
### 2.1 Chat vs Composer - Kdy Co Použít
| Feature | Chat (Cmd+L) | Composer (Cmd+I) |
|---------|--------------|------------------|
| Code explanation | ✅ Perfect | ❌ Overkill |
| Learning concepts | ✅ Best | ❌ Not suitable |
| Quick fixes | ✅ Good | ❌ Too heavy |
| Multi-file changes | ❌ Limited | ✅ Perfect |
| Debugging | ✅ Great | ⚠️ Depends |
| Architecture planning | ✅ Great | ⚠️ Better after plan |
**Golden Rule:** Chat = Thinking, Composer = Executing
### 2.2 Chat Workflow Patterns
**Pattern #1: Code Explanation**
```
You: Explain this tRPC middleware
[paste code]
AI: This middleware implements row-level security...
[detailed explanation]
You: How can I extend it to support team-based permissions?
AI: Here are 3 approaches:
1. Add teamId to context...
2. Create a higher-order middleware...
3. Use Prisma middleware for automatic filtering...
You: Show me approach #2 with code
AI: [generates implementation]
```
**Pattern #2: Debugging Workflow**
```
You: I'm getting "Cannot read property 'id' of undefined" in getUserProjects
AI: This error suggests that either:
1. `user` is undefined (auth issue)
2. `project.owner` is not populated (missing include)
Can you share:
- The getUserProjects function
- The tRPC context
- Recent changes to auth
You: [shares context]
AI: The issue is in your protectedProcedure middleware.
You're accessing ctx.session.user.id but session can be null.
Fix:
[shows code with proper null checking]
```
**Pattern #3: Architecture Discussion**
```
You: I need to implement real-time notifications. Should I use:
1. WebSockets
2. Server-Sent Events
3. Polling
4. Third-party service (Pusher)
Consider: Next.js 14 App Router, Vercel deployment, 1000+ users
AI: For your stack, I recommend Server-Sent Events (SSE):
Pros:
- Native Next.js support via Route Handlers
- Works with Vercel (unlike WebSockets)
- Simpler than WebSockets for one-way communication
- Built-in reconnection
Implementation:
[shows Next.js SSE example with tRPC integration]
Alternative for bi-directional: Use Vercel Edge Functions + Upstash Redis
[shows architecture diagram in text]
```
### 2.3 Advanced Chat Techniques
**Technique #1: Codebase Navigation**
```
You: @codebase Where is the user authentication logic?
AI: User authentication is implemented across these files:
1. lib/auth/session.ts - Session management
2. lib/trpc/middleware/auth.ts - tRPC auth middleware
3. app/api/auth/[...nextauth]/route.ts - NextAuth configuration
4. components/features/auth/LoginForm.tsx - Login UI
The main flow:
[explains authentication flow]
```
**Technique #2: Documentation Lookup**
```
You: @docs How do I use tRPC subscriptions in Next.js App Router?
AI: [searches tRPC docs]
tRPC subscriptions require WebSocket support...
[shows implementation with workaround for App Router]
```
**Technique #3: Git Integration**
```
You: @git What changed in the last commit that could break authentication?
AI: The last commit "Refactor auth middleware" modified:
1. lib/trpc/middleware/auth.ts
- Changed session validation logic
- Removed automatic user fetching
This could break auth because:
[explains breaking change]
Suggested fix:
[shows migration path]
```
---
## ⚡ 3. Code Generation - Boilerplate Automation
### 3.1 Component Generation
**Cmd+K inline generation:**
```typescript
// In your React component file, type comment:
// shadcn form component for project creation with name, description,
// use react-hook-form, zod validation, trpc mutation
// Press Cmd+K, AI generates:
"use client";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { Button } from "@/components/ui/button";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { api } from "@/lib/trpc/client";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
const formSchema = z.object({
name: z.string().min(1, "Name is required").max(100),
description: z.string().max(500).optional(),
});
type FormValues = z.infer<typeof formSchema>;
export function CreateProjectForm() {
const router = useRouter();
const form = useForm<FormValues>({
resolver: zodResolver(formSchema),
defaultValues: {
name: "",
description: "",
},
});
const createProject = api.project.create.useMutation({
onSuccess: (data) => {
toast.success("Project created successfully");
router.push(`/projects/${data.id}`);
},
onError: (error) => {
toast.error(error.message);
},
});
const onSubmit = (values: FormValues) => {
createProject.mutate(values);
};
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>Project Name</FormLabel>
<FormControl>
<Input placeholder="My Awesome Project" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="description"
render={({ field }) => (
<FormItem>
<FormLabel>Description</FormLabel>
<FormControl>
<Textarea
placeholder="Describe your project..."
className="resize-none"
{...field}
/>
</FormControl>
<FormDescription>
Optional description of your project
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit" disabled={createProject.isLoading}>
{createProject.isLoading ? "Creating..." : "Create Project"}
</Button>
</form>
</Form>
);
}
```
**One comment → Complete production-ready component!**
### 3.2 Test Generation
```typescript
// In your test file:
// Unit tests for CreateProjectForm component
// Test form validation, submission, error handling, loading states
// Use vitest, testing-library/react, MSW for API mocking
// Cmd+K generates complete test suite:
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { vi } from "vitest";
import { CreateProjectForm } from "./CreateProjectForm";
import { api } from "@/lib/trpc/client";
vi.mock("@/lib/trpc/client");
vi.mock("next/navigation", () => ({
useRouter: () => ({ push: vi.fn() }),
}));
describe("CreateProjectForm", () => {
it("renders form fields", () => {
render(<CreateProjectForm />);
expect(screen.getByLabelText("Project Name")).toBeInTheDocument();
expect(screen.getByLabelText("Description")).toBeInTheDocument();
expect(screen.getByRole("button", { name: /create/i })).toBeInTheDocument();
});
it("validates required fields", async () => {
const user = userEvent.setup();
render(<CreateProjectForm />);
const submitButton = screen.getByRole("button", { name: /create/i });
await user.click(submitButton);
expect(await screen.findByText("Name is required")).toBeInTheDocument();
});
it("submits form with valid data", async () => {
const user = userEvent.setup();
const mockMutate = vi.fn();
(api.project.create.useMutation as any).mockReturnValue({
mutate: mockMutate,
isLoading: false,
});
render(<CreateProjectForm />);
await user.type(screen.getByLabelText("Project Name"), "Test Project");
await user.type(screen.getByLabelText("Description"), "Test description");
await user.click(screen.getByRole("button", { name: /create/i }));
expect(mockMutate).toHaveBeenCalledWith({
name: "Test Project",
description: "Test description",
});
});
it("shows loading state during submission", async () => {
(api.project.create.useMutation as any).mockReturnValue({
mutate: vi.fn(),
isLoading: true,
});
render(<CreateProjectForm />);
expect(screen.getByRole("button", { name: /creating/i })).toBeDisabled();
});
it("handles submission errors", async () => {
const user = userEvent.setup();
const mockMutate = vi.fn();
const mockToast = vi.fn();
vi.mock("sonner", () => ({ toast: { error: mockToast } }));
(api.project.create.useMutation as any).mockReturnValue({
mutate: mockMutate,
isLoading: false,
error: new Error("Failed to create project"),
});
render(<CreateProjectForm />);
await user.type(screen.getByLabelText("Project Name"), "Test");
await user.click(screen.getByRole("button", { name: /create/i }));
await waitFor(() => {
expect(mockToast).toHaveBeenCalledWith("Failed to create project");
});
});
});
```
---
## 🔧 4. Refactoring Tools - Code Modernization
### 4.1 Automated Refactoring Patterns
**Pattern: Extract to Custom Hook**
```typescript
// Máte duplicitní logic across components:
// components/ProjectList.tsx a components/TaskList.tsx
// Select duplicated code, Cmd+K:
"Extract this data fetching logic into a custom hook useInfiniteQuery with TypeScript generics"
// Cursor vytvoří:
// hooks/useInfiniteQuery.ts
export function useInfiniteQuery<T>(
queryKey: string[],
fetcher: (page: number) => Promise<T[]>,
options?: { pageSize?: number }
) {
const [data, setData] = useState<T[]>([]);
const [page, setPage] = useState(1);
const [isLoading, setIsLoading] = useState(false);
const [hasMore, setHasMore] = useState(true);
const loadMore = useCallback(async () => {
if (isLoading || !hasMore) return;
setIsLoading(true);
try {
const newData = await fetcher(page);
setData(prev => [...prev, ...newData]);
setHasMore(newData.length === (options?.pageSize ?? 20));
setPage(prev => prev + 1);
} catch (error) {
console.error("Failed to load more:", error);
} finally {
setIsLoading(false);
}
}, [page, fetcher, isLoading, hasMore, options?.pageSize]);
return { data, isLoading, hasMore, loadMore };
}
// A automaticky refactoruje oba komponenty:
// components/ProjectList.tsx
const { data: projects, isLoading, hasMore, loadMore } = useInfiniteQuery(
["projects"],
(page) => api.project.list.query({ page }),
{ pageSize: 20 }
);
// components/TaskList.tsx
const { data: tasks, isLoading, hasMore, loadMore } = useInfiniteQuery(
["tasks"],
(page) => api.task.list.query({ page }),
{ pageSize: 20 }
);
```
### 4.2 Legacy Code Modernization
```
Chat prompt:
---
@oldComponent.js
Refactor this class component to functional component with hooks:
- Convert state to useState
- Convert componentDidMount to useEffect
- Convert class methods to functions
- Add TypeScript types
- Apply modern React patterns (memo, useCallback where appropriate)
- Maintain exact same functionality
---
// Cursor analyzuje class component a vygeneruje modern equivalent
```
---
## 🐛 5. Debugging Workflow
### 5.1 AI-Assisted Debugging
**Scenario: Production Bug**
```
Chat:
---
@logs/error.log @components/Dashboard.tsx
We're getting "Cannot read property 'map' of undefined" in production.
The error occurs intermittently on the dashboard page.
Error log shows it happens during initial render.
Help me identify the root cause and fix it.
---
AI Response:
The issue is a race condition in data fetching. Your Dashboard component
assumes `projects` array is always defined, but during initial SSR or when
API is slow, it can be undefined.
Root cause in Dashboard.tsx:47
```typescript
// ❌ Current code:
{projects.map(project => <ProjectCard key={project.id} project={project} />)}
// ✅ Recommended fix:
{(projects ?? []).map(project => <ProjectCard key={project.id} project={project} />)}
// Or better - add loading state:
{!projects ? (
<Skeleton />
) : projects.length === 0 ? (
<EmptyState />
) : (
projects.map(project => <ProjectCard key={project.id} project={project} />)
)}
```
Additional recommendations:
1. Add Suspense boundary around async components
2. Implement error boundary for graceful error handling
3. Add type guard for runtime safety
[Would you like me to implement these fixes across all similar patterns in the codebase?]
```
### 5.2 Performance Debugging
```
Chat:
---
@codebase
The project list page is slow (3-4 second load time).
Profile the application and suggest optimizations.
Key metrics:
- 500+ projects to display
- Each project has nested data (members, tasks, comments)
- Using tRPC for API calls
- Next.js App Router SSR
---
AI identifies issues:
1. N+1 query problem in tRPC router (fetching members separately)
2. Over-fetching data (loading all tasks when only count is needed)
3. No pagination implemented
4. Missing database indexes
Suggests optimized implementation:
[Shows optimized Prisma queries with includes, select, take/skip for pagination, indexes]
```
---
## 👥 6. Team Collaboration Workflows
### 6.1 Onboarding New Developers
**Day 1 Onboarding Guide Generation:**
```
Composer:
---
Generate a comprehensive onboarding guide for new developers:
1. Project overview (architecture, tech stack, key concepts)
2. Local development setup (step-by-step)
3. Code standards and conventions
4. Common tasks and how to do them (add feature, fix bug, deploy)
5. Important files to read first
6. Team practices (PR process, code review, testing)
Analyze the entire codebase (@codebase) and create a detailed guide
in ONBOARDING.md
---
// Cursor analyzuje 200+ souborů a vytvoří comprehensive guide
```
**Generated ONBOARDING.md includes:**
- Architecture diagram (ASCII art)
- Database schema visualization
- API endpoint overview
- UI component hierarchy
- Development workflow
- Troubleshooting common issues
**Time saved: 8+ hours** of manual documentation writing!
### 6.2 Code Review Assistance
```
Chat:
---
@git/pr/123
Review this pull request for:
1. Type safety issues
2. Security vulnerabilities
3. Performance problems
4. Code style violations
5. Missing tests
6. Breaking changes
Provide detailed feedback with code suggestions.
---
// AI analyzuje změny v PR a poskytne structured review
```
### 6.3 Knowledge Sharing
```
Chat:
---
@components/PaymentProcessor.tsx
Explain how payment processing works in this application.
Include:
- Flow diagram
- Security considerations
- Error handling strategy
- Testing approach
Format for team wiki documentation.
---
// AI vytvoří comprehensive documentation ready to paste into Notion/Confluence
```
---
## ⚙️ 7. Cursor Settings & Customization
### 7.1 Recommended Settings
```json
// .cursor/settings.json
{
"cursor.ai.model": "claude-3.5-sonnet", // Nejlepší pro complex tasks
"cursor.ai.useComposer": true,
"cursor.ai.includedFiles": 100, // Zvýšit pro large codebase
// Composer settings
"cursor.composer.maxTokens": 8000,
"cursor.composer.temperature": 0.3, // Nižší = více konzistentní
// Chat settings
"cursor.chat.showInlineChat": true,
"cursor.chat.contextWindow": "large",
// Code generation
"cursor.codeGeneration.autoImport": true,
"cursor.codeGeneration.respectEslint": true,
// Privacy
"cursor.privacy.enableTelemetry": false,
"cursor.privacy.neverSendCode": false // True pokud pracujete s sensitive codebase
}
```
### 7.2 Keyboard Shortcuts (macOS)
| Shortcut | Action | Use Case |
|----------|--------|----------|
| `Cmd+K` | Inline edit | Quick fixes, small changes |
| `Cmd+L` | Open chat | Questions, explanations, debugging |
| `Cmd+I` | Open Composer | Multi-file edits, features |
| `Cmd+Shift+L` | Chat with selection | Explain/refactor selected code |
| `Option+Cmd+I` | Quick question | Fast Q&A without opening full chat |
| `Cmd+` | Show AI suggestions | Review AI-generated code |
### 7.3 Project-Specific Rules
```
// .cursorrules file in project root
This is a Next.js 14 SaaS project with:
- TypeScript strict mode
- tRPC for API
- Prisma ORM
- Zod validation
- Shadcn/ui components
- TailwindCSS for styling
Code standards:
- Always use server components unless client-side interactivity is needed
- Validate all inputs with Zod
- Use tRPC procedures instead of API routes
- Follow shadcn/ui component patterns
- Prefer TypeScript utility types over custom type definitions
- Always add error boundaries around async components
- Use React Server Components for data fetching when possible
File structure conventions:
- API: lib/trpc/routers/*.ts
- Components: components/features/[feature]/*.tsx
- UI primitives: components/ui/*.tsx
- Types: types/*.ts
- Utils: lib/utils/*.ts
- Hooks: hooks/*.ts
Testing requirements:
- Unit tests for all business logic
- Integration tests for tRPC routers
- E2E tests for critical user flows
- Use vitest for unit/integration, Playwright for E2E
When generating code:
- Follow these conventions exactly
- Add appropriate error handling
- Include TypeScript types
- Write tests for new functionality
```
Cursor čte `.cursorrules` a **automaticky aplikuje** tyto standardy na veškerý generovaný kód!
---
## 📊 8. Measuring Success & Productivity
### 8.1 Metrics to Track
**Before Cursor (Week 1):**
- Features delivered: 3
- Bugs introduced: 8
- Code review time: 4 hours/week
- Time spent on boilerplate: 6 hours/week
- Developer satisfaction: 6/10
**After Cursor (Week 4):**
- Features delivered: 7 (+133%)
- Bugs introduced: 5 (-37%)
- Code review time: 2 hours/week (-50%)
- Time spent on boilerplate: 1 hour/week (-83%)
- Developer satisfaction: 9/10
**Key Performance Indicators:**
1. **Feature Velocity** - Story points per sprint
2. **Code Quality** - Bug rate, test coverage
3. **Developer Experience** - Satisfaction surveys
4. **Time Savings** - Hours saved on repetitive tasks
5. **Onboarding Time** - Time to first PR for new devs
### 8.2 ROI Calculation
**Cost:**
- Cursor Pro: $20/dev/month
- Team of 4: $80/month
**Savings:**
- 10 hours/dev/week × 4 devs = 40 hours/week
- At $50/hour = $2,000/week = **$8,000/month**
**ROI: 100x return on investment!**
---
## 🎓 Závěr: Your 30-Day Cursor Adoption Plan
### Week 1: Foundation
- [ ] Install Cursor, migrate from VS Code
- [ ] Configure settings and .cursorrules
- [ ] Complete 5 simple tasks with Chat
- [ ] Try Composer for 1 small feature
- [ ] Measure baseline productivity
### Week 2: Integration
- [ ] Use Composer for 3 multi-file features
- [ ] Generate tests with AI
- [ ] Refactor 1 module with Cursor
- [ ] Document learnings for team
- [ ] Track time savings
### Week 3: Collaboration
- [ ] Onboard 1 team member using AI-generated guide
- [ ] Use Cursor for code reviews
- [ ] Create team .cursorrules file
- [ ] Share best practices in team meeting
- [ ] Measure team productivity gains
### Week 4: Mastery
- [ ] Handle complex architecture changes with Composer
- [ ] Use AI for debugging production issues
- [ ] Optimize workflows based on metrics
- [ ] Document case studies for management
- [ ] Plan for org-wide rollout
**Success Criteria:**
- ✅ 50%+ time savings on boilerplate code
- ✅ 2x feature velocity without quality decrease
- ✅ Reduced onboarding time from weeks to days
- ✅ Team satisfaction score 8+/10
---
## 🚀 Next Level: Advanced Techniques
### Custom AI Instructions
Teach Cursor your team-specific patterns by showing examples in chat:
```
This is how we structure tRPC routers in our project:
[paste example router]
This is our error handling pattern:
[paste error handler]
This is our testing pattern:
[paste test example]
Remember these patterns and use them when generating code.
```
Cursor learns and applies patterns across future generations!
### Workflow Automation
Combine Cursor with shell scripts:
```bash
#!/bin/bash
# generate-feature.sh
FEATURE_NAME=$1
echo "Generating $FEATURE_NAME feature..."
# Open Composer with pre-filled prompt
cursor composer "Create a new $FEATURE_NAME feature following our project conventions.
Include:
- Database schema (Prisma)
- tRPC router with CRUD
- UI components
- Tests
- Documentation"
```
**Usage:** `./generate-feature.sh team-management`
### Integration with Other Tools
- **Linear/Jira:** Paste ticket → Cursor generates implementation
- **Figma:** Screenshot → Composer generates React components
- **Slack:** Error alert → Chat helps debug
- **GitHub:** PR description → Cursor generates code review
---
**Cursor není jen editor - je to kompletní AI development environment, který transformuje způsob, jakým píšete kód. Když ho kombinujete s dobrými praktikami a team collaboration, dosáhnete 2-3x produktivity při zachování (nebo zvýšení) kvality!** 🚀
S touto strategií pro váš Next.js + TypeScript + tRPC stack budete schopni:
- Vyvíjet features 2x rychleji
- Onboardovat nové členy za 2 dny místo 2 týdnů
- Refactorovat legacy code efektivně
- Debugovat komplexní issues s AI pomocí
**The future of coding is here - embrace it!** 💡
Kde použít tento prompt?
Najděte vhodné AI nástroje pro použití tohoto promptu a maximalizujte jeho efektivitu.
Podobné prompty
Advanced AI Features - Deep Dive do Pokročilých Funkcí
Komplexní průvodce pokročilými funkcemi AI nástrojů - od extended context a multimodality po tool use, streaming, a fine-tuning. Naučte se využívat plný potenciál moderních AI systémů.
Programování
Zobrazit
Algoritmus optimalizace
Optimalizace algoritmu z O(n²) na O(n log n) nebo lepší.
Programování
Zobrazit
API design s REST best practices
Návrh RESTful API s dokumentací a error handling.
Programování
Zobrazit
CI/CD pipeline setup
Konfigurace GitHub Actions / GitLab CI pipeline s testing a deployment.
Programování
Zobrazit
Objevte další AI prompty
Prozkoumejte naši sbírku Programování promptů a najděte ty, které vám pomohou dosáhnout lepších výsledků.